All files / src/utils readConfig.js

100% Statements 38/38
100% Branches 18/18
100% Functions 4/4
100% Lines 38/38

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                  1x 1x 1x 1x 1x 1x   1x   1x         1x 6x 6x 6x 6x 1x 1x 1x 1x 1x   6x 6x     1x 2x     1x 7x 7x 1x         6x   6x   6x       1x         5x     1x   1x 8x       8x 1x     7x   5x    
/**
 * 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.
 */
 
/* eslint-disable no-console */
 
const fs = require('fs');
const url = require('url');
const { helpers } = require('leap-core');
const Web3 = require('web3');
const { promisify } = require('util');
const { logNode } = require('./debug');
 
const readFile = promisify(fs.readFile);
 
const defaultConfig = {
  eventsDelay: 0,
  bridgeDelay: 0,
};
 
const fetchNodeConfig = async nodeUrl => {
  logNode(`Fetching config from: ${nodeUrl}`);
  const web3 = helpers.extendWeb3(new Web3(nodeUrl));
  const config = await web3.getConfig();
  if (config.p2pPort && config.nodeId) {
    const { hostname } = url.parse(nodeUrl);
    config.peers = config.peers || [];
    config.peers.push(`${config.nodeId}@${hostname}:${config.p2pPort}`);
    delete config.p2pPort;
    delete config.nodeId;
  }
  logNode(`Fetched config from: ${nodeUrl}`, config);
  return config;
};
 
const readConfigFile = async configPath => {
  return JSON.parse(await readFile(configPath));
};
 
const updateNetwork = async (config, cliRootNetwork) => {
  config.rootNetwork = cliRootNetwork || config.rootNetwork;
  if (!config.rootNetwork) {
    throw new Error(
      'rootNetwork is not defined, please specify it in the config file.'
    );
  }
 
  const web3 = new Web3(config.rootNetwork);
 
  const rootNetworkId = await web3.eth.net.getId();
 
  if (
    config.rootNetworkId !== undefined &&
    rootNetworkId !== config.rootNetworkId
  ) {
    throw new Error(
      `Chain Id mismatch, expected ${config.rootNetworkId}, found ${rootNetworkId}.`
    );
  }
 
  return { ...config, rootNetworkId };
};
 
const urlRegex = /^https{0,1}:\/\//;
 
module.exports = async (configPath, cliRootNetwork) => {
  let config = urlRegex.test(configPath)
    ? await fetchNodeConfig(configPath)
    : await readConfigFile(configPath);
 
  if (!config.exitHandlerAddr) {
    throw new Error('exitHandlerAddr is required');
  }
 
  config = await updateNetwork(config, cliRootNetwork);
 
  return Object.assign({}, defaultConfig, config);
};