All files / src/services TransactionsTracker.ts

99.5% Statements 199/200
94.87% Branches 37/39
100% Functions 82/82
99.45% Lines 183/184

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 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 56742x   42x                                                       42x   42x   42x 42x     42x 42x 42x                                                                         42x   42x       149x 149x   149x 149x 149x   149x 150x               150x 150x       149x     42x       14x   14x 26x 26x 22x   4x       14x     42x             11x   11x 24x   24x   32x 9x 9x     19x   5x       11x     42x                                   137x                 138x   138x 149x   149x         149x 149x         149x           149x 132x 128x 128x     132x       17x 3x 3x   3x     14x 14x       14x 15x     14x 8x 8x   8x         6x 1x   6x   5x 5x 1x   1x     6x             42x     137x 137x 137x 137x         11x         137x                       42x     143x     144x   262x 262x           42x 275x   261x   146x 146x 72x 47x 47x         42x                                               143x 32x       143x   143x 2373x     143x   29x     143x 108x     82x       125x   22x 22x     143x 36x 4x       4x     143x 29x 3x           143x 143x     31x   36x 36x   1x 1x     1x 1x   1x                 6x     23x 1x               9x       143x 72x 20x       143x 32x 21x   19x     143x     31x     36x 16x     36x                     19x                     70x 70x 36x 3x   33x   34x 15x     19x   70x 70x         143x     25x 29x     212x 61x     144x 262x       135x     368x 29x   339x 61x   278x 135x         2x     143x 143x 2x 3x     2x         368x           143x 143x 36x     143x                       121x 121x 121x 121x 121x 121x        
import { Cardano, ChainHistoryProvider } from '@cardano-sdk/core';
import { DocumentStore, OrderedCollectionStore } from '../persistence';
import {
  EMPTY,
  NEVER,
  Observable,
  Subject,
  combineLatest,
  concat,
  defaultIfEmpty,
  distinctUntilChanged,
  exhaustMap,
  filter,
  from,
  map,
  merge,
  mergeMap,
  mergeWith,
  of,
  partition,
  race,
  scan,
  share,
  startWith,
  switchMap,
  take,
  takeUntil,
  tap,
  withLatestFrom
} from 'rxjs';
import { FailedTx, OutgoingOnChainTx, OutgoingTx, TransactionFailure, TransactionsTracker, TxInFlight } from './types';
import { Logger } from 'ts-log';
import { Range, Shutdown, contextLogger } from '@cardano-sdk/util';
import { RetryBackoffConfig } from 'backoff-rxjs';
import { TrackerSubject, coldObservableProvider } from '@cardano-sdk/util-rxjs';
import { distinctBlock, signedTxsEquals, transactionsEquals, txInEquals } from './util';
 
import { WitnessedTx } from '@cardano-sdk/key-management';
import { newAndStoredMulticast } from './util/newAndStoredMulticast';
import chunk from 'lodash/chunk.js';
import sortBy from 'lodash/sortBy.js';
 
export interface TransactionsTrackerProps {
  chainHistoryProvider: ChainHistoryProvider;
  addresses$: Observable<Cardano.PaymentAddress[]>;
  tip$: Observable<Cardano.Tip>;
  retryBackoffConfig: RetryBackoffConfig;
  transactionsHistoryStore: OrderedCollectionStore<Cardano.HydratedTx>;
  inFlightTransactionsStore: DocumentStore<TxInFlight[]>;
  signedTransactionsStore: DocumentStore<WitnessedTx[]>;
  newTransactions: {
    submitting$: Observable<OutgoingTx>;
    pending$: Observable<OutgoingTx>;
    failedToSubmit$: Observable<FailedTx>;
    signed$: Observable<WitnessedTx>;
  };
  failedFromReemitter$?: Observable<FailedTx>;
  logger: Logger;
  onFatalError?: (value: unknown) => void;
}
 
export interface TransactionsTrackerInternals {
  transactionsSource$: Observable<Cardano.HydratedTx[]>;
  rollback$: Observable<Cardano.HydratedTx>;
}
 
export interface TransactionsTrackerInternalsProps {
  chainHistoryProvider: ChainHistoryProvider;
  addresses$: Observable<Cardano.PaymentAddress[]>;
  retryBackoffConfig: RetryBackoffConfig;
  tipBlockHeight$: Observable<Cardano.BlockNo>;
  store: OrderedCollectionStore<Cardano.HydratedTx>;
  logger: Logger;
  onFatalError?: (value: unknown) => void;
}
 
// Temporarily hardcoded. Will be replaced with ChainHistoryProvider 'maxPageSize' value once ADP-2249 is implemented
export const PAGE_SIZE = 25;
 
const allTransactionsByAddresses = async (
  chainHistoryProvider: ChainHistoryProvider,
  { addresses, blockRange }: { addresses: Cardano.PaymentAddress[]; blockRange: Range<Cardano.BlockNo> }
): Promise<Cardano.HydratedTx[]> => {
  const addressesSubGroups = chunk(addresses, PAGE_SIZE);
  let response: Cardano.HydratedTx[] = [];
 
  for (const addressGroup of addressesSubGroups) {
    let startAt = 0;
    let pageResults: Cardano.HydratedTx[] = [];
 
    do {
      pageResults = (
        await chainHistoryProvider.transactionsByAddresses({
          addresses: addressGroup,
          blockRange,
          pagination: { limit: PAGE_SIZE, startAt }
        })
      ).pageResults;
 
      startAt += PAGE_SIZE;
      response = [...response, ...pageResults];
    } while (pageResults.length === PAGE_SIZE);
  }
 
  return response;
};
 
const getLastTransactionsAtBlock = (
  transactions: Cardano.HydratedTx[],
  blockNo: Cardano.BlockNo
): Cardano.HydratedTx[] => {
  const txsFromSameBlock = [];
 
  for (let i = transactions.length - 1; i >= 0; --i) {
    const tx = transactions[i];
    if (tx.blockHeader.blockNo === blockNo) {
      txsFromSameBlock.push(tx);
    } else {
      break;
    }
  }
 
  return txsFromSameBlock;
};
 
export const revertLastBlock = (
  localTransactions: Cardano.HydratedTx[],
  blockNo: Cardano.BlockNo,
  rollback$: Subject<Cardano.HydratedTx>,
  newTransactions: Cardano.HydratedTx[],
  logger: Logger
) => {
  const result = [...localTransactions];
 
  while (result.length > 0) {
    const lastKnownTx = result[result.length - 1];
 
    if (lastKnownTx.blockHeader.blockNo === blockNo) {
      // only emit if the tx is also not present in the new transactions to be added
      if (newTransactions.findIndex((tx) => tx.id === lastKnownTx.id) === -1) {
        logger.debug(`Transaction ${lastKnownTx.id} was rolled back`);
        rollback$.next(lastKnownTx);
      }
 
      result.pop();
    } else {
      break;
    }
  }
 
  return result;
};
 
const findIntersectionAndUpdateTxStore = ({
  chainHistoryProvider,
  logger,
  store,
  retryBackoffConfig,
  onFatalError,
  tipBlockHeight$,
  rollback$,
  localTransactions,
  addresses
}: Pick<
  TransactionsTrackerInternalsProps,
  'chainHistoryProvider' | 'logger' | 'store' | 'retryBackoffConfig' | 'onFatalError' | 'tipBlockHeight$'
> & {
  localTransactions: Cardano.HydratedTx[];
  rollback$: Subject<Cardano.HydratedTx>;
  addresses: Cardano.PaymentAddress[];
}) =>
  coldObservableProvider({
    // Do not re-fetch transactions twice on load when tipBlockHeight$ loads from storage first
    // It should also help when using poor internet connection.
    // Caveat is that local transactions might get out of date...
    combinator: exhaustMap,
    equals: transactionsEquals,
    onFatalError,
    // eslint-disable-next-line sonarjs/cognitive-complexity
    provider: async () => {
      let rollbackOcurred = false;
      // eslint-disable-next-line no-constant-condition
      while (true) {
        const lastStoredTransaction: Cardano.HydratedTx | undefined = localTransactions[localTransactions.length - 1];
 
        lastStoredTransaction &&
          logger.debug(
            `Last stored tx: ${lastStoredTransaction?.id} block:${lastStoredTransaction?.blockHeader.blockNo}`
          );
 
        const lowerBound = lastStoredTransaction?.blockHeader.blockNo;
        const newTransactions = await allTransactionsByAddresses(chainHistoryProvider, {
          addresses,
          blockRange: { lowerBound }
        });
 
        logger.debug(
          `chainHistoryProvider returned ${newTransactions.length} transactions`,
          lowerBound !== undefined && `since block ${lowerBound}`
        );
 
        // Fetching transactions from scratch, nothing else to do here.
        if (lowerBound === undefined) {
          if (newTransactions.length > 0) {
            localTransactions = newTransactions;
            store.setAll(newTransactions);
          }
 
          return newTransactions;
        }
 
        // If no transactions found from that block range, it means the last known block has been rolled back.
        if (newTransactions.length === 0) {
          localTransactions = revertLastBlock(localTransactions, lowerBound, rollback$, newTransactions, logger);
          rollbackOcurred = true;
 
          continue;
        }
 
        const localTxsFromSameBlock = getLastTransactionsAtBlock(localTransactions, lowerBound);
        const firstSegmentOfNewTransactions = newTransactions.slice(0, localTxsFromSameBlock.length);
 
        // The first segment of new transaction should match exactly (same txs and same order) our last know TXs. Otherwise
        // roll them back and re-apply in new order.
        const sameTxAndOrder = localTxsFromSameBlock.every(
          (tx, index) => tx.id === firstSegmentOfNewTransactions[index].id
        );
 
        if (!sameTxAndOrder) {
          localTransactions = revertLastBlock(localTransactions, lowerBound, rollback$, newTransactions, logger);
          rollbackOcurred = true;
 
          continue;
        }
 
        // No rollbacks, if they overlap 100% do nothing, otherwise add the difference.
        const areTransactionsSame =
          newTransactions.length === localTxsFromSameBlock.length &&
          localTxsFromSameBlock.every((tx, index) => tx.id === newTransactions[index].id);
 
        if (!areTransactionsSame) {
          // Skip overlapping transactions to avoid duplicates
          localTransactions = [...localTransactions, ...newTransactions.slice(localTxsFromSameBlock.length)];
          store.setAll(localTransactions);
        } else if (rollbackOcurred) {
          // This case handles rollbacks without new additions
          store.setAll(localTransactions);
        }
 
        return localTransactions;
      }
    },
    retryBackoffConfig,
    trigger$: tipBlockHeight$
  });
 
export const createAddressTransactionsProvider = (
  props: TransactionsTrackerInternalsProps
): TransactionsTrackerInternals => {
  const { addresses$, store, logger } = props;
  const rollback$ = new Subject<Cardano.HydratedTx>();
  const storedTransactions$ = store.getAll().pipe(share());
  return {
    rollback$: rollback$.asObservable(),
    transactionsSource$: concat(
      storedTransactions$.pipe(
        tap((storedTransactions) =>
          logger.debug(`Stored history transactions count: ${storedTransactions?.length || 0}`)
        )
      ),
      combineLatest([addresses$, storedTransactions$.pipe(defaultIfEmpty([] as Cardano.HydratedTx[]))]).pipe(
        switchMap(([addresses, storedTransactions]) =>
          findIntersectionAndUpdateTxStore({
            addresses,
            localTransactions: [...storedTransactions],
            rollback$,
            ...props
          })
        )
      )
    )
  };
};
 
const createHistoricalTransactionsTrackerSubject = (
  transactions$: Observable<Cardano.HydratedTx[]>
): TrackerSubject<Cardano.HydratedTx[]> =>
  new TrackerSubject(
    transactions$.pipe(
      map((transactions) =>
        sortBy(
          transactions,
          ({ blockHeader: { blockNo } }) => blockNo,
          ({ index }) => index
        )
      )
    )
  );
 
export const newTransactions$ = <T extends Pick<Cardano.Tx, 'id'>>(transactions$: Observable<T[]>) =>
  transactions$.pipe(
    take(1),
    map((transactions) => transactions.map(({ id }) => id)),
    mergeMap((initialTransactionIds) => {
      const ignoredTransactionIds: Cardano.TransactionId[] = [...initialTransactionIds];
      return transactions$.pipe(
        map((transactions) => transactions.filter(({ id }) => !ignoredTransactionIds.includes(id))),
        tap((newTransactions) => ignoredTransactionIds.push(...newTransactions.map(({ id }) => id))),
        mergeMap((newTransactions) => concat(...newTransactions.map((tx) => of(tx))))
      );
    })
  );
 
export const createTransactionsTracker = (
  {
    tip$,
    chainHistoryProvider,
    addresses$,
    newTransactions: { submitting$: newSubmitting$, pending$, signed$: newSigned$, failedToSubmit$ },
    retryBackoffConfig,
    transactionsHistoryStore: transactionsStore,
    inFlightTransactionsStore: newTransactionsStore,
    signedTransactionsStore,
    logger,
    failedFromReemitter$,
    onFatalError
  }: TransactionsTrackerProps,
  { transactionsSource$: txSource$, rollback$ }: TransactionsTrackerInternals = createAddressTransactionsProvider({
    addresses$,
    chainHistoryProvider,
    logger: contextLogger(logger, 'AddressTransactionsProvider'),
    onFatalError,
    retryBackoffConfig,
    store: transactionsStore,
    tipBlockHeight$: distinctBlock(tip$)
  })
): TransactionsTracker & Shutdown => {
  const submitting$ = newSubmitting$.pipe(
    tap((newSubmitting) => logger.debug(`Got new submitting transaction: ${newSubmitting.id}`)),
    share()
  );
 
  const transactionsSource$ = new TrackerSubject(txSource$);
 
  const historicalTransactions$ = createHistoricalTransactionsTrackerSubject(transactionsSource$).pipe(
    tap((transactions) => logger.debug(`History transactions count: ${transactions?.length || 0}`))
  );
 
  const [onChainNewTxPhase2Failed$, onChainNewTxSuccess$] = partition(
    newTransactions$(historicalTransactions$).pipe(share()),
    (tx) => Cardano.util.isPhase2ValidationErrTx(tx)
  );
 
  const txOnChain$ = (evt: OutgoingTx): Observable<OutgoingOnChainTx> =>
    merge(
      historicalTransactions$.pipe(
        take(1),
        mergeMap((txs) => from(txs))
      ),
      onChainNewTxSuccess$
    ).pipe(
      filter((historyTx) => historyTx.id === evt.id),
      take(1),
      map((historyTx) => ({ ...evt, slot: historyTx.blockHeader.slot })),
      tap(({ slot }) => logger.debug(`Transaction ${evt.id} is on-chain in slot ${slot}`))
    );
 
  const submittingOrPreviouslySubmitted$ = newAndStoredMulticast<TxInFlight, Cardano.TransactionId>({
    groupByFn: ({ id }) => id,
    logStringfn: (transactions) => `Store contains ${transactions?.length} in flight transactions`,
    logger,
    new$: submitting$,
    stored$: newTransactionsStore.get(),
    storedFilterfn: ({ submittedAt }) => !!submittedAt
  });
 
  const newSignedOrPreviouslySigned$ = newAndStoredMulticast<WitnessedTx, Cardano.TransactionId>({
    groupByFn: ({ tx }) => tx.id,
    logStringfn: (WitnessedTxs) => `Store contains ${WitnessedTxs?.length} signed transactions`,
    logger,
    new$: newSigned$,
    stored$: signedTransactionsStore.get()
  });
 
  const failed$ = new Subject<FailedTx>();
  const failedSubscription = submittingOrPreviouslySubmitted$
    .pipe(
      mergeMap((group$) =>
        group$.pipe(
          switchMap((tx) => {
            const invalidHereafter = tx.body.validityInterval?.invalidHereafter;
            return race(
              onChainNewTxPhase2Failed$.pipe(
                filter((failedTx) => failedTx.id === tx.id),
                map((): FailedTx => ({ reason: TransactionFailure.Phase2Validation, ...tx }))
              ),
              rollback$.pipe(
                map((rolledBackTx) => rolledBackTx.id),
                filter((rolledBackTxId) => tx.body.inputs.some(({ txId }) => txId === rolledBackTxId)),
                map(
                  (rolledBackTxId): FailedTx => ({
                    error: new Error(
                      `Invalid inputs due to rolled back tx (${rolledBackTxId}}). Try to rebuild and resubmit.`
                    ),
                    reason: TransactionFailure.InvalidTransaction,
                    ...tx
                  })
                )
              ),
              failedToSubmit$.pipe(filter((failed) => failed.id === tx.id)),
              invalidHereafter
                ? tip$.pipe(
                    filter(({ slot }) => slot > invalidHereafter),
                    map(() => ({ reason: TransactionFailure.Timeout, ...tx }))
                  )
                : NEVER
            ).pipe(take(1), takeUntil(txOnChain$(tx)));
          })
        )
      ),
      mergeWith(failedFromReemitter$ || EMPTY),
      tap(({ id, reason }) => logger.debug(`Transaction ${id} failed`, reason))
    )
    .subscribe(failed$);
 
  const txFailed$ = (tx: OutgoingTx) =>
    failed$.pipe(
      filter((failed) => failed.id === tx.id),
      take(1)
    );
 
  const txPending$ = (tx: OutgoingTx) =>
    pending$.pipe(
      filter((pending) => pending.id === tx.id),
      withLatestFrom(tip$),
      map(([_, { slot }]) => ({ submittedAt: slot, ...tx }))
    );
 
  const inFlight$ = new TrackerSubject<TxInFlight[]>(
    submittingOrPreviouslySubmitted$.pipe(
      mergeMap((group$) =>
        group$.pipe(
          // Only keep 1 (latest) inner observable per tx id.
          switchMap((tx) => {
            const done$ = race(txOnChain$(tx), txFailed$(tx)).pipe(
              map(() => ({ op: 'remove' as const, tx })),
              share()
            );
            return merge(
              of({ op: 'add' as const, tx }),
              done$,
              tx.submittedAt
                ? EMPTY
                : // NOTE: current implementation might incorrectly update 'submittedAt'
                  // if transaction was attempted to resubmit and appeared to be already submitted.
                  // This property currently does not necessarily correspond to
                  // time when transaction got into a mempool - it works more like 'lastAttemptToSubmitAt',
                  // which isn't necessarily bad as it might prevent frequent resubmissions in some cases
                  txPending$(tx).pipe(
                    map((pendingTx) => ({
                      op: 'submitted' as const,
                      tx: pendingTx
                    })),
                    takeUntil(done$)
                  )
            );
          })
        )
      ),
      scan((inFlight, props) => {
        const idx = inFlight.findIndex((txInFlight) => txInFlight.id === props.tx.id);
        if (props.op === 'add') {
          if (idx >= 0) {
            return [...inFlight.slice(0, idx), props.tx, ...inFlight.slice(idx + 1)];
          }
          return [...inFlight, props.tx];
        }
        if (props.op === 'remove') {
          return [...inFlight.slice(0, idx), ...inFlight.slice(idx + 1)];
        }
        // props.op === 'submitted'
        return [...inFlight.slice(0, idx), props.tx, ...inFlight.slice(idx + 1)];
      }, [] as TxInFlight[]),
      tap((inFlight) => newTransactionsStore.set(inFlight)),
      tap((inFlight) => logger.debug(`${inFlight.length} in flight transactions`)),
      startWith([])
    )
  );
 
  const signed$ = new TrackerSubject<WitnessedTx[]>(
    merge(
      newSignedOrPreviouslySigned$.pipe(
        mergeMap((WitnessedTx$) => WitnessedTx$),
        map((witnessedTx) => ({ op: 'add' as const, witnessedTx }))
      ),
      inFlight$.pipe(
        mergeMap((txs) => txs),
        map((tx) => ({ id: tx.id, op: 'remove' as const }))
      ),
      historicalTransactions$.pipe(
        map((txs) => ({
          inputs: txs.flatMap((tx) => tx.body.inputs.map((inputs) => inputs)),
          op: 'check_inputs' as const
        }))
      ),
      tip$.pipe(map(({ slot }) => ({ op: 'check_interval' as const, slot })))
    ).pipe(
      scan((signed, action) => {
        if (action.op === 'add') {
          return [...signed, action.witnessedTx];
        }
        if (action.op === 'remove') {
          return signed.filter(({ tx }) => tx.id !== action.id);
        }
        if (action.op === 'check_interval') {
          return signed.filter(
            ({
              tx: {
                body: { validityInterval: { invalidHereafter } = {} }
              }
            }) => invalidHereafter && invalidHereafter > action.slot
          );
        }
        if (action.op === 'check_inputs') {
          return signed.filter(({ tx }) => {
            const anyUtxoIsUsed = tx.body.inputs.some((WitnessedTxInput) =>
              action.inputs.some((historicalInput) => txInEquals(WitnessedTxInput, historicalInput))
            );
 
            return !anyUtxoIsUsed;
          });
        }
        return signed;
      }, [] as WitnessedTx[]),
      tap((signed) => signedTransactionsStore.set(signed)),
      startWith([]),
      distinctUntilChanged(signedTxsEquals)
    )
  );
 
  const onChain$ = new Subject<OutgoingOnChainTx>();
  const onChainSubscription = submittingOrPreviouslySubmitted$
    .pipe(mergeMap((group$) => group$.pipe(switchMap((tx) => txOnChain$(tx).pipe(takeUntil(txFailed$(tx)))))))
    .subscribe(onChain$);
 
  return {
    history$: historicalTransactions$,
    outgoing: {
      failed$,
      inFlight$,
      onChain$,
      pending$,
      signed$,
      submitting$
    },
    rollback$,
    shutdown: () => {
      inFlight$.complete();
      onChainSubscription.unsubscribe();
      onChain$.complete();
      failedSubscription.unsubscribe();
      failed$.complete();
      logger.debug('Shutdown');
    }
  };
};