general - Adds default RPC port based on network param

This commit is contained in:
Sergi Delgado Segura
2020-06-11 15:59:08 +02:00
parent 4621a08dc5
commit 782806595c
6 changed files with 66 additions and 27 deletions

View File

@@ -54,14 +54,13 @@ By default, `teos` runs on `mainnet`. In order to run it on another network you
### Modifying the configuration file ### 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] [bitcoind]
btc_rpc_user = "user" btc_rpc_user = "user"
btc_rpc_password = "passwd" btc_rpc_password = "passwd"
btc_rpc_connect = "localhost" btc_rpc_connect = "localhost"
btc_rpc_port = 8332
btc_network = "mainnet" btc_network = "mainnet"
``` ```
@@ -72,7 +71,6 @@ For regtest, it should look like:
btc_rpc_user = "user" btc_rpc_user = "user"
btc_rpc_password = "passwd" btc_rpc_password = "passwd"
btc_rpc_connect = "localhost" btc_rpc_connect = "localhost"
btc_rpc_port = 18443
btc_network = "regtest" btc_network = "regtest"
``` ```

View File

@@ -31,6 +31,7 @@ class ConfigLoader:
self.conf_file_path = os.path.join(self.data_dir, conf_file_name) self.conf_file_path = os.path.join(self.data_dir, conf_file_name)
self.conf_fields = default_conf self.conf_fields = default_conf
self.command_line_conf = command_line_conf self.command_line_conf = command_line_conf
self.overwritten_fields = set()
def build_config(self): def build_config(self):
""" """
@@ -43,7 +44,6 @@ class ConfigLoader:
Returns: Returns:
:obj:`dict`: a dictionary containing all the configuration parameters. :obj:`dict`: a dictionary containing all the configuration parameters.
""" """
if os.path.exists(self.conf_file_path): if os.path.exists(self.conf_file_path):
@@ -65,9 +65,12 @@ class ConfigLoader:
else: else:
self.conf_fields[k_upper]["value"] = v self.conf_fields[k_upper]["value"] = v
self.overwritten_fields.add(k_upper)
# Override the command line parameters to the defaults / conf file # Override the command line parameters to the defaults / conf file
for k, v in self.command_line_conf.items(): for k, v in self.command_line_conf.items():
self.conf_fields[k]["value"] = v self.conf_fields[k]["value"] = v
self.overwritten_fields.add(k)
# Extend relative paths # Extend relative paths
self.extend_paths() self.extend_paths()

View File

@@ -8,6 +8,11 @@ HTTP_BAD_REQUEST = 400
HTTP_NOT_FOUND = 404 HTTP_NOT_FOUND = 404
HTTP_SERVICE_UNAVAILABLE = 503 HTTP_SERVICE_UNAVAILABLE = 503
# Bitcoin
MAINNET_RPC_PORT = 8332
TESTNET_RPC_PORT = 18332
REGTEST_RPC_PORT = 18443
# LN general nomenclature # LN general nomenclature
IRREVOCABLY_RESOLVED = 100 IRREVOCABLY_RESOLVED = 100

View File

@@ -1,4 +1,5 @@
import os import os
from common.constants import MAINNET_RPC_PORT
DATA_DIR = os.path.expanduser("~/.teos/") DATA_DIR = os.path.expanduser("~/.teos/")
CONF_FILE_NAME = "teos.conf" CONF_FILE_NAME = "teos.conf"
@@ -11,7 +12,7 @@ DEFAULT_CONF = {
"BTC_RPC_USER": {"value": "user", "type": str}, "BTC_RPC_USER": {"value": "user", "type": str},
"BTC_RPC_PASSWORD": {"value": "passwd", "type": str}, "BTC_RPC_PASSWORD": {"value": "passwd", "type": str},
"BTC_RPC_CONNECT": {"value": "127.0.0.1", "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_NETWORK": {"value": "mainnet", "type": str},
"BTC_FEED_PROTOCOL": {"value": "tcp", "type": str}, "BTC_FEED_PROTOCOL": {"value": "tcp", "type": str},
"BTC_FEED_CONNECT": {"value": "localhost", "type": str}, "BTC_FEED_CONNECT": {"value": "localhost", "type": str},

View File

@@ -20,8 +20,8 @@ from teos.gatekeeper import Gatekeeper
from teos.chain_monitor import ChainMonitor from teos.chain_monitor import ChainMonitor
from teos.block_processor import BlockProcessor from teos.block_processor import BlockProcessor
from teos.appointments_dbm import AppointmentsDBM 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 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) logger = Logger(actor="Daemon", log_name_prefix=LOG_PREFIX)
@@ -38,30 +38,35 @@ def handle_signals(signal_received, frame):
def main(command_line_conf): def main(command_line_conf):
global db_manager, chain_monitor global db_manager, chain_monitor
signal(SIGINT, handle_signals) try:
signal(SIGTERM, handle_signals) signal(SIGINT, handle_signals)
signal(SIGQUIT, handle_signals) signal(SIGTERM, handle_signals)
signal(SIGQUIT, handle_signals)
# Loads config and sets up the data folder and log file # 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 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_loader = ConfigLoader(data_dir, CONF_FILE_NAME, DEFAULT_CONF, command_line_conf)
config = config_loader.build_config() config = config_loader.build_config()
setup_data_folder(data_dir)
setup_logging(config.get("LOG_FILE"), LOG_PREFIX)
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")} setup_data_folder(data_dir)
bitcoind_feed_params = {k: v for k, v in config.items() if k.startswith("BTC_FEED")} setup_logging(config.get("LOG_FILE"), LOG_PREFIX)
if not can_connect_to_bitcoind(bitcoind_connect_params): logger.info("Starting TEOS")
logger.error("Cannot connect to bitcoind. Shutting down")
elif not in_correct_network(bitcoind_connect_params, config.get("BTC_NETWORK")): bitcoind_connect_params = {k: v for k, v in config.items() if k.startswith("BTC")}
logger.error("bitcoind is running on a different network, check conf.py and bitcoin.conf. Shutting down") bitcoind_feed_params = {k: v for k, v in config.items() if k.startswith("BTC_FEED")}
else: if not can_connect_to_bitcoind(bitcoind_connect_params):
try: 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")) secret_key_der = Cryptographer.load_key_file(config.get("TEOS_SECRET_KEY"))
if not secret_key_der: if not secret_key_der:
raise IOError("TEOS private key cannot be loaded") raise IOError("TEOS private key cannot be loaded")
@@ -160,9 +165,9 @@ def main(command_line_conf):
chain_monitor.monitor_chain() chain_monitor.monitor_chain()
inspector = Inspector(block_processor, config.get("MIN_TO_SELF_DELAY")) inspector = Inspector(block_processor, config.get("MIN_TO_SELF_DELAY"))
API(config.get("API_BIND"), config.get("API_PORT"), inspector, watcher).start() API(config.get("API_BIND"), config.get("API_PORT"), inspector, watcher).start()
except Exception as e: except Exception as e:
logger.error("An error occurred: {}. Shutting down".format(e)) logger.error("An error occurred: {}. Shutting down".format(e))
exit(1) exit(1)
if __name__ == "__main__": if __name__ == "__main__":

View File

@@ -3,11 +3,14 @@ from http.client import HTTPException
from teos.utils.auth_proxy import AuthServiceProxy, JSONRPCException 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. Tools is a module with general methods that can used by different entities in the codebase.
""" """
# NOTCOVERED
def bitcoin_cli(btc_connect_params): def bitcoin_cli(btc_connect_params):
""" """
An ``http`` connection with ``bitcoind`` using the ``json-rpc`` interface. 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 correct_network = True
return correct_network 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))