All files / src/services WalletUtil.ts

96.06% Statements 122/127
85.13% Branches 63/74
100% Functions 31/31
95.32% Lines 102/107

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 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325  43x 43x 43x 43x 43x 43x 43x 43x                                             130x   998x 998x 998x 998x 81x   162x   358x 238x     162x     162x         162x     4564x   998x   20x 5x   5x 3x       17x   17x 1x     16x                           43x 128x   128x 17x 5x     12x 12x 3x 3x     9x     128x     17x 4x 4x       17x 17x   8x                   126x   990x 1003x 1003x   9x             122x 9x                 43x     783x     43x 17x   23x                     43x         18x       18x 18x 22x       4x                   14x         8x     6x     1x   1x 1x             1x 1x 1x             2x         1x   1x             7x             43x       7x 5x     2x 2x             2x   2x 1x         1x                   43x 62x 62x 69x   62x 20x     20x             49x   42x   42x 42x             42x   42x 42x   42x                      
/* eslint-disable no-bitwise */
import * as Crypto from '@cardano-sdk/crypto';
import { Cardano, ChainHistoryProvider } from '@cardano-sdk/core';
import { GroupedAddress, util as KeyManagementUtil, WitnessedTx } from '@cardano-sdk/key-management';
import { Observable, firstValueFrom } from 'rxjs';
import { ObservableWallet, ScriptAddress, isScriptAddress } from '../types';
import { ProtocolParametersRequiredByOutputValidator, createOutputValidator } from '@cardano-sdk/tx-construction';
import { txInEquals } from './util';
import uniqBy from 'lodash/uniqBy.js';
 
export interface InputResolverContext {
  utxo: {
    /** Subscribed on every InputResolver call */
    available$: Observable<Cardano.Utxo[]>;
  };
  transactions: {
    history$: Observable<Cardano.HydratedTx[]>;
    outgoing: {
      signed$: Observable<WitnessedTx[]>;
    };
  };
}
 
export interface WalletOutputValidatorContext {
  /* Subscribed on every OutputValidator call */
  protocolParameters$: Observable<ProtocolParametersRequiredByOutputValidator>;
}
 
export type WalletUtilContext = WalletOutputValidatorContext &
  InputResolverContext & { chainHistoryProvider?: ChainHistoryProvider };
 
export const createInputResolver = ({ utxo, transactions }: InputResolverContext): Cardano.InputResolver => ({
  async resolveInput(input: Cardano.TxIn, options?: Cardano.ResolveOptions) {
    const txHistory = await firstValueFrom(transactions.history$);
    const utxoAvailable = await firstValueFrom(utxo.available$, { defaultValue: [] });
    const signedTransactions = await firstValueFrom(transactions.outgoing.signed$, { defaultValue: [] });
    const utxoFromSigned = signedTransactions.flatMap(({ tx: signedTx }, signedTxIndex) =>
      signedTx.body.outputs
        .filter((_, outputIndex) => {
          const alreadyConsumed = signedTransactions.some(
            ({ tx: { body } }, i) =>
              signedTxIndex !== i &&
              body.inputs.some((consumedInput) => txInEquals(consumedInput, { index: outputIndex, txId: signedTx.id }))
          );
 
          return !alreadyConsumed;
        })
        .map((txOut): Cardano.Utxo => {
          const txIn: Cardano.HydratedTxIn = {
            address: txOut.address,
            index: signedTx.body.outputs.indexOf(txOut),
            txId: signedTx.id
          };
          return [txIn, txOut];
        })
    );
    const availableUtxo = [...utxoAvailable, ...utxoFromSigned].find(([txIn]) => txInEquals(txIn, input));
 
    if (availableUtxo) return availableUtxo[1];
 
    if (options?.hints) {
      const tx = options?.hints.find((hint) => hint.id === input.txId);
 
      if (tx && tx.body.outputs.length > input.index) {
        return tx.body.outputs[input.index];
      }
    }
 
    const historyTx = txHistory.findLast((entry) => entry.id === input.txId);
 
    if (historyTx && historyTx.body.outputs.length > input.index) {
      return historyTx.body.outputs[input.index];
    }
 
    return null;
  }
});
 
/**
 * Creates an input resolver that fetch transaction inputs from the backend.
 *
 * This function tries to fetch the transaction from the backend using a `ChainHistoryProvider`. It
 * also caches fetched transactions to optimize subsequent input resolutions.
 *
 * @param provider The backend provider used to fetch transactions by their hashes if
 * they are not found by the inputResolver.
 * @returns An input resolver that can fetch unresolved inputs from the backend.
 */
export const createBackendInputResolver = (provider: ChainHistoryProvider): Cardano.InputResolver => {
  const txCache = new Map<Cardano.TransactionId, Cardano.Tx>();
 
  const fetchAndCacheTransaction = async (txId: Cardano.TransactionId): Promise<Cardano.Tx | null> => {
    if (txCache.has(txId)) {
      return txCache.get(txId)!;
    }
 
    const txs = await provider.transactionsByHashes({ ids: [txId] });
    if (txs.length > 0) {
      txCache.set(txId, txs[0]);
      return txs[0];
    }
 
    return null;
  };
 
  return {
    async resolveInput(input: Cardano.TxIn, options?: Cardano.ResolveOptions) {
      // Add hints to the cache
      if (options?.hints) {
        for (const hint of options.hints) {
          txCache.set(hint.id, hint);
        }
      }
 
      const tx = await fetchAndCacheTransaction(input.txId);
      if (!tx) return null;
 
      return tx.body.outputs.length > input.index ? tx.body.outputs[input.index] : null;
    }
  };
};
 
/**
 * Combines multiple input resolvers into a single resolver.
 *
 * @param resolvers The input resolvers to combine.
 */
export const combineInputResolvers = (...resolvers: Cardano.InputResolver[]): Cardano.InputResolver => ({
  async resolveInput(txIn: Cardano.TxIn, options?: Cardano.ResolveOptions) {
    for (const resolver of resolvers) {
      const resolved = await resolver.resolveInput(txIn, options);
      if (resolved) return resolved;
    }
    return null;
  }
});
 
/**
 * @returns common wallet utility functions that are aware of wallet state and computes useful things
 */
export const createWalletUtil = (context: WalletUtilContext) => ({
  ...createOutputValidator({ protocolParameters: () => firstValueFrom(context.protocolParameters$) }),
  ...(context.chainHistoryProvider
    ? combineInputResolvers(createInputResolver(context), createBackendInputResolver(context.chainHistoryProvider))
    : createInputResolver(context))
});
 
export type WalletUtil = ReturnType<typeof createWalletUtil>;
 
/** All transaction inputs and collaterals must come from our utxo set */
const hasForeignInputs = (
  { body: { inputs, collaterals = [] } }: { body: Pick<Cardano.TxBody, 'inputs' | 'collaterals'> },
  utxoSet: Cardano.Utxo[]
): boolean => [...inputs, ...collaterals].some((txIn) => utxoSet.every((utxo) => !txInEquals(txIn, utxo[0])));
 
/** Wallet does not include committee certificate keys, so they cannot be signed  */
const hasCommitteeCertificates = ({ certificates }: Cardano.TxBody) =>
  (certificates || []).some(
    (certificate) =>
      certificate.__typename === Cardano.CertificateType.AuthorizeCommitteeHot ||
      certificate.__typename === Cardano.CertificateType.ResignCommitteeCold
  );
 
/**
 * Gets whether the given transaction has certificates that require a witness that can not be provided by the script wallet.
 *
 * @param rewardAccount The reward account of the script wallet.
 * @param certificates The certificates to inspect.
 */
// eslint-disable-next-line complexity
const scriptWalletHasForeignCertificates = (
  rewardAccount: Cardano.RewardAccount,
  certificates?: Cardano.Certificate[]
  // eslint-disable-next-line sonarjs/cognitive-complexity
) => {
  Iif (!certificates) {
    return false;
  }
 
  const scriptHash = Cardano.RewardAccount.toHash(rewardAccount) as unknown as Crypto.Hash28ByteBase16;
  for (const certificate of certificates) {
    switch (certificate.__typename) {
      case Cardano.CertificateType.Registration:
      case Cardano.CertificateType.StakeRegistration:
      case Cardano.CertificateType.GenesisKeyDelegation:
        continue; // Doesnt require signature.
      case Cardano.CertificateType.StakeDeregistration:
      case Cardano.CertificateType.StakeDelegation:
      case Cardano.CertificateType.Unregistration:
      case Cardano.CertificateType.VoteDelegation:
      case Cardano.CertificateType.StakeVoteDelegation:
      case Cardano.CertificateType.StakeRegistrationDelegation:
      case Cardano.CertificateType.VoteRegistrationDelegation:
      case Cardano.CertificateType.MIR:
      case Cardano.CertificateType.StakeVoteRegistrationDelegation: {
        if (
          !certificate.stakeCredential ||
          certificate.stakeCredential.type !== Cardano.CredentialType.ScriptHash ||
          certificate.stakeCredential.hash !== scriptHash
        ) {
          return true;
        }
 
        break;
      }
      case Cardano.CertificateType.PoolRegistration: {
        const account = certificate.poolParameters.owners.find((acct) => acct === rewardAccount);
 
        if (!account) {
          return true;
        }
 
        break;
      }
      case Cardano.CertificateType.PoolRetirement:
        {
          const poolId = Cardano.PoolId.fromKeyHash(Cardano.RewardAccount.toHash(rewardAccount));
          if (certificate.poolId !== poolId) {
            return true;
          }
        }
        break;
      case Cardano.CertificateType.RegisterDelegateRepresentative:
      case Cardano.CertificateType.UnregisterDelegateRepresentative:
      case Cardano.CertificateType.UpdateDelegateRepresentative:
        if (
          !certificate.dRepCredential ||
          certificate.dRepCredential.type !== Cardano.CredentialType.ScriptHash ||
          certificate.dRepCredential.hash !== scriptHash
        ) {
          return true;
        }
        break;
      case Cardano.CertificateType.AuthorizeCommitteeHot:
      case Cardano.CertificateType.ResignCommitteeCold:
        return true;
    }
  }
 
  return false;
};
 
/**
 * Until CIP-095 supports script credential for dReps, we cant witness any voting procedures as the only
 * voter type for this type of wallet is DrepScriptHashVoter
 */
const scriptWalletHasForeignVotingProcedures = (
  rewardAccount: Cardano.RewardAccount,
  votingProcedures?: Cardano.VotingProcedures
) => {
  if (!votingProcedures) {
    return false;
  }
 
  for (const procedure of votingProcedures) {
    switch (procedure.voter.__typename) {
      case Cardano.VoterType.ccHotKeyHash:
      case Cardano.VoterType.ccHotScriptHash:
      case Cardano.VoterType.stakePoolKeyHash:
      case Cardano.VoterType.dRepKeyHash:
        return true;
      case Cardano.VoterType.dRepScriptHash: {
        const scriptHash = Cardano.RewardAccount.toHash(rewardAccount) as unknown as Crypto.Hash28ByteBase16;
 
        if (procedure.voter.credential.hash !== scriptHash) {
          return true;
        }
      }
    }
  }
  return false;
};
 
/**
 * Gets whether the given TX requires signatures that can not be provided by the given wallet.
 *
 * @param tx The transaction to inspect.
 * @param wallet The wallet that will provide the signatures.
 * @returns true if the wallet can not sign all inputs/certificates; otherwise; false.
 */
export const requiresForeignSignatures = async (tx: Cardano.Tx, wallet: ObservableWallet): Promise<boolean> => {
  const utxoSet = await firstValueFrom(wallet.utxo.total$);
  const knownAddresses = await firstValueFrom(wallet.addresses$);
  const isScriptWallet = knownAddresses.some((address) => isScriptAddress(address));
 
  if (isScriptWallet) {
    const scriptAddresses = knownAddresses.map((address) => address as ScriptAddress);
 
    // Script addresses have a single payment credential and stake credential.
    return (
      hasForeignInputs(tx, utxoSet) ||
      scriptWalletHasForeignCertificates(scriptAddresses[0].rewardAccount, tx.body.certificates) ||
      scriptWalletHasForeignVotingProcedures(scriptAddresses[0].rewardAccount, tx.body.votingProcedures)
    );
  }
 
  const keyHashAddresses = knownAddresses.map((address) => address as GroupedAddress);
 
  const uniqueAccounts: KeyManagementUtil.StakeKeySignerData[] = uniqBy(keyHashAddresses, 'rewardAccount')
    .map((groupedAddress) => {
      const stakeKeyHash = Cardano.RewardAccount.toHash(groupedAddress.rewardAccount);
      return {
        derivationPath: groupedAddress.stakeKeyDerivationPath,
        poolId: Cardano.PoolId.fromKeyHash(stakeKeyHash),
        rewardAccount: groupedAddress.rewardAccount,
        stakeKeyHash
      };
    })
    .filter((acct): acct is KeyManagementUtil.StakeKeySignerData => acct.derivationPath !== null);
 
  const dRepKey = await wallet.governance.getPubDRepKey();
  const dRepKeyHash = dRepKey ? (await Crypto.Ed25519PublicKey.fromHex(dRepKey).hash()).hex() : undefined;
 
  return (
    hasForeignInputs(tx, utxoSet) ||
    KeyManagementUtil.checkStakeCredentialCertificates(uniqueAccounts, tx.body).requiresForeignSignatures ||
    (dRepKeyHash &&
      KeyManagementUtil.getDRepCredentialKeyPaths({ dRepKeyHash, txBody: tx.body }).requiresForeignSignatures) ||
    (dRepKeyHash &&
      KeyManagementUtil.getVotingProcedureKeyPaths({ dRepKeyHash, groupedAddresses: keyHashAddresses, txBody: tx.body })
        .requiresForeignSignatures) ||
    hasCommitteeCertificates(tx.body)
  );
};