# All files / lib/chain ChainManager.ts

77.78% Statements 105/135
62.26% Branches 33/53
78.57% Functions 11/14
76.92% Lines 100/130

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
    1x
    1x
    1x

    1x
    1x

    1x
    1x
    1x
    1x

    1x

    9x

    9x
    9x
    9x
    9x

    6x

    6x
    6x
    6x
    6x

    6x
    6x

    6x

    2x

    2x
    2x
    2x
    2x

    2x

    2x

    2x
    2x

    2x

    2x
    2x

    2x

    2x

    6x
    6x
    6x
    6x
    6x

    6x

    6x
    4x

    6x

    6x

    6x

    6x
    4x

    6x
    4x

    6x

    6x

    4x

    4x
    4x
    4x
    4x

    4x
    4x

    4x
    4x

    4x

    4x

    4x

    4x

    4x
    2x
    2x

    2x

    2x

    2x

    2x
    2x
    2x
    2x
    2x
    2x

    2x

    2x

    2x

    2x
    2x

    2x
    2x
    4x
    4x
    4x

    2x
    2x

    2x
    2x
    2x

    2x

    2x
    2x
    2x
    2x
    2x

     /* eslint-disable @typescript-eslint/no-explicit-any */
    import { Tx } from '@node-dlc/bitcoin';
    import { Block, Transaction } from 'bitcoinjs-lib';
    import { EventEmitter } from 'events';

    import { DlcTransactions } from '../messages/DlcTransactions';
    import { sleep } from '../util';
    import { IDlcStore } from './DlcStore';
    import {
      HasHash,
      HasHeight,
      IChainFilterChainClient,
    } from './IChainFilterChainClient';

    export enum SyncState {
      Unsynced,
      Syncing,
      Synced,
    }

    export interface ILogger {
      area: string;
      instance: string;
      trace(...args: any[]): void;
      debug(...args: any[]): void;
      info(...args: any[]): void;
      warn(...args: any[]): void;
      error(...args: any[]): void;
      sub(area: string, instance?: string): ILogger;
    }

    /**
     * ChainManager validates and stores dlc txs
     * from chain updates
     */
    export class ChainManager extends EventEmitter {
      public blockHeight: number;
      public started = false;
      public syncState: SyncState;
      public isSynchronizing: boolean;
      public chainClient: IChainFilterChainClient;
      public logger: ILogger;
      public dlcStore: IDlcStore;
      public dlcTxsList: DlcTransactions[];

      constructor(
        logger: ILogger,
        chainClient: IChainFilterChainClient,
        dlcStore: IDlcStore,
      ) {
        super();
        this.logger = logger.sub('dlcmgr');
        this.dlcStore = dlcStore;
        this.chainClient = chainClient;
      }

      /**
       * Starts the chain manager. This method will load information
       * from the chain store, determine when the last information
       * was obtained, validate the existing messages
       */
      public async start(blockHeight = 0): Promise<void> {
        this.logger.info('starting dlc state manager');

        // wait for chain sync to complete
        Eif (this.chainClient) {
          this.logger.info('waiting for chain sync');
          await this.chainClient.waitForSync();
          this.logger.info('chain sync complete');
        }

        await this._restoreState(blockHeight);
        this.syncState = SyncState.Synced;

        // flag that the manager has now started
        this.started = true;
      }

      public async updateFundBroadcast(dlcTxs: DlcTransactions): Promise<void> {
        const info = await this.chainClient.getBlockchainInfo();
        const block = await this.chainClient.getBlock(info.bestblockhash);

        dlcTxs.fundBroadcastHeight = block.height;

        await this.dlcStore.saveDlcTransactions(dlcTxs);
      }

      public async updateCloseBroadcast(dlcTxs: DlcTransactions): Promise<void> {
        const info = await this.chainClient.getBlockchainInfo();
        const block = await this.chainClient.getBlock(info.bestblockhash);

        dlcTxs.closeBroadcastHeight = block.height;

        await this.dlcStore.saveDlcTransactions(dlcTxs);
      }

      public async updateFundEpoch(
        dlcTxs: DlcTransactions,
        block: HasHeight & HasHash,
      ): Promise<void> {
        this.logger.info(
          `updating fund epoch on dlc ${dlcTxs.contractId.toString('hex')}`,
        );
        dlcTxs.fundEpoch.hash = Buffer.from(block.hash, 'hex');
        dlcTxs.fundEpoch.height = block.height;

        if (dlcTxs.fundBroadcastHeight === 0) {
          dlcTxs.fundBroadcastHeight = block.height - 1;
        }

        await this.dlcStore.saveDlcTransactions(dlcTxs);

        this.logger.info(
          `fund epoch updated on dlc ${dlcTxs.contractId.toString('hex')}`,
        );
      }

      public async updateCloseEpoch(
        dlcTxs: DlcTransactions,
        tx: Tx,
        block: HasHeight & HasHash,
      ): Promise<void> {
        this.logger.info(
          `updating close epoch on dlc ${dlcTxs.contractId.toString('hex')}`,
        );
        dlcTxs.closeEpoch.hash = Buffer.from(block.hash, 'hex');
        dlcTxs.closeEpoch.height = Number(block.height);
        dlcTxs.closeTxHash = Buffer.from(tx.txId.toString(), 'hex');
        dlcTxs.closeType = 3; // Default to cooperative close if txid not refund or cet txid

        const _dlcTxs = await this.dlcStore.findDlcTransactions(dlcTxs.contractId);

        // figure out if it's execute, refund or mutual close
        Iif (tx.txId.toString() === dlcTxs.refundTx.txId.toString()) {
          dlcTxs.closeType = 2;
        } else {
          const cetIndex = _dlcTxs.cets.findIndex(
            (cet) => tx.txId.toString() === cet.txId.toString(),
          );
          Eif (cetIndex >= 0) dlcTxs.closeType = 1;
        }

        Eif (dlcTxs.closeBroadcastHeight === 0) {
          dlcTxs.closeBroadcastHeight = block.height - 1;
        }

        await this.dlcStore.saveDlcTransactions(dlcTxs);

        this.logger.info(
          `close epoch updated on dlc ${dlcTxs.contractId.toString('hex')}`,
        );
      }

      private async _restoreState(blockHeight = 0): Promise<void> {
        this.logger.info('retrieving dlc state from store');
        this.blockHeight = blockHeight;
        this.syncState = SyncState.Syncing;
        this.dlcTxsList = await this.dlcStore.findDlcTransactionsList();
        this.logger.info('found %d dlcs', this.dlcTxsList.length);

        Eif (blockHeight === 0) {
          // find best block height
          for (const dlcTxs of this.dlcTxsList) {
            this.blockHeight = Math.max(
              Math.max(this.blockHeight, dlcTxs.fundEpoch.height),
              dlcTxs.closeEpoch.height,
            );
          }
        }

        this.logger.info("highest block %d found from %d dlcs", this.blockHeight, this.dlcTxsList.length); // prettier-ignore

        // validate all utxos
        await this._validateUtxos(this.dlcTxsList);
      }

      private async _validateUtxos(_dlcTxsList: DlcTransactions[]) {
        Iif (!this.chainClient) {
          this.logger.info('skipping utxo validation, no chain_client configured');
          return;
        }

        const dlcTxsList = _dlcTxsList.filter(
          (dlcTxs) => dlcTxs.closeEpoch.height === 0,
        );

        const dlcTxsCount = dlcTxsList.reduce(
          (acc, msg) => acc + (msg instanceof DlcTransactions ? 1 : 0),
          0,
        );
        this.logger.info('validating %d funding utxos', dlcTxsCount);

        if (!dlcTxsCount) return;

        const dlcTxsToVerify: DlcTransactions[] = [];

        const oct = Math.trunc(dlcTxsCount / 16);
        for (let i = 0; i < dlcTxsList.length; i++) {
          const dlcTxs = dlcTxsList[i];
          Iif ((i + 1) % oct === 0) {
            this.logger.info(
              'validating funding utxos %s% complete',
              (((i + 1) / dlcTxsCount) * 100).toFixed(2),
            );
          }
          Eif (dlcTxs instanceof DlcTransactions) {
            const utxo = await this.chainClient.getUtxo(
              dlcTxs.fundTx.txId.toString(),
              dlcTxs.fundTxVout,
            );

            try {
              const tx = await this.chainClient.getTransaction(
                dlcTxs.fundTx.txId.toString(),
              );
              if (!utxo) dlcTxsToVerify.push(dlcTxs);

              Iif (utxo && Number(utxo.confirmations) === 0)
                this.updateFundBroadcast(dlcTxs);

              Iif (
                utxo &&
                Number(utxo.confirmations) > 0 &&
                dlcTxs.fundEpoch.height === 0
              ) {
                const block = await this.chainClient.getBlock(tx.blockhash);
                await this.updateFundEpoch(dlcTxs, block);
              }
            } catch (e) {
              /**
               * tx doesn't exist
               * fund tx wasn't broadcast in the first place
               */
            }
          }
        }
        this.logger.info('validating funding utxos 100% complete');

        if (dlcTxsToVerify.length === 0) {
          this.logger.info('no closing utxos to validate');
          return;
        }

        await this._validateClosingUtxos(dlcTxsToVerify);
      }

      private async _validateClosingUtxos(dlcTxsList: DlcTransactions[]) {
        let info = await this.chainClient.getBlockchainInfo();

        Iif (this.blockHeight === 0) {
          this.logger.info('cannot sync from block height 0');
          return;
        }

        let numBlocksToSync = Math.max(info.blocks - this.blockHeight, 0);
        this.logger.info('validating %d blocks for closing utxos', numBlocksToSync);
        const oct = Math.trunc(numBlocksToSync / 16);
        let i = 0;
        while (info.blocks > this.blockHeight) {
          await sleep(10);

          Iif ((i + 1) % oct === 0) {
            this.logger.info(
              'validating block %s, closing utxos %s% complete',
              this.blockHeight,
              (((i + 1) / numBlocksToSync) * 100).toFixed(2),
            );
          }

          // Log every 10 blocks
          Iif (this.blockHeight % 10 === 0) {
            this.logger.info(
              'Validating block %s for closing utxos',
              this.blockHeight,
            );
          }

          this.blockHeight += 1;

          const blockHash = await this.chainClient.getBlockHash(this.blockHeight);
          const blockBuf = await this.chainClient.getRawBlock(blockHash);

          const block = Block.fromBuffer(blockBuf);
          for (const transaction of block.transactions) {
            try {
              const bjsTx = Transaction.fromBuffer(transaction.toBuffer());
              if (!bjsTx.isCoinbase()) {
                // ignore coinbase txs for outpoint check
                const tx = Tx.fromBuffer(transaction.toBuffer());
                await this._checkOutpoints(dlcTxsList, tx, block.getId());
              }
            } catch (e) {
              this.logger.error(
                'Invalid tx for validating closing utxo: %s',
                transaction.toHex(),
              );
              this.logger.trace('Error: ', e);
            }
          }

          Eif (info.blocks === this.blockHeight) {
            info = await this.chainClient.getBlockchainInfo();
            Eif (info.blocks === this.blockHeight) break;
            numBlocksToSync += info.blocks - this.blockHeight;
          }

          i++;
        }

        this.logger.info('validating closing utxos 100% complete');
      }

      private async _checkOutpoints(
        dlcTxsList: DlcTransactions[],
        tx: Tx,
        blockHash: string,
      ) {
        for (const dlcTxs of dlcTxsList) {
          for (const input of tx.inputs) {
            Eif (dlcTxs.fundTx.txId.toString() === input.outpoint.txid.toString()) {
              const block = await this.chainClient.getBlock(blockHash);
              await this.updateCloseEpoch(dlcTxs, tx, block);
            }
          }
        }
      }
    }