All files / src/wallet-sdk/account get-app-private-key.ts

68.75% Statements 22/32
16.66% Branches 1/6
100% Functions 3/3
73.07% Lines 19/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  1x 1x 1x 1x   1x     1x 1x 1x 64x 64x 64x   1x     1x 1x                                       1x 1x 1x   1x   1x    
import { Account } from '../types';
import { bytesToHex, utf8ToBytes } from 'micro-stacks/common';
import { hashSha256 } from 'micro-stacks/crypto-sha';
import { HDKey, Versions } from '@scure/bip32';
import { isHardened } from '../utils';
 
const BITCOIN_VERSIONS: Versions = { private: 0x0488ade4, public: 0x0488b21e };
 
function hashCode(string: string): number {
  let hash = 0;
  Iif (string.length === 0) return hash;
  for (let i = 0; i < string.length; i++) {
    const character = string.charCodeAt(i);
    hash = (hash << 5) - hash + character;
    hash &= hash;
  }
  return hash & 0x7fffffff;
}
 
export function getAppPrivateKey(account: Account, appDomain: string, legacy = true): string {
  if (legacy) return getLegacyAppPrivateKey(account, appDomain);
  // Rather than using the `hashCode` function to derive an index for the child
  // which makes it so there's a unreasonable high probability that someone can
  // log into a new app (website) and it accidentally shares data with another one
  //
  // we want to use the `appDomain` + `salt` to generate a sha256 hash that is
  // then used as the chaincode for the new app keychain
  const chainCode = hashSha256(utf8ToBytes(`${appDomain}${account.salt}`));
  const rootNode = HDKey.fromExtendedKey(account.appsKey);
  Iif (!rootNode.privateKey) throw Error('no rootNode.privateKey');
  const appKeychain = new HDKey({
    privateKey: rootNode.privateKey,
    chainCode,
    versions: BITCOIN_VERSIONS,
  }).deriveChild(isHardened(0));
  Iif (!appKeychain.privateKey)
    throw new Error('[micro-stacks/wallet-sdk] getAppPrivateKey: No private key found');
  return bytesToHex(appKeychain.privateKey);
}
 
export function getLegacyAppPrivateKey(account: Account, appDomain: string): string {
  const hashBuffer = bytesToHex(hashSha256(utf8ToBytes(`${appDomain}${account.salt}`)));
  const appIndex = hashCode(hashBuffer);
  const appKeychain = HDKey.fromExtendedKey(account.appsKey).deriveChild(isHardened(appIndex));
  Iif (!appKeychain.privateKey)
    throw new Error('[micro-stacks/wallet-sdk] getLegacyAppPrivateKey: No private key found');
  return bytesToHex(appKeychain.privateKey);
}