All files / src/api createDb.js

92.68% Statements 76/82
78.26% Branches 18/23
93.33% Functions 28/30
97.26% Lines 71/73

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 1892x   2x   2x       17x 2x           17x 2x 2x 2x 2x 2x           2x       2x     2x 2x 2x 2x     2x                 2x   2x   2x 2x       17x 17x       11x 11x 10x 10x   6x       6x 1x             17x 1x           17x 3x           17x 1x 1x 1x             17x 3x           17x 1x     17x 1x     17x 1x     17x   17x 4x 4x 2x       17x 4x       4x 1x     3x 3x 3x 3x   3x 3x             17x 1x         17x 1x   17x 1x   17x   17x                                       2x  
const { Util } = require('leap-core');
 
const { fromJSON, toJSON } = Util;
 
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, toJSON(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()}`,
      toJSON({
        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
        Iif (jsonStr === null || jsonStr === undefined) return null;
        if (jsonStr.indexOf && jsonStr.indexOf('0x') === 0) return jsonStr;
        try {
          return fromJSON(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', toJSON(state));
  };
 
  const getNodeState = () => {
    return getNullable('nodeState');
  };
 
  const storeNodeState = async state => {
    await levelDb.put('nodeState', toJSON(state));
  };
 
  const getPeriodData = periodStart => getNullable(`period!${periodStart}`);
 
  const getPeriodDataByBlocksRoot = blocksRoot => {
    return getNullable(`period!${blocksRoot}`).then(periodDataKey => {
      if (!periodDataKey) return null;
      return getNullable(periodDataKey);
    });
  };
 
  const storeSubmission = async (periodStartHeight, submission) => {
    const existingRecord = await getPeriodDataByBlocksRoot(
      submission.blocksRoot
    );
    // skip saving if record with the same root exists, otherwise overwrite
    if (existingRecord && existingRecord.blocksRoot === submission.blocksRoot) {
      return Promise.resolve();
    }
 
    const dbOpsBatch = levelDb.batch();
    const key = `period!${periodStartHeight}`;
    dbOpsBatch.put(`period!${submission.blocksRoot}`, key);
    dbOpsBatch.put(key, toJSON(submission));
 
    return new Promise(resolve => {
      dbOpsBatch.write(resolve);
    });
  };
 
  /*
   * Returns the last seen root chain block height. If there is no such a number, returns 0.
   */
  const getLastSeenRootChainBlock = () =>
    levelDb.get('lastSeenRootChainBlock').catch(() => 0);
 
  /*
   * Saves last seen root chain block height
   */
  const setLastSeenRootChainBlock = (blockHeight = 0) =>
    levelDb.put('lastSeenRootChainBlock', blockHeight);
 
  const setStalePeriodProposal = periodProposal =>
    levelDb.put('stalePeriodProposal', toJSON(periodProposal));
 
  const getStalePeriodProposal = () => getNullable('stalePeriodProposal');
 
  return {
    getLastBlockSynced,
    storeBlock,
    getBlock,
    getTransaction,
    getTransactionByPrevOut,
    getChainState,
    getNodeState,
    storeChainState,
    storeSubmission,
    storeNodeState,
    getPeriodData,
    getLastSeenRootChainBlock,
    setLastSeenRootChainBlock,
    getPeriodDataByBlocksRoot,
    setStalePeriodProposal,
    getStalePeriodProposal,
  };
};
 
module.exports = createDb;