Use `ConsensusConstants` in many more places.

This commit is contained in:
Richard Kiss 2020-06-25 18:12:28 -07:00 committed by Gene Hoffman
parent 13525e824f
commit e4f3050667
13 changed files with 55 additions and 55 deletions

View File

@ -4,6 +4,7 @@ from typing import Dict, List, Optional, Tuple
import blspy
from src.consensus.block_rewards import calculate_block_reward
from src.consensus.constants import ConsensusConstants
from src.consensus.pot_iterations import calculate_iterations_quality
from src.full_node.difficulty_adjustment import get_next_difficulty, get_next_min_iters
from src.types.challenge import Challenge
@ -21,7 +22,7 @@ log = logging.getLogger(__name__)
async def validate_unfinished_block_header(
constants: Dict,
constants: ConsensusConstants,
headers: Dict[bytes32, Header],
height_to_hash: Dict[uint32, bytes32],
block_header: Header,
@ -169,7 +170,7 @@ async def validate_unfinished_block_header(
async def validate_finished_block_header(
constants: Dict,
constants: ConsensusConstants,
headers: Dict[bytes32, Header],
height_to_hash: Dict[uint32, bytes32],
block: HeaderBlock,
@ -236,7 +237,7 @@ async def validate_finished_block_header(
return None
def pre_validate_finished_block_header(constants: Dict, data: bytes):
def pre_validate_finished_block_header(constants: ConsensusConstants, data: bytes):
"""
Validates all parts of block that don't need to be serially checked
"""

View File

@ -9,8 +9,8 @@ from typing import Dict, List, Optional, Set, Tuple
from chiabip158 import PyBIP158
from clvm.casts import int_from_bytes
from src.consensus.constants import constants as consensus_constants
from src.consensus.block_rewards import calculate_base_fee
from src.consensus.constants import ConsensusConstants
from src.full_node.block_header_validation import (
validate_unfinished_block_header,
validate_finished_block_header,
@ -57,8 +57,7 @@ class ReceiveBlockResult(Enum):
class Blockchain:
# Allow passing in custom overrides for any consesus parameters
constants: Dict
constants: ConsensusConstants
# Tips of the blockchain
tips: List[Header]
# Least common ancestor of tips
@ -86,7 +85,7 @@ class Blockchain:
@staticmethod
async def create(
coin_store: CoinStore, block_store: BlockStore, override_constants: Dict = {},
coin_store: CoinStore, block_store: BlockStore, consensus_constants: ConsensusConstants,
):
"""
Initializes a blockchain with the header blocks from disk, assuming they have all been
@ -99,9 +98,7 @@ class Blockchain:
self.pool = concurrent.futures.ProcessPoolExecutor(
max_workers=max(cpu_count - 1, 1)
)
self.constants = consensus_constants.copy()
for key, value in override_constants.items():
self.constants[key] = value
self.constants = consensus_constants
self.tips = []
self.height_to_hash = {}
self.headers = {}
@ -225,7 +222,7 @@ class Blockchain:
"DIFFICULTY_DELAY"
]:
new_difficulty = get_next_difficulty(
self.constants, self.headers, self.height_to_hash, block.header
self.constants.copy(), self.headers, self.height_to_hash, block.header
)
else:
new_difficulty = None
@ -320,7 +317,7 @@ class Blockchain:
assert curr_header_block is not None
# Validate block header
error_code: Optional[Err] = await validate_finished_block_header(
self.constants,
self.constants.copy(),
self.headers,
self.height_to_hash,
curr_header_block,
@ -493,12 +490,12 @@ class Blockchain:
def get_next_difficulty(self, header_hash: bytes32) -> uint64:
return get_next_difficulty(
self.constants, self.headers, self.height_to_hash, header_hash
self.constants.copy(), self.headers, self.height_to_hash, header_hash
)
def get_next_min_iters(self, header_hash: bytes32) -> uint64:
return get_next_min_iters(
self.constants, self.headers, self.height_to_hash, header_hash
self.constants.copy(), self.headers, self.height_to_hash, header_hash
)
async def pre_validate_blocks_multiprocessing(
@ -531,7 +528,7 @@ class Blockchain:
prev_hb = self.get_header_block(prev_full_block)
assert prev_hb is not None
return await validate_unfinished_block_header(
self.constants,
self.constants.copy(),
self.headers,
self.height_to_hash,
block.header,

View File

@ -1,5 +1,6 @@
from typing import Dict, Optional, Union
from src.consensus.constants import ConsensusConstants
from src.consensus.pot_iterations import calculate_min_iters_from_iterations
from src.types.full_block import FullBlock
from src.types.header import Header
@ -13,7 +14,7 @@ from src.util.significant_bits import (
def get_next_difficulty(
constants: Dict,
constants: ConsensusConstants,
headers: Dict[bytes32, Header],
height_to_hash: Dict[uint32, bytes32],
block: Header,
@ -151,7 +152,7 @@ def get_next_difficulty(
def get_next_min_iters(
constants: Dict,
constants: ConsensusConstants,
headers: Dict[bytes32, Header],
height_to_hash: Dict[uint32, bytes32],
block: Union[FullBlock, HeaderBlock],

View File

@ -11,7 +11,7 @@ import aiosqlite
from chiabip158 import PyBIP158
from chiapos import Verifier
from src.consensus.constants import constants as consensus_constants
from src.consensus.constants import ConsensusConstants
from src.consensus.block_rewards import calculate_base_fee
from src.consensus.pot_iterations import calculate_iterations
from src.full_node.block_store import BlockStore
@ -70,22 +70,20 @@ class FullNode:
global_connections: Optional[PeerConnections]
server: Optional[ChiaServer]
log: logging.Logger
constants: Dict
constants: ConsensusConstants
_shut_down: bool
root_path: Path
state_changed_callback: Optional[Callable]
def __init__(
self, config: Dict, root_path: Path, name: str = None, override_constants={},
self, config: Dict, root_path: Path, consensus_constants: ConsensusConstants, name: str = None,
):
self.root_path = root_path
self.config = config
self.server = None
self._shut_down = False # Set to true to close all infinite loops
self.constants = consensus_constants.copy()
self.constants = consensus_constants
self.sync_peers_handler = None
for key, value in override_constants.items():
self.constants[key] = value
if name:
self.log = logging.getLogger(name)
else:

View File

@ -6,7 +6,7 @@ import logging
from chiabip158 import PyBIP158
from clvm.casts import int_from_bytes
from src.consensus.constants import constants as consensus_constants
from src.consensus.constants import ConsensusConstants
from src.types.condition_opcodes import ConditionOpcode
from src.types.condition_var_pair import ConditionVarPair
from src.util.bundle_tools import best_solution_program
@ -32,11 +32,8 @@ log = logging.getLogger(__name__)
class MempoolManager:
def __init__(self, coin_store: CoinStore, override_constants: Dict = {}):
# Allow passing in custom overrides
self.constants: Dict = consensus_constants.copy()
for key, value in override_constants.items():
self.constants[key] = value
def __init__(self, coin_store: CoinStore, consensus_constants: ConsensusConstants):
self.constants: ConsensusConstants = consensus_constants
# Transactions that were unable to enter mempool, used for retry. (they were invalid)
self.potential_txs: Dict[bytes32, SpendBundle] = {}

View File

@ -1,5 +1,6 @@
from multiprocessing import freeze_support
from src.consensus.constants import constants
from src.full_node.full_node import FullNode
from src.rpc.full_node_rpc_api import FullNodeRpcApi
from src.server.outbound_message import NodeType
@ -18,7 +19,7 @@ def service_kwargs_for_full_node(root_path):
service_name = "full_node"
config = load_config_cli(root_path, "config.yaml", service_name)
api = FullNode(config, root_path=root_path)
api = FullNode(config, root_path=root_path, consensus_constants=constants)
introducer = config["introducer_peer"]
peer_info = PeerInfo(introducer["host"], introducer["port"])

View File

@ -1,5 +1,6 @@
from multiprocessing import freeze_support
from src.consensus.constants import constants as consensus_constants
from src.wallet.wallet_node import WalletNode
from src.rpc.wallet_rpc_api import WalletRpcApi
from src.server.outbound_message import NodeType
@ -19,13 +20,12 @@ def service_kwargs_for_wallet(root_path):
config = load_config_cli(root_path, "config.yaml", service_name)
keychain = Keychain(testing=False)
wallet_constants = consensus_constants
if config["testing"] is True:
config["database_path"] = "test_db_wallet.db"
api = WalletNode(
config, keychain, root_path, override_constants=test_constants,
)
else:
api = WalletNode(config, keychain, root_path)
wallet_constants = wallet_constants.replace(test_constants)
api = WalletNode(config, keychain, root_path, consensus_constants=wallet_constants)
introducer = config["introducer_peer"]
peer_info = PeerInfo(introducer["host"], introducer["port"])

View File

@ -133,7 +133,7 @@ class FullNodeSimulator(FullNode):
fees = bundle.fees()
more_blocks = bt.get_consecutive_blocks(
self.constants,
self.constants.copy(),
1,
current_block,
10,
@ -159,7 +159,7 @@ class FullNodeSimulator(FullNode):
block_count = new_index - old_index
more_blocks = bt.get_consecutive_blocks(
self.constants,
self.constants.copy(),
block_count,
current_blocks[:old_index],
10,

View File

@ -18,7 +18,7 @@ from src.util.merkle_set import (
MerkleSet,
)
from src.protocols import introducer_protocol, wallet_protocol
from src.consensus.constants import constants as consensus_constants
from src.consensus.constants import ConsensusConstants
from src.server.connection import PeerConnections
from src.server.server import ChiaServer
from src.server.outbound_message import OutboundMessage, NodeType, Message, Delivery
@ -45,7 +45,7 @@ from src.wallet.trade_manager import TradeManager
class WalletNode:
key_config: Dict
config: Dict
constants: Dict
constants: ConsensusConstants
server: Optional[ChiaServer]
log: logging.Logger
@ -84,14 +84,12 @@ class WalletNode:
config: Dict,
keychain: Keychain,
root_path: Path,
consensus_constants: ConsensusConstants,
name: str = None,
override_constants: Dict = {},
):
self.config = config
self.constants = consensus_constants.copy()
self.constants = consensus_constants
self.root_path = root_path
for key, value in override_constants.items():
self.constants[key] = value
if name:
self.log = logging.getLogger(name)
else:

View File

@ -10,6 +10,7 @@ import aiosqlite
from chiabip158 import PyBIP158
from blspy import PublicKey, ExtendedPrivateKey
from src.consensus.constants import ConsensusConstants
from src.types.coin import Coin
from src.types.spend_bundle import SpendBundle
from src.types.sized_bytes import bytes32
@ -45,7 +46,7 @@ from src.consensus.find_fork_point import find_fork_point_in_chain
class WalletStateManager:
constants: Dict
constants: ConsensusConstants
config: Dict
wallet_store: WalletStore
tx_store: WalletTransactionStore
@ -85,7 +86,7 @@ class WalletStateManager:
private_key: ExtendedPrivateKey,
config: Dict,
db_path: Path,
constants: Dict,
constants: ConsensusConstants,
name: str = None,
):
self = WalletStateManager()

View File

@ -7,6 +7,7 @@ import random
import aiosqlite
import pytest
from src.consensus.constants import constants as consensus_constants
from src.full_node.block_store import BlockStore
from src.full_node.coin_store import CoinStore
from src.full_node.blockchain import Blockchain
@ -71,7 +72,8 @@ class TestBlockStore:
assert (await db.get_tips()) == [blocks[-2].header, blocks[-1].header]
coin_store: CoinStore = await CoinStore.create(connection_3)
b: Blockchain = await Blockchain.create(coin_store, db_3, test_constants)
hacked_constants = consensus_constants.replace(**test_constants)
b: Blockchain = await Blockchain.create(coin_store, db_3, hacked_constants)
assert b.lca_block == genesis.header
assert b.tips == [genesis.header]

View File

@ -10,11 +10,13 @@ from src.full_node.coin_store import CoinStore
from src.full_node.block_store import BlockStore
from tests.block_tools import BlockTools
from src.consensus.constants import constants as consensus_constants
from tests.setup_nodes import test_constants
from tests.setup_nodes import test_constants as override_constants
from tests.block_tools import BlockTools
bt = BlockTools()
test_constants = consensus_constants.replace(**override_constants)
test_constants_dict = test_constants.copy()
@pytest.fixture(scope="module")
def event_loop():
@ -25,7 +27,7 @@ def event_loop():
class TestCoinStore:
@pytest.mark.asyncio
async def test_basic_coin_store(self):
blocks = bt.get_consecutive_blocks(test_constants, 9, [], 9, b"0")
blocks = bt.get_consecutive_blocks(test_constants_dict, 9, [], 9, b"0")
db_path = Path("fndb_test.db")
if db_path.exists():
@ -46,7 +48,7 @@ class TestCoinStore:
@pytest.mark.asyncio
async def test_set_spent(self):
blocks = bt.get_consecutive_blocks(test_constants, 9, [], 9, b"0")
blocks = bt.get_consecutive_blocks(test_constants_dict, 9, [], 9, b"0")
db_path = Path("fndb_test.db")
if db_path.exists():
@ -74,7 +76,7 @@ class TestCoinStore:
@pytest.mark.asyncio
async def test_rollback(self):
blocks = bt.get_consecutive_blocks(test_constants, 9, [], 9, b"0")
blocks = bt.get_consecutive_blocks(test_constants_dict, 9, [], 9, b"0")
db_path = Path("fndb_test.db")
if db_path.exists():
@ -117,7 +119,7 @@ class TestCoinStore:
async def test_basic_reorg(self):
initial_block_count = 20
reorg_length = 15
blocks = bt.get_consecutive_blocks(test_constants, initial_block_count, [], 9)
blocks = bt.get_consecutive_blocks(test_constants_dict, initial_block_count, [], 9)
db_path = Path("blockchain_test.db")
if db_path.exists():
db_path.unlink()
@ -146,7 +148,7 @@ class TestCoinStore:
assert unspent_fee.name == block.header.data.fees_coin.name()
blocks_reorg_chain = bt.get_consecutive_blocks(
test_constants,
test_constants_dict,
reorg_length,
blocks[: initial_block_count - 10],
9,
@ -187,7 +189,7 @@ class TestCoinStore:
@pytest.mark.asyncio
async def test_get_puzzle_hash(self):
num_blocks = 10
blocks = bt.get_consecutive_blocks(test_constants, num_blocks, [], 9)
blocks = bt.get_consecutive_blocks(test_constants_dict, num_blocks, [], 9)
db_path = Path("blockchain_test.db")
if db_path.exists():
db_path.unlink()

View File

@ -85,11 +85,12 @@ async def setup_full_node(
config["target_peer_count"],
)
FullNodeApi = FullNodeSimulator if simulator else FullNode
hacked_constants = consensus_constants.replace(**test_constants_copy)
api = FullNodeApi(
config=config,
root_path=root_path,
consensus_constants=hacked_constants,
name=f"full_node_{port}",
override_constants=test_constants_copy,
)
started = asyncio.Event()
@ -154,11 +155,12 @@ async def setup_wallet_node(
db_path.unlink()
config["database_path"] = str(db_name)
hacked_constants = consensus_constants.replace(**test_constants_copy)
api = WalletNode(
config,
keychain,
root_path,
override_constants=test_constants_copy,
consensus_constants=hacked_constants,
name="wallet1",
)
periodic_introducer_poll = None