All files / src/block updateValidators.js

100% Statements 25/25
100% Branches 14/14
100% Functions 9/9
100% Lines 23/23

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            1x 1x   7x         1x 5x 11x   10x   7x     7x     5x 7x 8x   7x 3x 3x 4x 1x 1x         5x 7x 3x               3x         1x  
/**
 * Copyright (c) 2018-present, Leap DAO (leapdao.org)
 *
 * This source code is licensed under the Mozilla Public License Version 2.0
 * found in the LICENSE file in the root directory of this source tree.
 */
const { getAddress, hexToBase64, base64ToHex } = require('../utils');
const { logValidators } = require('../utils/debug');
 
const power = v => (typeof v === 'number' ? v : v.power);
 
/*
 * Removes validators except those having a slot
 */
module.exports = async (state, chainInfo) => {
  const validatorPubKeys = state.slots
    .filter(s => s) // filter undefined slots
    .filter(s =>
      s.activationEpoch ? s.activationEpoch - state.epoch.epoch > 2 : true
    )
    .map(s => s.tenderKey.replace('0x', ''))
    .map(hexToBase64);
  // logValidators(state.slots, validatorPubKeys, chainInfo.validators);
  const validatorAddrs = validatorPubKeys.map(key => getAddress(key));
 
  // Change existing validators
  Object.keys(chainInfo.validators).forEach(addr => {
    const idx = validatorAddrs.findIndex(
      a => a.toLowerCase() === addr.toLowerCase()
    );
    if (idx === -1 && power(chainInfo.validators[addr]) !== 0) {
      chainInfo.validators[addr] = 0;
      logValidators(`Remove 0x${base64ToHex(addr)}`);
    } else if (idx !== -1 && power(chainInfo.validators[addr]) === 0) {
      chainInfo.validators[addr] = 10;
      logValidators(`Add 0x${base64ToHex(addr)}`);
    }
  });
 
  // Add new validators
  validatorAddrs.forEach((addr, i) => {
    if (chainInfo.validators[addr] === undefined) {
      chainInfo.validators[addr] = {
        address: addr,
        pubKey: {
          data: validatorPubKeys[i],
          type: 'ed25519',
        },
        power: 10,
      };
      logValidators(`Add 0x${base64ToHex(addr)}`);
    }
  });
};
 
exports.getAddress = getAddress;