ethers.js/packages/json-wallets/src.ts/keystore.ts

378 lines
14 KiB
TypeScript
Raw Permalink Normal View History

2019-05-14 18:25:46 -04:00
"use strict";
import aes from "aes-js";
2020-11-14 17:42:36 -05:00
import scrypt from "scrypt-js";
2019-05-14 18:25:46 -04:00
import { ExternallyOwnedAccount } from "@ethersproject/abstract-signer";
import { getAddress } from "@ethersproject/address";
import { arrayify, Bytes, BytesLike, concat, hexlify } from "@ethersproject/bytes";
2020-01-18 21:09:02 -05:00
import { defaultPath, entropyToMnemonic, HDNode, Mnemonic, mnemonicToEntropy } from "@ethersproject/hdnode";
2019-05-14 18:25:46 -04:00
import { keccak256 } from "@ethersproject/keccak256";
import { pbkdf2 as _pbkdf2 } from "@ethersproject/pbkdf2";
2019-05-14 18:25:46 -04:00
import { randomBytes } from "@ethersproject/random";
import { Description } from "@ethersproject/properties";
import { computeAddress } from "@ethersproject/transactions";
import { getPassword, looseArrayify, searchPath, uuidV4, zpad } from "./utils";
2019-05-14 18:25:46 -04:00
2020-01-18 21:09:02 -05:00
import { Logger } from "@ethersproject/logger";
import { version } from "./_version";
const logger = new Logger(version);
2019-05-14 18:25:46 -04:00
// Exported Types
2020-01-18 21:09:02 -05:00
function hasMnemonic(value: any): value is { mnemonic: Mnemonic } {
return (value != null && value.mnemonic && value.mnemonic.phrase);
}
2020-04-25 01:06:28 -04:00
export interface _KeystoreAccount {
2020-01-07 19:47:55 -05:00
address: string;
privateKey: string;
2020-01-18 21:09:02 -05:00
mnemonic?: Mnemonic;
2020-01-07 19:47:55 -05:00
_isKeystoreAccount: boolean;
}
export class KeystoreAccount extends Description<_KeystoreAccount> implements ExternallyOwnedAccount {
2019-05-14 18:25:46 -04:00
readonly address: string;
readonly privateKey: string;
2020-01-18 21:09:02 -05:00
readonly mnemonic?: Mnemonic;
2019-05-14 18:25:46 -04:00
readonly _isKeystoreAccount: boolean;
isKeystoreAccount(value: any): value is KeystoreAccount {
return !!(value && value._isKeystoreAccount);
2019-05-14 18:25:46 -04:00
}
}
export type ProgressCallback = (percent: number) => void;
export type EncryptOptions = {
iv?: BytesLike;
entropy?: BytesLike;
client?: string;
salt?: BytesLike;
uuid?: string;
scrypt?: {
N?: number;
r?: number;
p?: number;
}
}
function _decrypt(data: any, key: Uint8Array, ciphertext: Uint8Array): Uint8Array {
const cipher = searchPath(data, "crypto/cipher");
if (cipher === "aes-128-ctr") {
const iv = looseArrayify(searchPath(data, "crypto/cipherparams/iv"))
const counter = new aes.Counter(iv);
2019-05-14 18:25:46 -04:00
const aesCtr = new aes.ModeOfOperation.ctr(key, counter);
2019-05-14 18:25:46 -04:00
return arrayify(aesCtr.decrypt(ciphertext));
}
2019-05-14 18:25:46 -04:00
return null;
}
2019-05-14 18:25:46 -04:00
function _getAccount(data: any, key: Uint8Array): KeystoreAccount {
const ciphertext = looseArrayify(searchPath(data, "crypto/ciphertext"));
2019-05-14 18:25:46 -04:00
const computedMAC = hexlify(keccak256(concat([ key.slice(16, 32), ciphertext ]))).substring(2);
if (computedMAC !== searchPath(data, "crypto/mac").toLowerCase()) {
throw new Error("invalid password");
2019-05-14 18:25:46 -04:00
}
const privateKey = _decrypt(data, key.slice(0, 16), ciphertext);
2019-05-14 18:25:46 -04:00
if (!privateKey) {
logger.throwError("unsupported cipher", Logger.errors.UNSUPPORTED_OPERATION, {
operation: "decrypt"
});
}
2019-05-14 18:25:46 -04:00
const mnemonicKey = key.slice(32, 64);
2019-05-14 18:25:46 -04:00
const address = computeAddress(privateKey);
if (data.address) {
let check = data.address.toLowerCase();
if (check.substring(0, 2) !== "0x") { check = "0x" + check; }
if (getAddress(check) !== address) {
throw new Error("address mismatch");
}
}
2019-05-14 18:25:46 -04:00
const account: _KeystoreAccount = {
_isKeystoreAccount: true,
address: address,
privateKey: hexlify(privateKey)
};
2019-05-14 18:25:46 -04:00
// Version 0.1 x-ethers metadata must contain an encrypted mnemonic phrase
if (searchPath(data, "x-ethers/version") === "0.1") {
const mnemonicCiphertext = looseArrayify(searchPath(data, "x-ethers/mnemonicCiphertext"));
const mnemonicIv = looseArrayify(searchPath(data, "x-ethers/mnemonicCounter"));
2019-05-14 18:25:46 -04:00
const mnemonicCounter = new aes.Counter(mnemonicIv);
const mnemonicAesCtr = new aes.ModeOfOperation.ctr(mnemonicKey, mnemonicCounter);
2019-05-14 18:25:46 -04:00
const path = searchPath(data, "x-ethers/path") || defaultPath;
const locale = searchPath(data, "x-ethers/locale") || "en";
2019-05-14 18:25:46 -04:00
const entropy = arrayify(mnemonicAesCtr.decrypt(mnemonicCiphertext));
2019-05-14 18:25:46 -04:00
try {
const mnemonic = entropyToMnemonic(entropy, locale);
const node = HDNode.fromMnemonic(mnemonic, null, locale).derivePath(path);
2019-05-14 18:25:46 -04:00
if (node.privateKey != account.privateKey) {
throw new Error("mnemonic mismatch");
}
2019-05-14 18:25:46 -04:00
account.mnemonic = node.mnemonic;
2020-01-18 21:09:02 -05:00
} catch (error) {
// If we don't have the locale wordlist installed to
// read this mnemonic, just bail and don't set the
// mnemonic
if (error.code !== Logger.errors.INVALID_ARGUMENT || error.argument !== "wordlist") {
throw error;
2020-01-18 21:09:02 -05:00
}
2019-05-14 18:25:46 -04:00
}
}
return new KeystoreAccount(account);
}
type ScryptFunc<T> = (pw: Uint8Array, salt: Uint8Array, n: number, r: number, p: number, dkLen: number, callback?: ProgressCallback) => T;
type Pbkdf2Func<T> = (pw: Uint8Array, salt: Uint8Array, c: number, dkLen: number, prfFunc: string) => T;
function pbkdf2Sync(passwordBytes: Uint8Array, salt: Uint8Array, count: number, dkLen: number, prfFunc: string): Uint8Array {
return arrayify(_pbkdf2(passwordBytes, salt, count, dkLen, prfFunc));
}
function pbkdf2(passwordBytes: Uint8Array, salt: Uint8Array, count: number, dkLen: number, prfFunc: string): Promise<Uint8Array> {
return Promise.resolve(pbkdf2Sync(passwordBytes, salt, count, dkLen, prfFunc));
}
function _computeKdfKey<T>(data: any, password: Bytes | string, pbkdf2Func: Pbkdf2Func<T>, scryptFunc: ScryptFunc<T>, progressCallback?: ProgressCallback): T {
const passwordBytes = getPassword(password);
2019-05-14 18:25:46 -04:00
2019-11-13 21:47:08 +09:00
const kdf = searchPath(data, "crypto/kdf");
2019-11-13 21:47:08 +09:00
if (kdf && typeof(kdf) === "string") {
2020-01-18 21:09:02 -05:00
const throwError = function(name: string, value: any): never {
return logger.throwArgumentError("invalid key-derivation function parameters", name, value);
}
2019-11-13 21:47:08 +09:00
if (kdf.toLowerCase() === "scrypt") {
const salt = looseArrayify(searchPath(data, "crypto/kdfparams/salt"));
const N = parseInt(searchPath(data, "crypto/kdfparams/n"));
const r = parseInt(searchPath(data, "crypto/kdfparams/r"));
const p = parseInt(searchPath(data, "crypto/kdfparams/p"));
2020-01-18 21:09:02 -05:00
// Check for all required parameters
if (!N || !r || !p) { throwError("kdf", kdf); }
2019-11-13 21:47:08 +09:00
// Make sure N is a power of 2
2020-01-18 21:09:02 -05:00
if ((N & (N - 1)) !== 0) { throwError("N", N); }
2019-11-13 21:47:08 +09:00
const dkLen = parseInt(searchPath(data, "crypto/kdfparams/dklen"));
2020-01-18 21:09:02 -05:00
if (dkLen !== 32) { throwError("dklen", dkLen); }
2019-11-13 21:47:08 +09:00
return scryptFunc(passwordBytes, salt, N, r, p, 64, progressCallback);
2019-11-13 21:47:08 +09:00
} else if (kdf.toLowerCase() === "pbkdf2") {
const salt = looseArrayify(searchPath(data, "crypto/kdfparams/salt"));
2019-05-14 18:25:46 -04:00
2019-11-13 21:47:08 +09:00
let prfFunc: string = null;
const prf = searchPath(data, "crypto/kdfparams/prf");
if (prf === "hmac-sha256") {
prfFunc = "sha256";
} else if (prf === "hmac-sha512") {
prfFunc = "sha512";
2019-05-14 18:25:46 -04:00
} else {
2020-01-18 21:09:02 -05:00
throwError("prf", prf);
2019-11-13 21:47:08 +09:00
}
const count = parseInt(searchPath(data, "crypto/kdfparams/c"));
2019-11-13 21:47:08 +09:00
const dkLen = parseInt(searchPath(data, "crypto/kdfparams/dklen"));
2020-01-18 21:09:02 -05:00
if (dkLen !== 32) { throwError("dklen", dkLen); }
2019-05-14 18:25:46 -04:00
return pbkdf2Func(passwordBytes, salt, count, dkLen, prfFunc);
2019-05-14 18:25:46 -04:00
}
2019-11-13 21:47:08 +09:00
}
2020-01-18 21:09:02 -05:00
return logger.throwArgumentError("unsupported key-derivation function", "kdf", kdf);
2019-05-14 18:25:46 -04:00
}
export function decryptSync(json: string, password: Bytes | string): KeystoreAccount {
const data = JSON.parse(json);
const key = _computeKdfKey(data, password, pbkdf2Sync, scrypt.syncScrypt);
return _getAccount(data, key);
}
export async function decrypt(json: string, password: Bytes | string, progressCallback?: ProgressCallback): Promise<KeystoreAccount> {
const data = JSON.parse(json);
const key = await _computeKdfKey(data, password, pbkdf2, scrypt.scrypt, progressCallback);
return _getAccount(data, key);
}
2019-05-14 18:25:46 -04:00
export function encrypt(account: ExternallyOwnedAccount, password: Bytes | string, options?: EncryptOptions, progressCallback?: ProgressCallback): Promise<string> {
try {
2020-01-18 21:09:02 -05:00
// Check the address matches the private key
2019-05-14 18:25:46 -04:00
if (getAddress(account.address) !== computeAddress(account.privateKey)) {
throw new Error("address/privateKey mismatch");
}
2020-01-18 21:09:02 -05:00
// Check the mnemonic (if any) matches the private key
if (hasMnemonic(account)) {
const mnemonic = account.mnemonic;
const node = HDNode.fromMnemonic(mnemonic.phrase, null, mnemonic.locale).derivePath(mnemonic.path || defaultPath);
2019-05-14 18:25:46 -04:00
if (node.privateKey != account.privateKey) {
throw new Error("mnemonic mismatch");
}
}
} catch (e) {
return Promise.reject(e);
}
2020-01-18 21:09:02 -05:00
// The options are optional, so adjust the call as needed
2019-05-14 18:25:46 -04:00
if (typeof(options) === "function" && !progressCallback) {
progressCallback = options;
options = {};
}
if (!options) { options = {}; }
const privateKey: Uint8Array = arrayify(account.privateKey);
const passwordBytes = getPassword(password);
2019-05-14 18:25:46 -04:00
let entropy: Uint8Array = null
2020-01-18 21:09:02 -05:00
let path: string = null;
let locale: string = null;
if (hasMnemonic(account)) {
const srcMnemonic = account.mnemonic;
entropy = arrayify(mnemonicToEntropy(srcMnemonic.phrase, srcMnemonic.locale || "en"));
path = srcMnemonic.path || defaultPath;
locale = srcMnemonic.locale || "en";
2019-05-14 18:25:46 -04:00
}
let client = options.client;
if (!client) { client = "ethers.js"; }
// Check/generate the salt
let salt: Uint8Array = null;
if (options.salt) {
salt = arrayify(options.salt);
} else {
salt = randomBytes(32);;
}
// Override initialization vector
let iv: Uint8Array = null;
if (options.iv) {
iv = arrayify(options.iv);
if (iv.length !== 16) { throw new Error("invalid iv"); }
} else {
iv = randomBytes(16);
}
// Override the uuid
let uuidRandom: Uint8Array = null;
if (options.uuid) {
uuidRandom = arrayify(options.uuid);
if (uuidRandom.length !== 16) { throw new Error("invalid uuid"); }
} else {
uuidRandom = randomBytes(16);
}
// Override the scrypt password-based key derivation function parameters
let N = (1 << 17), r = 8, p = 1;
if (options.scrypt) {
if (options.scrypt.N) { N = options.scrypt.N; }
if (options.scrypt.r) { r = options.scrypt.r; }
if (options.scrypt.p) { p = options.scrypt.p; }
}
2019-11-13 21:47:08 +09:00
// We take 64 bytes:
// - 32 bytes As normal for the Web3 secret storage (derivedKey, macPrefix)
// - 32 bytes AES key to encrypt mnemonic with (required here to be Ethers Wallet)
2019-11-20 18:29:42 +09:00
return scrypt.scrypt(passwordBytes, salt, N, r, p, 64, progressCallback).then((key) => {
2019-11-13 21:47:08 +09:00
key = arrayify(key);
// This will be used to encrypt the wallet (as per Web3 secret storage)
const derivedKey = key.slice(0, 16);
const macPrefix = key.slice(16, 32);
// This will be used to encrypt the mnemonic phrase (if any)
const mnemonicKey = key.slice(32, 64);
// Encrypt the private key
const counter = new aes.Counter(iv);
const aesCtr = new aes.ModeOfOperation.ctr(derivedKey, counter);
const ciphertext = arrayify(aesCtr.encrypt(privateKey));
// Compute the message authentication code, used to check the password
const mac = keccak256(concat([macPrefix, ciphertext]))
// See: https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition
const data: { [key: string]: any } = {
address: account.address.substring(2).toLowerCase(),
id: uuidV4(uuidRandom),
2019-11-13 21:47:08 +09:00
version: 3,
crypto: {
2019-11-13 21:47:08 +09:00
cipher: "aes-128-ctr",
cipherparams: {
iv: hexlify(iv).substring(2),
},
ciphertext: hexlify(ciphertext).substring(2),
kdf: "scrypt",
kdfparams: {
salt: hexlify(salt).substring(2),
n: N,
dklen: 32,
p: p,
r: r
},
mac: mac.substring(2)
2019-05-14 18:25:46 -04:00
}
2019-11-13 21:47:08 +09:00
};
// If we have a mnemonic, encrypt it into the JSON wallet
if (entropy) {
const mnemonicIv = randomBytes(16);
const mnemonicCounter = new aes.Counter(mnemonicIv);
const mnemonicAesCtr = new aes.ModeOfOperation.ctr(mnemonicKey, mnemonicCounter);
const mnemonicCiphertext = arrayify(mnemonicAesCtr.encrypt(entropy));
const now = new Date();
const timestamp = (now.getUTCFullYear() + "-" +
zpad(now.getUTCMonth() + 1, 2) + "-" +
zpad(now.getUTCDate(), 2) + "T" +
zpad(now.getUTCHours(), 2) + "-" +
zpad(now.getUTCMinutes(), 2) + "-" +
zpad(now.getUTCSeconds(), 2) + ".0Z"
);
data["x-ethers"] = {
client: client,
gethFilename: ("UTC--" + timestamp + "--" + data.address),
mnemonicCounter: hexlify(mnemonicIv).substring(2),
mnemonicCiphertext: hexlify(mnemonicCiphertext).substring(2),
path: path,
2020-01-18 21:09:02 -05:00
locale: locale,
2019-11-13 21:47:08 +09:00
version: "0.1"
};
}
return JSON.stringify(data);
2019-05-14 18:25:46 -04:00
});
}