import { pbkdf2 } from "@ethersproject/pbkdf2"; import { toUtf8Bytes, UnicodeNormalizationForm } from "@ethersproject/strings"; import { EthereumPrivateKeyProvider, EthereumPrivKeyProviderConfig, EthereumPrivKeyProviderState, } from "@web3auth/ethereum-provider"; import { HDNodeWallet, Mnemonic, TypedDataDomain, TypedDataField, Wallet, Wordlist, ethers, } from "ethers"; import { v4 } from "uuid"; import { InvalidWalletStateError, WalletAlreadyInitializedError, InvalidWalletError, } from "./error"; import { ISigner } from "./signer"; import { NewWalletCreateOptions, ProgressCallback, State } from "./types"; export interface IStorage { get(key: string, type?: "local" | "session"): Promise; set(key: string, value: string, type?: "local" | "session"): Promise; remove(key: string, type?: "local" | "session"): Promise; clear(type?: "local" | "session"): Promise; } export abstract class AbstractEmbeddedWallet implements ISigner { #state?: State; #wallet?: HDNodeWallet; protected constructor(state?: State ) { this.#state = state; } public isAvailable() { return typeof this.#state !== 'undefined'; } protected setState(state: State) { this.#state = state; } public generateRandomPassword(length: number): string { // Generate random bytes const randomBuffer = ethers.randomBytes(length); // Convert the buffer to a UTF-8 string const randomString = randomBuffer.toString(); // Ensure the string is printable const printableString = randomString.replace(/[^ -~]/g, "!"); const password = printableString.substring(0, length); const pwdBytes = toUtf8Bytes(password, UnicodeNormalizationForm.NFKD); return pbkdf2( pwdBytes, toUtf8Bytes("salt", UnicodeNormalizationForm.NFKD), 2048, 64, "sha512", ); } private createWallet(options?: { locale?: Wordlist; path?: string }): { wallet: HDNodeWallet; password: string; } { let entropy: Uint8Array = ethers.randomBytes(16); const pwd: string = this.generateRandomPassword(16); // 16 bytes of password if (!options) { options = {}; } const value = `0x0${new Date().getTime().toString(16)}`; const salt = ethers.getBytes(value); entropy = ethers.getBytes( ethers.dataSlice(ethers.keccak256(ethers.concat([entropy, salt])), 0, 16), ); const mnemonic = Mnemonic.entropyToPhrase(entropy, options.locale); return { wallet: Wallet.fromPhrase(mnemonic), password: pwd, }; } /** * @throws WalletAlreadyInitializedError * @protected */ protected async newWallet( opts?: NewWalletCreateOptions, ): Promise<{ id: string; password: string }> { if (this.isAvailable()) { throw new WalletAlreadyInitializedError(); } const { wallet, password } = this.createWallet(); const walletState = await wallet.encrypt(password, opts?.progressCallback); this.setState({ id: v4(), state: walletState, type: "passkey" }); if (opts?.walletCreateCallback) { opts.walletCreateCallback({ state: this.#state!, password }); } this.#wallet = wallet; return { id: this.#state!.id, password }; } public async persistent(): Promise { return JSON.stringify(this.#state); } /** * @throws InvalidWalletStateError * @param password * @param progressCallback * @returns boolean */ public async unlockWallet( password: string, progressCallback?: ProgressCallback, ): Promise { this.assertState(); this.#wallet = (await Wallet.fromEncryptedJson( this.#state!.state, password, progressCallback, )) as HDNodeWallet; return true; } abstract initialize(credentialId?: string): Promise; assertWallet() { if (!this.#wallet) { throw new InvalidWalletError(); } } assertState() { if (!this.#state) { throw new InvalidWalletStateError(); } } signTypedData( domain: TypedDataDomain, types: Record, value: Record, ): Promise { this.assertWallet(); return this.#wallet!.signTypedData(domain, types, value); } async getAddress(): Promise { this.assertWallet(); return await this.#wallet!.getAddress(); } signMessage(message: string | Uint8Array): Promise { this.assertWallet(); return this.#wallet!.signMessage(message); } public async toProvider(params: { config: EthereumPrivKeyProviderConfig; state?: Omit; }) { this.assertWallet(); const provider = new EthereumPrivateKeyProvider({ config: params.config, state: { name: params.state?.name, chainId: params.state?.chainId || params.config?.chainConfig?.chainId, privateKey: this.#wallet!.privateKey, }, }); return provider; } }