All files / evm-wallet-experiment/src/vats keyring-vat.ts

88% Statements 88/100
82.85% Branches 58/70
100% Functions 16/16
87.87% Lines 87/99

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287                                                                                                      235x                 7x                 4x 4x 1x 1x 2x                 114x 3x         235x 7x 7x   6x   1x       235x                     135x 1x   134x       134x 9x 1x       8x                   125x     133x     133x         5x 1x   4x     4x 4x         4x 4x       4x       37x       6x 6x 1x   4x     4x 4x 1x   3x     4x       169x 4x   165x       29x 29x     29x 29x 1x   28x             64x 64x     64x 64x 64x     64x 64x 1x   63x       4x 4x 1x   2x 2x 4x     2x 2x     2x       6x 6x     5x 5x 6x     5x 5x     5x                 5x 5x 1x   4x 4x 5x     4x 4x     4x                  
import { makeDefaultExo } from '@metamask/kernel-utils/exo';
import type { Logger } from '@metamask/logger';
import type { Baggage } from '@metamask/ocap-kernel';
import type { SignedAuthorization } from 'viem';
 
import { makeKeyring } from '../lib/keyring.ts';
import type {
  EncryptedKeyringInit,
  Keyring,
  KeyringInitOptions,
  StoredKeyringInit,
} from '../lib/keyring.ts';
import { encryptMnemonic, decryptMnemonic } from '../lib/mnemonic-crypto.ts';
import {
  signAuthorization,
  signHash,
  signTransaction,
  signMessage,
  signTypedData,
} from '../lib/signing.ts';
import type {
  Address,
  Eip712TypedData,
  Hex,
  TransactionRequest,
} from '../types.ts';
 
/**
 * Vat powers for the keyring vat.
 */
type VatPowers = {
  logger?: Logger;
};
 
/**
 * Build the root object for the keyring vat.
 *
 * The keyring vat isolates private keys. Keys never leave this vat.
 * Other vats send unsigned payloads and receive signed bytes.
 *
 * @param _vatPowers - Special powers granted to this vat.
 * @param _parameters - Initialization parameters.
 * @param baggage - Root of vat's persistent state.
 * @returns The root object for the keyring vat.
 */
export function buildRootObject(
  _vatPowers: VatPowers,
  _parameters: unknown,
  baggage: Baggage,
): object {
  let keyring: Keyring | undefined;
  let locked = false;
 
  /**
   * Check if stored data is encrypted.
   *
   * @param data - The stored keyring init data.
   * @returns True if the data is encrypted.
   */
  function isEncrypted(data: StoredKeyringInit): data is EncryptedKeyringInit {
    return 'encrypted' in data && data.encrypted;
  }
 
  /**
   * Rebuild the keyring from plaintext init options and re-derive accounts.
   *
   * @param initOptions - The plaintext keyring init options.
   */
  function rebuildKeyring(initOptions: KeyringInitOptions): void {
    keyring = makeKeyring(initOptions);
    if (baggage.has('accountCount')) {
      const count = baggage.get('accountCount') as number;
      for (let i = 1; i < count; i++) {
        keyring.deriveAccount(i);
      }
    }
  }
 
  /**
   * Throw if the keyring is locked.
   */
  function assertUnlocked(): void {
    if (locked) {
      throw new Error('Keyring is locked');
    }
  }
 
  // Restore keyring from baggage if previously initialized
  if (baggage.has('keyringInit')) {
    const stored = baggage.get('keyringInit') as StoredKeyringInit;
    if (isEncrypted(stored)) {
      // Encrypted — keyring stays undefined until unlock() is called
      locked = true;
    } else {
      rebuildKeyring(stored);
    }
  }
 
  return makeDefaultExo('walletKeyring', {
    async bootstrap(): Promise<void> {
      // No services needed for the keyring vat
    },
 
    async initialize(
      options: KeyringInitOptions,
      password?: string,
      salt?: string,
      pbkdf2Iterations?: number,
    ): Promise<void> {
      if (keyring || locked) {
        throw new Error('Keyring already initialized');
      }
      keyring = makeKeyring(options);
 
      // Determine what to persist: encrypted if password provided for SRP
      let stored: StoredKeyringInit;
      if (password && options.type === 'srp') {
        if (!salt) {
          throw new Error(
            'A random salt is required when encrypting the mnemonic',
          );
        }
        stored = {
          ...encryptMnemonic({
            mnemonic: options.mnemonic,
            password,
            salt,
            pbkdf2Iterations,
          }),
          type: 'srp',
        };
      } else {
        stored = options;
      }
 
      Iif (baggage.has('keyringInit')) {
        baggage.set('keyringInit', stored);
      } else {
        baggage.init('keyringInit', stored);
      }
    },
 
    async unlock(password: string, pbkdf2Iterations?: number): Promise<void> {
      if (!locked) {
        throw new Error('Keyring is not locked');
      }
      Iif (!baggage.has('keyringInit')) {
        throw new Error('No keyring data in baggage');
      }
      const stored = baggage.get('keyringInit') as EncryptedKeyringInit;
      const mnemonic = decryptMnemonic({
        data: stored,
        password,
        pbkdf2Iterations,
      });
      rebuildKeyring({ type: 'srp', mnemonic });
      locked = false;
    },
 
    async isLocked(): Promise<boolean> {
      return locked;
    },
 
    async hasKeys(): Promise<boolean> {
      return keyring?.hasKeys() ?? false;
    },
 
    async deriveAccount(index: number): Promise<Address> {
      assertUnlocked();
      if (!keyring) {
        throw new Error('Keyring not initialized');
      }
      const address = keyring.deriveAccount(index);
 
      // Persist the derived account count
      const accounts = keyring.getAccounts();
      if (baggage.has('accountCount')) {
        baggage.set('accountCount', accounts.length);
      } else {
        baggage.init('accountCount', accounts.length);
      }
 
      return address;
    },
 
    async getAccounts(): Promise<Address[]> {
      if (!keyring) {
        return [];
      }
      return keyring.getAccounts();
    },
 
    async signTransaction(tx: TransactionRequest): Promise<Hex> {
      assertUnlocked();
      Iif (!keyring) {
        throw new Error('Keyring not initialized');
      }
      const account = keyring.getAccount(tx.from);
      if (!account) {
        throw new Error(`No key for account ${tx.from}`);
      }
      return signTransaction({ account, tx });
    },
 
    async signTypedData(
      typedData: Eip712TypedData,
      from?: Address,
    ): Promise<Hex> {
      assertUnlocked();
      Iif (!keyring) {
        throw new Error('Keyring not initialized');
      }
      const accounts = keyring.getAccounts();
      const address = from ?? accounts[0];
      Iif (!address) {
        throw new Error('No accounts available');
      }
      const account = keyring.getAccount(address);
      if (!account) {
        throw new Error(`No key for account ${address}`);
      }
      return signTypedData({ account, typedData });
    },
 
    async signHash(hash: Hex, from?: Address): Promise<Hex> {
      assertUnlocked();
      if (!keyring) {
        throw new Error('Keyring not initialized');
      }
      const accounts = keyring.getAccounts();
      const address = from ?? accounts[0];
      Iif (!address) {
        throw new Error('No accounts available');
      }
      const account = keyring.getAccount(address);
      Iif (!account) {
        throw new Error(`No key for account ${address}`);
      }
      return signHash({ account, hash });
    },
 
    async signMessage(message: string, from?: Address): Promise<Hex> {
      assertUnlocked();
      Iif (!keyring) {
        throw new Error('Keyring not initialized');
      }
      const accounts = keyring.getAccounts();
      const address = from ?? accounts[0];
      Iif (!address) {
        throw new Error('No accounts available');
      }
      const account = keyring.getAccount(address);
      Iif (!account) {
        throw new Error(`No key for account ${address}`);
      }
      return signMessage({ account, message });
    },
 
    async signAuthorization(options: {
      contractAddress: Address;
      chainId: number;
      nonce?: number;
      from?: Address;
    }): Promise<SignedAuthorization> {
      assertUnlocked();
      if (!keyring) {
        throw new Error('Keyring not initialized');
      }
      const accounts = keyring.getAccounts();
      const address = options.from ?? accounts[0];
      Iif (!address) {
        throw new Error('No accounts available');
      }
      const account = keyring.getAccount(address);
      Iif (!account) {
        throw new Error(`No key for account ${address}`);
      }
      return signAuthorization({
        account,
        contractAddress: options.contractAddress,
        chainId: options.chainId,
        nonce: options.nonce,
      });
    },
  });
}