diff --git a/hathor/builder/builder.py b/hathor/builder/builder.py index 1c83b34942..0773347ed6 100644 --- a/hathor/builder/builder.py +++ b/hathor/builder/builder.py @@ -18,7 +18,7 @@ from structlog import get_logger from hathor.checkpoint import Checkpoint -from hathor.conf import HathorSettings +from hathor.conf.get_settings import get_settings from hathor.conf.settings import HathorSettings as HathorSettingsType from hathor.consensus import ConsensusAlgorithm from hathor.event import EventManager @@ -259,7 +259,7 @@ def set_peer_id(self, peer_id: PeerId) -> 'Builder': def _get_or_create_settings(self) -> HathorSettingsType: if self._settings is None: - self._settings = HathorSettings() + self._settings = get_settings() return self._settings def _get_reactor(self) -> Reactor: diff --git a/hathor/builder/cli_builder.py b/hathor/builder/cli_builder.py index d8760d46ee..d71a932a2f 100644 --- a/hathor/builder/cli_builder.py +++ b/hathor/builder/cli_builder.py @@ -56,8 +56,7 @@ def check_or_raise(self, condition: bool, message: str) -> None: def create_manager(self, reactor: Reactor) -> HathorManager: import hathor - from hathor.conf import HathorSettings - from hathor.conf.get_settings import get_settings_source + from hathor.conf.get_settings import get_settings, get_settings_source from hathor.daa import TestMode, _set_test_mode from hathor.event.storage import EventMemoryStorage, EventRocksDBStorage, EventStorage from hathor.event.websocket.factory import EventWebsocketFactory @@ -73,7 +72,7 @@ def create_manager(self, reactor: Reactor) -> HathorManager: ) from hathor.util import get_environment_info - settings = HathorSettings() + settings = get_settings() # only used for logging its location settings_source = get_settings_source() diff --git a/hathor/builder/resources_builder.py b/hathor/builder/resources_builder.py index f119b3f42f..5fb42ed0ae 100644 --- a/hathor/builder/resources_builder.py +++ b/hathor/builder/resources_builder.py @@ -77,7 +77,7 @@ def create_prometheus(self) -> PrometheusMetricsExporter: return prometheus def create_resources(self) -> server.Site: - from hathor.conf import HathorSettings + from hathor.conf.get_settings import get_settings from hathor.debug_resources import ( DebugCrashResource, DebugLogResource, @@ -141,7 +141,7 @@ def create_resources(self) -> server.Site: ) from hathor.websocket import HathorAdminWebsocketFactory, WebsocketStatsResource - settings = HathorSettings() + settings = get_settings() cpu = get_cpu_profiler() # TODO get this from a file. How should we do with the factory? diff --git a/hathor/cli/db_export.py b/hathor/cli/db_export.py index f2018d3954..1a13afd9e0 100644 --- a/hathor/cli/db_export.py +++ b/hathor/cli/db_export.py @@ -34,8 +34,8 @@ def register_signal_handlers(self) -> None: @classmethod def create_parser(cls) -> ArgumentParser: - from hathor.conf import HathorSettings - settings = HathorSettings() + from hathor.conf.get_settings import get_settings + settings = get_settings() def max_height(arg: str) -> Optional[int]: if arg.lower() == 'checkpoint': @@ -80,8 +80,8 @@ def prepare(self, *, register_resources: bool = True) -> None: self.skip_voided = self._args.export_skip_voided def iter_tx(self) -> Iterator['BaseTransaction']: - from hathor.conf import HathorSettings - settings = HathorSettings() + from hathor.conf.get_settings import get_settings + settings = get_settings() soft_voided_ids = set(settings.SOFT_VOIDED_TX_IDS) for tx in self._iter_tx: diff --git a/hathor/cli/events_simulator/scenario.py b/hathor/cli/events_simulator/scenario.py index db2b6db271..ea8f165286 100644 --- a/hathor/cli/events_simulator/scenario.py +++ b/hathor/cli/events_simulator/scenario.py @@ -51,10 +51,10 @@ def simulate_single_chain_one_block(simulator: 'Simulator', manager: 'HathorMana def simulate_single_chain_blocks_and_transactions(simulator: 'Simulator', manager: 'HathorManager') -> None: from hathor import daa - from hathor.conf import HathorSettings + from hathor.conf.get_settings import get_settings from tests.utils import add_new_blocks, gen_new_tx - settings = HathorSettings() + settings = get_settings() assert manager.wallet is not None address = manager.wallet.get_unused_address(mark_as_used=False) diff --git a/hathor/cli/nginx_config.py b/hathor/cli/nginx_config.py index d441a48427..18a6f4afe0 100644 --- a/hathor/cli/nginx_config.py +++ b/hathor/cli/nginx_config.py @@ -115,9 +115,9 @@ def generate_nginx_config(openapi: dict[str, Any], *, out_file: TextIO, rate_k: """ from datetime import datetime - from hathor.conf import HathorSettings + from hathor.conf.get_settings import get_settings - settings = HathorSettings() + settings = get_settings() api_prefix = settings.API_VERSION_PREFIX locations: dict[str, dict[str, Any]] = {} diff --git a/hathor/cli/run_node.py b/hathor/cli/run_node.py index f3198fc26b..b39cb02554 100644 --- a/hathor/cli/run_node.py +++ b/hathor/cli/run_node.py @@ -159,8 +159,8 @@ def prepare(self, *, register_resources: bool = True) -> None: assert self.manager.stratum_factory is not None self.reactor.listenTCP(self._args.stratum, self.manager.stratum_factory) - from hathor.conf import HathorSettings - settings = HathorSettings() + from hathor.conf.get_settings import get_settings + settings = get_settings() if register_resources: resources_builder = ResourcesBuilder( @@ -204,8 +204,8 @@ def start_sentry_if_possible(self) -> None: sys.exit(-3) import hathor - from hathor.conf import HathorSettings - settings = HathorSettings() + from hathor.conf.get_settings import get_settings + settings = get_settings() sentry_sdk.init( dsn=self._args.sentry_dsn, release=hathor.__version__, diff --git a/hathor/consensus/block_consensus.py b/hathor/consensus/block_consensus.py index 9ad148de41..18a6da20d6 100644 --- a/hathor/consensus/block_consensus.py +++ b/hathor/consensus/block_consensus.py @@ -17,7 +17,7 @@ from structlog import get_logger -from hathor.conf import HathorSettings +from hathor.conf.get_settings import get_settings from hathor.profiler import get_cpu_profiler from hathor.transaction import BaseTransaction, Block, Transaction, sum_weights from hathor.util import classproperty, not_none @@ -26,7 +26,6 @@ from hathor.consensus.context import ConsensusAlgorithmContext logger = get_logger() -settings = HathorSettings() cpu = get_cpu_profiler() _base_transaction_log = logger.new() @@ -36,6 +35,7 @@ class BlockConsensusAlgorithm: """Implement the consensus algorithm for blocks.""" def __init__(self, context: 'ConsensusAlgorithmContext') -> None: + self._settings = get_settings() self.context = context @classproperty @@ -149,7 +149,7 @@ def update_voided_info(self, block: Block) -> None: storage.indexes.height.add_new(block.get_height(), block.hash, block.timestamp) storage.update_best_block_tips_cache([block.hash]) # The following assert must be true, but it is commented out for performance reasons. - if settings.SLOW_ASSERTS: + if self._settings.SLOW_ASSERTS: assert len(storage.get_best_block_tips(skip_cache=True)) == 1 else: # Resolve all other cases, but (i). @@ -179,7 +179,7 @@ def update_voided_info(self, block: Block) -> None: score = self.calculate_score(block) # Finally, check who the winner is. - if score <= best_score - settings.WEIGHT_TOL: + if score <= best_score - self._settings.WEIGHT_TOL: # Just update voided_by from parents. self.update_voided_by_from_parents(block) @@ -200,7 +200,7 @@ def update_voided_info(self, block: Block) -> None: common_block = self._find_first_parent_in_best_chain(block) self.add_voided_by_to_multiple_chains(block, heads, common_block) - if score >= best_score + settings.WEIGHT_TOL: + if score >= best_score + self._settings.WEIGHT_TOL: # We have a new winner candidate. self.update_score_and_mark_as_the_best_chain_if_possible(block) # As `update_score_and_mark_as_the_best_chain_if_possible` may affect `voided_by`, @@ -294,10 +294,10 @@ def update_score_and_mark_as_the_best_chain_if_possible(self, block: Block) -> N best_heads: list[Block] for head in heads: head_meta = head.get_metadata(force_reload=True) - if head_meta.score <= best_score - settings.WEIGHT_TOL: + if head_meta.score <= best_score - self._settings.WEIGHT_TOL: continue - if head_meta.score >= best_score + settings.WEIGHT_TOL: + if head_meta.score >= best_score + self._settings.WEIGHT_TOL: best_heads = [head] best_score = head_meta.score else: diff --git a/hathor/consensus/consensus.py b/hathor/consensus/consensus.py index acf3c5d6fc..6ffe1acbad 100644 --- a/hathor/consensus/consensus.py +++ b/hathor/consensus/consensus.py @@ -14,7 +14,7 @@ from structlog import get_logger -from hathor.conf import HathorSettings +from hathor.conf.get_settings import get_settings from hathor.consensus.block_consensus import BlockConsensusAlgorithmFactory from hathor.consensus.context import ConsensusAlgorithmContext from hathor.consensus.transaction_consensus import TransactionConsensusAlgorithmFactory @@ -24,7 +24,6 @@ from hathor.util import not_none logger = get_logger() -settings = HathorSettings() cpu = get_cpu_profiler() _base_transaction_log = logger.new() @@ -57,6 +56,7 @@ class ConsensusAlgorithm: """ def __init__(self, soft_voided_tx_ids: set[bytes], pubsub: PubSubManager) -> None: + self._settings = get_settings() self.log = logger.new() self._pubsub = pubsub self.soft_voided_tx_ids = frozenset(soft_voided_tx_ids) @@ -76,7 +76,7 @@ def update(self, base: BaseTransaction) -> None: try: self._unsafe_update(base) except Exception: - meta.add_voided_by(settings.CONSENSUS_FAIL_ID) + meta.add_voided_by(self._settings.CONSENSUS_FAIL_ID) assert base.storage is not None base.storage.save_transaction(base, only_metadata=True) raise @@ -87,7 +87,7 @@ def _unsafe_update(self, base: BaseTransaction) -> None: # XXX: first make sure we can run the consensus update on this tx: meta = base.get_metadata() - assert meta.voided_by is None or (settings.PARTIALLY_VALIDATED_ID not in meta.voided_by) + assert meta.voided_by is None or (self._settings.PARTIALLY_VALIDATED_ID not in meta.voided_by) assert meta.validation.is_fully_connected() # this context instance will live only while this update is running @@ -152,9 +152,9 @@ def filter_out_soft_voided_entries(self, tx: BaseTransaction, voided_by: set[byt return voided_by ret = set() for h in voided_by: - if h == settings.SOFT_VOIDED_ID: + if h == self._settings.SOFT_VOIDED_ID: continue - if h == settings.CONSENSUS_FAIL_ID: + if h == self._settings.CONSENSUS_FAIL_ID: continue if h == tx.hash: continue diff --git a/hathor/consensus/context.py b/hathor/consensus/context.py index 0e74737ae3..5896ed5536 100644 --- a/hathor/consensus/context.py +++ b/hathor/consensus/context.py @@ -16,7 +16,6 @@ from structlog import get_logger -from hathor.conf import HathorSettings from hathor.profiler import get_cpu_profiler from hathor.pubsub import PubSubManager from hathor.transaction import BaseTransaction, Block @@ -27,7 +26,6 @@ from hathor.consensus.transaction_consensus import TransactionConsensusAlgorithm logger = get_logger() -settings = HathorSettings() cpu = get_cpu_profiler() _base_transaction_log = logger.new() diff --git a/hathor/consensus/transaction_consensus.py b/hathor/consensus/transaction_consensus.py index 78c4454d9f..0747c17530 100644 --- a/hathor/consensus/transaction_consensus.py +++ b/hathor/consensus/transaction_consensus.py @@ -16,7 +16,7 @@ from structlog import get_logger -from hathor.conf import HathorSettings +from hathor.conf.get_settings import get_settings from hathor.profiler import get_cpu_profiler from hathor.transaction import BaseTransaction, Block, Transaction, TxInput, sum_weights from hathor.util import classproperty @@ -25,7 +25,6 @@ from hathor.consensus.context import ConsensusAlgorithmContext logger = get_logger() -settings = HathorSettings() cpu = get_cpu_profiler() _base_transaction_log = logger.new() @@ -35,6 +34,7 @@ class TransactionConsensusAlgorithm: """Implement the consensus algorithm for transactions.""" def __init__(self, context: 'ConsensusAlgorithmContext') -> None: + self._settings = get_settings() self.context = context @classproperty @@ -180,7 +180,7 @@ def update_voided_info(self, tx: Transaction) -> None: parent_meta = parent.get_metadata() if parent_meta.voided_by: voided_by.update(self.context.consensus.filter_out_soft_voided_entries(parent, parent_meta.voided_by)) - assert settings.SOFT_VOIDED_ID not in voided_by + assert self._settings.SOFT_VOIDED_ID not in voided_by assert not (self.context.consensus.soft_voided_tx_ids & voided_by) # Union of voided_by of inputs @@ -189,13 +189,13 @@ def update_voided_info(self, tx: Transaction) -> None: spent_meta = spent_tx.get_metadata() if spent_meta.voided_by: voided_by.update(spent_meta.voided_by) - voided_by.discard(settings.SOFT_VOIDED_ID) - assert settings.SOFT_VOIDED_ID not in voided_by + voided_by.discard(self._settings.SOFT_VOIDED_ID) + assert self._settings.SOFT_VOIDED_ID not in voided_by # Update accumulated weight of the transactions voiding us. assert tx.hash not in voided_by for h in voided_by: - if h == settings.SOFT_VOIDED_ID: + if h == self._settings.SOFT_VOIDED_ID: continue tx2 = tx.storage.get_transaction(h) tx2_meta = tx2.get_metadata() @@ -207,7 +207,7 @@ def update_voided_info(self, tx: Transaction) -> None: assert not meta.voided_by or meta.voided_by == {tx.hash} assert meta.accumulated_weight == tx.weight if tx.hash in self.context.consensus.soft_voided_tx_ids: - voided_by.add(settings.SOFT_VOIDED_ID) + voided_by.add(self._settings.SOFT_VOIDED_ID) voided_by.add(tx.hash) if meta.conflict_with: voided_by.add(tx.hash) @@ -221,7 +221,7 @@ def update_voided_info(self, tx: Transaction) -> None: # Check conflicts of the transactions voiding us. for h in voided_by: - if h == settings.SOFT_VOIDED_ID: + if h == self._settings.SOFT_VOIDED_ID: continue if h == tx.hash: continue @@ -300,7 +300,7 @@ def check_conflicts(self, tx: Transaction) -> None: candidate.update_accumulated_weight(stop_value=meta.accumulated_weight) tx_meta = candidate.get_metadata() d = tx_meta.accumulated_weight - meta.accumulated_weight - if abs(d) < settings.WEIGHT_TOL: + if abs(d) < self._settings.WEIGHT_TOL: tie_list.append(candidate) elif d > 0: is_highest = False diff --git a/hathor/crypto/util.py b/hathor/crypto/util.py index 128ec0be1a..9bf4bad897 100644 --- a/hathor/crypto/util.py +++ b/hathor/crypto/util.py @@ -27,11 +27,9 @@ load_der_private_key, ) -from hathor.conf import HathorSettings +from hathor.conf.get_settings import get_settings from hathor.util import not_none -settings = HathorSettings() - _BACKEND = default_backend() @@ -119,8 +117,7 @@ def get_address_b58_from_public_key_hash(public_key_hash: bytes) -> str: return base58.b58encode(address).decode('utf-8') -def get_address_from_public_key_hash(public_key_hash: bytes, - version_byte: bytes = settings.P2PKH_VERSION_BYTE) -> bytes: +def get_address_from_public_key_hash(public_key_hash: bytes, version_byte: Optional[bytes] = None) -> bytes: """Gets the address in bytes from the public key hash :param public_key_hash: hash of public key (sha256 and ripemd160) @@ -132,9 +129,11 @@ def get_address_from_public_key_hash(public_key_hash: bytes, :return: address in bytes :rtype: bytes """ + settings = get_settings() address = b'' + actual_version_byte: bytes = version_byte if version_byte is not None else settings.P2PKH_VERSION_BYTE # Version byte - address += version_byte + address += actual_version_byte # Pubkey hash address += public_key_hash checksum = get_checksum(address) @@ -200,8 +199,7 @@ def get_public_key_from_bytes_compressed(public_key_bytes: bytes) -> ec.Elliptic return ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256K1(), public_key_bytes) -def get_address_b58_from_redeem_script_hash(redeem_script_hash: bytes, - version_byte: bytes = settings.MULTISIG_VERSION_BYTE) -> str: +def get_address_b58_from_redeem_script_hash(redeem_script_hash: bytes, version_byte: Optional[bytes] = None) -> str: """Gets the b58 address from the hash of the redeem script in multisig. :param redeem_script_hash: hash of the redeem script (sha256 and ripemd160) @@ -210,12 +208,13 @@ def get_address_b58_from_redeem_script_hash(redeem_script_hash: bytes, :return: address in base 58 :rtype: string """ - address = get_address_from_redeem_script_hash(redeem_script_hash, version_byte) + settings = get_settings() + actual_version_byte: bytes = version_byte if version_byte is not None else settings.MULTISIG_VERSION_BYTE + address = get_address_from_redeem_script_hash(redeem_script_hash, actual_version_byte) return base58.b58encode(address).decode('utf-8') -def get_address_from_redeem_script_hash(redeem_script_hash: bytes, - version_byte: bytes = settings.MULTISIG_VERSION_BYTE) -> bytes: +def get_address_from_redeem_script_hash(redeem_script_hash: bytes, version_byte: Optional[bytes] = None) -> bytes: """Gets the address in bytes from the redeem script hash :param redeem_script_hash: hash of redeem script (sha256 and ripemd160) @@ -227,9 +226,11 @@ def get_address_from_redeem_script_hash(redeem_script_hash: bytes, :return: address in bytes :rtype: bytes """ + settings = get_settings() + actual_version_byte: bytes = version_byte if version_byte is not None else settings.MULTISIG_VERSION_BYTE address = b'' # Version byte - address += version_byte + address += actual_version_byte # redeem script hash address += redeem_script_hash checksum = get_checksum(address) diff --git a/hathor/graphviz.py b/hathor/graphviz.py index f0abe04fe3..3e06bed8bf 100644 --- a/hathor/graphviz.py +++ b/hathor/graphviz.py @@ -18,16 +18,15 @@ from graphviz import Digraph -from hathor.conf import HathorSettings +from hathor.conf.get_settings import get_settings from hathor.transaction import BaseTransaction from hathor.transaction.storage import TransactionStorage -settings = HathorSettings() - class GraphvizVisualizer: def __init__(self, storage: TransactionStorage, include_funds: bool = False, include_verifications: bool = False, only_blocks: bool = False): + self._settings = get_settings() self.storage = storage # Indicate whether it should show fund edges @@ -92,7 +91,7 @@ def get_node_attrs(self, tx: BaseTransaction) -> dict[str, str]: if meta.voided_by and len(meta.voided_by) > 0: if meta.voided_by and tx.hash in meta.voided_by: node_attrs.update(self.conflict_attrs) - if settings.SOFT_VOIDED_ID in meta.voided_by: + if self._settings.SOFT_VOIDED_ID in meta.voided_by: node_attrs.update(self.soft_voided_attrs) else: node_attrs.update(self.voided_attrs) diff --git a/hathor/indexes/rocksdb_height_index.py b/hathor/indexes/rocksdb_height_index.py index 72964f7540..512606de8d 100644 --- a/hathor/indexes/rocksdb_height_index.py +++ b/hathor/indexes/rocksdb_height_index.py @@ -16,14 +16,12 @@ from structlog import get_logger -from hathor.conf import HathorSettings from hathor.indexes.height_index import BLOCK_GENESIS_ENTRY, HeightIndex, HeightInfo, IndexEntry from hathor.indexes.rocksdb_utils import RocksDBIndexUtils if TYPE_CHECKING: # pragma: no cover import rocksdb -settings = HathorSettings() logger = get_logger() _CF_NAME_HEIGHT_INDEX = b'height-index' diff --git a/hathor/indexes/rocksdb_tokens_index.py b/hathor/indexes/rocksdb_tokens_index.py index 2f001610d0..575b44f376 100644 --- a/hathor/indexes/rocksdb_tokens_index.py +++ b/hathor/indexes/rocksdb_tokens_index.py @@ -18,7 +18,7 @@ from structlog import get_logger -from hathor.conf import HathorSettings +from hathor.conf.get_settings import get_settings from hathor.indexes.rocksdb_utils import ( InternalUid, RocksDBIndexUtils, @@ -34,7 +34,6 @@ if TYPE_CHECKING: # pragma: no cover import rocksdb -settings = HathorSettings() logger = get_logger() _CF_NAME_TOKENS_INDEX = b'tokens-index' @@ -86,6 +85,7 @@ class RocksDBTokensIndex(TokensIndex, RocksDBIndexUtils): """ def __init__(self, db: 'rocksdb.DB', *, cf_name: Optional[bytes] = None) -> None: + self._settings = get_settings() self.log = logger.new() RocksDBIndexUtils.__init__(self, db, cf_name or _CF_NAME_TOKENS_INDEX) @@ -219,16 +219,16 @@ def _remove_authority_utxo(self, token_uid: bytes, tx_hash: bytes, index: int, * def _create_genesis_info(self) -> None: self._create_token_info( - settings.HATHOR_TOKEN_UID, - settings.HATHOR_TOKEN_NAME, - settings.HATHOR_TOKEN_SYMBOL, - settings.GENESIS_TOKENS, + self._settings.HATHOR_TOKEN_UID, + self._settings.HATHOR_TOKEN_NAME, + self._settings.HATHOR_TOKEN_SYMBOL, + self._settings.GENESIS_TOKENS, ) def _add_to_total(self, token_uid: bytes, amount: int) -> None: key_info = self._to_key_info(token_uid) old_value_info = self._db.get((self._cf, key_info)) - if token_uid == settings.HATHOR_TOKEN_UID and old_value_info is None: + if token_uid == self._settings.HATHOR_TOKEN_UID and old_value_info is None: self._create_genesis_info() old_value_info = self._db.get((self._cf, key_info)) assert old_value_info is not None @@ -240,7 +240,7 @@ def _add_to_total(self, token_uid: bytes, amount: int) -> None: def _subtract_from_total(self, token_uid: bytes, amount: int) -> None: key_info = self._to_key_info(token_uid) old_value_info = self._db.get((self._cf, key_info)) - if token_uid == settings.HATHOR_TOKEN_UID and old_value_info is None: + if token_uid == self._settings.HATHOR_TOKEN_UID and old_value_info is None: self._create_genesis_info() old_value_info = self._db.get((self._cf, key_info)) assert old_value_info is not None diff --git a/hathor/indexes/rocksdb_utils.py b/hathor/indexes/rocksdb_utils.py index 87fddcb542..8ce19ba39c 100644 --- a/hathor/indexes/rocksdb_utils.py +++ b/hathor/indexes/rocksdb_utils.py @@ -15,15 +15,13 @@ from collections.abc import Collection from typing import TYPE_CHECKING, Iterable, Iterator, NewType -from hathor.conf import HathorSettings +from hathor.conf.get_settings import get_settings if TYPE_CHECKING: # pragma: no cover import rocksdb import structlog -settings = HathorSettings() - # the following type is used to help a little bit to distinguish when we're using a byte sequence that should only be # internally used InternalUid = NewType('InternalUid', bytes) @@ -32,6 +30,7 @@ def to_internal_token_uid(token_uid: bytes) -> InternalUid: """Normalizes a token_uid so that the native token (\x00) will have the same length as custom tokens.""" + settings = get_settings() if token_uid == settings.HATHOR_TOKEN_UID: return _INTERNAL_HATHOR_TOKEN_UID assert len(token_uid) == 32 @@ -41,6 +40,7 @@ def to_internal_token_uid(token_uid: bytes) -> InternalUid: def from_internal_token_uid(token_uid: InternalUid) -> bytes: """De-normalizes the token_uid so that the native token is b'\x00' as expected""" assert len(token_uid) == 32 + settings = get_settings() if token_uid == _INTERNAL_HATHOR_TOKEN_UID: return settings.HATHOR_TOKEN_UID return token_uid diff --git a/hathor/indexes/utxo_index.py b/hathor/indexes/utxo_index.py index f99a62c51d..5b1cf34eec 100644 --- a/hathor/indexes/utxo_index.py +++ b/hathor/indexes/utxo_index.py @@ -18,7 +18,7 @@ from structlog import get_logger -from hathor.conf import HathorSettings +from hathor.conf.get_settings import get_settings from hathor.indexes.base_index import BaseIndex from hathor.indexes.scope import Scope from hathor.transaction import BaseTransaction, Block, TxOutput @@ -26,7 +26,6 @@ from hathor.util import sorted_merger logger = get_logger() -settings = HathorSettings() SCOPE = Scope( include_blocks=True, @@ -61,6 +60,7 @@ def __repr__(self): @classmethod def from_tx_output(cls, tx: BaseTransaction, index: int, tx_output: TxOutput) -> 'UtxoIndexItem': assert tx.hash is not None + settings = get_settings() if tx_output.is_token_authority(): raise ValueError('UtxoIndexItem cannot be used with a token authority output') @@ -206,6 +206,7 @@ def iter_utxos(self, *, address: str, target_amount: int, token_uid: Optional[by target_height: Optional[int] = None) -> Iterator[UtxoIndexItem]: """ Search UTXOs for a given token_uid+address+target_value, if no token_uid is given, HTR is assumed. """ + settings = get_settings() actual_token_uid = token_uid if token_uid is not None else settings.HATHOR_TOKEN_UID iter_nolock = self._iter_utxos_nolock(token_uid=actual_token_uid, address=address, target_amount=target_amount) diff --git a/hathor/merged_mining/coordinator.py b/hathor/merged_mining/coordinator.py index 0c32cf9853..61c9c2a650 100644 --- a/hathor/merged_mining/coordinator.py +++ b/hathor/merged_mining/coordinator.py @@ -28,7 +28,6 @@ from structlog import get_logger from hathor.client import IHathorClient, IMiningChannel -from hathor.conf import HathorSettings from hathor.crypto.util import decode_address from hathor.difficulty import Hash, PDiff, Target, Weight from hathor.merged_mining.bitcoin import ( @@ -51,7 +50,6 @@ from hathor.util import MaxSizeOrderedDict, Random, ichunks logger = get_logger() -settings = HathorSettings() MAGIC_NUMBER = b'Hath' # bytes.fromhex('48617468') or 0x68746148.to_bytes(4, 'little') diff --git a/hathor/mining/ws.py b/hathor/mining/ws.py index acd040ace1..e4839f525b 100644 --- a/hathor/mining/ws.py +++ b/hathor/mining/ws.py @@ -22,14 +22,12 @@ from autobahn.twisted.websocket import WebSocketServerFactory, WebSocketServerProtocol from structlog import get_logger -from hathor.conf import HathorSettings from hathor.manager import HathorManager from hathor.pubsub import EventArguments, HathorEvents from hathor.transaction.base_transaction import tx_or_block_from_bytes from hathor.util import json_dumpb, json_loadb logger = get_logger() -settings = HathorSettings() JsonRpcId = Union[str, int, float] JsonValue = Optional[Union[dict[str, Any], list[Any], str, int, float]] diff --git a/hathor/p2p/peer_id.py b/hathor/p2p/peer_id.py index ad313dde1d..612459e7a3 100644 --- a/hathor/p2p/peer_id.py +++ b/hathor/p2p/peer_id.py @@ -28,14 +28,12 @@ from twisted.internet.ssl import Certificate, CertificateOptions, TLSVersion, trustRootFromCertificates from hathor import daa -from hathor.conf import HathorSettings +from hathor.conf.get_settings import get_settings from hathor.p2p.utils import connection_string_to_host, discover_dns, generate_certificate if TYPE_CHECKING: from hathor.p2p.protocol import HathorProtocol # noqa: F401 -settings = HathorSettings() - class InvalidPeerIdException(Exception): pass @@ -66,6 +64,7 @@ class PeerId: flags: set[str] def __init__(self, auto_generate_keys: bool = True) -> None: + self._settings = get_settings() self.id = None self.private_key = None self.public_key = None @@ -255,9 +254,9 @@ def increment_retry_attempt(self, now: int) -> None: """ self.retry_timestamp = now + self.retry_interval self.retry_attempts += 1 - self.retry_interval = self.retry_interval * settings.PEER_CONNECTION_RETRY_INTERVAL_MULTIPLIER - if self.retry_interval > settings.PEER_CONNECTION_RETRY_MAX_RETRY_INTERVAL: - self.retry_interval = settings.PEER_CONNECTION_RETRY_MAX_RETRY_INTERVAL + self.retry_interval = self.retry_interval * self._settings.PEER_CONNECTION_RETRY_INTERVAL_MULTIPLIER + if self.retry_interval > self._settings.PEER_CONNECTION_RETRY_MAX_RETRY_INTERVAL: + self.retry_interval = self._settings.PEER_CONNECTION_RETRY_MAX_RETRY_INTERVAL def reset_retry_timestamp(self) -> None: """ Resets retry values. @@ -279,7 +278,11 @@ def can_retry(self, now: int) -> bool: def get_certificate(self) -> x509.Certificate: if not self.certificate: assert self.private_key is not None - certificate = generate_certificate(self.private_key, settings.CA_FILEPATH, settings.CA_KEY_FILEPATH) + certificate = generate_certificate( + self.private_key, + self._settings.CA_FILEPATH, + self._settings.CA_KEY_FILEPATH + ) self.certificate = certificate return self.certificate @@ -300,7 +303,7 @@ def _get_certificate_options(self) -> CertificateOptions: assert self.private_key is not None openssl_pkey = PKey.from_cryptography_key(self.private_key) - with open(settings.CA_FILEPATH, 'rb') as f: + with open(self._settings.CA_FILEPATH, 'rb') as f: ca = x509.load_pem_x509_certificate(data=f.read(), backend=default_backend()) openssl_ca = X509.from_cryptography(ca) diff --git a/hathor/p2p/protocol.py b/hathor/p2p/protocol.py index f2d729c871..822973bedc 100644 --- a/hathor/p2p/protocol.py +++ b/hathor/p2p/protocol.py @@ -23,7 +23,7 @@ from twisted.protocols.basic import LineReceiver from twisted.python.failure import Failure -from hathor.conf import HathorSettings +from hathor.conf.get_settings import get_settings from hathor.p2p.messages import ProtocolMessages from hathor.p2p.peer_id import PeerId from hathor.p2p.rate_limiter import RateLimiter @@ -36,7 +36,6 @@ from hathor.manager import HathorManager # noqa: F401 from hathor.p2p.manager import ConnectionsManager # noqa: F401 -settings = HathorSettings() logger = get_logger() cpu = get_cpu_profiler() @@ -94,6 +93,7 @@ class WarningFlags(str, Enum): def __init__(self, network: str, my_peer: PeerId, p2p_manager: 'ConnectionsManager', *, use_ssl: bool, inbound: bool) -> None: + self._settings = get_settings() self.network = network self.my_peer = my_peer self.connections = p2p_manager @@ -108,7 +108,7 @@ def __init__(self, network: str, my_peer: PeerId, p2p_manager: 'ConnectionsManag self.inbound = inbound # Maximum period without receiving any messages. - self.idle_timeout = settings.PEER_IDLE_TIMEOUT + self.idle_timeout = self._settings.PEER_IDLE_TIMEOUT self._idle_timeout_call_later: Optional[IDelayedCall] = None self._state_instances = {}