evm-blockchain-tools
Version:
This is a collection of resuseable tools to support development for EVM-powered blockchains
197 lines • 9.1 kB
JavaScript
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (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 () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.EvmCryptoWallet = void 0;
const ethers_1 = require("ethers");
const crypto = __importStar(require("crypto"));
const libsodium_wrappers_1 = __importDefault(require("libsodium-wrappers"));
const aes_encryption_1 = require("../aes-encryption");
const web3_utils_1 = require("../web3-utils");
const SEP = "\x00";
const VERSION = "v1";
const SHARD_LENGTH = 16;
class EvmCryptoWallet {
constructor(config) {
this.config = config;
this.isInitialized = false;
this.tryDec = (hex, key) => {
if (!hex || !key)
return undefined;
try {
return (0, aes_encryption_1.decrypt)(hex, key);
}
catch (_a) {
return undefined;
}
};
}
validateServerKey(serverKeyHex) {
return __awaiter(this, void 0, void 0, function* () {
const key = (0, web3_utils_1.norm32KeyHex)(serverKeyHex);
const n = libsodium_wrappers_1.default.randombytes_buf(24);
const m = libsodium_wrappers_1.default.randombytes_buf(16);
const ct = libsodium_wrappers_1.default.crypto_secretbox_easy(m, n, key);
const pt = libsodium_wrappers_1.default.crypto_secretbox_open_easy(ct, n, key);
if (!libsodium_wrappers_1.default.memcmp(pt, m))
throw new Error("server key self-test failed");
this.serverPrivateKey = key;
});
}
init() {
return __awaiter(this, void 0, void 0, function* () {
if (this.isInitialized) {
return;
}
this.isInitialized = true;
yield libsodium_wrappers_1.default.ready;
yield this.validateServerKey(this.config.privateKey);
});
}
buildUserPrivate(userPin) {
const { privateKey: secret, defaultUserPin } = this.config;
return [VERSION, "user", secret, userPin !== null && userPin !== void 0 ? userPin : defaultUserPin].join(SEP);
}
buildServerPrivate() {
const { privateKey: secret, adminPin } = this.config;
return [VERSION, "server", secret, adminPin].join(SEP);
}
buildRecoveryPrivate(userPin) {
const { privateKey: secret, adminPin, defaultUserPin } = this.config;
return [
VERSION,
"recovery",
secret,
userPin !== null && userPin !== void 0 ? userPin : defaultUserPin,
adminPin,
].join(SEP);
}
importWallet(privateKey, userPin) {
return __awaiter(this, void 0, void 0, function* () {
yield this.init();
const wallet = new ethers_1.ethers.Wallet(privateKey);
const publicKey = yield wallet.getAddress();
return this.processGeneratedKey(userPin, privateKey, publicKey);
});
}
createWallet(userPin) {
return __awaiter(this, void 0, void 0, function* () {
yield this.init();
const { privateKey, publicKey } = yield this.generateKeyPair();
return this.processGeneratedKey(userPin, privateKey, publicKey);
});
}
processGeneratedKey(userPin, privateKey, publicKey) {
const evmHex = privateKey.replace(/^0x/, "").padStart(64, "0");
const pkBytes = libsodium_wrappers_1.default.from_hex(evmHex);
const nonce = crypto.randomBytes(24);
const [userSecret, serverSecret, recoverySecret] = this.splitPrivateKeyToParts(pkBytes, nonce);
const signedUserSecret = (0, aes_encryption_1.encrypt)(userSecret, this.buildUserPrivate(userPin));
const signedServerSecret = (0, aes_encryption_1.encrypt)(serverSecret, this.buildServerPrivate());
const signedRecoverySecret = (0, aes_encryption_1.encrypt)(recoverySecret, this.buildRecoveryPrivate(userPin));
return {
address: publicKey,
nonce: nonce.toString("hex"),
serverSecretPart: signedServerSecret,
userSecretPart: signedUserSecret,
recoverySecretPart: signedRecoverySecret,
};
}
generateKeyPair() {
return __awaiter(this, void 0, void 0, function* () {
const wallet = ethers_1.ethers.Wallet.createRandom();
const privateKey = wallet.privateKey.toString();
const publicKey = yield wallet.getAddress();
return {
privateKey,
publicKey,
};
});
}
splitPrivateKeyToParts(pkBytes, nonce) {
const ct = libsodium_wrappers_1.default.crypto_secretbox_easy(pkBytes, nonce, this.serverPrivateKey);
const buf = Buffer.from(ct);
const A = buf.subarray(0, SHARD_LENGTH);
const B = buf.subarray(SHARD_LENGTH, 2 * SHARD_LENGTH);
const C = buf.subarray(2 * SHARD_LENGTH);
const user = Buffer.concat([A, B]);
const server = Buffer.concat([B, C]);
const recovery = Buffer.concat([A, C]);
return [
user.toString("hex"),
server.toString("hex"),
recovery.toString("hex"),
];
}
recoverPrivateKey(data) {
return __awaiter(this, void 0, void 0, function* () {
yield this.init();
const userKeyStr = this.buildUserPrivate(data.userPin);
const serverKeyStr = this.buildServerPrivate();
const recovKeyStr = this.buildRecoveryPrivate(data.userPin);
const decUser = this.tryDec(data.userSecret, userKeyStr);
const decServer = this.tryDec(data.serverSecret, serverKeyStr);
const decRecovery = this.tryDec(data.recoverySecret, recovKeyStr);
const okUS = !!(decUser && decServer);
const okUR = !!(decUser && decRecovery);
const okSR = !!(decServer && decRecovery);
if (!okUS && !okUR && !okSR) {
throw new Error("must provide 2 out of 3 keys (share unwrap failed)");
}
const first = Buffer.from((decUser !== null && decUser !== void 0 ? decUser : decRecovery), "hex").subarray(0, SHARD_LENGTH);
const second = decUser
? Buffer.from(decUser, "hex").subarray(SHARD_LENGTH)
: Buffer.from(decServer, "hex").subarray(0, SHARD_LENGTH);
const third = Buffer.from((decServer !== null && decServer !== void 0 ? decServer : decRecovery), "hex").subarray(SHARD_LENGTH);
const reunited = Buffer.concat([first, second, third]);
const pt = libsodium_wrappers_1.default.crypto_secretbox_open_easy(new Uint8Array(reunited), Buffer.from(data.nonce, "hex"), this.serverPrivateKey);
const evmPrivHex = libsodium_wrappers_1.default.to_hex(pt);
return "0x" + evmPrivHex;
});
}
}
exports.EvmCryptoWallet = EvmCryptoWallet;
//# sourceMappingURL=evm-crypto-wallet.js.map