Skip to content

Commit f11e52b

Browse files
committed
refactor(daa): remove global daa test mode
1 parent ba12e49 commit f11e52b

14 files changed

+51
-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
@@ -204,7 +204,13 @@ def create_manager(self, reactor: Reactor) -> HathorManager:
204204
not_support_features=self._args.signal_not_support
205205
)
206206

207-
daa = DifficultyAdjustmentAlgorithm(settings=settings)
207+
test_mode = TestMode.DISABLED
208+
if self._args.test_mode_tx_weight:
209+
test_mode = TestMode.TEST_TX_WEIGHT
210+
if self.wallet:
211+
self.wallet.test_mode = True
212+
213+
daa = DifficultyAdjustmentAlgorithm(settings=settings, test_mode=test_mode)
208214

209215
vertex_verifiers = VertexVerifiers.create(settings=settings, daa=daa)
210216
verification_service = VerificationService(verifiers=vertex_verifiers)
@@ -273,11 +279,6 @@ def create_manager(self, reactor: Reactor) -> HathorManager:
273279
if self._args.bootstrap:
274280
self.manager.add_peer_discovery(BootstrapPeerDiscovery(self._args.bootstrap))
275281

276-
if self._args.test_mode_tx_weight:
277-
_set_test_mode(TestMode.TEST_TX_WEIGHT)
278-
if self.wallet:
279-
self.wallet.test_mode = True
280-
281282
if self._args.x_rocksdb_indexes:
282283
self.log.warn('--x-rocksdb-indexes is now the default, no need to specify it')
283284
if self._args.memory_indexes:

hathor/daa.py

+8-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,20 @@ 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+
singleton: ClassVar[Optional['DifficultyAdjustmentAlgorithm']] = None
5850

59-
def __init__(self, *, settings: HathorSettings) -> None:
51+
def __init__(self, *, settings: HathorSettings, test_mode: TestMode = TestMode.DISABLED) -> None:
6052
self._settings = settings
6153
self.AVG_TIME_BETWEEN_BLOCKS = self._settings.AVG_TIME_BETWEEN_BLOCKS
6254
self.MIN_BLOCK_WEIGHT = self._settings.MIN_BLOCK_WEIGHT
55+
self.TEST_MODE = test_mode
56+
DifficultyAdjustmentAlgorithm.singleton = self
6357

6458
@cpu.profiler(key=lambda _, block: 'calculate_block_difficulty!{}'.format(block.hash.hex()))
6559
def calculate_block_difficulty(self, block: 'Block') -> float:
6660
""" Calculate block weight according to the ascendents of `block`, using calculate_next_weight."""
67-
if TEST_MODE & TestMode.TEST_BLOCK_WEIGHT:
61+
if self.TEST_MODE & TestMode.TEST_BLOCK_WEIGHT:
6862
return 1.0
6963

7064
if block.is_genesis:
@@ -79,7 +73,7 @@ def calculate_next_weight(self, parent_block: 'Block', timestamp: int) -> float:
7973
8074
The weight must not be less than `MIN_BLOCK_WEIGHT`.
8175
"""
82-
if TEST_MODE & TestMode.TEST_BLOCK_WEIGHT:
76+
if self.TEST_MODE & TestMode.TEST_BLOCK_WEIGHT:
8377
return 1.0
8478

8579
from hathor.transaction import sum_weights
@@ -166,7 +160,7 @@ def minimum_tx_weight(self, tx: 'Transaction') -> float:
166160
"""
167161
# In test mode we don't validate the minimum weight for tx
168162
# We do this to allow generating many txs for testing
169-
if TEST_MODE & TestMode.TEST_TX_WEIGHT:
163+
if self.TEST_MODE & TestMode.TEST_TX_WEIGHT:
170164
return 1.0
171165

172166
if tx.is_genesis:

hathor/p2p/peer_id.py

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

30-
from hathor import daa
3130
from hathor.conf.get_settings import get_settings
31+
from hathor.daa import DifficultyAdjustmentAlgorithm
3232
from hathor.p2p.utils import connection_string_to_host, discover_dns, generate_certificate
33+
from hathor.util import not_none
3334

3435
if TYPE_CHECKING:
3536
from hathor.p2p.protocol import HathorProtocol # noqa: F401
@@ -344,7 +345,8 @@ def validate_entrypoint(self, protocol: 'HathorProtocol') -> Generator[Any, Any,
344345
break
345346
host = connection_string_to_host(entrypoint)
346347
# TODO: don't use `daa.TEST_MODE` for this
347-
result = yield discover_dns(host, daa.TEST_MODE)
348+
test_mode = not_none(DifficultyAdjustmentAlgorithm.singleton).TEST_MODE
349+
result = yield discover_dns(host, test_mode)
348350
if protocol.connection_string in result:
349351
# Found the entrypoint
350352
found_entrypoint = True
@@ -363,7 +365,8 @@ def validate_entrypoint(self, protocol: 'HathorProtocol') -> Generator[Any, Any,
363365
if connection_host == host:
364366
found_entrypoint = True
365367
break
366-
result = yield discover_dns(host, daa.TEST_MODE)
368+
test_mode = not_none(DifficultyAdjustmentAlgorithm.singleton).TEST_MODE
369+
result = yield discover_dns(host, test_mode)
367370
if connection_host in [connection_string_to_host(x) for x in result]:
368371
# Found the entrypoint
369372
found_entrypoint = True

hathor/simulator/simulator.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222

2323
from hathor.builder import BuildArtifacts, Builder
2424
from hathor.conf.get_settings import get_settings
25-
from hathor.daa import DifficultyAdjustmentAlgorithm, TestMode, _set_test_mode
25+
from hathor.daa import DifficultyAdjustmentAlgorithm
2626
from hathor.manager import HathorManager
2727
from hathor.p2p.peer_id import PeerId
2828
from hathor.simulator.clock import HeapClock, MemoryReactorHeapClock
@@ -62,7 +62,6 @@ def _apply_patches(cls):
6262
Patches:
6363
6464
- disable Transaction.resolve method
65-
- set DAA test-mode to DISABLED (will actually run the pow function, that won't actually verify the pow)
6665
"""
6766
from hathor.transaction import BaseTransaction
6867

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

77-
_set_test_mode(TestMode.DISABLED)
78-
7976
@classmethod
8077
def _remove_patches(cls):
8178
""" 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
@@ -25,8 +25,8 @@ def create_peer(self, network, unlock_wallet=True):
2525
wallet = HDWallet(gap_limit=2)
2626
wallet._manually_initialize()
2727

28-
_set_test_mode(TestMode.TEST_ALL_WEIGHT)
2928
manager = super().create_peer(network, wallet=wallet)
29+
manager.daa.TEST_MODE = TestMode.TEST_ALL_WEIGHT
3030
manager.avg_time_between_blocks = 64
3131

3232
# 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
@@ -69,10 +69,10 @@ def test_genesis_weight(self):
6969

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

76-
_set_test_mode(TestMode.DISABLED)
76+
self._daa.TEST_MODE = TestMode.DISABLED
7777
self.assertEqual(self._daa.calculate_block_difficulty(genesis_block), genesis_block.weight)
7878
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,
@@ -630,8 +630,8 @@ def test_update_timestamp(self):
630630
self.assertEquals(tx.timestamp, ts)
631631

632632
def test_propagation_error(self):
633-
_set_test_mode(TestMode.DISABLED)
634633
manager = self.create_peer('testnet', unlock_wallet=True)
634+
manager.daa.TEST_MODE = TestMode.DISABLED
635635

636636
# 1. propagate genesis
637637
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
@@ -155,7 +155,7 @@ def test_storage_basic_v2(self):
155155
self.assertEqual(set(tx_parents_hash), {self.genesis_txs[0].hash, self.genesis_txs[1].hash})
156156

157157
def test_vertices_count(self):
158-
_set_test_mode(TestMode.TEST_ALL_WEIGHT)
158+
self.manager.daa.TEST_MODE = TestMode.TEST_ALL_WEIGHT
159159

160160
blocks_count = 1
161161
txs_count = 2
@@ -532,7 +532,7 @@ def _add_new_block(self, parents=None):
532532
return block
533533

534534
def test_best_block_tips_cache(self):
535-
_set_test_mode(TestMode.TEST_ALL_WEIGHT)
535+
self.manager.daa.TEST_MODE = TestMode.TEST_ALL_WEIGHT
536536
self.manager.wallet.unlock(b'MYPASS')
537537
spent_blocks = add_new_blocks(self.manager, 10)
538538
self.assertEqual(self.tx_storage._best_block_tips_cache, [spent_blocks[-1].hash])
@@ -544,7 +544,7 @@ def test_best_block_tips_cache(self):
544544
self.assertEqual(self.tx_storage._best_block_tips_cache, [latest_blocks[-1].hash])
545545

546546
def test_topological_sort(self):
547-
_set_test_mode(TestMode.TEST_ALL_WEIGHT)
547+
self.manager.daa.TEST_MODE = TestMode.TEST_ALL_WEIGHT
548548
_total = 0
549549
blocks = add_new_blocks(self.manager, 1, advance_clock=1)
550550
_total += len(blocks)

0 commit comments

Comments
 (0)