All files / src/wallet-sdk/account derive-account.ts

60.71% Statements 17/28
11.11% Branches 1/9
66.66% Functions 2/3
65.38% Lines 17/26

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 702x 2x   2x 2x                   2x 6x   6x   6x 6x   6x   6x 6x   6x     6x                 2x 1x               2x                                          
import { HDKey } from '@scure/bip32';
import { bytesToHex } from 'micro-stacks/common';
 
import { DATA_DERIVATION_PATH, STX_DERIVATION_PATH } from '../constants';
import { isCompressed, isHardened } from '../utils';
 
import type { Account, Wallet } from '../types';
 
/**
 * Derive an account from a wallet
 * @param rootNode
 * @param index
 * @param salt
 */
export function deriveAccount(rootNode: HDKey, index: number, salt: string): Account {
  const childKey = rootNode.derive(STX_DERIVATION_PATH).deriveChild(index);
 
  Iif (!childKey.privateKey) throw Error('no private key');
 
  const identitiesKeychain = rootNode.derive(DATA_DERIVATION_PATH);
  const identityKeychain = identitiesKeychain.deriveChild(isHardened(index));
 
  Iif (!identityKeychain.privateKey) throw new Error('Must have private key to derive identities');
 
  const dataPrivateKey = bytesToHex(identityKeychain.privateKey);
  const appsKey = identityKeychain.deriveChild(isHardened(0)).privateExtendedKey;
 
  const stxPrivateKey = `${bytesToHex(childKey.privateKey)}${
    isCompressed(childKey.privateKey) ? '01' : ''
  }`;
  return {
    stxPrivateKey,
    dataPrivateKey,
    appsKey,
    salt,
    index,
  };
}
 
export function deriveNextAccountFromWallet(wallet: Wallet): Account {
  return deriveAccount(
    HDKey.fromExtendedKey(wallet.rootKey),
    // this function generates the next account for the wallet
    wallet.accounts.length,
    wallet.salt
  );
}
 
export function deriveManyAccountsForWallet(
  wallet: Wallet,
  count: number,
  startingIndex?: number
): Account[] {
  const accounts: Account[] = [];
  const indexes = [...Array(count).keys()];
  for (const _index of indexes) {
    const offset = startingIndex
      ? startingIndex
      : wallet.accounts.length > 0
      ? wallet.accounts.length - 1
      : 0;
 
    const index = offset + _index;
    const match = wallet.accounts[index];
    Iif (!match)
      accounts.push(deriveAccount(HDKey.fromExtendedKey(wallet.rootKey), index, wallet.salt));
  }
  return accounts;
}