From 782806595c323ad6dbe317790ca51f62c27e463d Mon Sep 17 00:00:00 2001 From: Sergi Delgado Segura Date: Thu, 11 Jun 2020 15:59:08 +0200 Subject: [PATCH] general - Adds default RPC port based on network param --- README.md | 4 +--- common/config_loader.py | 5 ++++- common/constants.py | 5 +++++ teos/__init__.py | 3 ++- teos/teosd.py | 49 +++++++++++++++++++++++------------------ teos/tools.py | 27 +++++++++++++++++++++++ 6 files changed, 66 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index 037b237..e2b44f4 100644 --- a/README.md +++ b/README.md @@ -54,14 +54,13 @@ By default, `teos` runs on `mainnet`. In order to run it on another network you ### Modifying the configuration file -The configuration file options to change the network where `teos` will run are the `btc_rpc_port` and the `btc_network` under the `bitcoind` section: +The configuration file option to change the network where `teos` will run is `btc_network` under the `bitcoind` section: ``` [bitcoind] btc_rpc_user = "user" btc_rpc_password = "passwd" btc_rpc_connect = "localhost" -btc_rpc_port = 8332 btc_network = "mainnet" ``` @@ -72,7 +71,6 @@ For regtest, it should look like: btc_rpc_user = "user" btc_rpc_password = "passwd" btc_rpc_connect = "localhost" -btc_rpc_port = 18443 btc_network = "regtest" ``` diff --git a/common/config_loader.py b/common/config_loader.py index d0bafb0..087bfec 100644 --- a/common/config_loader.py +++ b/common/config_loader.py @@ -31,6 +31,7 @@ class ConfigLoader: self.conf_file_path = os.path.join(self.data_dir, conf_file_name) self.conf_fields = default_conf self.command_line_conf = command_line_conf + self.overwritten_fields = set() def build_config(self): """ @@ -43,7 +44,6 @@ class ConfigLoader: Returns: :obj:`dict`: a dictionary containing all the configuration parameters. - """ if os.path.exists(self.conf_file_path): @@ -65,9 +65,12 @@ class ConfigLoader: else: self.conf_fields[k_upper]["value"] = v + self.overwritten_fields.add(k_upper) + # Override the command line parameters to the defaults / conf file for k, v in self.command_line_conf.items(): self.conf_fields[k]["value"] = v + self.overwritten_fields.add(k) # Extend relative paths self.extend_paths() diff --git a/common/constants.py b/common/constants.py index 6e8a6ee..b333378 100644 --- a/common/constants.py +++ b/common/constants.py @@ -8,6 +8,11 @@ HTTP_BAD_REQUEST = 400 HTTP_NOT_FOUND = 404 HTTP_SERVICE_UNAVAILABLE = 503 +# Bitcoin +MAINNET_RPC_PORT = 8332 +TESTNET_RPC_PORT = 18332 +REGTEST_RPC_PORT = 18443 + # LN general nomenclature IRREVOCABLY_RESOLVED = 100 diff --git a/teos/__init__.py b/teos/__init__.py index 96a474a..86f0ece 100644 --- a/teos/__init__.py +++ b/teos/__init__.py @@ -1,4 +1,5 @@ import os +from common.constants import MAINNET_RPC_PORT DATA_DIR = os.path.expanduser("~/.teos/") CONF_FILE_NAME = "teos.conf" @@ -11,7 +12,7 @@ DEFAULT_CONF = { "BTC_RPC_USER": {"value": "user", "type": str}, "BTC_RPC_PASSWORD": {"value": "passwd", "type": str}, "BTC_RPC_CONNECT": {"value": "127.0.0.1", "type": str}, - "BTC_RPC_PORT": {"value": 8332, "type": int}, + "BTC_RPC_PORT": {"value": MAINNET_RPC_PORT, "type": int}, "BTC_NETWORK": {"value": "mainnet", "type": str}, "BTC_FEED_PROTOCOL": {"value": "tcp", "type": str}, "BTC_FEED_CONNECT": {"value": "localhost", "type": str}, diff --git a/teos/teosd.py b/teos/teosd.py index 5d68efa..f9e752b 100644 --- a/teos/teosd.py +++ b/teos/teosd.py @@ -20,8 +20,8 @@ from teos.gatekeeper import Gatekeeper from teos.chain_monitor import ChainMonitor from teos.block_processor import BlockProcessor from teos.appointments_dbm import AppointmentsDBM -from teos.tools import can_connect_to_bitcoind, in_correct_network from teos import LOG_PREFIX, DATA_DIR, DEFAULT_CONF, CONF_FILE_NAME +from teos.tools import can_connect_to_bitcoind, in_correct_network, get_default_rpc_port logger = Logger(actor="Daemon", log_name_prefix=LOG_PREFIX) @@ -38,30 +38,35 @@ def handle_signals(signal_received, frame): def main(command_line_conf): global db_manager, chain_monitor - signal(SIGINT, handle_signals) - signal(SIGTERM, handle_signals) - signal(SIGQUIT, handle_signals) + try: + signal(SIGINT, handle_signals) + signal(SIGTERM, handle_signals) + signal(SIGQUIT, handle_signals) - # Loads config and sets up the data folder and log file - data_dir = command_line_conf.pop("DATA_DIR") if "DATA_DIR" in command_line_conf else DATA_DIR - config_loader = ConfigLoader(data_dir, CONF_FILE_NAME, DEFAULT_CONF, command_line_conf) - config = config_loader.build_config() - setup_data_folder(data_dir) - setup_logging(config.get("LOG_FILE"), LOG_PREFIX) + # Loads config and sets up the data folder and log file + data_dir = command_line_conf.pop("DATA_DIR") if "DATA_DIR" in command_line_conf else DATA_DIR + config_loader = ConfigLoader(data_dir, CONF_FILE_NAME, DEFAULT_CONF, command_line_conf) + config = config_loader.build_config() - logger.info("Starting TEOS") + # Set default RPC port if not overwritten by the user. + if "BTC_RPC_PORT" not in config_loader.overwritten_fields: + config["BTC_RPC_PORT"] = get_default_rpc_port(config.get("BTC_NETWORK")) - bitcoind_connect_params = {k: v for k, v in config.items() if k.startswith("BTC")} - bitcoind_feed_params = {k: v for k, v in config.items() if k.startswith("BTC_FEED")} + setup_data_folder(data_dir) + setup_logging(config.get("LOG_FILE"), LOG_PREFIX) - if not can_connect_to_bitcoind(bitcoind_connect_params): - logger.error("Cannot connect to bitcoind. Shutting down") + logger.info("Starting TEOS") - elif not in_correct_network(bitcoind_connect_params, config.get("BTC_NETWORK")): - logger.error("bitcoind is running on a different network, check conf.py and bitcoin.conf. Shutting down") + bitcoind_connect_params = {k: v for k, v in config.items() if k.startswith("BTC")} + bitcoind_feed_params = {k: v for k, v in config.items() if k.startswith("BTC_FEED")} - else: - try: + if not can_connect_to_bitcoind(bitcoind_connect_params): + logger.error("Cannot connect to bitcoind. Shutting down") + + elif not in_correct_network(bitcoind_connect_params, config.get("BTC_NETWORK")): + logger.error("bitcoind is running on a different network, check conf.py and bitcoin.conf. Shutting down") + + else: secret_key_der = Cryptographer.load_key_file(config.get("TEOS_SECRET_KEY")) if not secret_key_der: raise IOError("TEOS private key cannot be loaded") @@ -160,9 +165,9 @@ def main(command_line_conf): chain_monitor.monitor_chain() inspector = Inspector(block_processor, config.get("MIN_TO_SELF_DELAY")) API(config.get("API_BIND"), config.get("API_PORT"), inspector, watcher).start() - except Exception as e: - logger.error("An error occurred: {}. Shutting down".format(e)) - exit(1) + except Exception as e: + logger.error("An error occurred: {}. Shutting down".format(e)) + exit(1) if __name__ == "__main__": diff --git a/teos/tools.py b/teos/tools.py index 36e9afd..11b954e 100644 --- a/teos/tools.py +++ b/teos/tools.py @@ -3,11 +3,14 @@ from http.client import HTTPException from teos.utils.auth_proxy import AuthServiceProxy, JSONRPCException +from common.constants import MAINNET_RPC_PORT, TESTNET_RPC_PORT, REGTEST_RPC_PORT + """ Tools is a module with general methods that can used by different entities in the codebase. """ +# NOTCOVERED def bitcoin_cli(btc_connect_params): """ An ``http`` connection with ``bitcoind`` using the ``json-rpc`` interface. @@ -82,3 +85,27 @@ def in_correct_network(btc_connect_params, network): correct_network = True return correct_network + + +def get_default_rpc_port(network): + """ + Returns the default RPC port given a network name. + + Args: + network (:obj:`str`): the network name. Either ``mainnet``, ``testnet`` or ``regtest``. + + Returns: + :obj:`int`: The default RPC port depending on the given network name. + + Raises: + :obj:`ValueError`: If the network is not mainnet, testnet or regtest. + """ + + if network == "mainnet": + return MAINNET_RPC_PORT + elif network == "testnet": + return TESTNET_RPC_PORT + elif network == "regtest": + return REGTEST_RPC_PORT + else: + raise ValueError("Wrong Bitcoin network. Expected: mainnet, testnet or regtest. Received: {}".format(network))