Socket
Socket
Sign inDemoInstall

@celo/utils

Package Overview
Dependencies
Maintainers
21
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 1.3.1 to 1.3.3

lib/sign-typed-data-utils.test.d.ts

64

lib/account.js
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

@@ -65,13 +84,11 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }

};
var __spread = (this && this.__spread) || function () {
for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
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 __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -81,2 +98,3 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

Object.defineProperty(exports, "__esModule", { value: true });
exports.AccountUtils = exports.generateKeysFromSeed = exports.generateSeed = exports.generateDeterministicInviteCode = exports.generateKeys = exports.suggestMnemonicCorrections = exports.detectMnemonicLanguage = exports.mnemonicLengthFromStrength = exports.getAllLanguages = exports.formatNonAccentedCharacters = exports.normalizeMnemonic = exports.invalidMnemonicWords = exports.validateMnemonic = exports.generateMnemonic = exports.MnemonicStrength = exports.MnemonicLanguages = exports.CELO_DERIVATION_PATH_BASE = void 0;
var account_1 = require("@celo/base/lib/account");

@@ -93,5 +111,5 @@ var string_1 = require("@celo/base/lib/string");

var account_2 = require("@celo/base/lib/account");
exports.CELO_DERIVATION_PATH_BASE = account_2.CELO_DERIVATION_PATH_BASE;
exports.MnemonicLanguages = account_2.MnemonicLanguages;
exports.MnemonicStrength = account_2.MnemonicStrength;
Object.defineProperty(exports, "CELO_DERIVATION_PATH_BASE", { enumerable: true, get: function () { return account_2.CELO_DERIVATION_PATH_BASE; } });
Object.defineProperty(exports, "MnemonicLanguages", { enumerable: true, get: function () { return account_2.MnemonicLanguages; } });
Object.defineProperty(exports, "MnemonicStrength", { enumerable: true, get: function () { return account_2.MnemonicStrength; } });
function defaultGenerateMnemonic(strength, rng, wordlist) {

@@ -197,4 +215,4 @@ return new Promise(function (resolve, reject) {

var wordList = getWordList(language);
var normalizedWordMap_1 = new Map(wordList.map(function (word) { return [string_1.normalizeAccents(word), word]; }));
return words.map(function (word) { var _a; return (_a = normalizedWordMap_1.get(string_1.normalizeAccents(word))) !== null && _a !== void 0 ? _a : word; });
var normalizedWordMap_1 = new Map(wordList.map(function (word) { return [(0, string_1.normalizeAccents)(word), word]; }));
return words.map(function (word) { var _a; return (_a = normalizedWordMap_1.get((0, string_1.normalizeAccents)(word))) !== null && _a !== void 0 ? _a : word; });
}

@@ -277,3 +295,3 @@ return words;

function splitMnemonic(mnemonic) {
return __spread(mnemonic.trim().split(/\s+/));
return __spreadArray([], __read(mnemonic.trim().split(/\s+/)), false);
}

@@ -310,3 +328,3 @@ /**

else if (score === leadingScore) {
return [__spread(leaders, [candidate]), leadingScore];
return [__spreadArray(__spreadArray([], __read(leaders), false), [candidate], false), leadingScore];
}

@@ -414,7 +432,7 @@ return [leaders, leadingScore];

case 2:
remaining = __spread(suggestionsLists.slice(1));
remaining = __spreadArray([], __read(suggestionsLists.slice(1)), false);
_o.label = 3;
case 3:
_o.trys.push([3, 20, 21, 22]);
_a = __values(__spread(suggestions.keys()).sort()), _b = _a.next();
_a = __values(__spreadArray([], __read(suggestions.keys()), false).sort()), _b = _a.next();
_o.label = 4;

@@ -443,3 +461,3 @@ case 4:

suggestion = _f.value;
return [4 /*yield*/, __spread([suggestion], list)];
return [4 /*yield*/, __spreadArray([suggestion], __read(list), false)];
case 9:

@@ -543,3 +561,3 @@ _o.sent();

return getWordList(language)
.map(function (word) { return ({ distance: levenshtein_1.levenshteinDistance(typo, word), word: word }); })
.map(function (word) { return ({ distance: (0, levenshtein_1.levenshteinDistance)(typo, word), word: word }); })
.reduce(function (map, _a) {

@@ -580,3 +598,3 @@ var distance = _a.distance, word = _a.word;

if (derivationPath === void 0) { derivationPath = account_1.CELO_DERIVATION_PATH_BASE; }
var seed = ethereumjs_util_1.keccak256(recipientPhoneHash + recipientPepper);
var seed = (0, ethereumjs_util_1.keccak256)(recipientPhoneHash + recipientPepper);
return generateKeysFromSeed(seed, changeIndex, addressIndex, derivationPath);

@@ -621,3 +639,3 @@ }

publicKey: newNode.publicKey.toString('hex'),
address: address_1.privateKeyToAddress(newNode.privateKey.toString('hex')),
address: (0, address_1.privateKeyToAddress)(newNode.privateKey.toString('hex')),
};

@@ -624,0 +642,0 @@ }

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

@@ -49,9 +68,2 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }

};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });

@@ -68,3 +80,3 @@ var account_1 = require("@celo/base/lib/account");

switch (_a.label) {
case 0: return [4 /*yield*/, account_2.generateMnemonic()];
case 0: return [4 /*yield*/, (0, account_2.generateMnemonic)()];
case 1:

@@ -81,3 +93,3 @@ mnemonic = _a.sent();

switch (_a.label) {
case 0: return [4 /*yield*/, account_2.generateMnemonic(account_2.MnemonicStrength.s128_12words)];
case 0: return [4 /*yield*/, (0, account_2.generateMnemonic)(account_2.MnemonicStrength.s128_12words)];
case 1:

@@ -96,3 +108,3 @@ mnemonic = _a.sent();

switch (_a.label) {
case 0: return [4 /*yield*/, account_2.generateMnemonic(undefined, language)];
case 0: return [4 /*yield*/, (0, account_2.generateMnemonic)(undefined, language)];
case 1:

@@ -102,3 +114,3 @@ mnemonic = _a.sent();

// This validates against all languages
expect(account_2.validateMnemonic(mnemonic)).toBeTruthy();
expect((0, account_2.validateMnemonic)(mnemonic)).toBeTruthy();
// This validates using a specific wordlist

@@ -112,3 +124,3 @@ expect(bip39.validateMnemonic(mnemonic, bip39.wordlists[languageName])).toBeTruthy();

try {
for (var _b = __values(account_2.getAllLanguages()), _c = _b.next(); !_c.done; _c = _b.next()) {
for (var _b = __values((0, account_2.getAllLanguages)()), _c = _b.next(); !_c.done; _c = _b.next()) {
var language = _c.value;

@@ -145,3 +157,3 @@ _loop_1(language);

// This validates against all languages
expect(account_2.validateMnemonic(mnemonic)).toBeTruthy();
expect((0, account_2.validateMnemonic)(mnemonic)).toBeTruthy();
// This validates using a specific wordlist

@@ -152,3 +164,3 @@ expect(bip39.validateMnemonic(mnemonic, bip39.wordlists[languageName])).toBeTruthy();

try {
for (var _c = __values(account_2.getAllLanguages()), _d = _c.next(); !_d.done; _d = _c.next()) {
for (var _c = __values((0, account_2.getAllLanguages)()), _d = _c.next(); !_d.done; _d = _c.next()) {
var language = _d.value;

@@ -235,10 +247,10 @@ _loop_2(language);

if (!(i < mnemonics.length)) return [3 /*break*/, 6];
expect(account_2.validateMnemonic(mnemonics[i])).toBe(true);
return [4 /*yield*/, account_2.generateKeys(mnemonics[i])];
expect((0, account_2.validateMnemonic)(mnemonics[i])).toBe(true);
return [4 /*yield*/, (0, account_2.generateKeys)(mnemonics[i])];
case 2:
derivation0 = _a.sent();
return [4 /*yield*/, account_2.generateKeys(mnemonics[i], undefined, 0, 1)];
return [4 /*yield*/, (0, account_2.generateKeys)(mnemonics[i], undefined, 0, 1)];
case 3:
derivation1 = _a.sent();
return [4 /*yield*/, account_2.generateKeys(mnemonics[i], 'password')];
return [4 /*yield*/, (0, account_2.generateKeys)(mnemonics[i], 'password')];
case 4:

@@ -266,3 +278,3 @@ password = _a.sent();

'yerno obvio ninez pierna bebe pomelo retorno flujo sacar odio oxigeno rabo',
'yérno obvio ninez pierña bebe pomelo retorno flujo sacar odio oxigéno rabo',
'yérno obvio ninez pierña bebe pomelo retorno flujo sacar odio oxigéno rabo', // Incorrect accents.
];

@@ -273,3 +285,3 @@ var expectedMnemonic = spanishMnemonics[0];

var mnemonic = spanishMnemonics_1_1.value;
expect(account_2.normalizeMnemonic(mnemonic)).toEqual(expectedMnemonic);
expect((0, account_2.normalizeMnemonic)(mnemonic)).toEqual(expectedMnemonic);
}

@@ -309,3 +321,3 @@ }

var _b = cases_1_1.value, mnemonic = _b.mnemonic, language = _b.language, expected = _b.expected;
expect(account_2.normalizeMnemonic(mnemonic, language)).toEqual(expected);
expect((0, account_2.normalizeMnemonic)(mnemonic, language)).toEqual(expected);
}

@@ -324,3 +336,3 @@ }

var expected = 'female cousin rapid exotic ribbon level equip legal fun river hotel duty trip youth rebel';
expect(account_2.normalizeMnemonic(mnemonic)).toEqual(expected);
expect((0, account_2.normalizeMnemonic)(mnemonic)).toEqual(expected);
});

@@ -330,3 +342,3 @@ it('should normalize extra and non-standard whitespace', function () {

var expected = 'female cousin rapid exotic ribbon level equip legal fun river hotel duty trip youth rebel';
expect(account_2.normalizeMnemonic(mnemonic)).toEqual(expected);
expect((0, account_2.normalizeMnemonic)(mnemonic)).toEqual(expected);
});

@@ -336,3 +348,3 @@ it('should normalize extra and non-standard whitespace', function () {

var expected = 'female cousin rapid exotic ribbon level equip legal fun river hotel duty trip youth rebel';
expect(account_2.normalizeMnemonic(mnemonic)).toEqual(expected);
expect((0, account_2.normalizeMnemonic)(mnemonic)).toEqual(expected);
});

@@ -342,3 +354,3 @@ it('should normalize whitespace of Japanese mnemonics using ideographic spaces', function () {

var expected = 'せけん まなぶ せんえい ねっしん はくしゅ うなずく いがく ひこく にちようび いがく なふだ ばかり どんぶり せきらんうん きかく';
expect(account_2.normalizeMnemonic(mnemonic)).toEqual(expected);
expect((0, account_2.normalizeMnemonic)(mnemonic)).toEqual(expected);
});

@@ -350,6 +362,6 @@ var _loop_3 = function (language) {

switch (_a.label) {
case 0: return [4 /*yield*/, account_2.generateMnemonic(account_2.MnemonicStrength.s256_24words, language)];
case 0: return [4 /*yield*/, (0, account_2.generateMnemonic)(account_2.MnemonicStrength.s256_24words, language)];
case 1:
mnemonic = _a.sent();
expect(account_2.normalizeMnemonic(mnemonic)).toEqual(mnemonic);
expect((0, account_2.normalizeMnemonic)(mnemonic)).toEqual(mnemonic);
return [2 /*return*/];

@@ -361,3 +373,3 @@ }

try {
for (var _b = __values(account_2.getAllLanguages()), _c = _b.next(); !_c.done; _c = _b.next()) {
for (var _b = __values((0, account_2.getAllLanguages)()), _c = _b.next(); !_c.done; _c = _b.next()) {
var language = _c.value;

@@ -379,7 +391,7 @@ _loop_3(language);

var invalidWords = ['roayl', 'dufbuty', 'wabnt', 'ynfikd', 'oik', 'approbe', 'blish'];
expect(account_2.invalidMnemonicWords(mnemonic)).toEqual(invalidWords);
expect((0, account_2.invalidMnemonicWords)(mnemonic)).toEqual(invalidWords);
});
it('should return an empty list when given a correct phrase', function () {
var mnemonic = 'salute royal possible rare dignity want unfold oil cabbage labor approve winner claw conduct spider velvet buyer level second adult payment blush inject draw';
expect(account_2.invalidMnemonicWords(mnemonic)).toEqual([]);
expect((0, account_2.invalidMnemonicWords)(mnemonic)).toEqual([]);
});

@@ -389,3 +401,3 @@ it('should return undefined when the language is undetermined', function () {

var mnemonic = 'oil sponsor unlock diet aprove trim usual ethics tip prepare twist hunt neto sanidad tregua cuneta cazar tirón trueno enredo tauro pan torpedo húmedo';
expect(account_2.invalidMnemonicWords(mnemonic)).not.toBeDefined();
expect((0, account_2.invalidMnemonicWords)(mnemonic)).not.toBeDefined();
});

@@ -421,3 +433,3 @@ });

var _b = cases_2_1.value, mnemonic = _b.mnemonic, corrected = _b.corrected;
expect(account_2.suggestMnemonicCorrections(mnemonic).next().value).toEqual(corrected);
expect((0, account_2.suggestMnemonicCorrections)(mnemonic).next().value).toEqual(corrected);
}

@@ -476,3 +488,3 @@ }

try {
for (var _d = (e_8 = void 0, __values(account_2.suggestMnemonicCorrections(mnemonic))), _e = _d.next(); !_e.done; _e = _d.next()) {
for (var _d = (e_8 = void 0, __values((0, account_2.suggestMnemonicCorrections)(mnemonic))), _e = _d.next(); !_e.done; _e = _d.next()) {
var suggestion = _e.value;

@@ -512,6 +524,6 @@ attempts++;

try {
for (var _b = __values(account_2.suggestMnemonicCorrections(mnemonic)), _c = _b.next(); !_c.done; _c = _b.next()) {
for (var _b = __values((0, account_2.suggestMnemonicCorrections)(mnemonic)), _c = _b.next(); !_c.done; _c = _b.next()) {
var suggestion = _c.value;
trials++;
expect(account_2.validateMnemonic(suggestion)).toBe(true);
expect((0, account_2.validateMnemonic)(suggestion)).toBe(true);
if (trials >= 100) {

@@ -535,3 +547,3 @@ break;

try {
for (var _b = __values(account_2.suggestMnemonicCorrections(mnemonic)), _c = _b.next(); !_c.done; _c = _b.next()) {
for (var _b = __values((0, account_2.suggestMnemonicCorrections)(mnemonic)), _c = _b.next(); !_c.done; _c = _b.next()) {
var suggestion = _c.value;

@@ -538,0 +550,0 @@ expect(seen.has(suggestion)).toBe(false);

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
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");

@@ -16,31 +29,36 @@ var ethereumjs_util_1 = require("ethereumjs-util");

var address_2 = require("@celo/base/lib/address");
exports.bufferToHex = address_2.bufferToHex;
exports.ensureLeading0x = address_2.ensureLeading0x;
exports.eqAddress = address_2.eqAddress;
exports.findAddressIndex = address_2.findAddressIndex;
exports.getAddressChunks = address_2.getAddressChunks;
exports.hexToBuffer = address_2.hexToBuffer;
exports.isHexString = address_2.isHexString;
exports.mapAddressListDataOnto = address_2.mapAddressListDataOnto;
exports.mapAddressListOnto = address_2.mapAddressListOnto;
exports.normalizeAddress = address_2.normalizeAddress;
exports.normalizeAddressWith0x = address_2.normalizeAddressWith0x;
exports.NULL_ADDRESS = address_2.NULL_ADDRESS;
exports.trimLeading0x = address_2.trimLeading0x;
Object.defineProperty(exports, "bufferToHex", { enumerable: true, get: function () { return address_2.bufferToHex; } });
Object.defineProperty(exports, "ensureLeading0x", { enumerable: true, get: function () { return address_2.ensureLeading0x; } });
Object.defineProperty(exports, "eqAddress", { enumerable: true, get: function () { return address_2.eqAddress; } });
Object.defineProperty(exports, "findAddressIndex", { enumerable: true, get: function () { return address_2.findAddressIndex; } });
Object.defineProperty(exports, "getAddressChunks", { enumerable: true, get: function () { return address_2.getAddressChunks; } });
Object.defineProperty(exports, "hexToBuffer", { enumerable: true, get: function () { return address_2.hexToBuffer; } });
Object.defineProperty(exports, "isHexString", { enumerable: true, get: function () { return address_2.isHexString; } });
Object.defineProperty(exports, "mapAddressListDataOnto", { enumerable: true, get: function () { return address_2.mapAddressListDataOnto; } });
Object.defineProperty(exports, "mapAddressListOnto", { enumerable: true, get: function () { return address_2.mapAddressListOnto; } });
Object.defineProperty(exports, "normalizeAddress", { enumerable: true, get: function () { return address_2.normalizeAddress; } });
Object.defineProperty(exports, "normalizeAddressWith0x", { enumerable: true, get: function () { return address_2.normalizeAddressWith0x; } });
Object.defineProperty(exports, "NULL_ADDRESS", { enumerable: true, get: function () { return address_2.NULL_ADDRESS; } });
Object.defineProperty(exports, "trimLeading0x", { enumerable: true, get: function () { return address_2.trimLeading0x; } });
var ethereumjs_util_2 = require("ethereumjs-util");
exports.isValidChecksumAddress = ethereumjs_util_2.isValidChecksumAddress;
exports.toChecksumAddress = ethereumjs_util_2.toChecksumAddress;
exports.privateKeyToAddress = function (privateKey) {
return ethereumjs_util_1.toChecksumAddress(address_1.ensureLeading0x(ethereumjs_util_1.privateToAddress(address_1.hexToBuffer(privateKey)).toString('hex')));
Object.defineProperty(exports, "isValidChecksumAddress", { enumerable: true, get: function () { return ethereumjs_util_2.isValidChecksumAddress; } });
Object.defineProperty(exports, "toChecksumAddress", { enumerable: true, get: function () { return ethereumjs_util_2.toChecksumAddress; } });
var privateKeyToAddress = function (privateKey) {
return (0, ethereumjs_util_1.toChecksumAddress)((0, address_1.ensureLeading0x)((0, ethereumjs_util_1.privateToAddress)((0, address_1.hexToBuffer)(privateKey)).toString('hex')));
};
exports.privateKeyToPublicKey = function (privateKey) {
return ethereumjs_util_1.toChecksumAddress(address_1.ensureLeading0x(ethereumjs_util_1.privateToPublic(address_1.hexToBuffer(privateKey)).toString('hex')));
exports.privateKeyToAddress = privateKeyToAddress;
var privateKeyToPublicKey = function (privateKey) {
return (0, ethereumjs_util_1.toChecksumAddress)((0, address_1.ensureLeading0x)((0, ethereumjs_util_1.privateToPublic)((0, address_1.hexToBuffer)(privateKey)).toString('hex')));
};
exports.publicKeyToAddress = function (publicKey) {
return ethereumjs_util_1.toChecksumAddress(address_1.ensureLeading0x(ethereumjs_util_1.pubToAddress(ethereumjs_util_1.toBuffer(address_1.ensureLeading0x(publicKey)), true).toString('hex')));
exports.privateKeyToPublicKey = privateKeyToPublicKey;
var publicKeyToAddress = function (publicKey) {
return (0, ethereumjs_util_1.toChecksumAddress)((0, address_1.ensureLeading0x)((0, ethereumjs_util_1.pubToAddress)((0, ethereumjs_util_1.toBuffer)((0, address_1.ensureLeading0x)(publicKey)), true).toString('hex')));
};
exports.isValidPrivateKey = function (privateKey) {
return privateKey.startsWith('0x') && ethereumjs_util_1.isValidPrivate(address_1.hexToBuffer(privateKey));
exports.publicKeyToAddress = publicKeyToAddress;
var isValidPrivateKey = function (privateKey) {
return privateKey.startsWith('0x') && (0, ethereumjs_util_1.isValidPrivate)((0, address_1.hexToBuffer)(privateKey));
};
exports.isValidAddress = function (input) { return Web3Utils.isAddress(input); };
exports.isValidPrivateKey = isValidPrivateKey;
var isValidAddress = function (input) { return Web3Utils.isAddress(input); };
exports.isValidAddress = isValidAddress;
//# sourceMappingURL=address.js.map

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

return __generator(this, function (_a) {
expect(address_1.getAddressChunks('0xce10ce10ce10ce10ce10ce10ce10ce10ce10ce10')).toEqual([
expect((0, address_1.getAddressChunks)('0xce10ce10ce10ce10ce10ce10ce10ce10ce10ce10')).toEqual([
'ce10',

@@ -46,0 +46,0 @@ 'ce10',

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sleep = exports.selectiveRetryAsyncWithBackOff = exports.retryAsyncWithBackOff = exports.retryAsync = exports.concurrentValuesMap = exports.concurrentMap = void 0;
// Exports moved to @celo/base, forwarding them
// here for backwards compatibility
var async_1 = require("@celo/base/lib/async");
exports.concurrentMap = async_1.concurrentMap;
exports.concurrentValuesMap = async_1.concurrentValuesMap;
exports.retryAsync = async_1.retryAsync;
exports.retryAsyncWithBackOff = async_1.retryAsyncWithBackOff;
exports.selectiveRetryAsyncWithBackOff = async_1.selectiveRetryAsyncWithBackOff;
exports.sleep = async_1.sleep;
Object.defineProperty(exports, "concurrentMap", { enumerable: true, get: function () { return async_1.concurrentMap; } });
Object.defineProperty(exports, "concurrentValuesMap", { enumerable: true, get: function () { return async_1.concurrentValuesMap; } });
Object.defineProperty(exports, "retryAsync", { enumerable: true, get: function () { return async_1.retryAsync; } });
Object.defineProperty(exports, "retryAsyncWithBackOff", { enumerable: true, get: function () { return async_1.retryAsyncWithBackOff; } });
Object.defineProperty(exports, "selectiveRetryAsyncWithBackOff", { enumerable: true, get: function () { return async_1.selectiveRetryAsyncWithBackOff; } });
Object.defineProperty(exports, "sleep", { enumerable: true, get: function () { return async_1.sleep; } });
//# sourceMappingURL=async.js.map

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

mockFunction = jest.fn();
return [4 /*yield*/, async_1.retryAsync(mockFunction, 3, [], 1)];
return [4 /*yield*/, (0, async_1.retryAsync)(mockFunction, 3, [], 1)];
case 1:

@@ -67,3 +67,3 @@ _a.sent();

_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, async_1.retryAsync(mockFunction, 3, [], 1)];
return [4 /*yield*/, (0, async_1.retryAsync)(mockFunction, 3, [], 1)];
case 2:

@@ -97,3 +97,3 @@ _a.sent();

_b.trys.push([1, 3, , 4]);
return [4 /*yield*/, async_1.selectiveRetryAsyncWithBackOff(mockFunction, 3, ['test'], [])];
return [4 /*yield*/, (0, async_1.selectiveRetryAsyncWithBackOff)(mockFunction, 3, ['test'], [])];
case 2:

@@ -124,3 +124,3 @@ _b.sent();

switch (_a.label) {
case 0: return [4 /*yield*/, async_1.sleep(5)];
case 0: return [4 /*yield*/, (0, async_1.sleep)(5)];
case 1:

@@ -149,3 +149,3 @@ _a.sent();

expected = _a.sent();
return [4 /*yield*/, async_1.concurrentMap(3, xs, fn)];
return [4 /*yield*/, (0, async_1.concurrentMap)(3, xs, fn)];
case 2:

@@ -168,5 +168,5 @@ result = _a.sent();

p1 = Promise.all(xs.map(c1.inc));
p2 = async_1.concurrentMap(2, xs, c2.inc);
p2 = (0, async_1.concurrentMap)(2, xs, c2.inc);
// sleep enough for Promise.all to finish
return [4 /*yield*/, async_1.sleep(7)];
return [4 /*yield*/, (0, async_1.sleep)(7)];
case 1:

@@ -177,3 +177,3 @@ // sleep enough for Promise.all to finish

expect(c1.val()).not.toEqual(c2.val());
return [4 /*yield*/, async_1.sleep(20)];
return [4 /*yield*/, (0, async_1.sleep)(20)];
case 2:

@@ -199,4 +199,4 @@ _a.sent();

xs = [1, 3, 4];
p = async_1.concurrentMap(5, xs, c.inc);
return [4 /*yield*/, async_1.sleep(7)];
p = (0, async_1.concurrentMap)(5, xs, c.inc);
return [4 /*yield*/, (0, async_1.sleep)(7)];
case 1:

@@ -203,0 +203,0 @@ _a.sent();

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AttestationUtils = exports.extractSecurityCodeWithPrefix = exports.attestToIdentifier = exports.getAttestationMessageToSignFromPhoneNumber = exports.getAttestationMessageToSignFromIdentifier = exports.hashIdentifier = exports.sanitizeMessageBase64 = exports.messageContainsAttestationCode = exports.isAccountConsideredVerified = exports.IdentifierType = exports.getIdentifierPrefix = exports.extractAttestationCodeFromMessage = exports.base64ToHex = void 0;
var attestations_1 = require("@celo/base/lib/attestations");

@@ -10,16 +11,16 @@ var web3_utils_1 = require("web3-utils");

var attestations_2 = require("@celo/base/lib/attestations");
exports.base64ToHex = attestations_2.base64ToHex;
exports.extractAttestationCodeFromMessage = attestations_2.extractAttestationCodeFromMessage;
exports.getIdentifierPrefix = attestations_2.getIdentifierPrefix;
exports.IdentifierType = attestations_2.IdentifierType;
exports.isAccountConsideredVerified = attestations_2.isAccountConsideredVerified;
exports.messageContainsAttestationCode = attestations_2.messageContainsAttestationCode;
exports.sanitizeMessageBase64 = attestations_2.sanitizeMessageBase64;
var sha3 = function (v) { return web3_utils_1.soliditySha3({ type: 'string', value: v }); };
Object.defineProperty(exports, "base64ToHex", { enumerable: true, get: function () { return attestations_2.base64ToHex; } });
Object.defineProperty(exports, "extractAttestationCodeFromMessage", { enumerable: true, get: function () { return attestations_2.extractAttestationCodeFromMessage; } });
Object.defineProperty(exports, "getIdentifierPrefix", { enumerable: true, get: function () { return attestations_2.getIdentifierPrefix; } });
Object.defineProperty(exports, "IdentifierType", { enumerable: true, get: function () { return attestations_2.IdentifierType; } });
Object.defineProperty(exports, "isAccountConsideredVerified", { enumerable: true, get: function () { return attestations_2.isAccountConsideredVerified; } });
Object.defineProperty(exports, "messageContainsAttestationCode", { enumerable: true, get: function () { return attestations_2.messageContainsAttestationCode; } });
Object.defineProperty(exports, "sanitizeMessageBase64", { enumerable: true, get: function () { return attestations_2.sanitizeMessageBase64; } });
var sha3 = function (v) { return (0, web3_utils_1.soliditySha3)({ type: 'string', value: v }); };
function hashIdentifier(identifier, type, salt) {
return attestations_1.hashIdentifier(sha3, identifier, type, salt);
return (0, attestations_1.hashIdentifier)(sha3, identifier, type, salt);
}
exports.hashIdentifier = hashIdentifier;
function getAttestationMessageToSignFromIdentifier(identifier, account) {
var messageHash = web3_utils_1.soliditySha3({ type: 'bytes32', value: identifier }, { type: 'address', value: account });
var messageHash = (0, web3_utils_1.soliditySha3)({ type: 'bytes32', value: identifier }, { type: 'address', value: account });
return messageHash;

@@ -33,3 +34,3 @@ }

function attestToIdentifier(identifier, account, privateKey) {
var issuer = address_1.privateKeyToAddress(privateKey);
var issuer = (0, address_1.privateKeyToAddress)(privateKey);
var _a = signatureUtils_1.SignatureUtils.signMessage(getAttestationMessageToSignFromIdentifier(identifier, account), privateKey, issuer), v = _a.v, r = _a.r, s = _a.s;

@@ -36,0 +37,0 @@ return { v: v, r: r, s: s };

@@ -16,11 +16,11 @@ "use strict";

it('should check if a message contains a attestation code', function () {
expect(attestations_1.messageContainsAttestationCode(MESSAGE_1)).toBeTruthy();
expect(attestations_1.messageContainsAttestationCode(MESSAGE_2)).toBeTruthy();
expect(attestations_1.messageContainsAttestationCode(MESSAGE_3)).toBeTruthy();
expect(attestations_1.messageContainsAttestationCode(MESSAGE_3_WITH_LINK)).toBeTruthy();
expect((0, attestations_1.messageContainsAttestationCode)(MESSAGE_1)).toBeTruthy();
expect((0, attestations_1.messageContainsAttestationCode)(MESSAGE_2)).toBeTruthy();
expect((0, attestations_1.messageContainsAttestationCode)(MESSAGE_3)).toBeTruthy();
expect((0, attestations_1.messageContainsAttestationCode)(MESSAGE_3_WITH_LINK)).toBeTruthy();
});
it('should fail if a message does not contain a attestation code', function () {
expect(attestations_1.messageContainsAttestationCode('asdfasdaf')).toBeFalsy();
expect(attestations_1.messageContainsAttestationCode('')).toBeFalsy();
expect(attestations_1.messageContainsAttestationCode('Howdy there')).toBeFalsy();
expect((0, attestations_1.messageContainsAttestationCode)('asdfasdaf')).toBeFalsy();
expect((0, attestations_1.messageContainsAttestationCode)('')).toBeFalsy();
expect((0, attestations_1.messageContainsAttestationCode)('Howdy there')).toBeFalsy();
});

@@ -30,7 +30,7 @@ });

it('should extract the code from a message', function () {
expect(attestations_1.extractAttestationCodeFromMessage(MESSAGE_1)).toBe(MESSAGE_1_DECODED);
expect(attestations_1.extractAttestationCodeFromMessage(MESSAGE_2)).toBe(MESSAGE_2_DECODED);
expect(attestations_1.extractAttestationCodeFromMessage(MESSAGE_3)).toBe(MESSAGE_3_DECODED);
expect(attestations_1.extractAttestationCodeFromMessage(MESSAGE_3_WITH_LINK)).toBe(MESSAGE_3_DECODED);
expect(attestations_1.extractAttestationCodeFromMessage(MESSAGE_4_UNSANITIZED)).toBe(MESSAGE_4_DECODED);
expect((0, attestations_1.extractAttestationCodeFromMessage)(MESSAGE_1)).toBe(MESSAGE_1_DECODED);
expect((0, attestations_1.extractAttestationCodeFromMessage)(MESSAGE_2)).toBe(MESSAGE_2_DECODED);
expect((0, attestations_1.extractAttestationCodeFromMessage)(MESSAGE_3)).toBe(MESSAGE_3_DECODED);
expect((0, attestations_1.extractAttestationCodeFromMessage)(MESSAGE_3_WITH_LINK)).toBe(MESSAGE_3_DECODED);
expect((0, attestations_1.extractAttestationCodeFromMessage)(MESSAGE_4_UNSANITIZED)).toBe(MESSAGE_4_DECODED);
});

@@ -40,6 +40,6 @@ });

it('should extract 8 digit code', function () {
expect(attestations_1.extractSecurityCodeWithPrefix('<#> Celo security code: 51365977 5yaJvJcZt2P')).toEqual('51365977');
expect((0, attestations_1.extractSecurityCodeWithPrefix)('<#> Celo security code: 51365977 5yaJvJcZt2P')).toEqual('51365977');
});
it('should NOT extract not 8 digit code', function () {
expect(attestations_1.extractSecurityCodeWithPrefix('<#> Celo security code: 5136597 5yaJvJcZt2P')).toEqual(null);
expect((0, attestations_1.extractSecurityCodeWithPrefix)('<#> Celo security code: 5136597 5yaJvJcZt2P')).toEqual(null);
});

@@ -55,5 +55,5 @@ });

it('sanitizes correctly', function () {
expect(attestations_1.sanitizeMessageBase64(CODE_1)).toBe(SANITIZED_CODE_1);
expect(attestations_1.sanitizeMessageBase64(CODE_2)).toBe(SANITIZED_CODE_2);
expect(attestations_1.sanitizeMessageBase64(NORMAL_CODE)).toBe(NORMAL_CODE);
expect((0, attestations_1.sanitizeMessageBase64)(CODE_1)).toBe(SANITIZED_CODE_1);
expect((0, attestations_1.sanitizeMessageBase64)(CODE_2)).toBe(SANITIZED_CODE_2);
expect((0, attestations_1.sanitizeMessageBase64)(NORMAL_CODE)).toBe(NORMAL_CODE);
});

@@ -60,0 +60,0 @@ });

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getBlsPoP = exports.getBlsPublicKey = exports.blsPrivateKeyToProcessedPrivateKey = exports.BLS_POP_SIZE = exports.BLS_PUBLIC_KEY_SIZE = void 0;
// this is an implementation of a subset of BLS12-377

@@ -20,3 +33,3 @@ var keccak256 = require('keccak256');

exports.BLS_POP_SIZE = 48;
exports.blsPrivateKeyToProcessedPrivateKey = function (privateKeyHex) {
var blsPrivateKeyToProcessedPrivateKey = function (privateKeyHex) {
for (var i = 0; i < 256; i++) {

@@ -43,12 +56,14 @@ var originalPrivateKeyBytes = Buffer.from(privateKeyHex, 'hex');

};
exports.blsPrivateKeyToProcessedPrivateKey = blsPrivateKeyToProcessedPrivateKey;
var getBlsPrivateKey = function (privateKeyHex) {
var blsPrivateKeyBytes = exports.blsPrivateKeyToProcessedPrivateKey(privateKeyHex.slice(2));
var blsPrivateKeyBytes = (0, exports.blsPrivateKeyToProcessedPrivateKey)(privateKeyHex.slice(2));
return blsPrivateKeyBytes;
};
exports.getBlsPublicKey = function (privateKeyHex) {
var getBlsPublicKey = function (privateKeyHex) {
var blsPrivateKeyBytes = getBlsPrivateKey(privateKeyHex);
return '0x' + bls12377js.BLS.privateToPublicBytes(blsPrivateKeyBytes).toString('hex');
};
exports.getBlsPoP = function (address, privateKeyHex) {
if (!address_1.isValidAddress(address)) {
exports.getBlsPublicKey = getBlsPublicKey;
var getBlsPoP = function (address, privateKeyHex) {
if (!(0, address_1.isValidAddress)(address)) {
throw new Error('Invalid checksum address for generating BLS proof-of-possession');

@@ -60,2 +75,3 @@ }

};
exports.getBlsPoP = getBlsPoP;
//# sourceMappingURL=bls.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.compareBN = void 0;
function compareBN(a, b) {

@@ -4,0 +5,0 @@ if (a.eq(b)) {

@@ -6,2 +6,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.CELO_AMOUNT_FOR_ESTIMATE = exports.DOLLAR_AMOUNT_FOR_ESTIMATE = void 0;
var bignumber_js_1 = __importDefault(require("bignumber.js"));

@@ -8,0 +9,0 @@ var WEI_PER_UNIT = 1000000000000000000;

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.linkedListChanges = exports.linkedListChange = exports.zip3 = exports.zip = exports.zeroRange = exports.notEmpty = exports.intersection = void 0;
var base = __importStar(require("@celo/base/lib/collections"));

@@ -14,7 +27,7 @@ // Exports moved to @celo/base, forwarding them

var collections_1 = require("@celo/base/lib/collections");
exports.intersection = collections_1.intersection;
exports.notEmpty = collections_1.notEmpty;
exports.zeroRange = collections_1.zeroRange;
exports.zip = collections_1.zip;
exports.zip3 = collections_1.zip3;
Object.defineProperty(exports, "intersection", { enumerable: true, get: function () { return collections_1.intersection; } });
Object.defineProperty(exports, "notEmpty", { enumerable: true, get: function () { return collections_1.notEmpty; } });
Object.defineProperty(exports, "zeroRange", { enumerable: true, get: function () { return collections_1.zeroRange; } });
Object.defineProperty(exports, "zip", { enumerable: true, get: function () { return collections_1.zip; } });
Object.defineProperty(exports, "zip3", { enumerable: true, get: function () { return collections_1.zip3; } });
// BigNumber comparator

@@ -21,0 +34,0 @@ var bigNumberComparator = function (a, b) { return a.lt(b); };

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

};
expect(collections_1.linkedListChange(lst, change)).toMatchObject(expected);
expect((0, collections_1.linkedListChange)(lst, change)).toMatchObject(expected);
});

@@ -33,3 +33,3 @@ it('becoming greatest', function () {

};
expect(collections_1.linkedListChange(lst, change)).toMatchObject(expected);
expect((0, collections_1.linkedListChange)(lst, change)).toMatchObject(expected);
});

@@ -49,3 +49,3 @@ it('becoming smallest', function () {

};
expect(collections_1.linkedListChange(lst, change)).toMatchObject(expected);
expect((0, collections_1.linkedListChange)(lst, change)).toMatchObject(expected);
});

@@ -67,3 +67,3 @@ it('change order', function () {

};
expect(collections_1.linkedListChange(lst, change)).toMatchObject(expected);
expect((0, collections_1.linkedListChange)(lst, change)).toMatchObject(expected);
});

@@ -79,3 +79,3 @@ });

};
expect(collections_1.linkedListChanges(lst, changes)).toMatchObject(expected);
expect((0, collections_1.linkedListChanges)(lst, changes)).toMatchObject(expected);
});

@@ -94,3 +94,3 @@ it('becoming greatest', function () {

};
expect(collections_1.linkedListChanges(lst, changes)).toMatchObject(expected);
expect((0, collections_1.linkedListChanges)(lst, changes)).toMatchObject(expected);
});

@@ -110,3 +110,3 @@ it('becoming smallest', function () {

};
expect(collections_1.linkedListChanges(lst, changes)).toMatchObject(expected);
expect((0, collections_1.linkedListChanges)(lst, changes)).toMatchObject(expected);
});

@@ -128,3 +128,3 @@ it('change order', function () {

};
expect(collections_1.linkedListChanges(lst, changes)).toMatchObject(expected);
expect((0, collections_1.linkedListChanges)(lst, changes)).toMatchObject(expected);
});

@@ -149,3 +149,3 @@ it('change order, become smallest', function () {

};
expect(collections_1.linkedListChanges(lst, changes)).toMatchObject(expected);
expect((0, collections_1.linkedListChanges)(lst, changes)).toMatchObject(expected);
});

@@ -170,3 +170,3 @@ it('change order, become largest', function () {

};
expect(collections_1.linkedListChanges(lst, changes)).toMatchObject(expected);
expect((0, collections_1.linkedListChanges)(lst, changes)).toMatchObject(expected);
});

@@ -191,3 +191,3 @@ it('change order, then replace with another', function () {

};
expect(collections_1.linkedListChanges(lst, changes)).toMatchObject(expected);
expect((0, collections_1.linkedListChanges)(lst, changes)).toMatchObject(expected);
});

@@ -213,3 +213,3 @@ it('change order, then replace with another again', function () {

};
expect(collections_1.linkedListChanges(lst, changes)).toMatchObject(expected);
expect((0, collections_1.linkedListChanges)(lst, changes)).toMatchObject(expected);
});

@@ -216,0 +216,0 @@ });

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CommentEncryptionUtils = exports.decryptComment = exports.encryptComment = exports.decryptData = exports.encryptData = void 0;
var crypto_1 = require("crypto");

@@ -18,6 +19,6 @@ var dataEncryptionKey_1 = require("./dataEncryptionKey");

function encryptData(data, pubKeyRecipient, pubKeySelf) {
var sessionKey = crypto_1.randomBytes(16);
var sessionKeyToSelf = ecies_1.Encrypt(pubKeySelf, sessionKey);
var sessionKeyToOther = ecies_1.Encrypt(pubKeyRecipient, sessionKey);
var ciphertext = ecies_1.AES128EncryptAndHMAC(sessionKey, sessionKey, data);
var sessionKey = (0, crypto_1.randomBytes)(16);
var sessionKeyToSelf = (0, ecies_1.Encrypt)(pubKeySelf, sessionKey);
var sessionKeyToOther = (0, ecies_1.Encrypt)(pubKeyRecipient, sessionKey);
var ciphertext = (0, ecies_1.AES128EncryptAndHMAC)(sessionKey, sessionKey, data);
return Buffer.concat([sessionKeyToOther, sessionKeyToSelf, ciphertext]);

@@ -42,5 +43,5 @@ }

: data.slice(0, ECIES_SESSION_KEY_LEN);
var sessionKey = ecies_1.Decrypt(key, sessionKeyEncrypted);
var sessionKey = (0, ecies_1.Decrypt)(key, sessionKeyEncrypted);
var encryptedMessage = data.slice(ECIES_SESSION_KEY_LEN * 2);
return ecies_1.AES128DecryptAndHMAC(sessionKey, sessionKey, encryptedMessage);
return (0, ecies_1.AES128DecryptAndHMAC)(sessionKey, sessionKey, encryptedMessage);
}

@@ -65,4 +66,4 @@ exports.decryptData = decryptData;

// Uncompress public keys & strip out the leading 0x04
var pubRecip = dataEncryptionKey_1.decompressPublicKey(pubKeyRecipient);
var pubSelf = dataEncryptionKey_1.decompressPublicKey(pubKeySelf);
var pubRecip = (0, dataEncryptionKey_1.decompressPublicKey)(pubKeyRecipient);
var pubSelf = (0, dataEncryptionKey_1.decompressPublicKey)(pubKeySelf);
var data = encryptData(Buffer.from(comment, 'ucs2'), pubRecip, pubSelf).toString('base64');

@@ -69,0 +70,0 @@ return {

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

describe('Comment Encryption', function () {
var self = ec.keyFromPrivate(crypto_1.randomBytes(32));
var self = ec.keyFromPrivate((0, crypto_1.randomBytes)(32));
var selfPublic = Buffer.from(self.getPublic('hex'), 'hex');
var selfPriv = Buffer.from(self.getPrivate('hex'), 'hex');
var recip = ec.keyFromPrivate(crypto_1.randomBytes(32));
var recip = ec.keyFromPrivate((0, crypto_1.randomBytes)(32));
var recipPublic = Buffer.from(recip.getPublic('hex'), 'hex');

@@ -19,3 +19,3 @@ var recipPriv = Buffer.from(recip.getPrivate('hex'), 'hex');

it('should encrypt message without error', function () {
var _a = commentEncryption_1.encryptComment(comment, recipPublic, selfPublic), ciphertext = _a.comment, success = _a.success;
var _a = (0, commentEncryption_1.encryptComment)(comment, recipPublic, selfPublic), ciphertext = _a.comment, success = _a.success;
expect(ciphertext.length).toBeGreaterThan(226 + 32);

@@ -27,4 +27,4 @@ expect(success).toBeTruthy();

it('should return the same plaintext as sender', function () {
var encryptedData = commentEncryption_1.encryptComment(comment, recipPublic, selfPublic).comment;
var _a = commentEncryption_1.decryptComment(encryptedData, selfPriv, true), plaintext = _a.comment, success = _a.success;
var encryptedData = (0, commentEncryption_1.encryptComment)(comment, recipPublic, selfPublic).comment;
var _a = (0, commentEncryption_1.decryptComment)(encryptedData, selfPriv, true), plaintext = _a.comment, success = _a.success;
expect(plaintext).toEqual(comment);

@@ -34,4 +34,4 @@ expect(success).toBeTruthy();

it('should return the same plaintext as recipient', function () {
var encryptedData = commentEncryption_1.encryptComment(comment, recipPublic, selfPublic).comment;
var _a = commentEncryption_1.decryptComment(encryptedData, recipPriv, false), plaintext = _a.comment, success = _a.success;
var encryptedData = (0, commentEncryption_1.encryptComment)(comment, recipPublic, selfPublic).comment;
var _a = (0, commentEncryption_1.decryptComment)(encryptedData, recipPriv, false), plaintext = _a.comment, success = _a.success;
expect(plaintext).toEqual(comment);

@@ -41,4 +41,4 @@ expect(success).toBeTruthy();

it('should return the same plaintext as sender with emojis', function () {
var encryptedData = commentEncryption_1.encryptComment(emojis, recipPublic, selfPublic).comment;
var _a = commentEncryption_1.decryptComment(encryptedData, selfPriv, true), plaintext = _a.comment, success = _a.success;
var encryptedData = (0, commentEncryption_1.encryptComment)(emojis, recipPublic, selfPublic).comment;
var _a = (0, commentEncryption_1.decryptComment)(encryptedData, selfPriv, true), plaintext = _a.comment, success = _a.success;
expect(plaintext).toEqual(emojis);

@@ -48,4 +48,4 @@ expect(success).toBeTruthy();

it('should return the same plaintext as recipient with emojis', function () {
var encryptedData = commentEncryption_1.encryptComment(emojis, recipPublic, selfPublic).comment;
var _a = commentEncryption_1.decryptComment(encryptedData, recipPriv, false), plaintext = _a.comment, success = _a.success;
var encryptedData = (0, commentEncryption_1.encryptComment)(emojis, recipPublic, selfPublic).comment;
var _a = (0, commentEncryption_1.decryptComment)(encryptedData, recipPriv, false), plaintext = _a.comment, success = _a.success;
expect(plaintext).toEqual(emojis);

@@ -57,3 +57,3 @@ expect(success).toBeTruthy();

it('should return comment if comment is not encrypted', function () {
var _a = commentEncryption_1.decryptComment(comment, selfPriv, true), decrypted = _a.comment, success = _a.success;
var _a = (0, commentEncryption_1.decryptComment)(comment, selfPriv, true), decrypted = _a.comment, success = _a.success;
expect(decrypted).toEqual(comment);

@@ -63,3 +63,3 @@ expect(success).toBeFalsy();

it('should return comment if comment is not encrypted with emojis', function () {
var _a = commentEncryption_1.decryptComment(emojis, selfPriv, true), decrypted = _a.comment, success = _a.success;
var _a = (0, commentEncryption_1.decryptComment)(emojis, selfPriv, true), decrypted = _a.comment, success = _a.success;
expect(decrypted).toEqual(emojis);

@@ -80,3 +80,3 @@ expect(success).toBeFalsy();

'XZHcFj+EMJEW2VXtTgKe2IYOPKEb/+oYAA0+qcXmmkKRJsaHqRYVs90HCsNco=';
var _a = commentEncryption_1.decryptComment(data, selfPriv, true), decrypted = _a.comment, success = _a.success;
var _a = (0, commentEncryption_1.decryptComment)(data, selfPriv, true), decrypted = _a.comment, success = _a.success;
expect(decrypted).toEqual(data);

@@ -101,3 +101,3 @@ expect(success).toBeFalsy();

it('should not regress for sender', function () {
var _a = commentEncryption_1.decryptComment(encrypted, senderPriv, true), decrypted = _a.comment, didDecrypt = _a.success;
var _a = (0, commentEncryption_1.decryptComment)(encrypted, senderPriv, true), decrypted = _a.comment, didDecrypt = _a.success;
expect(decrypted).toEqual(newComment);

@@ -107,3 +107,3 @@ expect(didDecrypt).toBeTruthy();

it('should not regress for recipeient', function () {
var _a = commentEncryption_1.decryptComment(encrypted, newRecipPriv, false), decrypted = _a.comment, didDecrypt = _a.success;
var _a = (0, commentEncryption_1.decryptComment)(encrypted, newRecipPriv, false), decrypted = _a.comment, didDecrypt = _a.success;
expect(decrypted).toEqual(newComment);

@@ -110,0 +110,0 @@ expect(didDecrypt).toBeTruthy();

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getContactNameHash = exports.isContact = exports.getContactPhoneNumber = void 0;
var Web3Utils = __importStar(require("web3-utils"));

@@ -14,5 +27,5 @@ // Exports moved to @celo/base, forwarding them

var contacts_1 = require("@celo/base/lib/contacts");
exports.getContactPhoneNumber = contacts_1.getContactPhoneNumber;
exports.isContact = contacts_1.isContact;
exports.getContactNameHash = function (contact) {
Object.defineProperty(exports, "getContactPhoneNumber", { enumerable: true, get: function () { return contacts_1.getContactPhoneNumber; } });
Object.defineProperty(exports, "isContact", { enumerable: true, get: function () { return contacts_1.isContact; } });
var getContactNameHash = function (contact) {
if (!contact) {

@@ -23,2 +36,3 @@ throw new Error('Invalid contact');

};
exports.getContactNameHash = getContactNameHash;
//# sourceMappingURL=contacts.js.map

@@ -17,2 +17,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.Countries = void 0;
var country_data_1 = __importDefault(require("country-data"));

@@ -79,5 +80,6 @@ // more countries @ https://github.com/umpirsky/country-list

var countryCallingCode = country.countryCallingCodes[0].split(' ')[0];
var localizedCountry = __assign(__assign({ names: names,
displayName: displayName, displayNameNoDiacritics: removeDiacritics(displayName), countryPhonePlaceholder: {
national: phoneNumbers_1.getExampleNumber(countryCallingCode),
var localizedCountry = __assign(__assign({ names: names, displayName: displayName, displayNameNoDiacritics: removeDiacritics(displayName), countryPhonePlaceholder: {
national: (0, phoneNumbers_1.getExampleNumber)(countryCallingCode),
// Not needed right now
// international: getExampleNumber(countryCallingCode, true, true),
}, countryCallingCode: countryCallingCode }, country), {

@@ -84,0 +86,0 @@ // Use default emoji when flag emoji is missing

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SHORT_CURRENCIES = exports.resolveCurrency = exports.CURRENCY_ENUM = exports.currencyToShortMap = exports.CURRENCIES = void 0;
// Exports moved to @celo/base, forwarding them
// here for backwards compatibility
var currencies_1 = require("@celo/base/lib/currencies");
exports.CURRENCIES = currencies_1.CURRENCIES;
exports.currencyToShortMap = currencies_1.currencyToShortMap;
exports.CURRENCY_ENUM = currencies_1.CURRENCY_ENUM;
exports.resolveCurrency = currencies_1.resolveCurrency;
exports.SHORT_CURRENCIES = currencies_1.SHORT_CURRENCIES;
Object.defineProperty(exports, "CURRENCIES", { enumerable: true, get: function () { return currencies_1.CURRENCIES; } });
Object.defineProperty(exports, "currencyToShortMap", { enumerable: true, get: function () { return currencies_1.currencyToShortMap; } });
Object.defineProperty(exports, "CURRENCY_ENUM", { enumerable: true, get: function () { return currencies_1.CURRENCY_ENUM; } });
Object.defineProperty(exports, "resolveCurrency", { enumerable: true, get: function () { return currencies_1.resolveCurrency; } });
Object.defineProperty(exports, "SHORT_CURRENCIES", { enumerable: true, get: function () { return currencies_1.SHORT_CURRENCIES; } });
//# sourceMappingURL=currencies.js.map

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

Object.defineProperty(exports, "__esModule", { value: true });
exports.parseDappKitRequestDeeplink = exports.parseDappkitResponseDeeplink = exports.serializeDappKitRequestDeeplink = exports.SignTxRequest = exports.produceResponseDeeplink = exports.SignTxResponseSuccess = exports.AccountAuthResponseSuccess = exports.AccountAuthRequest = exports.DappKitResponseStatus = exports.DappKitRequestTypes = exports.DAPPKIT_BASE_HOST = void 0;
var querystring_1 = require("querystring");

@@ -28,4 +29,5 @@ var url_1 = require("url");

})(DappKitResponseStatus = exports.DappKitResponseStatus || (exports.DappKitResponseStatus = {}));
exports.AccountAuthRequest = function (meta) { return (__assign({ type: DappKitRequestTypes.ACCOUNT_ADDRESS }, meta)); };
exports.AccountAuthResponseSuccess = function (address, phoneNumber, pepper) { return ({
var AccountAuthRequest = function (meta) { return (__assign({ type: DappKitRequestTypes.ACCOUNT_ADDRESS }, meta)); };
exports.AccountAuthRequest = AccountAuthRequest;
var AccountAuthResponseSuccess = function (address, phoneNumber, pepper) { return ({
type: DappKitRequestTypes.ACCOUNT_ADDRESS,

@@ -37,3 +39,4 @@ status: DappKitResponseStatus.SUCCESS,

}); };
exports.SignTxResponseSuccess = function (rawTxs) { return ({
exports.AccountAuthResponseSuccess = AccountAuthResponseSuccess;
var SignTxResponseSuccess = function (rawTxs) { return ({
type: DappKitRequestTypes.SIGN_TX,

@@ -43,2 +46,3 @@ status: DappKitResponseStatus.SUCCESS,

}); };
exports.SignTxResponseSuccess = SignTxResponseSuccess;
function produceResponseDeeplink(request, response) {

@@ -60,6 +64,6 @@ var params = { type: response.type, status: response.status, requestId: request.requestId };

}
return request.callback + '?' + querystring_1.stringify(params);
return request.callback + '?' + (0, querystring_1.stringify)(params);
}
exports.produceResponseDeeplink = produceResponseDeeplink;
exports.SignTxRequest = function (txs, meta) { return (__assign({ type: DappKitRequestTypes.SIGN_TX, txs: txs.map(function (tx) { return ({
var SignTxRequest = function (txs, meta) { return (__assign({ type: DappKitRequestTypes.SIGN_TX, txs: txs.map(function (tx) { return ({
txData: tx.txData,

@@ -73,2 +77,3 @@ estimatedGas: tx.estimatedGas,

}); }) }, meta)); };
exports.SignTxRequest = SignTxRequest;
function assertString(objectName, key, value) {

@@ -104,3 +109,3 @@ if (value === undefined) {

}
return exports.DAPPKIT_BASE_HOST + '?' + querystring_1.stringify(params);
return exports.DAPPKIT_BASE_HOST + '?' + (0, querystring_1.stringify)(params);
}

@@ -111,3 +116,3 @@ exports.serializeDappKitRequestDeeplink = serializeDappKitRequestDeeplink;

function parseDappkitResponseDeeplink(url) {
var rawParams = url_1.parse(url, true);
var rawParams = (0, url_1.parse)(url, true);
if (rawParams.query.type === undefined) {

@@ -168,3 +173,3 @@ throw new Error('Invalid Deeplink: does not contain type:' + url);

function parseDappKitRequestDeeplink(url) {
var rawParams = url_1.parse(url, true);
var rawParams = (0, url_1.parse)(url, true);
if (rawParams.query.type === undefined) {

@@ -186,3 +191,3 @@ throw new Error('Invalid Deeplink: does not contain type:' + url);

case DappKitRequestTypes.ACCOUNT_ADDRESS:
return exports.AccountAuthRequest(requestMeta);
return (0, exports.AccountAuthRequest)(requestMeta);
break;

@@ -189,0 +194,0 @@ case DappKitRequestTypes.SIGN_TX:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DataEncryptionKeyUtils = exports.deriveDek = exports.decompressPublicKey = exports.compressedPubKey = void 0;
var elliptic_1 = require("elliptic");

@@ -15,3 +16,3 @@ var account_1 = require("./account");

var key = ec.keyFromPrivate(privateKey);
return address_1.ensureLeading0x(key.getPublic(true, 'hex'));
return (0, address_1.ensureLeading0x)(key.getPublic(true, 'hex'));
}

@@ -40,3 +41,3 @@ exports.compressedPubKey = compressedPubKey;

}
return account_1.generateKeys(mnemonic, undefined, 1, // The DEK is derived from change index 1, not 0 like the wallet's transaction keys
return (0, account_1.generateKeys)(mnemonic, undefined, 1, // The DEK is derived from change index 1, not 0 like the wallet's transaction keys
0, bip39ToUse);

@@ -43,0 +44,0 @@ }

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

mnemonic = 'language quiz proud sample canoe trend topic upper coil rack choice engage noodle panda mutual grab shallow thrive forget trophy pull pool mask height';
return [4 /*yield*/, dataEncryptionKey_1.deriveDek(mnemonic)];
return [4 /*yield*/, (0, dataEncryptionKey_1.deriveDek)(mnemonic)];
case 1:

@@ -63,6 +63,6 @@ _a = _b.sent(), publicKey = _a.publicKey, privateKey = _a.privateKey;

it('should work with compressed input', function () {
var privateKey = ec.keyFromPrivate(crypto_1.randomBytes(32));
var privateKey = ec.keyFromPrivate((0, crypto_1.randomBytes)(32));
var publicKeyFull = Buffer.from(privateKey.getPublic(false, 'hex'), 'hex');
var publicKeyCompressed = Buffer.from(privateKey.getPublic(true, 'hex'), 'hex');
var decompressed = dataEncryptionKey_1.decompressPublicKey(publicKeyCompressed);
var decompressed = (0, dataEncryptionKey_1.decompressPublicKey)(publicKeyCompressed);
expect(Buffer.concat([Buffer.from('04', 'hex'), decompressed])).toEqual(publicKeyFull);

@@ -72,5 +72,5 @@ expect(decompressed).toHaveLength(64);

it('should work with long form input', function () {
var privateKey = ec.keyFromPrivate(crypto_1.randomBytes(32));
var privateKey = ec.keyFromPrivate((0, crypto_1.randomBytes)(32));
var publicKeyFull = Buffer.from(privateKey.getPublic(false, 'hex'), 'hex');
var decompressed = dataEncryptionKey_1.decompressPublicKey(publicKeyFull);
var decompressed = (0, dataEncryptionKey_1.decompressPublicKey)(publicKeyFull);
expect(Buffer.concat([Buffer.from('04', 'hex'), decompressed])).toEqual(publicKeyFull);

@@ -77,0 +77,0 @@ expect(decompressed).toHaveLength(64);

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getErrorMessage = void 0;
// Exports moved to @celo/base, forwarding them
// here for backwards compatibility
var displayFormatting_1 = require("@celo/base/lib/displayFormatting");
exports.getErrorMessage = displayFormatting_1.getErrorMessage;
Object.defineProperty(exports, "getErrorMessage", { enumerable: true, get: function () { return displayFormatting_1.getErrorMessage; } });
//# sourceMappingURL=displayFormatting.js.map
"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");

@@ -8,4 +9,4 @@ var crypto_1 = require("crypto");

function computeSharedSecret(privateKey, publicKey) {
var ecdh = crypto_1.createECDH('secp256k1');
ecdh.setPrivateKey(Buffer.from(address_1.trimLeading0x(privateKey), 'hex'));
var ecdh = (0, crypto_1.createECDH)('secp256k1');
ecdh.setPrivateKey(Buffer.from((0, address_1.trimLeading0x)(privateKey), 'hex'));
return ecdh.computeSecret(Buffer.from(ensureCompressed(publicKey), 'hex'));

@@ -15,3 +16,3 @@ }

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

@@ -28,3 +29,3 @@ return true;

function ensureUncompressed(publicKey) {
var noLeading0x = address_1.trimLeading0x(publicKey);
var noLeading0x = (0, address_1.trimLeading0x)(publicKey);
var uncompressed = secp256k1

@@ -37,3 +38,3 @@ .keyFromPublic(ensureUncompressedPrefix(noLeading0x), 'hex')

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

@@ -46,3 +47,3 @@ return noLeading0x.slice(2);

function ensureUncompressedPrefix(publicKey) {
var noLeading0x = address_1.trimLeading0x(publicKey);
var noLeading0x = (0, address_1.trimLeading0x)(publicKey);
if (noLeading0x.length === 128) {

@@ -49,0 +50,0 @@ return "04" + noLeading0x;

@@ -9,2 +9,3 @@ /**

Object.defineProperty(exports, "__esModule", { value: true });
exports.ECIES = exports.Decrypt = exports.Encrypt = exports.AES128DecryptAndHMAC = exports.AES128Decrypt = exports.AES128EncryptAndHMAC = exports.AES128Encrypt = exports.IV_LENGTH = void 0;
var crypto_1 = require("crypto");

@@ -47,3 +48,3 @@ var elliptic_1 = require("elliptic");

for (var i = 0; i <= reps; i++) {
var hash = crypto_1.createHash('sha256');
var hash = (0, crypto_1.createHash)('sha256');
hash.update(counter);

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

function AES128Encrypt(encryptionKey, iv, plaintext) {
var cipher = crypto_1.createCipheriv('aes-128-ctr', encryptionKey, iv);
var cipher = (0, crypto_1.createCipheriv)('aes-128-ctr', encryptionKey, iv);
var firstChunk = cipher.update(plaintext);

@@ -79,5 +80,5 @@ var secondChunk = cipher.final();

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

@@ -94,3 +95,3 @@ }

function AES128Decrypt(encryptionKey, iv, ciphertext) {
var cipher = crypto_1.createDecipheriv('aes-128-ctr', encryptionKey, iv);
var cipher = (0, crypto_1.createDecipheriv)('aes-128-ctr', encryptionKey, iv);
var firstChunk = cipher.update(ciphertext);

@@ -113,3 +114,3 @@ var secondChunk = cipher.final();

var dataToMac = Buffer.concat([iv, message]);
var computedMac = crypto_1.createHmac('sha256', macKey).update(dataToMac).digest();
var computedMac = (0, crypto_1.createHmac)('sha256', macKey).update(dataToMac).digest();
if (!mac.equals(computedMac)) {

@@ -128,3 +129,3 @@ throw new Error('MAC mismatch');

function Encrypt(pubKeyTo, plaintext) {
var ephemPrivKey = ec.keyFromPrivate(crypto_1.randomBytes(32));
var ephemPrivKey = ec.keyFromPrivate((0, crypto_1.randomBytes)(32));
var ephemPubKey = ephemPrivKey.getPublic(false, 'hex');

@@ -135,7 +136,7 @@ var ephemPubKeyEncoded = Buffer.from(ephemPubKey, 'hex');

var encryptionKey = hash.slice(0, 16);
var macKey = crypto_1.createHash('sha256').update(hash.slice(16)).digest();
var macKey = (0, crypto_1.createHash)('sha256').update(hash.slice(16)).digest();
var message = AES128EncryptAndHMAC(encryptionKey, macKey, plaintext);
var serializedCiphertext = Buffer.concat([
ephemPubKeyEncoded,
message,
message, // iv + ciphertext + mac (min 48 bytes)
]);

@@ -160,3 +161,3 @@ return serializedCiphertext;

var encryptionKey = hash.slice(0, 16);
var macKey = crypto_1.createHash('sha256').update(hash.slice(16)).digest();
var macKey = (0, crypto_1.createHash)('sha256').update(hash.slice(16)).digest();
return AES128DecryptAndHMAC(encryptionKey, macKey, symmetricEncrypted);

@@ -163,0 +164,0 @@ }

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

it('should encrypt a message without error', function () {
var privKey = crypto_1.randomBytes(32);
var privKey = (0, crypto_1.randomBytes)(32);
var pubKey = eutil.privateToPublic(privKey);

@@ -17,3 +17,3 @@ var message = new Buffer("foo");

it('should throw an error if priv key is given', function () {
var privKey = crypto_1.randomBytes(32);
var privKey = (0, crypto_1.randomBytes)(32);
var message = new Buffer('foo');

@@ -32,3 +32,3 @@ try {

var plaintext = new Buffer('spam');
var privKey = crypto_1.randomBytes(32);
var privKey = (0, crypto_1.randomBytes)(32);
var pubKey = eutil.privateToPublic(privKey);

@@ -41,5 +41,5 @@ var encrypted = ecies_1.ECIES.Encrypt(pubKey, plaintext);

var plaintext = new Buffer('spam');
var privKey = crypto_1.randomBytes(32);
var privKey = (0, crypto_1.randomBytes)(32);
var pubKey = eutil.privateToPublic(privKey);
var fakePrivKey = crypto_1.randomBytes(32);
var fakePrivKey = (0, crypto_1.randomBytes)(32);
try {

@@ -55,4 +55,4 @@ ecies_1.ECIES.Encrypt(pubKey, plaintext);

it('should be able to encrypt and decrypt a longer message (1024 bytes)', function () {
var plaintext = crypto_1.randomBytes(1024);
var privKey = crypto_1.randomBytes(32);
var plaintext = (0, crypto_1.randomBytes)(1024);
var privKey = (0, crypto_1.randomBytes)(32);
var pubKey = eutil.privateToPublic(privKey);

@@ -69,4 +69,4 @@ var encrypted = ecies_1.ECIES.Encrypt(pubKey, plaintext);

var plaintext = new Buffer('spam');
var encKey = crypto_1.randomBytes(16);
var macKey = crypto_1.randomBytes(16);
var encKey = (0, crypto_1.randomBytes)(16);
var macKey = (0, crypto_1.randomBytes)(16);
var encrypted = ecies_1.ECIES.AES128EncryptAndHMAC(encKey, macKey, plaintext);

@@ -79,4 +79,4 @@ expect(encrypted.length).toBeGreaterThanOrEqual(plaintext.length);

var plaintext = new Buffer('spam');
var encKey = crypto_1.randomBytes(16);
var macKey = crypto_1.randomBytes(16);
var encKey = (0, crypto_1.randomBytes)(16);
var macKey = (0, crypto_1.randomBytes)(16);
var encrypted = ecies_1.ECIES.AES128EncryptAndHMAC(encKey, macKey, plaintext);

@@ -88,5 +88,5 @@ var decrypted = ecies_1.ECIES.AES128DecryptAndHMAC(encKey, macKey, encrypted);

var plaintext = new Buffer('spam');
var encKey = crypto_1.randomBytes(16);
var macKey = crypto_1.randomBytes(16);
var fakeKey = crypto_1.randomBytes(16);
var encKey = (0, crypto_1.randomBytes)(16);
var macKey = (0, crypto_1.randomBytes)(16);
var fakeKey = (0, crypto_1.randomBytes)(16);
var encrypted = ecies_1.ECIES.AES128EncryptAndHMAC(encKey, macKey, plaintext);

@@ -98,5 +98,5 @@ console.info(encrypted.toString('hex').length);

it('should be able to encrypt and decrypt a longer message (1024 bytes)', function () {
var plaintext = crypto_1.randomBytes(1024);
var encKey = crypto_1.randomBytes(16);
var macKey = crypto_1.randomBytes(16);
var plaintext = (0, crypto_1.randomBytes)(1024);
var encKey = (0, crypto_1.randomBytes)(16);
var macKey = (0, crypto_1.randomBytes)(16);
var encrypted = ecies_1.ECIES.AES128EncryptAndHMAC(encKey, macKey, plaintext);

@@ -111,5 +111,5 @@ var decrypted = ecies_1.ECIES.AES128DecryptAndHMAC(encKey, macKey, encrypted);

var plaintext = new Buffer('spam');
var encKey = crypto_1.randomBytes(16);
var macKey = crypto_1.randomBytes(16);
var fakeKey = crypto_1.randomBytes(16);
var encKey = (0, crypto_1.randomBytes)(16);
var macKey = (0, crypto_1.randomBytes)(16);
var fakeKey = (0, crypto_1.randomBytes)(16);
var encrypted = ecies_1.ECIES.AES128EncryptAndHMAC(encKey, macKey, plaintext);

@@ -116,0 +116,0 @@ ecies_1.ECIES.AES128DecryptAndHMAC(encKey, fakeKey, encrypted);

@@ -6,25 +6,32 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
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"));
exports.digits = new bignumber_js_1.default('24');
exports.fixed1 = new bignumber_js_1.default('1000000000000000000000000');
exports.toFixed = function (n) {
var toFixed = function (n) {
return exports.fixed1.times(n).integerValue(bignumber_js_1.default.ROUND_FLOOR);
};
exports.toFixed = toFixed;
// Keeps the decimal portion
exports.fromFixed = function (f) {
var fromFixed = function (f) {
return f.div(exports.fixed1);
};
exports.fromFixed = fromFixed;
// Returns an integer
exports.fixedToInt = function (f) {
var fixedToInt = function (f) {
return f.idiv(exports.fixed1);
};
exports.multiply = function (a, b) {
exports.fixedToInt = fixedToInt;
var multiply = function (a, b) {
return a.times(b).idiv(exports.fixed1);
};
exports.divide = function (a, b) {
exports.multiply = multiply;
var divide = function (a, b) {
return a.times(exports.fixed1).idiv(b);
};
exports.reciprocal = function (f) {
return exports.divide(exports.fixed1, f);
exports.divide = divide;
var reciprocal = function (f) {
return (0, exports.divide)(exports.fixed1, f);
};
exports.reciprocal = reciprocal;
//# sourceMappingURL=fixidity.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toFuture = exports.pipeToFuture = exports.Future = void 0;
// Exports moved to @celo/base, forwarding them
// here for backwards compatibility
var future_1 = require("@celo/base/lib/future");
exports.Future = future_1.Future;
exports.pipeToFuture = future_1.pipeToFuture;
exports.toFuture = future_1.toFuture;
Object.defineProperty(exports, "Future", { enumerable: true, get: function () { return future_1.Future; } });
Object.defineProperty(exports, "pipeToFuture", { enumerable: true, get: function () { return future_1.pipeToFuture; } });
Object.defineProperty(exports, "toFuture", { enumerable: true, get: function () { return future_1.toFuture; } });
//# sourceMappingURL=future.js.map
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AddressUtils = exports.StringUtils = exports.SignatureUtils = exports.PhoneNumberUtils = exports.IstanbulUtils = exports.ECIES = exports.DataEncryptionKeyUtils = exports.CommentEncryptionUtils = exports.AttestationUtils = exports.AccountUtils = void 0;
var AddressUtils = __importStar(require("./address"));
exports.AddressUtils = AddressUtils;
var account_1 = require("./account");
exports.AccountUtils = account_1.AccountUtils;
Object.defineProperty(exports, "AccountUtils", { enumerable: true, get: function () { return account_1.AccountUtils; } });
var attestations_1 = require("./attestations");
exports.AttestationUtils = attestations_1.AttestationUtils;
Object.defineProperty(exports, "AttestationUtils", { enumerable: true, get: function () { return attestations_1.AttestationUtils; } });
var commentEncryption_1 = require("./commentEncryption");
exports.CommentEncryptionUtils = commentEncryption_1.CommentEncryptionUtils;
__export(require("./contacts"));
__export(require("./countries"));
__export(require("./currencies"));
__export(require("./dappkit"));
Object.defineProperty(exports, "CommentEncryptionUtils", { enumerable: true, get: function () { return commentEncryption_1.CommentEncryptionUtils; } });
__exportStar(require("./contacts"), exports);
__exportStar(require("./countries"), exports);
__exportStar(require("./currencies"), exports);
__exportStar(require("./dappkit"), exports);
var dataEncryptionKey_1 = require("./dataEncryptionKey");
exports.DataEncryptionKeyUtils = dataEncryptionKey_1.DataEncryptionKeyUtils;
Object.defineProperty(exports, "DataEncryptionKeyUtils", { enumerable: true, get: function () { return dataEncryptionKey_1.DataEncryptionKeyUtils; } });
var ecies_1 = require("./ecies");
exports.ECIES = ecies_1.ECIES;
Object.defineProperty(exports, "ECIES", { enumerable: true, get: function () { return ecies_1.ECIES; } });
var istanbul_1 = require("./istanbul");
exports.IstanbulUtils = istanbul_1.IstanbulUtils;
Object.defineProperty(exports, "IstanbulUtils", { enumerable: true, get: function () { return istanbul_1.IstanbulUtils; } });
var phoneNumbers_1 = require("./phoneNumbers");
exports.PhoneNumberUtils = phoneNumbers_1.PhoneNumberUtils;
Object.defineProperty(exports, "PhoneNumberUtils", { enumerable: true, get: function () { return phoneNumbers_1.PhoneNumberUtils; } });
var signatureUtils_1 = require("./signatureUtils");
exports.SignatureUtils = signatureUtils_1.SignatureUtils;
Object.defineProperty(exports, "SignatureUtils", { enumerable: true, get: function () { return signatureUtils_1.SignatureUtils; } });
var string_1 = require("./string");
exports.StringUtils = string_1.StringUtils;
Object.defineProperty(exports, "StringUtils", { enumerable: true, get: function () { return string_1.StringUtils; } });
//# sourceMappingURL=index.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateInput = exports.validatePhone = exports.ValidatorKind = exports.validateInteger = exports.validateDecimal = void 0;
var inputValidation_1 = require("@celo/base/lib/inputValidation");

@@ -8,5 +9,5 @@ var phoneNumbers_1 = require("./phoneNumbers");

var inputValidation_2 = require("@celo/base/lib/inputValidation");
exports.validateDecimal = inputValidation_2.validateDecimal;
exports.validateInteger = inputValidation_2.validateInteger;
exports.ValidatorKind = inputValidation_2.ValidatorKind;
Object.defineProperty(exports, "validateDecimal", { enumerable: true, get: function () { return inputValidation_2.validateDecimal; } });
Object.defineProperty(exports, "validateInteger", { enumerable: true, get: function () { return inputValidation_2.validateInteger; } });
Object.defineProperty(exports, "ValidatorKind", { enumerable: true, get: function () { return inputValidation_2.ValidatorKind; } });
function validatePhone(input, countryCallingCode) {

@@ -17,3 +18,3 @@ input = input.replace(/[^0-9()\- ]/g, '');

}
var displayNumber = phoneNumbers_1.getDisplayPhoneNumber(input, countryCallingCode);
var displayNumber = (0, phoneNumbers_1.getDisplayPhoneNumber)(input, countryCallingCode);
if (!displayNumber) {

@@ -31,5 +32,5 @@ return input;

case 'decimal':
return inputValidation_1.validateDecimal(input, props.decimalSeparator);
return (0, inputValidation_1.validateDecimal)(input, props.decimalSeparator);
case 'integer':
return inputValidation_1.validateInteger(input);
return (0, inputValidation_1.validateInteger)(input);
case 'phone':

@@ -36,0 +37,0 @@ return validatePhone(input, props.countryCallingCode);

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

return inputs.forEach(function (input) {
var result = inputValidation_1.validateInput(input, __assign({ validator: validator, countryCallingCode: '1' }, props));
var result = (0, inputValidation_1.validateInput)(input, __assign({ validator: validator, countryCallingCode: '1' }, props));
expect(result).toEqual(expected);

@@ -36,5 +36,5 @@ });

'(4023) 9-39-88-9',
'4-0-2-3-9-3-9-8-8-9',
'4-0-2-3-9-3-9-8-8-9', // phone-kebab
], inputValidation_1.ValidatorKind.Phone, '(402) 393-9889');
});
//# sourceMappingURL=inputValidation.test.js.map
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AttestationResponseType = exports.GetAttestationRequestType = exports.AttestationRequestType = exports.AttestationServiceTestRequestType = exports.AttestationServiceStatusResponseType = exports.SaltType = exports.SignatureType = exports.PublicKeyType = exports.AddressType = exports.E164PhoneNumberType = exports.JSONStringType = exports.UrlType = exports.URL_REGEX = exports.isValidUrl = void 0;
var io_1 = require("@celo/base/lib/io");

@@ -19,4 +32,4 @@ var ethereumjs_util_1 = require("ethereumjs-util");

var io_2 = require("@celo/base/lib/io");
exports.isValidUrl = io_2.isValidUrl;
exports.URL_REGEX = io_2.URL_REGEX;
Object.defineProperty(exports, "isValidUrl", { enumerable: true, get: function () { return io_2.isValidUrl; } });
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) {

@@ -42,3 +55,3 @@ return Either_1.either.chain(t.string.validate(input, context), function (stringValue) {

return Either_1.either.chain(t.string.validate(input, context), function (stringValue) {
return phoneNumbers_1.isE164NumberStrict(stringValue)
return (0, phoneNumbers_1.isE164NumberStrict)(stringValue)
? t.success(stringValue)

@@ -50,4 +63,4 @@ : t.failure(stringValue, context, 'is not a valid e164 number');

return Either_1.either.chain(t.string.validate(input, context), function (stringValue) {
return address_1.isValidAddress(stringValue)
? t.success(ethereumjs_util_1.toChecksumAddress(stringValue))
return (0, address_1.isValidAddress)(stringValue)
? t.success((0, ethereumjs_util_1.toChecksumAddress)(stringValue))
: t.failure(stringValue, context, 'is not a valid address');

@@ -58,4 +71,4 @@ });

return Either_1.either.chain(t.string.validate(input, context), function (stringValue) {
return stringValue.startsWith('0x') && ethereumjs_util_1.isValidPublic(Buffer.from(stringValue.slice(2), 'hex'), true)
? t.success(ethereumjs_util_1.toChecksumAddress(stringValue))
return stringValue.startsWith('0x') && (0, ethereumjs_util_1.isValidPublic)(Buffer.from(stringValue.slice(2), 'hex'), true)
? t.success((0, ethereumjs_util_1.toChecksumAddress)(stringValue))
: t.failure(stringValue, context, 'is not a valid public key');

@@ -62,0 +75,0 @@ });

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.IstanbulUtils = exports.bitIsSet = exports.parseBlockExtraData = void 0;
var bignumber_js_1 = __importDefault(require("bignumber.js"));

@@ -34,3 +47,3 @@ var ethereumjs_util_1 = require("ethereumjs-util");

return {
addedValidators: decode[0].map(function (addr) { return ethereumjs_util_1.toChecksumAddress(addr.toString('hex')); }),
addedValidators: decode[0].map(function (addr) { return (0, ethereumjs_util_1.toChecksumAddress)(addr.toString('hex')); }),
addedValidatorsPublicKeys: decode[1].map(function (key) { return '0x' + key.toString('hex'); }),

@@ -37,0 +50,0 @@ removedValidators: bigNumberFromBuffer(decode[2]),

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

it('should decode the Istanbul extra data correctly', function () {
expect(istanbul_1.parseBlockExtraData(testExtraData)).toEqual(expected);
expect((0, istanbul_1.parseBlockExtraData)(testExtraData)).toEqual(expected);
});

@@ -49,10 +49,10 @@ });

for (var i = 0; i < testBitmapAsBinary.length; i++) {
expect(istanbul_1.bitIsSet(testBitmap, i)).toBe(testBitmapAsBinary[i]);
expect((0, istanbul_1.bitIsSet)(testBitmap, i)).toBe(testBitmapAsBinary[i]);
}
});
it('should return false when the index is too large', function () {
expect(istanbul_1.bitIsSet(testBitmap, 1000)).toBe(false);
expect((0, istanbul_1.bitIsSet)(testBitmap, 1000)).toBe(false);
});
it('should throw an error when the index is negative', function () {
expect(function () { return istanbul_1.bitIsSet(testBitmap, -1); }).toThrow();
expect(function () { return (0, istanbul_1.bitIsSet)(testBitmap, -1); }).toThrow();
});

@@ -59,0 +59,0 @@ });

@@ -6,2 +6,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.levenshteinDistance = void 0;
var _min = function (d0, d1, d2, bx, ay) {

@@ -8,0 +9,0 @@ return d0 < d1 || d2 < d1 ? (d0 > d2 ? d2 + 1 : d0 + 1) : bx === ay ? d1 : d1 + 1;

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

it("should report a distance of " + distance + " between '" + a + "' and '" + b + "'", function () {
expect(levenshtein_1.levenshteinDistance(a, b)).toBe(distance);
expect((0, levenshtein_1.levenshteinDistance)(a, b)).toBe(distance);
});

@@ -104,0 +104,0 @@ };

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.prefixLogger = exports.noopLogger = exports.consoleLogger = void 0;
// Exports moved to @celo/base, forwarding them
// here for backwards compatibility
var logger_1 = require("@celo/base/lib/logger");
exports.consoleLogger = logger_1.consoleLogger;
exports.noopLogger = logger_1.noopLogger;
exports.prefixLogger = logger_1.prefixLogger;
Object.defineProperty(exports, "consoleLogger", { enumerable: true, get: function () { return logger_1.consoleLogger; } });
Object.defineProperty(exports, "noopLogger", { enumerable: true, get: function () { return logger_1.noopLogger; } });
Object.defineProperty(exports, "prefixLogger", { enumerable: true, get: function () { return logger_1.prefixLogger; } });
//# sourceMappingURL=logger.js.map

@@ -6,2 +6,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.parseInputAmount = exports.stringToBoolean = exports.parseSolidityStringArray = void 0;
var bignumber_js_1 = __importDefault(require("bignumber.js"));

@@ -11,5 +12,5 @@ // Exports moved to @celo/base, forwarding them

var parsing_1 = require("@celo/base/lib/parsing");
exports.parseSolidityStringArray = parsing_1.parseSolidityStringArray;
exports.stringToBoolean = parsing_1.stringToBoolean;
exports.parseInputAmount = function (inputString, decimalSeparator) {
Object.defineProperty(exports, "parseSolidityStringArray", { enumerable: true, get: function () { return parsing_1.parseSolidityStringArray; } });
Object.defineProperty(exports, "stringToBoolean", { enumerable: true, get: function () { return parsing_1.stringToBoolean; } });
var parseInputAmount = function (inputString, decimalSeparator) {
if (decimalSeparator === void 0) { decimalSeparator = '.'; }

@@ -21,2 +22,3 @@ if (decimalSeparator !== '.') {

};
exports.parseInputAmount = parseInputAmount;
//# sourceMappingURL=parsing.js.map

@@ -9,20 +9,20 @@ "use strict";

test('stringToBoolean()', function () {
expect(parsing_1.stringToBoolean('true')).toBe(true);
expect(parsing_1.stringToBoolean(' true ')).toBe(true);
expect(parsing_1.stringToBoolean('false')).toBe(false);
expect(parsing_1.stringToBoolean(' false ')).toBe(false);
expect(parsing_1.stringToBoolean('FaLse')).toBe(false);
expect(parsing_1.stringToBoolean('TruE')).toBe(true);
expect(function () { return parsing_1.stringToBoolean('fals'); }).toThrow("Unable to parse 'fals' as boolean");
expect((0, parsing_1.stringToBoolean)('true')).toBe(true);
expect((0, parsing_1.stringToBoolean)(' true ')).toBe(true);
expect((0, parsing_1.stringToBoolean)('false')).toBe(false);
expect((0, parsing_1.stringToBoolean)(' false ')).toBe(false);
expect((0, parsing_1.stringToBoolean)('FaLse')).toBe(false);
expect((0, parsing_1.stringToBoolean)('TruE')).toBe(true);
expect(function () { return (0, parsing_1.stringToBoolean)('fals'); }).toThrow("Unable to parse 'fals' as boolean");
});
test('stringToBigNum()', function () {
expect(parsing_1.parseInputAmount('.1')).toStrictEqual(new bignumber_js_1.default('0.1'));
expect(parsing_1.parseInputAmount('.1 ')).toStrictEqual(new bignumber_js_1.default('0.1'));
expect(parsing_1.parseInputAmount('1.')).toStrictEqual(new bignumber_js_1.default('1'));
expect(parsing_1.parseInputAmount('0')).toStrictEqual(new bignumber_js_1.default('0'));
expect(parsing_1.parseInputAmount('')).toStrictEqual(new bignumber_js_1.default('0'));
expect(parsing_1.parseInputAmount('1.23')).toStrictEqual(new bignumber_js_1.default('1.23'));
expect(parsing_1.parseInputAmount('1,23')).toStrictEqual(new bignumber_js_1.default(NaN));
expect(parsing_1.parseInputAmount('1,23', ',')).toStrictEqual(new bignumber_js_1.default('1.23'));
expect((0, parsing_1.parseInputAmount)('.1')).toStrictEqual(new bignumber_js_1.default('0.1'));
expect((0, parsing_1.parseInputAmount)('.1 ')).toStrictEqual(new bignumber_js_1.default('0.1'));
expect((0, parsing_1.parseInputAmount)('1.')).toStrictEqual(new bignumber_js_1.default('1'));
expect((0, parsing_1.parseInputAmount)('0')).toStrictEqual(new bignumber_js_1.default('0'));
expect((0, parsing_1.parseInputAmount)('')).toStrictEqual(new bignumber_js_1.default('0'));
expect((0, parsing_1.parseInputAmount)('1.23')).toStrictEqual(new bignumber_js_1.default('1.23'));
expect((0, parsing_1.parseInputAmount)('1,23')).toStrictEqual(new bignumber_js_1.default(NaN));
expect((0, parsing_1.parseInputAmount)('1,23', ',')).toStrictEqual(new bignumber_js_1.default('1.23'));
});
//# sourceMappingURL=parsing.test.js.map

@@ -6,2 +6,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.PhoneNumberUtils = exports.getExampleNumber = exports.parsePhoneNumber = exports.isE164NumberStrict = exports.getE164Number = exports.getE164DisplayNumber = exports.getDisplayNumberInternational = exports.getDisplayPhoneNumber = exports.getRegionCodeFromCountryCode = exports.getRegionCode = exports.getCountryCode = exports.getCountryEmoji = exports.getPhoneHash = exports.isE164Number = exports.anonymizedPhone = void 0;
var phoneNumbers_1 = require("@celo/base/lib/phoneNumbers");

@@ -14,8 +15,9 @@ var country_data_1 = __importDefault(require("country-data"));

var phoneNumbers_2 = require("@celo/base/lib/phoneNumbers");
exports.anonymizedPhone = phoneNumbers_2.anonymizedPhone;
exports.isE164Number = phoneNumbers_2.isE164Number;
var sha3 = function (v) { return web3_utils_1.soliditySha3({ type: 'string', value: v }); };
exports.getPhoneHash = function (phoneNumber, salt) {
return phoneNumbers_1.getPhoneHash(sha3, phoneNumber, salt);
Object.defineProperty(exports, "anonymizedPhone", { enumerable: true, get: function () { return phoneNumbers_2.anonymizedPhone; } });
Object.defineProperty(exports, "isE164Number", { enumerable: true, get: function () { return phoneNumbers_2.isE164Number; } });
var sha3 = function (v) { return (0, web3_utils_1.soliditySha3)({ type: 'string', value: v }); };
var getPhoneHash = function (phoneNumber, salt) {
return (0, phoneNumbers_1.getPhoneHash)(sha3, phoneNumber, salt);
};
exports.getPhoneHash = getPhoneHash;
var phoneUtil = google_libphonenumber_1.PhoneNumberUtil.getInstance();

@@ -108,3 +110,3 @@ var MIN_PHONE_LENGTH = 4;

var phoneDetails = parsePhoneNumber(phoneNumber, defaultCountryCode);
if (phoneDetails && phoneNumbers_1.isE164Number(phoneDetails.e164Number)) {
if (phoneDetails && (0, phoneNumbers_1.isE164Number)(phoneDetails.e164Number)) {
return phoneDetails.e164Number;

@@ -111,0 +113,0 @@ }

@@ -40,10 +40,10 @@ "use strict";

it('Hashes an valid number without a salt', function () {
expect(phoneNumbers_1.getPhoneHash(TEST_PHONE_NUMBERS.VALID_E164)).toBe('0x483128504c69591aed5751690805ba9aad6c390644421dc189f6dbb6e085aadf');
expect((0, phoneNumbers_1.getPhoneHash)(TEST_PHONE_NUMBERS.VALID_E164)).toBe('0x483128504c69591aed5751690805ba9aad6c390644421dc189f6dbb6e085aadf');
});
it('Hashes an valid number with a salt', function () {
expect(phoneNumbers_1.getPhoneHash(TEST_PHONE_NUMBERS.VALID_E164, 'abcdefg')).toBe('0xf08257f6b126597dbd090fecf4f5106cfb59c98ef997644cef16f9349464810c');
expect((0, phoneNumbers_1.getPhoneHash)(TEST_PHONE_NUMBERS.VALID_E164, 'abcdefg')).toBe('0xf08257f6b126597dbd090fecf4f5106cfb59c98ef997644cef16f9349464810c');
});
it('Throws for an invalid number', function () {
try {
phoneNumbers_1.getPhoneHash(TEST_PHONE_NUMBERS.VALID_US_1);
(0, phoneNumbers_1.getPhoneHash)(TEST_PHONE_NUMBERS.VALID_US_1);
fail('expected an error');

@@ -58,48 +58,48 @@ }

it('Invalid empty', function () {
expect(phoneNumbers_1.getE164Number(TEST_PHONE_NUMBERS.INVALID_EMPTY, COUNTRY_CODES.US)).toBe(null);
expect((0, phoneNumbers_1.getE164Number)(TEST_PHONE_NUMBERS.INVALID_EMPTY, COUNTRY_CODES.US)).toBe(null);
});
it('Format US phone simple, no country code', function () {
expect(phoneNumbers_1.getE164Number(TEST_PHONE_NUMBERS.VALID_US_1, COUNTRY_CODES.US)).toBe('+16282287826');
expect((0, phoneNumbers_1.getE164Number)(TEST_PHONE_NUMBERS.VALID_US_1, COUNTRY_CODES.US)).toBe('+16282287826');
});
it('Format US phone messy, no country code', function () {
expect(phoneNumbers_1.getE164Number(TEST_PHONE_NUMBERS.VALID_US_2, COUNTRY_CODES.US)).toBe('+16282287826');
expect((0, phoneNumbers_1.getE164Number)(TEST_PHONE_NUMBERS.VALID_US_2, COUNTRY_CODES.US)).toBe('+16282287826');
});
it('Format US phone simple, with country code and wrong region', function () {
expect(phoneNumbers_1.getE164Number(TEST_PHONE_NUMBERS.VALID_US_3, COUNTRY_CODES.AR)).toBe('+16282287826');
expect((0, phoneNumbers_1.getE164Number)(TEST_PHONE_NUMBERS.VALID_US_3, COUNTRY_CODES.AR)).toBe('+16282287826');
});
it('Format US phone simple, with country code no plus', function () {
expect(phoneNumbers_1.getE164Number(TEST_PHONE_NUMBERS.VALID_US_4, COUNTRY_CODES.US)).toBe('+16282287826');
expect((0, phoneNumbers_1.getE164Number)(TEST_PHONE_NUMBERS.VALID_US_4, COUNTRY_CODES.US)).toBe('+16282287826');
});
it('Format DE phone simple, no country code', function () {
expect(phoneNumbers_1.getE164Number(TEST_PHONE_NUMBERS.VALID_DE_1, COUNTRY_CODES.DE)).toBe('+4915229355106');
expect((0, phoneNumbers_1.getE164Number)(TEST_PHONE_NUMBERS.VALID_DE_1, COUNTRY_CODES.DE)).toBe('+4915229355106');
});
it('Format DE phone messy, no country code', function () {
expect(phoneNumbers_1.getE164Number(TEST_PHONE_NUMBERS.VALID_DE_2, COUNTRY_CODES.DE)).toBe('+4915229355106');
expect((0, phoneNumbers_1.getE164Number)(TEST_PHONE_NUMBERS.VALID_DE_2, COUNTRY_CODES.DE)).toBe('+4915229355106');
});
it('Format DE phone messy, wrong country code', function () {
expect(phoneNumbers_1.getE164Number(TEST_PHONE_NUMBERS.VALID_DE_2, COUNTRY_CODES.US)).toBe(null);
expect((0, phoneNumbers_1.getE164Number)(TEST_PHONE_NUMBERS.VALID_DE_2, COUNTRY_CODES.US)).toBe(null);
});
it('Format DE phone with country code', function () {
expect(phoneNumbers_1.getE164Number(TEST_PHONE_NUMBERS.VALID_DE_3, COUNTRY_CODES.DE)).toBe('+4915229355106');
expect((0, phoneNumbers_1.getE164Number)(TEST_PHONE_NUMBERS.VALID_DE_3, COUNTRY_CODES.DE)).toBe('+4915229355106');
});
it('Format AR phone simple, no country code', function () {
expect(phoneNumbers_1.getE164Number(TEST_PHONE_NUMBERS.VALID_AR_1, COUNTRY_CODES.AR)).toBe(TEST_PHONE_NUMBERS.FORMATTED_AR);
expect((0, phoneNumbers_1.getE164Number)(TEST_PHONE_NUMBERS.VALID_AR_1, COUNTRY_CODES.AR)).toBe(TEST_PHONE_NUMBERS.FORMATTED_AR);
});
it('Format AR phone messy, no country code', function () {
expect(phoneNumbers_1.getE164Number(TEST_PHONE_NUMBERS.VALID_AR_2, COUNTRY_CODES.AR)).toBe(TEST_PHONE_NUMBERS.FORMATTED_AR);
expect((0, phoneNumbers_1.getE164Number)(TEST_PHONE_NUMBERS.VALID_AR_2, COUNTRY_CODES.AR)).toBe(TEST_PHONE_NUMBERS.FORMATTED_AR);
});
it('Format AR phone with country code', function () {
expect(phoneNumbers_1.getE164Number(TEST_PHONE_NUMBERS.VALID_AR_3, COUNTRY_CODES.AR)).toBe(TEST_PHONE_NUMBERS.FORMATTED_AR);
expect((0, phoneNumbers_1.getE164Number)(TEST_PHONE_NUMBERS.VALID_AR_3, COUNTRY_CODES.AR)).toBe(TEST_PHONE_NUMBERS.FORMATTED_AR);
});
it('Format MX phone simple, no country code', function () {
expect(phoneNumbers_1.getE164Number(TEST_PHONE_NUMBERS.VALID_MX_1, COUNTRY_CODES.MX)).toBe(TEST_PHONE_NUMBERS.FORMATTED_MX);
expect((0, phoneNumbers_1.getE164Number)(TEST_PHONE_NUMBERS.VALID_MX_1, COUNTRY_CODES.MX)).toBe(TEST_PHONE_NUMBERS.FORMATTED_MX);
});
it('Format MX phone simple with 1, no country code', function () {
expect(phoneNumbers_1.getE164Number(TEST_PHONE_NUMBERS.VALID_MX_2, COUNTRY_CODES.MX)).toBe(TEST_PHONE_NUMBERS.FORMATTED_MX);
expect((0, phoneNumbers_1.getE164Number)(TEST_PHONE_NUMBERS.VALID_MX_2, COUNTRY_CODES.MX)).toBe(TEST_PHONE_NUMBERS.FORMATTED_MX);
});
it('Format MX phone with country code', function () {
expect(phoneNumbers_1.getE164Number(TEST_PHONE_NUMBERS.VALID_MX_3, COUNTRY_CODES.MX)).toBe(TEST_PHONE_NUMBERS.FORMATTED_MX);
expect((0, phoneNumbers_1.getE164Number)(TEST_PHONE_NUMBERS.VALID_MX_3, COUNTRY_CODES.MX)).toBe(TEST_PHONE_NUMBERS.FORMATTED_MX);
});
it('Format LR phone with country code', function () {
expect(phoneNumbers_1.getE164Number(TEST_PHONE_NUMBERS.VALID_LR, COUNTRY_CODES.LR)).toBe(TEST_PHONE_NUMBERS.FORMATTED_LR);
expect((0, phoneNumbers_1.getE164Number)(TEST_PHONE_NUMBERS.VALID_LR, COUNTRY_CODES.LR)).toBe(TEST_PHONE_NUMBERS.FORMATTED_LR);
});

@@ -109,45 +109,45 @@ });

it('Invalid empty', function () {
expect(phoneNumbers_1.getDisplayPhoneNumber(TEST_PHONE_NUMBERS.INVALID_EMPTY, COUNTRY_CODES.US)).toBe('');
expect((0, phoneNumbers_1.getDisplayPhoneNumber)(TEST_PHONE_NUMBERS.INVALID_EMPTY, COUNTRY_CODES.US)).toBe('');
});
it('Format US phone simple, no country code', function () {
expect(phoneNumbers_1.getDisplayPhoneNumber(TEST_PHONE_NUMBERS.VALID_US_1, COUNTRY_CODES.US)).toBe('(628) 228-7826');
expect((0, phoneNumbers_1.getDisplayPhoneNumber)(TEST_PHONE_NUMBERS.VALID_US_1, COUNTRY_CODES.US)).toBe('(628) 228-7826');
});
it('Format US phone messy, no country code', function () {
expect(phoneNumbers_1.getDisplayPhoneNumber(TEST_PHONE_NUMBERS.VALID_US_2, COUNTRY_CODES.US)).toBe('(628) 228-7826');
expect((0, phoneNumbers_1.getDisplayPhoneNumber)(TEST_PHONE_NUMBERS.VALID_US_2, COUNTRY_CODES.US)).toBe('(628) 228-7826');
});
it('Format US phone simple, with country code and wrong region', function () {
expect(phoneNumbers_1.getDisplayPhoneNumber(TEST_PHONE_NUMBERS.VALID_US_3, COUNTRY_CODES.AR)).toBe('(628) 228-7826');
expect((0, phoneNumbers_1.getDisplayPhoneNumber)(TEST_PHONE_NUMBERS.VALID_US_3, COUNTRY_CODES.AR)).toBe('(628) 228-7826');
});
it('Format US phone simple, with country code but no param', function () {
expect(phoneNumbers_1.getDisplayPhoneNumber(TEST_PHONE_NUMBERS.VALID_US_3, COUNTRY_CODES.US)).toBe('(628) 228-7826');
expect((0, phoneNumbers_1.getDisplayPhoneNumber)(TEST_PHONE_NUMBERS.VALID_US_3, COUNTRY_CODES.US)).toBe('(628) 228-7826');
});
it('Format US phone simple, with country code no plus', function () {
expect(phoneNumbers_1.getDisplayPhoneNumber(TEST_PHONE_NUMBERS.VALID_US_4, COUNTRY_CODES.US)).toBe('(628) 228-7826');
expect((0, phoneNumbers_1.getDisplayPhoneNumber)(TEST_PHONE_NUMBERS.VALID_US_4, COUNTRY_CODES.US)).toBe('(628) 228-7826');
});
it('Format DE phone simple, no country code', function () {
expect(phoneNumbers_1.getDisplayPhoneNumber(TEST_PHONE_NUMBERS.VALID_DE_1, COUNTRY_CODES.DE)).toBe('01522 9355106');
expect((0, phoneNumbers_1.getDisplayPhoneNumber)(TEST_PHONE_NUMBERS.VALID_DE_1, COUNTRY_CODES.DE)).toBe('01522 9355106');
});
it('Format DE phone messy, no country code', function () {
expect(phoneNumbers_1.getDisplayPhoneNumber(TEST_PHONE_NUMBERS.VALID_DE_2, COUNTRY_CODES.DE)).toBe('01522 9355106');
expect((0, phoneNumbers_1.getDisplayPhoneNumber)(TEST_PHONE_NUMBERS.VALID_DE_2, COUNTRY_CODES.DE)).toBe('01522 9355106');
});
it('Format DE phone messy, wrong country code', function () {
expect(phoneNumbers_1.getDisplayPhoneNumber(TEST_PHONE_NUMBERS.VALID_DE_2, COUNTRY_CODES.US)).toBe(TEST_PHONE_NUMBERS.VALID_DE_2);
expect((0, phoneNumbers_1.getDisplayPhoneNumber)(TEST_PHONE_NUMBERS.VALID_DE_2, COUNTRY_CODES.US)).toBe(TEST_PHONE_NUMBERS.VALID_DE_2);
});
it('Format DE phone with country code', function () {
expect(phoneNumbers_1.getDisplayPhoneNumber(TEST_PHONE_NUMBERS.VALID_DE_3, COUNTRY_CODES.DE)).toBe('01522 9355106');
expect((0, phoneNumbers_1.getDisplayPhoneNumber)(TEST_PHONE_NUMBERS.VALID_DE_3, COUNTRY_CODES.DE)).toBe('01522 9355106');
});
it('Format AR phone simple, no country code', function () {
expect(phoneNumbers_1.getDisplayPhoneNumber(TEST_PHONE_NUMBERS.VALID_AR_1, COUNTRY_CODES.AR)).toBe(TEST_PHONE_NUMBERS.DISPLAY_AR);
expect((0, phoneNumbers_1.getDisplayPhoneNumber)(TEST_PHONE_NUMBERS.VALID_AR_1, COUNTRY_CODES.AR)).toBe(TEST_PHONE_NUMBERS.DISPLAY_AR);
});
it('Format AR phone messy, no country code', function () {
expect(phoneNumbers_1.getDisplayPhoneNumber(TEST_PHONE_NUMBERS.VALID_AR_2, COUNTRY_CODES.AR)).toBe(TEST_PHONE_NUMBERS.DISPLAY_AR);
expect((0, phoneNumbers_1.getDisplayPhoneNumber)(TEST_PHONE_NUMBERS.VALID_AR_2, COUNTRY_CODES.AR)).toBe(TEST_PHONE_NUMBERS.DISPLAY_AR);
});
it('Format AR phone with country code', function () {
expect(phoneNumbers_1.getDisplayPhoneNumber(TEST_PHONE_NUMBERS.VALID_AR_3, COUNTRY_CODES.AR)).toBe(TEST_PHONE_NUMBERS.DISPLAY_AR);
expect((0, phoneNumbers_1.getDisplayPhoneNumber)(TEST_PHONE_NUMBERS.VALID_AR_3, COUNTRY_CODES.AR)).toBe(TEST_PHONE_NUMBERS.DISPLAY_AR);
});
it('Format MX phone with country code', function () {
expect(phoneNumbers_1.getDisplayPhoneNumber(TEST_PHONE_NUMBERS.VALID_MX_3, COUNTRY_CODES.MX)).toBe(TEST_PHONE_NUMBERS.DISPLAY_MX);
expect((0, phoneNumbers_1.getDisplayPhoneNumber)(TEST_PHONE_NUMBERS.VALID_MX_3, COUNTRY_CODES.MX)).toBe(TEST_PHONE_NUMBERS.DISPLAY_MX);
});
it('Format LR phone with no country code', function () {
expect(phoneNumbers_1.getDisplayPhoneNumber(TEST_PHONE_NUMBERS.VALID_LR, COUNTRY_CODES.LR)).toBe(TEST_PHONE_NUMBERS.DISPLAY_LR);
expect((0, phoneNumbers_1.getDisplayPhoneNumber)(TEST_PHONE_NUMBERS.VALID_LR, COUNTRY_CODES.LR)).toBe(TEST_PHONE_NUMBERS.DISPLAY_LR);
});

@@ -157,9 +157,9 @@ });

it('Invalid empty', function () {
expect(phoneNumbers_1.parsePhoneNumber(TEST_PHONE_NUMBERS.INVALID_EMPTY, COUNTRY_CODES.US)).toBe(null);
expect((0, phoneNumbers_1.parsePhoneNumber)(TEST_PHONE_NUMBERS.INVALID_EMPTY, COUNTRY_CODES.US)).toBe(null);
});
it('Too short', function () {
expect(phoneNumbers_1.parsePhoneNumber(TEST_PHONE_NUMBERS.TOO_SHORT, COUNTRY_CODES.US)).toBe(null);
expect((0, phoneNumbers_1.parsePhoneNumber)(TEST_PHONE_NUMBERS.TOO_SHORT, COUNTRY_CODES.US)).toBe(null);
});
it('Format US messy phone #', function () {
expect(phoneNumbers_1.parsePhoneNumber(TEST_PHONE_NUMBERS.VALID_US_2, COUNTRY_CODES.US)).toMatchObject({
expect((0, phoneNumbers_1.parsePhoneNumber)(TEST_PHONE_NUMBERS.VALID_US_2, COUNTRY_CODES.US)).toMatchObject({
e164Number: '+16282287826',

@@ -172,3 +172,3 @@ displayNumber: '(628) 228-7826',

it('Format DE messy phone #', function () {
expect(phoneNumbers_1.parsePhoneNumber(TEST_PHONE_NUMBERS.VALID_DE_2, COUNTRY_CODES.DE)).toMatchObject({
expect((0, phoneNumbers_1.parsePhoneNumber)(TEST_PHONE_NUMBERS.VALID_DE_2, COUNTRY_CODES.DE)).toMatchObject({
e164Number: '+4915229355106',

@@ -181,3 +181,3 @@ displayNumber: '01522 9355106',

it('Format AR messy phone # 1', function () {
expect(phoneNumbers_1.parsePhoneNumber(TEST_PHONE_NUMBERS.VALID_AR_4, COUNTRY_CODES.AR)).toMatchObject({
expect((0, phoneNumbers_1.parsePhoneNumber)(TEST_PHONE_NUMBERS.VALID_AR_4, COUNTRY_CODES.AR)).toMatchObject({
e164Number: TEST_PHONE_NUMBERS.FORMATTED_AR,

@@ -190,3 +190,3 @@ displayNumber: TEST_PHONE_NUMBERS.DISPLAY_AR,

it('Format MX phone # 1', function () {
expect(phoneNumbers_1.parsePhoneNumber(TEST_PHONE_NUMBERS.VALID_MX_1, COUNTRY_CODES.MX)).toMatchObject({
expect((0, phoneNumbers_1.parsePhoneNumber)(TEST_PHONE_NUMBERS.VALID_MX_1, COUNTRY_CODES.MX)).toMatchObject({
e164Number: TEST_PHONE_NUMBERS.FORMATTED_MX,

@@ -201,24 +201,24 @@ displayNumber: TEST_PHONE_NUMBERS.DISPLAY_MX,

it('gets country code', function () {
expect(phoneNumbers_1.getCountryCode(TEST_PHONE_NUMBERS.VALID_US_3)).toBe(1);
expect(phoneNumbers_1.getCountryCode(TEST_PHONE_NUMBERS.VALID_DE_3)).toBe(49);
expect(phoneNumbers_1.getCountryCode(TEST_PHONE_NUMBERS.VALID_AR_3)).toBe(54);
expect((0, phoneNumbers_1.getCountryCode)(TEST_PHONE_NUMBERS.VALID_US_3)).toBe(1);
expect((0, phoneNumbers_1.getCountryCode)(TEST_PHONE_NUMBERS.VALID_DE_3)).toBe(49);
expect((0, phoneNumbers_1.getCountryCode)(TEST_PHONE_NUMBERS.VALID_AR_3)).toBe(54);
});
it('gets region code', function () {
expect(phoneNumbers_1.getRegionCode(TEST_PHONE_NUMBERS.VALID_US_3)).toBe('US');
expect(phoneNumbers_1.getRegionCode(TEST_PHONE_NUMBERS.VALID_DE_3)).toBe('DE');
expect(phoneNumbers_1.getRegionCode(TEST_PHONE_NUMBERS.VALID_AR_3)).toBe('AR');
expect((0, phoneNumbers_1.getRegionCode)(TEST_PHONE_NUMBERS.VALID_US_3)).toBe('US');
expect((0, phoneNumbers_1.getRegionCode)(TEST_PHONE_NUMBERS.VALID_DE_3)).toBe('DE');
expect((0, phoneNumbers_1.getRegionCode)(TEST_PHONE_NUMBERS.VALID_AR_3)).toBe('AR');
});
it('gets region code from country code', function () {
expect(phoneNumbers_1.getRegionCodeFromCountryCode(COUNTRY_CODES.US)).toBe('US');
expect(phoneNumbers_1.getRegionCodeFromCountryCode(COUNTRY_CODES.DE)).toBe('DE');
expect(phoneNumbers_1.getRegionCodeFromCountryCode(COUNTRY_CODES.AR)).toBe('AR');
expect((0, phoneNumbers_1.getRegionCodeFromCountryCode)(COUNTRY_CODES.US)).toBe('US');
expect((0, phoneNumbers_1.getRegionCodeFromCountryCode)(COUNTRY_CODES.DE)).toBe('DE');
expect((0, phoneNumbers_1.getRegionCodeFromCountryCode)(COUNTRY_CODES.AR)).toBe('AR');
});
it('checks if number is e164', function () {
// @ts-ignore
expect(phoneNumbers_1.isE164Number(null)).toBe(false);
expect(phoneNumbers_1.isE164Number('')).toBe(false);
expect(phoneNumbers_1.isE164Number(TEST_PHONE_NUMBERS.VALID_US_1)).toBe(false);
expect(phoneNumbers_1.isE164Number(TEST_PHONE_NUMBERS.VALID_US_2)).toBe(false);
expect(phoneNumbers_1.isE164Number(TEST_PHONE_NUMBERS.VALID_US_3)).toBe(true);
expect(phoneNumbers_1.isE164Number(TEST_PHONE_NUMBERS.VALID_US_4)).toBe(false);
expect((0, phoneNumbers_1.isE164Number)(null)).toBe(false);
expect((0, phoneNumbers_1.isE164Number)('')).toBe(false);
expect((0, phoneNumbers_1.isE164Number)(TEST_PHONE_NUMBERS.VALID_US_1)).toBe(false);
expect((0, phoneNumbers_1.isE164Number)(TEST_PHONE_NUMBERS.VALID_US_2)).toBe(false);
expect((0, phoneNumbers_1.isE164Number)(TEST_PHONE_NUMBERS.VALID_US_3)).toBe(true);
expect((0, phoneNumbers_1.isE164Number)(TEST_PHONE_NUMBERS.VALID_US_4)).toBe(false);
});

@@ -228,15 +228,15 @@ });

it('gets example by country showing zeros', function () {
expect(phoneNumbers_1.getExampleNumber(COUNTRY_CODES.AR)).toBe('000 0000-0000');
expect(phoneNumbers_1.getExampleNumber(COUNTRY_CODES.DE)).toBe('000 000000');
expect(phoneNumbers_1.getExampleNumber(COUNTRY_CODES.US)).toBe('(000) 000-0000');
expect((0, phoneNumbers_1.getExampleNumber)(COUNTRY_CODES.AR)).toBe('000 0000-0000');
expect((0, phoneNumbers_1.getExampleNumber)(COUNTRY_CODES.DE)).toBe('000 000000');
expect((0, phoneNumbers_1.getExampleNumber)(COUNTRY_CODES.US)).toBe('(000) 000-0000');
});
it('gets example by country', function () {
expect(phoneNumbers_1.getExampleNumber(COUNTRY_CODES.AR, false)).toBe('011 2345-6789');
expect(phoneNumbers_1.getExampleNumber(COUNTRY_CODES.DE, false)).toBe('030 123456');
expect(phoneNumbers_1.getExampleNumber(COUNTRY_CODES.US, false)).toBe('(201) 555-0123');
expect((0, phoneNumbers_1.getExampleNumber)(COUNTRY_CODES.AR, false)).toBe('011 2345-6789');
expect((0, phoneNumbers_1.getExampleNumber)(COUNTRY_CODES.DE, false)).toBe('030 123456');
expect((0, phoneNumbers_1.getExampleNumber)(COUNTRY_CODES.US, false)).toBe('(201) 555-0123');
});
it('gets example by country showing zeros in international way', function () {
expect(phoneNumbers_1.getExampleNumber(COUNTRY_CODES.AR, true, true)).toBe('+54 00 0000-0000');
expect(phoneNumbers_1.getExampleNumber(COUNTRY_CODES.DE, true, true)).toBe('+49 00 000000');
expect(phoneNumbers_1.getExampleNumber(COUNTRY_CODES.US, true, true)).toBe('+1 000-000-0000');
expect((0, phoneNumbers_1.getExampleNumber)(COUNTRY_CODES.AR, true, true)).toBe('+54 00 0000-0000');
expect((0, phoneNumbers_1.getExampleNumber)(COUNTRY_CODES.DE, true, true)).toBe('+49 00 000000');
expect((0, phoneNumbers_1.getExampleNumber)(COUNTRY_CODES.US, true, true)).toBe('+1 000-000-0000');
});

@@ -243,0 +243,0 @@ });

/// <reference types="node" />
import { BigNumber } from 'bignumber.js';
export interface EIP712Parameter {

@@ -9,3 +10,7 @@ name: string;

}
export declare type EIP712ObjectValue = string | number | EIP712Object;
export interface EIP712TypesWithPrimary {
types: EIP712Types;
primaryType: string;
}
export declare type EIP712ObjectValue = string | number | BigNumber | boolean | Buffer | EIP712Object | EIP712ObjectValue[];
export interface EIP712Object {

@@ -15,3 +20,5 @@ [key: string]: EIP712ObjectValue;

export interface EIP712TypedData {
types: EIP712Types;
types: EIP712Types & {
EIP712Domain: EIP712Parameter[];
};
domain: EIP712Object;

@@ -21,3 +28,31 @@ message: EIP712Object;

}
/** Array of all EIP-712 atomic type names. */
export declare const EIP712_ATOMIC_TYPES: string[];
export declare const EIP712_DYNAMIC_TYPES: string[];
export declare const EIP712_BUILTIN_TYPES: string[];
/**
* Utility type representing an optional value in a EIP-712 compatible manner, as long as the
* concrete type T is a subtype of EIP712ObjectValue.
*
* @remarks EIP712Optonal is not part of the EIP712 standard, but is fully compatible with it.
*/
export declare type EIP712Optional<T extends EIP712ObjectValue> = {
defined: boolean;
value: T;
};
/**
* Utility to build EIP712Optional<T> types to insert in EIP-712 type arrays.
* @param typeName EIP-712 string type name. Should be builtin or defined in the EIP712Types
* structure into which this type will be merged.
*/
export declare const eip712OptionalType: (typeName: string) => EIP712Types;
/** Utility to construct an defined EIP712Optional value with inferred type. */
export declare const defined: <T extends EIP712ObjectValue>(value: T) => EIP712Optional<T>;
/** Undefined EIP712Optional type with value type boolean. */
export declare const noBool: EIP712Optional<boolean>;
/** Undefined EIP712Optional type with value type number. */
export declare const noNumber: EIP712Optional<number>;
/** Undefined EIP712Optional type with value type string. */
export declare const noString: EIP712Optional<string>;
/**
* Generates the EIP712 Typed Data hash for signing

@@ -28,2 +63,23 @@ * @param typedData An object that conforms to the EIP712TypedData interface

export declare function generateTypedDataHash(typedData: EIP712TypedData): Buffer;
/**
* Creates a string encoding of the primary type, including all dependencies.
* E.g. "Transaction(Person from,Person to,Asset tx)Asset(address token,uint256 amount)Person(address wallet,string name)"
*/
export declare function encodeType(primaryType: string, types: EIP712Types): string;
export declare function typeHash(primaryType: string, types: EIP712Types): Buffer;
/**
* Constructs the struct encoding of the data as the primary type.
*/
export declare function encodeData(primaryType: string, data: EIP712Object, types: EIP712Types): Buffer;
export declare function structHash(primaryType: string, data: EIP712Object, types: EIP712Types): Buffer;
/**
* Produce the zero value for a given type.
*
* @remarks
* All atomic types will encode as the 32-byte zero value. Dynamic types as an empty hash.
* Dynamic arrays will return an empty array. Fixed length arrays will have members set to zero.
* Structs will have the values of all fields set to zero recursively.
*
* Note that EIP-712 does not specify zero values, and so this is non-standard.
*/
export declare function zeroValue(primaryType: string, types?: EIP712Types): EIP712ObjectValue;
"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 __values = (this && this.__values) || function(o) {

@@ -13,2 +24,27 @@ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;

};
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 __importDefault = (this && this.__importDefault) || function (mod) {

@@ -18,6 +54,61 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

Object.defineProperty(exports, "__esModule", { value: true });
exports.zeroValue = exports.structHash = exports.encodeData = exports.typeHash = exports.encodeType = exports.generateTypedDataHash = exports.noString = exports.noNumber = exports.noBool = exports.defined = 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 bignumber_js_1 = require("bignumber.js");
var ethereumjs_util_1 = require("ethereumjs-util");
var web3_eth_abi_1 = __importDefault(require("web3-eth-abi"));
/** Array of all EIP-712 atomic type names. */
exports.EIP712_ATOMIC_TYPES = [
'bytes1',
'bytes32',
'uint8',
'uint256',
'int8',
'int256',
'bool',
'address',
];
exports.EIP712_DYNAMIC_TYPES = ['bytes', 'string'];
exports.EIP712_BUILTIN_TYPES = exports.EIP712_ATOMIC_TYPES.concat(exports.EIP712_DYNAMIC_TYPES);
// Regular expression used to identify and parse EIP-712 array type strings.
var EIP712_ARRAY_REGEXP = /^(?<memberType>[\w<>\[\]_\-]+)(\[(?<fixedLength>\d+)?\])$/;
// Regular experssion used to identity EIP-712 integer types (e.g. int256, uint256, uint8).
var EIP712_INT_REGEXP = /^u?int\d*$/;
/**
* Utility to build EIP712Optional<T> types to insert in EIP-712 type arrays.
* @param typeName EIP-712 string type name. Should be builtin or defined in the EIP712Types
* structure into which this type will be merged.
*/
var eip712OptionalType = function (typeName) {
var _a;
return (_a = {},
_a["Optional<" + typeName + ">"] = [
{ name: 'defined', type: 'bool' },
{ name: 'value', type: typeName },
],
_a);
};
exports.eip712OptionalType = eip712OptionalType;
/** Utility to construct an defined EIP712Optional value with inferred type. */
var defined = function (value) { return ({
defined: true,
value: value,
}); };
exports.defined = defined;
/** Undefined EIP712Optional type with value type boolean. */
exports.noBool = {
defined: false,
value: false,
};
/** Undefined EIP712Optional type with value type number. */
exports.noNumber = {
defined: false,
value: 0,
};
/** Undefined EIP712Optional type with value type string. */
exports.noString = {
defined: false,
value: '',
};
/**
* Generates the EIP712 Typed Data hash for signing

@@ -28,3 +119,3 @@ * @param typedData An object that conforms to the EIP712TypedData interface

function generateTypedDataHash(typedData) {
return ethereumjs_util_1.sha3(Buffer.concat([
return (0, ethereumjs_util_1.keccak)(Buffer.concat([
Buffer.from('1901', 'hex'),

@@ -36,27 +127,32 @@ structHash('EIP712Domain', typedData.domain, typedData.types),

exports.generateTypedDataHash = generateTypedDataHash;
/**
* Given the primary type, and dictionary of types, this function assembles a sorted list
* representing the transitive dependency closure of the primary type. (Inclusive of the primary
* type itself.)
*/
function findDependencies(primaryType, types, found) {
var e_1, _a, e_2, _b;
var e_1, _a;
var _b;
if (found === void 0) { found = []; }
if (found.includes(primaryType) || types[primaryType] === undefined) {
return found;
// If we have aready found the dependencies of this type, or it is a builtin, return early.
if (found.includes(primaryType) || exports.EIP712_BUILTIN_TYPES.includes(primaryType)) {
return [];
}
found.push(primaryType);
// If this is an array type, return the results for its member type.
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;
return findDependencies(memberType, types, found);
}
// If this is not a builtin and is not defined, we cannot correctly construct a type encoding.
if (types[primaryType] === undefined) {
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;
try {
for (var _e = (e_2 = void 0, __values(findDependencies(field.type, types, found))), _f = _e.next(); !_f.done; _f = _e.next()) {
var dep = _f.value;
if (!found.includes(dep)) {
found.push(dep);
}
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
}
finally { if (e_2) throw e_2.error; }
}
dependencies.push.apply(dependencies, __spreadArray([], __read(findDependencies(field.type, types, found.concat(dependencies))), false));
}

@@ -71,6 +167,10 @@ }

}
return found;
return dependencies;
}
/**
* Creates a string encoding of the primary type, including all dependencies.
* E.g. "Transaction(Person from,Person to,Asset tx)Asset(address token,uint256 amount)Person(address wallet,string name)"
*/
function encodeType(primaryType, types) {
var e_3, _a;
var e_2, _a;
var deps = findDependencies(primaryType, types);

@@ -89,3 +189,3 @@ deps = deps.filter(function (d) { return d !== primaryType; });

}
catch (e_3_1) { e_3 = { error: e_3_1 }; }
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {

@@ -95,57 +195,113 @@ try {

}
finally { if (e_3) throw e_3.error; }
finally { if (e_2) throw e_2.error; }
}
return result;
}
function encodeData(primaryType, data, types) {
var e_4, _a;
var encodedTypes = ['bytes32'];
var encodedValues = [typeHash(primaryType, types)];
try {
for (var _b = __values(types[primaryType]), _c = _b.next(); !_c.done; _c = _b.next()) {
var field = _c.value;
var value = data[field.name];
if (field.type === 'string' || field.type === 'bytes') {
var hashValue = ethereumjs_util_1.sha3(value);
encodedTypes.push('bytes32');
encodedValues.push(hashValue);
}
else if (types[field.type] !== undefined) {
encodedTypes.push('bytes32');
var hashValue = ethereumjs_util_1.sha3(
// tslint:disable-next-line:no-unnecessary-type-assertion
encodeData(field.type, value, types));
encodedValues.push(hashValue);
}
else if (field.type.lastIndexOf(']') === field.type.length - 1) {
throw new Error('Arrays currently unimplemented in encodeData');
}
else {
encodedTypes.push(field.type);
var normalizedValue = normalizeValue(field.type, value);
encodedValues.push(normalizedValue);
}
}
exports.encodeType = encodeType;
function typeHash(primaryType, types) {
return (0, ethereumjs_util_1.keccak)(encodeType(primaryType, types));
}
exports.typeHash = typeHash;
/** Encodes a single EIP-712 value to a 32-byte buffer */
function encodeValue(valueType, value, types) {
var _a;
// Encode the atomic types as their corresponding soldity ABI type.
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));
return Buffer.from((0, address_1.trimLeading0x)(hexEncoded), 'hex');
}
catch (e_4_1) { e_4 = { error: e_4_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_4) throw e_4.error; }
// Encode `string` and `bytes` types as their keccak hash.
if (valueType === 'string') {
// Converting to Buffer before passing to `keccak` prevents an issue where the string is
// interpretted as a hex-encoded string when is starts with 0x.
// https://github.com/ethereumjs/ethereumjs-util/blob/7e3be1d97b4e11fbc4924836b8c444e644f643ac/index.js#L155-L183
return (0, ethereumjs_util_1.keccak)(Buffer.from(value, 'utf8'));
}
// @ts-ignore
return web3_eth_abi_1.default.encodeParameters(encodedTypes, encodedValues);
if (valueType === 'bytes') {
// Allow the user to use either utf8 (plain string) or hex encoding for their bytes.
// Note: keccak throws if the value cannot be converted into a Buffer,
return (0, ethereumjs_util_1.keccak)(value);
}
// Encode structs as its hashStruct (e.g. keccak(typeHash || encodeData(struct)) ).
if (types[valueType] !== undefined) {
// tslint:disable-next-line:no-unnecessary-type-assertion.
return structHash(valueType, value, types);
}
// Encode arrays as the hash of the concatenated encoding of the underlying types.
if (EIP712_ARRAY_REGEXP.test(valueType)) {
// 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, ethereumjs_util_1.keccak)(Buffer.concat(value.map(function (member) { return encodeValue(memberType_1, member, types); })));
}
throw new Error("Unrecognized or unsupported type in EIP-712 encoding: " + valueType);
}
function normalizeValue(type, value) {
var normalizedValue = type === 'uint256' && bignumber_js_1.BigNumber.isBigNumber(value) ? value.toString() : value;
var normalizedValue = EIP712_INT_REGEXP.test(type) && bignumber_js_1.BigNumber.isBigNumber(value) ? value.toString() : value;
return normalizedValue;
}
function typeHash(primaryType, types) {
return ethereumjs_util_1.sha3(encodeType(primaryType, types));
/**
* Constructs the struct encoding of the data as the primary type.
*/
function encodeData(primaryType, data, types) {
var fields = types[primaryType];
if (fields === undefined) {
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); }));
}
exports.encodeData = encodeData;
function structHash(primaryType, data, types) {
return ethereumjs_util_1.sha3(encodeData(primaryType, data, types));
return (0, ethereumjs_util_1.keccak)(Buffer.concat([typeHash(primaryType, types), encodeData(primaryType, data, types)]));
}
exports.structHash = structHash;
/**
* Produce the zero value for a given type.
*
* @remarks
* All atomic types will encode as the 32-byte zero value. Dynamic types as an empty hash.
* Dynamic arrays will return an empty array. Fixed length arrays will have members set to zero.
* Structs will have the values of all fields set to zero recursively.
*
* Note that EIP-712 does not specify zero values, and so this is non-standard.
*/
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.
if (['bytes', 'bytes1', 'bytes32'].includes(primaryType)) {
return Buffer.alloc(0);
}
if (['uint8', 'uint256', 'int8', 'int256'].includes(primaryType)) {
return 0;
}
if (primaryType === 'bool') {
return false;
}
if (primaryType === 'address') {
return address_1.NULL_ADDRESS;
}
if (primaryType === 'string') {
return '';
}
// If the type is an array, return an empty array or an array of the given fixed length.
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); });
}
// Must be user-defined type. Return an object with all fields set to their zero value.
var fields = types[primaryType];
if (fields === undefined) {
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)));
}, {});
}
exports.zeroValue = zeroValue;
//# sourceMappingURL=sign-typed-data-utils.js.map

@@ -30,3 +30,22 @@ import { NativeSigner, serializeSignature, Signer } from '@celo/base/lib/signatureUtils';

};
export declare function recoverEIP712TypedDataSigner(typedData: EIP712TypedData, signature: string): string;
/**
* Recover signer from RSV-serialized signature over signed typed data.
* @param typedData EIP712 typed data
* @param signature RSV signature of signed type data by signer
* @returns string signer, or throws error if parsing fails
*/
export declare function recoverEIP712TypedDataSignerRsv(typedData: EIP712TypedData, signature: string): string;
/**
* Recover signer from VRS-serialized signature over signed typed data.
* @param typedData EIP712 typed data
* @param signature VRS signature of signed type data by signer
* @returns string signer, or throws error if parsing fails
*/
export declare function recoverEIP712TypedDataSignerVrs(typedData: EIP712TypedData, signature: string): string;
/**
* @param typedData EIP712 typed data
* @param signature VRS or SRV signature of `typedData` by `signer`
* @param signer address to verify signed the `typedData`
* @returns boolean, true if `signer` is a possible signer of `signature`
*/
export declare function verifyEIP712TypedDataSigner(typedData: EIP712TypedData, signature: string, signer: string): boolean;

@@ -42,4 +61,5 @@ export declare function guessSigner(message: string, signature: string): string;

serializeSignature: typeof serializeSignature;
recoverEIP712TypedDataSigner: typeof recoverEIP712TypedDataSigner;
recoverEIP712TypedDataSignerRsv: typeof recoverEIP712TypedDataSignerRsv;
recoverEIP712TypedDataSignerVrs: typeof recoverEIP712TypedDataSignerVrs;
verifyEIP712TypedDataSigner: typeof verifyEIP712TypedDataSigner;
};
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

@@ -49,10 +68,4 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }

};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
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");

@@ -65,5 +78,5 @@ var Web3Utils = __importStar(require("web3-utils"));

var signatureUtils_2 = require("@celo/base/lib/signatureUtils");
exports.NativeSigner = signatureUtils_2.NativeSigner;
exports.POP_SIZE = signatureUtils_2.POP_SIZE;
exports.serializeSignature = signatureUtils_2.serializeSignature;
Object.defineProperty(exports, "NativeSigner", { enumerable: true, get: function () { return signatureUtils_2.NativeSigner; } });
Object.defineProperty(exports, "POP_SIZE", { enumerable: true, get: function () { return signatureUtils_2.POP_SIZE; } });
Object.defineProperty(exports, "serializeSignature", { enumerable: true, get: function () { return signatureUtils_2.serializeSignature; } });
var ethjsutil = require('ethereumjs-util');

@@ -103,3 +116,3 @@ // If messages is a hex, the length of it should be the number of bytes

computedAddr = ethjsutil.pubToAddress(pubKey).toString('hex');
if (!address_1.eqAddress(computedAddr, signer)) {
if (!(0, address_1.eqAddress)(computedAddr, signer)) {
throw new Error('computed address !== signer');

@@ -118,3 +131,3 @@ }

return __generator(this, function (_a) {
return [2 /*return*/, Promise.resolve(signatureUtils_1.serializeSignature(signMessage(message, privateKey, address_1.privateKeyToAddress(privateKey))))];
return [2 /*return*/, Promise.resolve((0, signatureUtils_1.serializeSignature)(signMessage(message, privateKey, (0, address_1.privateKeyToAddress)(privateKey))))];
});

@@ -131,3 +144,3 @@ }); },

function signMessage(message, privateKey, address) {
return signMessageWithoutPrefix(hashMessageWithPrefix(message), address_1.ensureLeading0x(privateKey), address);
return signMessageWithoutPrefix(hashMessageWithPrefix(message), (0, address_1.ensureLeading0x)(privateKey), address);
}

@@ -176,15 +189,47 @@ exports.signMessage = signMessage;

exports.parseSignatureWithoutPrefix = parseSignatureWithoutPrefix;
function recoverEIP712TypedDataSigner(typedData, signature) {
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 = ethjsutil.ecrecover(ethjsutil.toBuffer(dataBuff), v, ethjsutil.toBuffer(r), ethjsutil.toBuffer(s));
// TODO test error handling on this
return ethjsutil.bufferToHex(ethjsutil.pubToAddress(publicKey));
}
/**
* Recover signer from RSV-serialized signature over signed typed data.
* @param typedData EIP712 typed data
* @param signature RSV signature of signed type data by signer
* @returns string signer, or throws error if parsing fails
*/
function recoverEIP712TypedDataSignerRsv(typedData, signature) {
return recoverEIP712TypedDataSigner(typedData, signature, parseSignatureAsRsv);
}
exports.recoverEIP712TypedDataSignerRsv = recoverEIP712TypedDataSignerRsv;
/**
* Recover signer from VRS-serialized signature over signed typed data.
* @param typedData EIP712 typed data
* @param signature VRS signature of signed type data by signer
* @returns string signer, or throws error if parsing fails
*/
function recoverEIP712TypedDataSignerVrs(typedData, signature) {
return recoverEIP712TypedDataSigner(typedData, signature, parseSignatureAsVrs);
}
exports.recoverEIP712TypedDataSignerVrs = recoverEIP712TypedDataSignerVrs;
/**
* @param typedData EIP712 typed data
* @param signature VRS or SRV signature of `typedData` by `signer`
* @param signer address to verify signed the `typedData`
* @returns boolean, true if `signer` is a possible signer of `signature`
*/
function verifyEIP712TypedDataSigner(typedData, signature, signer) {
var e_1, _a;
var dataBuff = sign_typed_data_utils_1.generateTypedDataHash(typedData);
try {
for (var _b = __values([parseSignatureAsRsv, parseSignatureAsVrs]), _c = _b.next(); !_c.done; _c = _b.next()) {
var parse = _c.value;
for (var _b = __values([recoverEIP712TypedDataSignerVrs, recoverEIP712TypedDataSignerRsv]), _c = _b.next(); !_c.done; _c = _b.next()) {
var recover = _c.value;
try {
var _d = parse(signature.slice(2)), r = _d.r, s = _d.s, v = _d.v;
var publicKey = ethjsutil.ecrecover(ethjsutil.toBuffer(dataBuff), v, ethjsutil.toBuffer(r), ethjsutil.toBuffer(s));
return ethjsutil.bufferToHex(ethjsutil.pubToAddress(publicKey));
if ((0, address_1.eqAddress)(recover(typedData, signature), signer)) {
return true;
}
}
catch (e) {
// try both serialization formats before throwing
// try both serialization formats before failing to verify
}

@@ -200,9 +245,4 @@ }

}
throw new Error('Unable to recover signature');
return false;
}
exports.recoverEIP712TypedDataSigner = recoverEIP712TypedDataSigner;
function verifyEIP712TypedDataSigner(typedData, signature, signer) {
var recoveredSigner = recoverEIP712TypedDataSigner(typedData, signature);
return address_1.eqAddress(signer, recoveredSigner);
}
exports.verifyEIP712TypedDataSigner = verifyEIP712TypedDataSigner;

@@ -238,3 +278,3 @@ function guessSigner(message, signature) {

var retrievedAddress = ethjsutil.bufferToHex(ethjsutil.pubToAddress(publicKey));
return address_1.eqAddress(retrievedAddress, signer);
return (0, address_1.eqAddress)(retrievedAddress, signer);
}

@@ -253,5 +293,6 @@ catch (err) {

serializeSignature: signatureUtils_1.serializeSignature,
recoverEIP712TypedDataSigner: recoverEIP712TypedDataSigner,
recoverEIP712TypedDataSignerRsv: recoverEIP712TypedDataSignerRsv,
recoverEIP712TypedDataSignerVrs: recoverEIP712TypedDataSignerVrs,
verifyEIP712TypedDataSigner: verifyEIP712TypedDataSigner,
};
//# sourceMappingURL=signatureUtils.js.map
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;

@@ -13,20 +25,58 @@ };

var signatureUtils_1 = require("./signatureUtils");
var typed_data_constructors_1 = require("./typed-data-constructors");
describe('signatures', function () {
it('should sign appropriately with a hash of a message', function () {
var pKey = '0x62633f7c9583780a7d3904a2f55d792707c345f21de1bacb2d389934d82796b2';
var address = address_1.privateKeyToAddress(pKey);
var address = (0, address_1.privateKeyToAddress)(pKey);
var messageHash = Web3Utils.soliditySha3({ type: 'string', value: 'identifier' });
var signature = signatureUtils_1.signMessageWithoutPrefix(messageHash, pKey, address);
var serializedSig = signatureUtils_1.serializeSignature(signature);
signatureUtils_1.parseSignatureWithoutPrefix(messageHash, serializedSig, address);
var signature = (0, signatureUtils_1.signMessageWithoutPrefix)(messageHash, pKey, address);
var serializedSig = (0, signatureUtils_1.serializeSignature)(signature);
(0, signatureUtils_1.parseSignatureWithoutPrefix)(messageHash, serializedSig, address);
});
it('should sign appropriately with just the message', function () {
var pKey = '0x62633f7c9583780a7d3904a2f55d792707c345f21de1bacb2d389934d82796b2';
var address = address_1.privateKeyToAddress(pKey);
var address = (0, address_1.privateKeyToAddress)(pKey);
var message = 'mymessage';
var signature = signatureUtils_1.signMessage(message, pKey, address);
var serializedSig = signatureUtils_1.serializeSignature(signature);
signatureUtils_1.parseSignature(message, serializedSig, address);
var signature = (0, signatureUtils_1.signMessage)(message, pKey, address);
var serializedSig = (0, signatureUtils_1.serializeSignature)(signature);
(0, signatureUtils_1.parseSignature)(message, serializedSig, address);
});
describe('EIP712 signatures', function () {
var pKey = '0xac8ca7aeb0f57f1ed1ce98a695dabcb0278faf03d68e1bae08c9095355a28b06';
var signer = (0, address_1.privateKeyToAddress)(pKey);
var typedData = (0, typed_data_constructors_1.attestationSecurityCode)('1000023');
// generated via LocalWallet's signTypedData
var rsvSignature = '0x106c6f892c5667c298dddc023161b58657c47fb03348fa0ec9b3b515841df47b39985d448104683fcef8d81f2cdcf8bce83c97f8dfb130438f7d26c6e3b2a10001';
// generated via contractKit's signTypedData
var vrsSignature = '0x1c106c6f892c5667c298dddc023161b58657c47fb03348fa0ec9b3b515841df47b39985d448104683fcef8d81f2cdcf8bce83c97f8dfb130438f7d26c6e3b2a100';
var signature = {
v: 28,
r: '0x106c6f892c5667c298dddc023161b58657c47fb03348fa0ec9b3b515841df47b',
s: '0x39985d448104683fcef8d81f2cdcf8bce83c97f8dfb130438f7d26c6e3b2a100',
};
// Modified 'v' from 1c -> 1b (28 -> 27)
var invalidVrsSignature = '0x1b106c6f892c5667c298dddc023161b58657c47fb03348fa0ec9b3b515841df47b39985d448104683fcef8d81f2cdcf8bce83c97f8dfb130438f7d26c6e3b2a100';
it('should recover signer from RSV-serialized sig of EIP712 typed data ', function () {
var recoveredSigner = signatureUtils_1.SignatureUtils.recoverEIP712TypedDataSignerRsv(typedData, rsvSignature);
expect(signer.toLowerCase()).toEqual(recoveredSigner.toLowerCase());
});
it('should recover signer from VSR-serialized sig of EIP712 typed data', function () {
var recoveredSigner = signatureUtils_1.SignatureUtils.recoverEIP712TypedDataSignerVrs(typedData, vrsSignature);
expect(signer.toLowerCase()).toEqual(recoveredSigner.toLowerCase());
});
it('should verify signer from RSV-serialized sig of EIP712 typed data', function () {
expect(signatureUtils_1.SignatureUtils.verifyEIP712TypedDataSigner(typedData, rsvSignature, signer)).toBeTruthy();
});
it('should verify signer from VSR-serialized sig of EIP712 typed data', function () {
expect(signatureUtils_1.SignatureUtils.verifyEIP712TypedDataSigner(typedData, vrsSignature, signer)).toBeTruthy();
});
it('should verify signer from serializeSignature output', function () {
var serializedSig = signatureUtils_1.SignatureUtils.serializeSignature(signature);
expect(signatureUtils_1.SignatureUtils.verifyEIP712TypedDataSigner(typedData, serializedSig, signer)).toBeTruthy();
});
it('should not verify signer from invalid sig of EIP712 typed data', function () {
expect(signatureUtils_1.SignatureUtils.verifyEIP712TypedDataSigner(typedData, invalidVrsSignature, signer)).toBeFalsy();
});
});
});
//# sourceMappingURL=signatureUtils.test.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.soliditySha3Raw = exports.soliditySha3 = exports.sha3 = void 0;
var web3_utils_1 = require("web3-utils");
exports.sha3 = web3_utils_1.sha3;
exports.soliditySha3 = web3_utils_1.soliditySha3;
exports.soliditySha3Raw = web3_utils_1.soliditySha3Raw;
Object.defineProperty(exports, "sha3", { enumerable: true, get: function () { return web3_utils_1.sha3; } });
Object.defineProperty(exports, "soliditySha3", { enumerable: true, get: function () { return web3_utils_1.soliditySha3; } });
Object.defineProperty(exports, "soliditySha3Raw", { enumerable: true, get: function () { return web3_utils_1.soliditySha3Raw; } });
//# sourceMappingURL=solidity.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");

@@ -7,4 +8,4 @@ // Exports moved to @celo/base, forwarding them

var string_2 = require("@celo/base/lib/string");
exports.appendPath = string_2.appendPath;
exports.normalizeAccents = string_2.normalizeAccents;
Object.defineProperty(exports, "appendPath", { enumerable: true, get: function () { return string_2.appendPath; } });
Object.defineProperty(exports, "normalizeAccents", { enumerable: true, get: function () { return string_2.normalizeAccents; } });
exports.StringUtils = {

@@ -11,0 +12,0 @@ appendPath: string_1.appendPath,

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.tryObtainValueWithRetries = exports.repeatTask = exports.conditionWatcher = void 0;
// Exports moved to @celo/base, forwarding them
// here for backwards compatibility
var task_1 = require("@celo/base/lib/task");
exports.conditionWatcher = task_1.conditionWatcher;
exports.repeatTask = task_1.repeatTask;
exports.tryObtainValueWithRetries = task_1.tryObtainValueWithRetries;
Object.defineProperty(exports, "conditionWatcher", { enumerable: true, get: function () { return task_1.conditionWatcher; } });
Object.defineProperty(exports, "repeatTask", { enumerable: true, get: function () { return task_1.repeatTask; } });
Object.defineProperty(exports, "tryObtainValueWithRetries", { enumerable: true, get: function () { return task_1.tryObtainValueWithRetries; } });
//# sourceMappingURL=task.js.map

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

fn = jest.fn().mockResolvedValue(null);
task = task_1.repeatTask({
task = (0, task_1.repeatTask)({
name: 'testTask',
timeInBetweenMS: 10,
}, fn);
return [4 /*yield*/, async_1.sleep(15)];
return [4 /*yield*/, (0, async_1.sleep)(15)];
case 1:

@@ -69,3 +69,3 @@ _a.sent();

task.stop();
return [4 /*yield*/, async_1.sleep(10)];
return [4 /*yield*/, (0, async_1.sleep)(10)];
case 2:

@@ -85,7 +85,7 @@ _a.sent();

fn = jest.fn().mockRejectedValue(new Error('Failed'));
task = task_1.repeatTask({
task = (0, task_1.repeatTask)({
name: 'testTask',
timeInBetweenMS: 10,
}, fn);
return [4 /*yield*/, async_1.sleep(35)];
return [4 /*yield*/, (0, async_1.sleep)(35)];
case 1:

@@ -111,7 +111,7 @@ _a.sent();

}); });
task = task_1.repeatTask({
task = (0, task_1.repeatTask)({
name: 'testTask',
timeInBetweenMS: 10,
}, fn);
return [4 /*yield*/, async_1.sleep(35)];
return [4 /*yield*/, (0, async_1.sleep)(35)];
case 1:

@@ -140,3 +140,3 @@ _a.sent();

logger = jest.fn();
task_1.repeatTask({
(0, task_1.repeatTask)({
name: 'testTask',

@@ -146,3 +146,3 @@ timeInBetweenMS: 10,

}, fn);
return [4 /*yield*/, async_1.sleep(5)];
return [4 /*yield*/, (0, async_1.sleep)(5)];
case 1:

@@ -181,7 +181,7 @@ _d.sent();

}); });
task = task_1.repeatTask({
task = (0, task_1.repeatTask)({
name: 'testTask',
timeInBetweenMS: 10,
}, fn);
return [4 /*yield*/, async_1.sleep(25)];
return [4 /*yield*/, (0, async_1.sleep)(25)];
case 1:

@@ -201,3 +201,3 @@ _a.sent();

fn = jest.fn().mockResolvedValue(null);
task = task_1.repeatTask({
task = (0, task_1.repeatTask)({
name: 'testTask',

@@ -207,7 +207,7 @@ initialDelayMS: 10,

}, fn);
return [4 /*yield*/, async_1.sleep(2)];
return [4 /*yield*/, (0, async_1.sleep)(2)];
case 1:
_a.sent();
expect(fn).toHaveBeenCalledTimes(0);
return [4 /*yield*/, async_1.sleep(10)];
return [4 /*yield*/, (0, async_1.sleep)(10)];
case 2:

@@ -230,3 +230,3 @@ _a.sent();

onSuccess = jest.fn();
task = task_1.conditionWatcher({
task = (0, task_1.conditionWatcher)({
name: 'testCondition',

@@ -237,3 +237,3 @@ onSuccess: onSuccess,

});
return [4 /*yield*/, async_1.sleep(25)];
return [4 /*yield*/, (0, async_1.sleep)(25)];
case 1:

@@ -258,3 +258,3 @@ _a.sent();

onSuccess = jest.fn();
task = task_1.conditionWatcher({
task = (0, task_1.conditionWatcher)({
name: 'testCondition',

@@ -265,3 +265,3 @@ onSuccess: onSuccess,

});
return [4 /*yield*/, async_1.sleep(25)];
return [4 /*yield*/, (0, async_1.sleep)(25)];
case 1:

@@ -283,3 +283,3 @@ _a.sent();

onSuccess = jest.fn().mockRejectedValue(new Error('fail'));
task = task_1.conditionWatcher({
task = (0, task_1.conditionWatcher)({
name: 'testCondition',

@@ -290,3 +290,3 @@ onSuccess: onSuccess,

});
return [4 /*yield*/, async_1.sleep(25)];
return [4 /*yield*/, (0, async_1.sleep)(25)];
case 1:

@@ -307,3 +307,3 @@ _a.sent();

case 0:
task = task_1.tryObtainValueWithRetries({
task = (0, task_1.tryObtainValueWithRetries)({
name: 'testGet',

@@ -326,3 +326,3 @@ maxAttemps: 2,

case 0:
task = task_1.tryObtainValueWithRetries({
task = (0, task_1.tryObtainValueWithRetries)({
name: 'testGet',

@@ -349,3 +349,3 @@ maxAttemps: 2,

case 0:
task = task_1.tryObtainValueWithRetries({
task = (0, task_1.tryObtainValueWithRetries)({
name: 'testGet',

@@ -372,3 +372,3 @@ maxAttemps: 2,

tryGetValue = jest.fn().mockResolvedValue(null);
task = task_1.tryObtainValueWithRetries({
task = (0, task_1.tryObtainValueWithRetries)({
name: 'testGet',

@@ -379,3 +379,3 @@ maxAttemps: 15,

});
return [4 /*yield*/, async_1.sleep(15)];
return [4 /*yield*/, (0, async_1.sleep)(15)];
case 1:

@@ -388,3 +388,3 @@ _a.sent();

currentCalls = tryGetValue.mock.calls.length;
return [4 /*yield*/, async_1.sleep(10)];
return [4 /*yield*/, (0, async_1.sleep)(10)];
case 3:

@@ -391,0 +391,0 @@ _a.sent();

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.authorizeSigner = exports.attestationSecurityCode = void 0;
function attestationSecurityCode(code) {

@@ -23,3 +24,3 @@ return {

exports.attestationSecurityCode = attestationSecurityCode;
exports.authorizeSigner = function (_a) {
var authorizeSigner = function (_a) {
var account = _a.account, signer = _a.signer, chainId = _a.chainId, role = _a.role, accountsContractAddress = _a.accountsContractAddress;

@@ -54,2 +55,3 @@ return ({

};
exports.authorizeSigner = authorizeSigner;
//# sourceMappingURL=typed-data-constructors.js.map
{
"name": "@celo/utils",
"version": "1.3.1",
"version": "1.3.3",
"description": "Celo common utils",

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

"dependencies": {
"@celo/base": "1.3.1",
"@celo/base": "1.3.3",
"@types/country-data": "^0.0.0",

@@ -25,0 +25,0 @@ "@types/elliptic": "^6.4.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

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

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