# All files / src/api createDb.js

93.44% Statements 57/61
75% Branches 9/12
95.65% Functions 22/23
96.43% Lines 54/56

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

    11x
    2x

    11x
    2x
    2x
    2x
    2x
    2x

    2x

    2x

    2x
    2x
    2x
    2x

    2x

    2x

    2x

    2x
    2x

    11x
    12x

    6x
    5x
    5x

    2x

    6x
    1x

    11x
    1x

    11x
    3x

    11x
    1x
    1x
    1x

    11x
    3x

    11x
    1x

    11x
    2x
    2x

    3x
    3x
    3x
    3x
    3x
    3x

    2x
    2x

    11x

    11x

    2x
     const createDb = levelDb => {
      /*
       * Returns last synced block number from the db. If there is no such a number, returns 0
       */
      const getLastBlockSynced = () =>
        levelDb.get('lastBlockSynced').catch(maybeNotFound => 0); // eslint-disable-line no-unused-vars

      /*
       * Stores block and all it's txs into level db.
       * Sets lastBlockSynced value to the given block height.
       */
      const storeBlock = async (block, logsCache) => {
        const dbOpsBatch = levelDb.batch();
        block.txList.forEach((tx, txPos) => {
          const txHash = tx.hash();
          const txKey = `tx!${txHash}`;
          const value = {
            txData: tx.toJSON(),
            blockHash: block.hash(),
            height: block.height,
            txPos,
          };
          Iif (logsCache && logsCache[txHash]) {
            value.logs = [...logsCache[txHash]]; // copy array
            delete logsCache[txHash];
          }
          dbOpsBatch.put(txKey, JSON.stringify(value));

          // create 'utxoId → tx' index
          tx.inputs
            .filter(i => i.isSpend())
            .map(i => `${i.prevout.txid()}:${i.prevout.index}`)
            .forEach(utxo => dbOpsBatch.put(`out!${utxo}`, txKey));
        });

        dbOpsBatch.put(
          `block!${block.hash()}`,
          JSON.stringify({
            blockData: block.toJSON(),
            height: block.height,
          })
        );

        // index blocks by height for getBlockByNumber
        dbOpsBatch.put(`block!${block.height}`, block.hash());

        dbOpsBatch.put('lastBlockSynced', block.height);

        return new Promise(resolve => {
          dbOpsBatch.write(resolve);
        });
      };

      const getNullable = key => {
        return levelDb
          .get(key)
          .then(jsonStr => {
            // hash, not object
            if (jsonStr.indexOf('0x') === 0) return jsonStr;
            try {
              return JSON.parse(jsonStr);
            } catch (e) {
              return jsonStr;
            }
          })
          .catch(e => {
            if (e.type === 'NotFoundError') return null;
            throw e;
          });
      };

      /*
       * Returns block data for a given hash
       */
      const getBlock = hash => {
        return getNullable(`block!${hash}`);
      };

      /*
       * Returns tx data for a given hash
       */
      const getTransaction = hash => {
        return getNullable(`tx!${hash}`);
      };

      /*
       * Returns tx data for tx spending a given utxo
       */
      const getTransactionByPrevOut = outpoint => {
        return getNullable(`out!${outpoint}`).then(txKey => {
          Iif (!txKey) return null;
          return getNullable(txKey);
        });
      };

      /*
       * Returns the `BridgeState.currentState` or null
       */
      const getChainState = () => {
        return getNullable('chainState');
      };

      /*
       * Saves the `BridgeState.currentState`
       */
      const storeChainState = async state => {
        await levelDb.put('chainState', JSON.stringify(state));
      };

      const storePeriods = async submissions => {
        const dbOpsBatch = levelDb.batch();
        await Promise.all(
          submissions.map(submission => {
            const key = `period!${submission.periodStart}`;
            return getNullable(key).then(existingRecords => {
              const records = existingRecords || [];
              delete submission.periodStart;
              records.push(submission);
              dbOpsBatch.put(key, JSON.stringify(records));
            });
          })
        );

        return new Promise(resolve => {
          dbOpsBatch.write(resolve);
        });
      };

      const getPeriodData = periodStart => getNullable(`period!${periodStart}`);

      return {
        getLastBlockSynced,
        storeBlock,
        getBlock,
        getTransaction,
        getTransactionByPrevOut,
        getChainState,
        storeChainState,
        storePeriods,
        getPeriodData,
      };
    };

    module.exports = createDb;