All files / src/validator/periods startNewPeriod.js

100% Statements 27/27
100% Branches 8/8
100% Functions 2/2
100% Lines 27/27

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 711x 1x 1x 1x   1x 3x     1x 1x 1x         3x   3x         3x               3x   3x   3x           3x     1x 5x 5x 1x     4x         4x 1x 1x       3x     4x       4x    
const { Period } = require('leap-core');
const { logPeriod } = require('../../utils/debug');
const { getCurrentSlotId } = require('../../utils');
const submitPeriodVote = require('./submitPeriodVote');
 
const createNewProposal = async (height, bridgeState) => {
  if (bridgeState.periodProposal) {
    // by setting stalePeriodProposal here we are enabling checkBridge to
    // stop consensus until stale period proposal is processed
    bridgeState.stalePeriodProposal = bridgeState.periodProposal;
    bridgeState.db.setStalePeriodProposal(bridgeState.stalePeriodProposal);
    logPeriod(
      "WARNING: period proposal already exists. Probably it wasn't submitted yet"
    );
  }
 
  const currentPeriodBlocksRoot = bridgeState.currentPeriod.merkleRoot();
 
  const proposerSlotId = getCurrentSlotId(
    bridgeState.currentState.slots,
    height
  );
 
  bridgeState.periodProposal = {
    height,
    proposerSlotId,
    votes: [],
    blocksRoot: currentPeriodBlocksRoot,
    prevPeriodRoot: bridgeState.lastProcessedPeriodRoot,
  };
 
  logPeriod('[startNewPeriod] New period proposal', bridgeState.periodProposal);
 
  await bridgeState.saveNodeState();
 
  await submitPeriodVote(
    currentPeriodBlocksRoot,
    bridgeState.periodProposal,
    bridgeState
  );
 
  return currentPeriodBlocksRoot;
};
 
module.exports = async (height, bridgeState) => {
  logPeriod(`[startNewPeriod] height: ${height}`);
  if (height % 32 !== 0) {
    return;
  }
 
  const { periodProposal } = bridgeState;
  let currentPeriodBlocksRoot;
  // periodProposal.height === height only when we replay the current period
  // after node restart. We don't have period data at this point anymore, so we
  // take prev hash from the period proposal
  if (periodProposal && periodProposal.height === height) {
    currentPeriodBlocksRoot = periodProposal.blocksRoot;
    logPeriod(
      `[startNewPeriod] Reusing saved period proposal: ${currentPeriodBlocksRoot}`
    );
  } else {
    currentPeriodBlocksRoot = await createNewProposal(height, bridgeState);
  }
 
  logPeriod(
    '[startNewPeriod] Creating new period. Previous period blocks root:',
    currentPeriodBlocksRoot
  );
  bridgeState.currentPeriod = new Period(currentPeriodBlocksRoot);
};