Skip to content

Commit 88c0162

Browse files
committed
refactor(daa): remove global daa test mode
1 parent 22c4e78 commit 88c0162

14 files changed

+52
-58
lines changed

hathor/builder/cli_builder.py

+8-7
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ def check_or_raise(self, condition: bool, message: str) -> None:
5959
def create_manager(self, reactor: Reactor) -> HathorManager:
6060
import hathor
6161
from hathor.conf.get_settings import get_settings, get_settings_source
62-
from hathor.daa import TestMode, _set_test_mode
62+
from hathor.daa import TestMode
6363
from hathor.event.storage import EventMemoryStorage, EventRocksDBStorage, EventStorage
6464
from hathor.event.websocket.factory import EventWebsocketFactory
6565
from hathor.p2p.netfilter.utils import add_peer_id_blacklist
@@ -208,7 +208,13 @@ def create_manager(self, reactor: Reactor) -> HathorManager:
208208
not_support_features=self._args.signal_not_support
209209
)
210210

211-
daa = DifficultyAdjustmentAlgorithm(settings=settings)
211+
test_mode = TestMode.DISABLED
212+
if self._args.test_mode_tx_weight:
213+
test_mode = TestMode.TEST_TX_WEIGHT
214+
if self.wallet:
215+
self.wallet.test_mode = True
216+
217+
daa = DifficultyAdjustmentAlgorithm(settings=settings, test_mode=test_mode)
212218

213219
vertex_verifiers = VertexVerifiers.create_defaults(
214220
settings=settings,
@@ -281,11 +287,6 @@ def create_manager(self, reactor: Reactor) -> HathorManager:
281287
if self._args.bootstrap:
282288
p2p_manager.add_peer_discovery(BootstrapPeerDiscovery(self._args.bootstrap))
283289

284-
if self._args.test_mode_tx_weight:
285-
_set_test_mode(TestMode.TEST_TX_WEIGHT)
286-
if self.wallet:
287-
self.wallet.test_mode = True
288-
289290
if self._args.x_rocksdb_indexes:
290291
self.log.warn('--x-rocksdb-indexes is now the default, no need to specify it')
291292
if self._args.memory_indexes:

hathor/daa.py

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

2222
from enum import IntFlag
2323
from math import log
24-
from typing import TYPE_CHECKING
24+
from typing import TYPE_CHECKING, ClassVar, Optional
2525

2626
from structlog import get_logger
2727

@@ -45,26 +45,21 @@ class TestMode(IntFlag):
4545
TEST_ALL_WEIGHT = 3
4646

4747

48-
TEST_MODE = TestMode.DISABLED
49-
50-
51-
def _set_test_mode(mode: TestMode) -> None:
52-
global TEST_MODE
53-
logger.debug('change DAA test mode', from_mode=TEST_MODE.name, to_mode=mode.name)
54-
TEST_MODE = mode
55-
56-
5748
class DifficultyAdjustmentAlgorithm:
49+
# TODO: This singleton is temporary, and only used in PeerId. It should be removed from there, and then from here.
50+
singleton: ClassVar[Optional['DifficultyAdjustmentAlgorithm']] = None
5851

59-
def __init__(self, *, settings: HathorSettings) -> None:
52+
def __init__(self, *, settings: HathorSettings, test_mode: TestMode = TestMode.DISABLED) -> None:
6053
self._settings = settings
6154
self.AVG_TIME_BETWEEN_BLOCKS = self._settings.AVG_TIME_BETWEEN_BLOCKS
6255
self.MIN_BLOCK_WEIGHT = self._settings.MIN_BLOCK_WEIGHT
56+
self.TEST_MODE = test_mode
57+
DifficultyAdjustmentAlgorithm.singleton = self
6358

6459
@cpu.profiler(key=lambda _, block: 'calculate_block_difficulty!{}'.format(block.hash.hex()))
6560
def calculate_block_difficulty(self, block: 'Block') -> float:
6661
""" Calculate block weight according to the ascendents of `block`, using calculate_next_weight."""
67-
if TEST_MODE & TestMode.TEST_BLOCK_WEIGHT:
62+
if self.TEST_MODE & TestMode.TEST_BLOCK_WEIGHT:
6863
return 1.0
6964

7065
if block.is_genesis:
@@ -79,7 +74,7 @@ def calculate_next_weight(self, parent_block: 'Block', timestamp: int) -> float:
7974
8075
The weight must not be less than `MIN_BLOCK_WEIGHT`.
8176
"""
82-
if TEST_MODE & TestMode.TEST_BLOCK_WEIGHT:
77+
if self.TEST_MODE & TestMode.TEST_BLOCK_WEIGHT:
8378
return 1.0
8479

8580
from hathor.transaction import sum_weights
@@ -166,7 +161,7 @@ def minimum_tx_weight(self, tx: 'Transaction') -> float:
166161
"""
167162
# In test mode we don't validate the minimum weight for tx
168163
# We do this to allow generating many txs for testing
169-
if TEST_MODE & TestMode.TEST_TX_WEIGHT:
164+
if self.TEST_MODE & TestMode.TEST_TX_WEIGHT:
170165
return 1.0
171166

172167
if tx.is_genesis:

hathor/p2p/peer_id.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,10 @@
2828
from twisted.internet.interfaces import ISSLTransport
2929
from twisted.internet.ssl import Certificate, CertificateOptions, TLSVersion, trustRootFromCertificates
3030

31-
from hathor import daa
3231
from hathor.conf.get_settings import get_settings
32+
from hathor.daa import DifficultyAdjustmentAlgorithm
3333
from hathor.p2p.utils import connection_string_to_host, discover_dns, generate_certificate
34+
from hathor.util import not_none
3435

3536
if TYPE_CHECKING:
3637
from hathor.p2p.protocol import HathorProtocol # noqa: F401
@@ -347,7 +348,8 @@ def validate_entrypoint(self, protocol: 'HathorProtocol') -> Generator[Any, Any,
347348
break
348349
host = connection_string_to_host(entrypoint)
349350
# TODO: don't use `daa.TEST_MODE` for this
350-
result = yield discover_dns(host, daa.TEST_MODE)
351+
test_mode = not_none(DifficultyAdjustmentAlgorithm.singleton).TEST_MODE
352+
result = yield discover_dns(host, test_mode)
351353
if protocol.connection_string in result:
352354
# Found the entrypoint
353355
found_entrypoint = True
@@ -366,7 +368,8 @@ def validate_entrypoint(self, protocol: 'HathorProtocol') -> Generator[Any, Any,
366368
if connection_host == host:
367369
found_entrypoint = True
368370
break
369-
result = yield discover_dns(host, daa.TEST_MODE)
371+
test_mode = not_none(DifficultyAdjustmentAlgorithm.singleton).TEST_MODE
372+
result = yield discover_dns(host, test_mode)
370373
if connection_host in [connection_string_to_host(x) for x in result]:
371374
# Found the entrypoint
372375
found_entrypoint = True

hathor/simulator/simulator.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
from hathor.builder import BuildArtifacts, Builder
2424
from hathor.conf.get_settings import get_settings
2525
from hathor.conf.settings import HathorSettings
26-
from hathor.daa import DifficultyAdjustmentAlgorithm, TestMode, _set_test_mode
26+
from hathor.daa import DifficultyAdjustmentAlgorithm
2727
from hathor.feature_activation.feature_service import FeatureService
2828
from hathor.manager import HathorManager
2929
from hathor.p2p.peer_id import PeerId
@@ -63,7 +63,6 @@ def _apply_patches(cls):
6363
Patches:
6464
6565
- disable Transaction.resolve method
66-
- set DAA test-mode to DISABLED (will actually run the pow function, that won't actually verify the pow)
6766
"""
6867
from hathor.transaction import BaseTransaction
6968

@@ -75,8 +74,6 @@ def resolve(self: BaseTransaction, update_time: bool = True) -> bool:
7574
cls._original_resolve = BaseTransaction.resolve
7675
BaseTransaction.resolve = resolve
7776

78-
_set_test_mode(TestMode.DISABLED)
79-
8077
@classmethod
8178
def _remove_patches(cls):
8279
""" Remove the patches previously applied.

tests/p2p/test_split_brain.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import pytest
22
from mnemonic import Mnemonic
33

4-
from hathor.daa import TestMode, _set_test_mode
4+
from hathor.daa import TestMode
55
from hathor.graphviz import GraphvizVisualizer
66
from hathor.simulator import FakeConnection
77
from hathor.wallet import HDWallet
@@ -24,8 +24,8 @@ def create_peer(self, network, unlock_wallet=True):
2424
wallet = HDWallet(gap_limit=2)
2525
wallet._manually_initialize()
2626

27-
_set_test_mode(TestMode.TEST_ALL_WEIGHT)
2827
manager = super().create_peer(network, wallet=wallet)
28+
manager.daa.TEST_MODE = TestMode.TEST_ALL_WEIGHT
2929
manager.avg_time_between_blocks = 64
3030

3131
# Don't use it anywhere else. It is unsafe to generate mnemonic words like this.

tests/resources/base_resource.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from twisted.web import server
33
from twisted.web.test.requesthelper import DummyRequest
44

5-
from hathor.daa import TestMode, _set_test_mode
5+
from hathor.daa import TestMode
66
from hathor.util import json_dumpb, json_loadb
77
from tests import unittest
88

@@ -19,7 +19,7 @@ def setUp(self, *, utxo_index: bool = False, unlock_wallet: bool = True) -> None
1919
unlock_wallet=unlock_wallet
2020
)
2121
self.manager.allow_mining_without_peers()
22-
_set_test_mode(TestMode.TEST_ALL_WEIGHT)
22+
self.manager.daa.TEST_MODE = TestMode.TEST_ALL_WEIGHT
2323

2424
def tearDown(self):
2525
return self.manager.stop()

tests/resources/transaction/test_create_tx.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
from twisted.internet.defer import inlineCallbacks
44

5-
from hathor.daa import TestMode, _set_test_mode
5+
from hathor.daa import TestMode
66
from hathor.transaction import Transaction
77
from hathor.transaction.resources import CreateTxResource
88
from hathor.transaction.scripts import P2PKH, create_base_script
@@ -195,7 +195,7 @@ def test_spend_tx_by_script(self):
195195

196196
@inlineCallbacks
197197
def test_tx_propagate(self):
198-
_set_test_mode(TestMode.DISABLED) # disable test_mode so the weight is not 1
198+
self.manager.daa.TEST_MODE = TestMode.DISABLED # disable test_mode so the weight is not 1
199199
src_tx = self.unspent_tx
200200
output_address = 'HNXsVtRUmwDCtpcCJUrH4QiHo9kUKx199A'
201201
resp = (yield self.web.post('create_tx', {
@@ -233,7 +233,7 @@ def test_tx_propagate(self):
233233

234234
@inlineCallbacks
235235
def test_tx_propagate_multiple_inputs(self):
236-
_set_test_mode(TestMode.DISABLED) # disable test_mode so the weight is not 1
236+
self.manager.daa.TEST_MODE = TestMode.DISABLED # disable test_mode so the weight is not 1
237237
output_address = 'HNXsVtRUmwDCtpcCJUrH4QiHo9kUKx199A'
238238
resp = (yield self.web.post('create_tx', {
239239
'inputs': [

tests/resources/wallet/test_send_tokens.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
from twisted.internet.defer import inlineCallbacks
44

5-
from hathor.daa import TestMode, _set_test_mode
5+
from hathor.daa import TestMode
66
from hathor.p2p.resources import MiningResource
77
from hathor.wallet.resources import BalanceResource, HistoryResource, SendTokensResource
88
from tests import unittest
@@ -168,7 +168,7 @@ def test_post(self):
168168

169169
@inlineCallbacks
170170
def test_tx_weight(self):
171-
_set_test_mode(TestMode.DISABLED)
171+
self.manager.daa.TEST_MODE = TestMode.DISABLED
172172
add_new_blocks(self.manager, 3, advance_clock=1)
173173
add_blocks_unlock_reward(self.manager)
174174
self.reactor.advance(3)

tests/tx/test_blockchain.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from itertools import chain
22

33
from hathor.conf import HathorSettings
4-
from hathor.daa import DifficultyAdjustmentAlgorithm, TestMode, _set_test_mode
4+
from hathor.daa import DifficultyAdjustmentAlgorithm, TestMode
55
from hathor.transaction import sum_weights
66
from hathor.transaction.storage import TransactionMemoryStorage
77
from tests import unittest
@@ -390,8 +390,8 @@ def test_block_rewards(self):
390390

391391
def test_daa_sanity(self):
392392
# sanity test the DAA
393-
_set_test_mode(TestMode.DISABLED)
394393
manager = self.create_peer('testnet', tx_storage=self.tx_storage)
394+
manager.daa.TEST_MODE = TestMode.DISABLED
395395
N = settings.BLOCK_DIFFICULTY_N_BLOCKS
396396
T = settings.AVG_TIME_BETWEEN_BLOCKS
397397
manager.avg_time_between_blocks = T
@@ -417,7 +417,7 @@ def test_daa_sanity(self):
417417
self.assertLess(new_weight, base_weight)
418418

419419
def test_daa_weight_decay_amount(self):
420-
_set_test_mode(TestMode.DISABLED)
420+
self.daa.TEST_MODE = TestMode.DISABLED
421421
amount = settings.WEIGHT_DECAY_AMOUNT
422422

423423
for distance in range(0, settings.WEIGHT_DECAY_ACTIVATE_DISTANCE, 10):
@@ -434,8 +434,8 @@ def test_daa_weight_decay_amount(self):
434434
self.assertAlmostEqual(self.daa.get_weight_decay_amount(distance), 11 * amount)
435435

436436
def test_daa_weight_decay_blocks(self):
437-
_set_test_mode(TestMode.DISABLED)
438437
manager = self.create_peer('testnet', tx_storage=self.tx_storage)
438+
manager.daa.TEST_MODE = TestMode.DISABLED
439439
amount = settings.WEIGHT_DECAY_AMOUNT
440440

441441
manager.daa.AVG_TIME_BETWEEN_BLOCKS = settings.AVG_TIME_BETWEEN_BLOCKS

tests/tx/test_cache_storage.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from hathor.daa import TestMode, _set_test_mode
1+
from hathor.daa import TestMode
22
from hathor.transaction import Transaction, TransactionMetadata
33
from hathor.transaction.storage import TransactionCacheStorage
44
from tests import unittest
@@ -144,7 +144,7 @@ def test_flush_thread(self):
144144
self.cache_storage._flush_to_storage(self.cache_storage.dirty_txs.copy())
145145

146146
def test_topological_sort_dfs(self):
147-
_set_test_mode(TestMode.TEST_ALL_WEIGHT)
147+
self.manager.daa.TEST_MODE = TestMode.TEST_ALL_WEIGHT
148148
add_new_blocks(self.manager, 11, advance_clock=1)
149149
tx = add_new_transactions(self.manager, 1, advance_clock=1)[0]
150150

tests/tx/test_genesis.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from hathor.conf import HathorSettings
2-
from hathor.daa import DifficultyAdjustmentAlgorithm, TestMode, _set_test_mode
2+
from hathor.daa import DifficultyAdjustmentAlgorithm, TestMode
33
from hathor.transaction.storage import TransactionMemoryStorage
44
from hathor.verification.verification_service import VerificationService, VertexVerifiers
55
from hathor.verification.vertex_verifier import VertexVerifier
@@ -70,10 +70,10 @@ def test_genesis_weight(self):
7070

7171
# Validate the block and tx weight
7272
# in test mode weight is always 1
73-
_set_test_mode(TestMode.TEST_ALL_WEIGHT)
73+
self._daa.TEST_MODE = TestMode.TEST_ALL_WEIGHT
7474
self.assertEqual(self._daa.calculate_block_difficulty(genesis_block), 1)
7575
self.assertEqual(self._daa.minimum_tx_weight(genesis_tx), 1)
7676

77-
_set_test_mode(TestMode.DISABLED)
77+
self._daa.TEST_MODE = TestMode.DISABLED
7878
self.assertEqual(self._daa.calculate_block_difficulty(genesis_block), genesis_block.weight)
7979
self.assertEqual(self._daa.minimum_tx_weight(genesis_tx), genesis_tx.weight)

tests/tx/test_tx.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from math import isinf, isnan
44

55
from hathor.crypto.util import decode_address, get_address_from_public_key, get_private_key_from_bytes
6-
from hathor.daa import TestMode, _set_test_mode
6+
from hathor.daa import TestMode
77
from hathor.transaction import MAX_OUTPUT_VALUE, Block, Transaction, TxInput, TxOutput
88
from hathor.transaction.exceptions import (
99
BlockWithInputs,
@@ -629,8 +629,8 @@ def test_update_timestamp(self):
629629
self.assertEquals(tx.timestamp, ts)
630630

631631
def test_propagation_error(self):
632-
_set_test_mode(TestMode.DISABLED)
633632
manager = self.create_peer('testnet', unlock_wallet=True)
633+
manager.daa.TEST_MODE = TestMode.DISABLED
634634

635635
# 1. propagate genesis
636636
genesis_block = self.genesis_blocks[0]

tests/tx/test_tx_storage.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from twisted.trial import unittest
1010

1111
from hathor.conf import HathorSettings
12-
from hathor.daa import TestMode, _set_test_mode
12+
from hathor.daa import TestMode
1313
from hathor.transaction import Block, Transaction, TxInput, TxOutput
1414
from hathor.transaction.scripts import P2PKH
1515
from hathor.transaction.storage.exceptions import TransactionDoesNotExist
@@ -145,7 +145,7 @@ def test_storage_basic_v2(self):
145145
self.assertEqual(set(tx_parents_hash), {self.genesis_txs[0].hash, self.genesis_txs[1].hash})
146146

147147
def test_vertices_count(self):
148-
_set_test_mode(TestMode.TEST_ALL_WEIGHT)
148+
self.manager.daa.TEST_MODE = TestMode.TEST_ALL_WEIGHT
149149

150150
blocks_count = 1
151151
txs_count = 2
@@ -522,7 +522,7 @@ def _add_new_block(self, parents=None):
522522
return block
523523

524524
def test_best_block_tips_cache(self):
525-
_set_test_mode(TestMode.TEST_ALL_WEIGHT)
525+
self.manager.daa.TEST_MODE = TestMode.TEST_ALL_WEIGHT
526526
self.manager.wallet.unlock(b'MYPASS')
527527
spent_blocks = add_new_blocks(self.manager, 10)
528528
self.assertEqual(self.tx_storage._best_block_tips_cache, [spent_blocks[-1].hash])
@@ -534,7 +534,7 @@ def test_best_block_tips_cache(self):
534534
self.assertEqual(self.tx_storage._best_block_tips_cache, [latest_blocks[-1].hash])
535535

536536
def test_topological_sort(self):
537-
_set_test_mode(TestMode.TEST_ALL_WEIGHT)
537+
self.manager.daa.TEST_MODE = TestMode.TEST_ALL_WEIGHT
538538
_total = 0
539539
blocks = add_new_blocks(self.manager, 1, advance_clock=1)
540540
_total += len(blocks)

0 commit comments

Comments
 (0)