Skip to content

Commit 3794dd5

Browse files
authored
refactor: move get settings [part 3] (#770)
1 parent 87ae52e commit 3794dd5

24 files changed

+96
-109
lines changed

hathor/cli/run_node.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -266,8 +266,8 @@ def check_unsafe_arguments(self) -> None:
266266
'',
267267
]
268268

269-
from hathor.conf import HathorSettings
270-
settings = HathorSettings()
269+
from hathor.conf.get_settings import get_settings
270+
settings = get_settings()
271271

272272
if self._args.unsafe_mode != settings.NETWORK_NAME:
273273
message.extend([

hathor/p2p/resources/mining_info.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,11 @@
1616

1717
from hathor.api_util import Resource, set_cors
1818
from hathor.cli.openapi_files.register import register_resource
19-
from hathor.conf import HathorSettings
19+
from hathor.conf.get_settings import get_settings
2020
from hathor.daa import get_mined_tokens
2121
from hathor.difficulty import Weight
2222
from hathor.util import json_dumpb
2323

24-
settings = HathorSettings()
25-
2624

2725
@register_resource
2826
class MiningInfoResource(Resource):
@@ -33,6 +31,7 @@ class MiningInfoResource(Resource):
3331
isLeaf = True
3432

3533
def __init__(self, manager):
34+
self._settings = get_settings()
3635
self.manager = manager
3736

3837
def render_GET(self, request):
@@ -48,7 +47,7 @@ def render_GET(self, request):
4847

4948
# We can use any address.
5049
burn_address = bytes.fromhex(
51-
settings.P2PKH_VERSION_BYTE.hex() + 'acbfb94571417423c1ed66f706730c4aea516ac5762cccb8'
50+
self._settings.P2PKH_VERSION_BYTE.hex() + 'acbfb94571417423c1ed66f706730c4aea516ac5762cccb8'
5251
)
5352
block = self.manager.generate_mining_block(address=burn_address)
5453

hathor/p2p/resources/status.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,10 @@
1717
import hathor
1818
from hathor.api_util import Resource, set_cors
1919
from hathor.cli.openapi_files.register import register_resource
20-
from hathor.conf import HathorSettings
20+
from hathor.conf.get_settings import get_settings
2121
from hathor.p2p.utils import to_serializable_best_blockchain
2222
from hathor.util import json_dumpb
2323

24-
settings = HathorSettings()
25-
2624

2725
@register_resource
2826
class StatusResource(Resource):
@@ -34,6 +32,7 @@ class StatusResource(Resource):
3432
isLeaf = True
3533

3634
def __init__(self, manager):
35+
self._settings = get_settings()
3736
self.manager = manager
3837

3938
def render_GET(self, request):
@@ -94,7 +93,7 @@ def render_GET(self, request):
9493
best_block_tips.append({'hash': tx.hash_hex, 'height': meta.height})
9594

9695
best_block = self.manager.tx_storage.get_best_block()
97-
raw_best_blockchain = self.manager.tx_storage.get_n_height_tips(settings.DEFAULT_BEST_BLOCKCHAIN_BLOCKS)
96+
raw_best_blockchain = self.manager.tx_storage.get_n_height_tips(self._settings.DEFAULT_BEST_BLOCKCHAIN_BLOCKS)
9897
best_blockchain = to_serializable_best_blockchain(raw_best_blockchain)
9998

10099
data = {

hathor/p2p/states/hello.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
from structlog import get_logger
1818

1919
import hathor
20-
from hathor.conf import HathorSettings
20+
from hathor.conf.get_settings import get_settings
2121
from hathor.exception import HathorError
2222
from hathor.p2p.messages import ProtocolMessages
2323
from hathor.p2p.states.base import BaseState
@@ -30,12 +30,11 @@
3030

3131
logger = get_logger()
3232

33-
settings = HathorSettings()
34-
3533

3634
class HelloState(BaseState):
3735
def __init__(self, protocol: 'HathorProtocol') -> None:
3836
super().__init__(protocol)
37+
self._settings = get_settings()
3938
self.log = logger.new(**protocol.get_logger_context())
4039
self.cmd_map.update({
4140
ProtocolMessages.HELLO: self.handle_hello,
@@ -103,7 +102,7 @@ def handle_hello(self, payload: str) -> None:
103102
protocol.send_error_and_close_connection('Invalid payload.')
104103
return
105104

106-
if settings.ENABLE_PEER_WHITELIST and settings.CAPABILITY_WHITELIST not in data['capabilities']:
105+
if self._settings.ENABLE_PEER_WHITELIST and self._settings.CAPABILITY_WHITELIST not in data['capabilities']:
107106
# If peer is not sending whitelist capability we must close the connection
108107
protocol.send_error_and_close_connection('Must have whitelist capability.')
109108
return
@@ -142,7 +141,7 @@ def handle_hello(self, payload: str) -> None:
142141
return
143142

144143
dt = data['timestamp'] - protocol.node.reactor.seconds()
145-
if abs(dt) > settings.MAX_FUTURE_TIMESTAMP_ALLOWED / 2:
144+
if abs(dt) > self._settings.MAX_FUTURE_TIMESTAMP_ALLOWED / 2:
146145
protocol.send_error_and_close_connection('Nodes timestamps too far apart.')
147146
return
148147

@@ -173,6 +172,7 @@ def handle_hello(self, payload: str) -> None:
173172

174173
def _parse_sync_versions(hello_data: dict[str, Any]) -> set[SyncVersion]:
175174
"""Versions that are not recognized will not be included."""
175+
settings = get_settings()
176176
if settings.CAPABILITY_SYNC_VERSION in hello_data['capabilities']:
177177
if 'sync_versions' not in hello_data:
178178
raise HathorError('protocol error, expected sync_versions field')

hathor/p2p/states/ready.py

+9-9
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
from structlog import get_logger
1919
from twisted.internet.task import LoopingCall
2020

21-
from hathor.conf import HathorSettings
21+
from hathor.conf.get_settings import get_settings
2222
from hathor.indexes.height_index import HeightInfo
2323
from hathor.p2p.messages import ProtocolMessages
2424
from hathor.p2p.peer_id import PeerId
@@ -33,12 +33,11 @@
3333

3434
logger = get_logger()
3535

36-
settings = HathorSettings()
37-
3836

3937
class ReadyState(BaseState):
4038
def __init__(self, protocol: 'HathorProtocol') -> None:
4139
super().__init__(protocol)
40+
self._settings = get_settings()
4241

4342
self.log = logger.new(**self.protocol.get_logger_context())
4443

@@ -79,7 +78,7 @@ def __init__(self, protocol: 'HathorProtocol') -> None:
7978

8079
# if the peer has the GET-BEST-BLOCKCHAIN capability
8180
common_capabilities = protocol.capabilities & set(protocol.node.capabilities)
82-
if (settings.CAPABILITY_GET_BEST_BLOCKCHAIN in common_capabilities):
81+
if (self._settings.CAPABILITY_GET_BEST_BLOCKCHAIN in common_capabilities):
8382
# set the loop to get the best blockchain from the peer
8483
self.lc_get_best_blockchain = LoopingCall(self.send_get_best_blockchain)
8584
self.lc_get_best_blockchain.clock = self.reactor
@@ -110,7 +109,7 @@ def on_enter(self) -> None:
110109
self.send_get_peers()
111110

112111
if self.lc_get_best_blockchain is not None:
113-
self.lc_get_best_blockchain.start(settings.BEST_BLOCKCHAIN_INTERVAL, now=False)
112+
self.lc_get_best_blockchain.start(self._settings.BEST_BLOCKCHAIN_INTERVAL, now=False)
114113

115114
self.sync_agent.start()
116115

@@ -209,11 +208,12 @@ def handle_pong(self, payload: str) -> None:
209208
self.ping_start_time = None
210209
self.log.debug('rtt updated', rtt=self.ping_rtt, min_rtt=self.ping_min_rtt)
211210

212-
def send_get_best_blockchain(self, n_blocks: int = settings.DEFAULT_BEST_BLOCKCHAIN_BLOCKS) -> None:
211+
def send_get_best_blockchain(self, n_blocks: Optional[int] = None) -> None:
213212
""" Send a GET-BEST-BLOCKCHAIN command, requesting a list of the latest
214213
N blocks from the best blockchain.
215214
"""
216-
self.send_message(ProtocolMessages.GET_BEST_BLOCKCHAIN, str(n_blocks))
215+
actual_n_blocks: int = n_blocks if n_blocks is not None else self._settings.DEFAULT_BEST_BLOCKCHAIN_BLOCKS
216+
self.send_message(ProtocolMessages.GET_BEST_BLOCKCHAIN, str(actual_n_blocks))
217217

218218
def handle_get_best_blockchain(self, payload: str) -> None:
219219
""" Executed when a GET-BEST-BLOCKCHAIN command is received.
@@ -228,9 +228,9 @@ def handle_get_best_blockchain(self, payload: str) -> None:
228228
)
229229
return
230230

231-
if not (0 < n_blocks <= settings.MAX_BEST_BLOCKCHAIN_BLOCKS):
231+
if not (0 < n_blocks <= self._settings.MAX_BEST_BLOCKCHAIN_BLOCKS):
232232
self.protocol.send_error_and_close_connection(
233-
f'N out of bounds. Valid range: [1, {settings.MAX_BEST_BLOCKCHAIN_BLOCKS}].'
233+
f'N out of bounds. Valid range: [1, {self._settings.MAX_BEST_BLOCKCHAIN_BLOCKS}].'
234234
)
235235
return
236236

hathor/transaction/resources/dashboard.py

+4-5
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,9 @@
1414

1515
from hathor.api_util import Resource, get_args, get_missing_params_msg, parse_args, parse_int, set_cors
1616
from hathor.cli.openapi_files.register import register_resource
17-
from hathor.conf import HathorSettings
17+
from hathor.conf.get_settings import get_settings
1818
from hathor.util import json_dumpb
1919

20-
settings = HathorSettings()
21-
2220
ARGS = ['block', 'tx']
2321

2422

@@ -33,6 +31,7 @@ class DashboardTransactionResource(Resource):
3331

3432
def __init__(self, manager):
3533
# Important to have the manager so we can know the tx_storage
34+
self._settings = get_settings()
3635
self.manager = manager
3736

3837
def render_GET(self, request):
@@ -69,8 +68,8 @@ def render_GET(self, request):
6968
})
7069

7170
# Restrict counts
72-
block_count = min(block_count, settings.MAX_DASHBOARD_COUNT)
73-
tx_count = min(tx_count, settings.MAX_DASHBOARD_COUNT)
71+
block_count = min(block_count, self._settings.MAX_DASHBOARD_COUNT)
72+
tx_count = min(tx_count, self._settings.MAX_DASHBOARD_COUNT)
7473

7574
transactions, _ = self.manager.tx_storage.get_newest_txs(count=tx_count)
7675
serialized_tx = [tx.to_json_extended() for tx in transactions]

hathor/transaction/resources/mempool.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,10 @@
1818

1919
from hathor.api_util import Resource, get_args, parse_args, set_cors
2020
from hathor.cli.openapi_files.register import register_resource
21-
from hathor.conf import HathorSettings
21+
from hathor.conf.get_settings import get_settings
2222
from hathor.transaction import Transaction
2323
from hathor.util import json_dumpb
2424

25-
settings = HathorSettings()
26-
2725
if TYPE_CHECKING:
2826
from twisted.web.http import Request
2927

@@ -46,6 +44,7 @@ class MempoolResource(Resource):
4644

4745
def __init__(self, manager: 'HathorManager'):
4846
# Important to have the manager so we can know the tx_storage
47+
self._settings = get_settings()
4948
self.manager = manager
5049

5150
def render_GET(self, request: 'Request') -> bytes:
@@ -82,7 +81,7 @@ def render_GET(self, request: 'Request') -> bytes:
8281
sorted(list(self._get_from_index(index_source)), key=lambda tx: tx.timestamp),
8382
)
8483
# Only return up to settings.MEMPOOL_API_TX_LIMIT txs per call (default: 100)
85-
data = {'success': True, 'transactions': list(islice(tx_ids, settings.MEMPOOL_API_TX_LIMIT))}
84+
data = {'success': True, 'transactions': list(islice(tx_ids, self._settings.MEMPOOL_API_TX_LIMIT))}
8685
return json_dumpb(data)
8786

8887
def _get_from_index(self, index_source: IndexSource) -> Iterator[Transaction]:

hathor/transaction/resources/push_tx.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121

2222
from hathor.api_util import Resource, get_args, parse_args, render_options, set_cors
2323
from hathor.cli.openapi_files.register import register_resource
24-
from hathor.conf import HathorSettings
24+
from hathor.conf.get_settings import get_settings
2525
from hathor.exception import InvalidNewTransaction
2626
from hathor.transaction import Transaction
2727
from hathor.transaction.base_transaction import tx_or_block_from_bytes
@@ -31,7 +31,6 @@
3131
if TYPE_CHECKING:
3232
from hathor.manager import HathorManager
3333

34-
settings = HathorSettings()
3534
logger = get_logger()
3635

3736
ARGS = ['hex_tx']
@@ -47,11 +46,12 @@ class PushTxResource(Resource):
4746

4847
def __init__(self, manager: 'HathorManager', max_output_script_size: Optional[int] = None,
4948
allow_non_standard_script: bool = False) -> None:
49+
self._settings = get_settings()
5050
self.log = logger.new()
5151
# Important to have the manager so we can know the tx_storage
5252
self.manager = manager
5353
self.max_output_script_size: int = (
54-
settings.PUSHTX_MAX_OUTPUT_SCRIPT_SIZE
54+
self._settings.PUSHTX_MAX_OUTPUT_SCRIPT_SIZE
5555
if max_output_script_size is None else
5656
max_output_script_size
5757
)

hathor/transaction/resources/transaction.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,11 @@
2424
validate_tx_hash,
2525
)
2626
from hathor.cli.openapi_files.register import register_resource
27-
from hathor.conf import HathorSettings
27+
from hathor.conf.get_settings import get_settings
2828
from hathor.transaction.base_transaction import BaseTransaction, TxVersion
2929
from hathor.transaction.token_creation_tx import TokenCreationTransaction
3030
from hathor.util import json_dumpb
3131

32-
settings = HathorSettings()
33-
3432
GET_LIST_ARGS = ['count', 'type']
3533

3634

@@ -51,6 +49,7 @@ def get_tx_extra_data(tx: BaseTransaction, *, detail_tokens: bool = True) -> dic
5149
assert tx.storage is not None
5250
assert tx.storage.indexes is not None
5351

52+
settings = get_settings()
5453
serialized = tx.to_json(decode_script=True)
5554
serialized['raw'] = tx.get_struct().hex()
5655
serialized['nonce'] = str(tx.nonce)
@@ -206,6 +205,7 @@ def get_list_tx(self, request):
206205
'timestamp': int, the timestamp reference we are in the pagination
207206
'page': 'previous' or 'next', to indicate if the user wants after or before the hash reference
208207
"""
208+
settings = get_settings()
209209
raw_args = get_args(request)
210210
parsed = parse_args(raw_args, GET_LIST_ARGS)
211211
if not parsed['success']:

hathor/transaction/resources/utxo_search.py

+3-5
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
set_cors,
2525
)
2626
from hathor.cli.openapi_files.register import register_resource
27-
from hathor.conf import HathorSettings
27+
from hathor.conf.get_settings import get_settings
2828
from hathor.crypto.util import decode_address
2929
from hathor.util import json_dumpb
3030
from hathor.wallet.exceptions import InvalidAddress
@@ -35,9 +35,6 @@
3535
from hathor.manager import HathorManager
3636

3737

38-
settings = HathorSettings()
39-
40-
4138
@register_resource
4239
class UtxoSearchResource(Resource):
4340
""" Implements a web server API to return a list of UTXOs that fit a given search criteria.
@@ -48,6 +45,7 @@ class UtxoSearchResource(Resource):
4845

4946
def __init__(self, manager: 'HathorManager'):
5047
# Important to have the manager so we can know the tx_storage
48+
self._settings = get_settings()
5149
self.manager = manager
5250

5351
def render_GET(self, request: 'Request') -> bytes:
@@ -86,7 +84,7 @@ def render_GET(self, request: 'Request') -> bytes:
8684
# token_uid parameter must be a valid hash
8785
try:
8886
token_uid = bytes.fromhex(args['token_uid'])
89-
if token_uid != settings.HATHOR_TOKEN_UID and len(token_uid) != 32:
87+
if token_uid != self._settings.HATHOR_TOKEN_UID and len(token_uid) != 32:
9088
raise ValueError('not a valid hash length')
9189
except ValueError as e:
9290
return json_dumpb({

0 commit comments

Comments
 (0)