Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion hathor/builder/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -530,8 +530,9 @@ def _get_or_create_bit_signaling_service(self) -> BitSignalingService:

def _get_or_create_verification_service(self) -> VerificationService:
if self._verification_service is None:
settings = self._get_or_create_settings()
verifiers = self._get_or_create_vertex_verifiers()
self._verification_service = VerificationService(verifiers=verifiers)
self._verification_service = VerificationService(settings=settings, verifiers=verifiers)

return self._verification_service

Expand Down
2 changes: 1 addition & 1 deletion hathor/builder/cli_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,7 @@ def create_manager(self, reactor: Reactor) -> HathorManager:
daa=daa,
feature_service=self.feature_service
)
verification_service = VerificationService(verifiers=vertex_verifiers)
verification_service = VerificationService(settings=settings, verifiers=vertex_verifiers)

cpu_mining_service = CpuMiningService()

Expand Down
7 changes: 4 additions & 3 deletions hathor/builder/resources_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,9 +266,10 @@ def create_resources(self) -> server.Site:
ws_factory.start()
root.putChild(b'ws', WebSocketResource(ws_factory))

# Mining websocket resource
mining_ws_factory = MiningWebsocketFactory(self.manager)
root.putChild(b'mining_ws', WebSocketResource(mining_ws_factory))
if settings.CONSENSUS_ALGORITHM.is_pow():
# Mining websocket resource
mining_ws_factory = MiningWebsocketFactory(self.manager)
root.putChild(b'mining_ws', WebSocketResource(mining_ws_factory))

ws_factory.subscribe(self.manager.pubsub)

Expand Down
2 changes: 1 addition & 1 deletion hathor/cli/mining.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ def execute(args: Namespace) -> None:
settings = get_global_settings()
daa = DifficultyAdjustmentAlgorithm(settings=settings)
verifiers = VertexVerifiers.create_defaults(settings=settings, daa=daa, feature_service=Mock())
verification_service = VerificationService(verifiers=verifiers)
verification_service = VerificationService(settings=settings, verifiers=verifiers)
verification_service.verify_without_storage(block)
except HathorError:
print('[{}] ERROR: Block has not been pushed because it is not valid.'.format(datetime.datetime.now()))
Expand Down
11 changes: 8 additions & 3 deletions hathor/conf/get_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,16 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import annotations

import importlib
import os
from typing import NamedTuple, Optional
from typing import TYPE_CHECKING, NamedTuple, Optional

from structlog import get_logger

from hathor import conf
from hathor.conf.settings import HathorSettings as Settings
if TYPE_CHECKING:
from hathor.conf.settings import HathorSettings as Settings

logger = get_logger()

Expand Down Expand Up @@ -51,6 +53,7 @@ def HathorSettings() -> Settings:
if settings_module_filepath is not None:
return _load_settings_singleton(settings_module_filepath, is_yaml=False)

from hathor import conf
settings_yaml_filepath = os.environ.get('HATHOR_CONFIG_YAML', conf.MAINNET_SETTINGS_FILEPATH)
return _load_settings_singleton(settings_yaml_filepath, is_yaml=True)

Expand Down Expand Up @@ -94,9 +97,11 @@ def _load_module_settings(module_path: str) -> Settings:
)
settings_module = importlib.import_module(module_path)
settings = getattr(settings_module, 'SETTINGS')
from hathor.conf.settings import HathorSettings as Settings
assert isinstance(settings, Settings)
return settings


def _load_yaml_settings(filepath: str) -> Settings:
from hathor.conf.settings import HathorSettings as Settings
return Settings.from_yaml(filepath=filepath)
35 changes: 30 additions & 5 deletions hathor/conf/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,12 @@
import os
from math import log
from pathlib import Path
from typing import NamedTuple, Optional, Union
from typing import Any, NamedTuple, Optional, Union

import pydantic

from hathor.checkpoint import Checkpoint
from hathor.consensus.consensus_settings import ConsensusSettings, PowSettings
from hathor.feature_activation.settings import Settings as FeatureActivationSettings
from hathor.utils import yaml
from hathor.utils.named_tuple import validated_named_tuple_from_dict
Expand Down Expand Up @@ -436,6 +437,9 @@ def GENESIS_TX2_TIMESTAMP(self) -> int:
# List of enabled blueprints.
BLUEPRINTS: dict[bytes, 'str'] = {}

# The consensus algorithm protocol settings.
CONSENSUS_ALGORITHM: ConsensusSettings = PowSettings()

@classmethod
def from_yaml(cls, *, filepath: str) -> 'HathorSettings':
"""Takes a filepath to a yaml file and returns a validated HathorSettings instance."""
Expand Down Expand Up @@ -473,7 +477,7 @@ def _parse_blueprints(blueprints_raw: dict[str, str]) -> dict[bytes, str]:
return blueprints


def _parse_hex_str(hex_str: Union[str, bytes]) -> bytes:
def parse_hex_str(hex_str: Union[str, bytes]) -> bytes:
"""Parse a raw hex string into bytes."""
if isinstance(hex_str, str):
return bytes.fromhex(hex_str.lstrip('x'))
Expand All @@ -484,6 +488,24 @@ def _parse_hex_str(hex_str: Union[str, bytes]) -> bytes:
return hex_str


def _validate_consensus_algorithm(consensus_algorithm: ConsensusSettings, values: dict[str, Any]) -> ConsensusSettings:
"""Validate that if Proof-of-Authority is enabled, block rewards must not be set."""
if consensus_algorithm.is_pow():
return consensus_algorithm

assert consensus_algorithm.is_poa()
blocks_per_halving = values.get('BLOCKS_PER_HALVING')
initial_token_units_per_block = values.get('INITIAL_TOKEN_UNITS_PER_BLOCK')
minimum_token_units_per_block = values.get('MINIMUM_TOKEN_UNITS_PER_BLOCK')
assert initial_token_units_per_block is not None, 'INITIAL_TOKEN_UNITS_PER_BLOCK must be set'
assert minimum_token_units_per_block is not None, 'MINIMUM_TOKEN_UNITS_PER_BLOCK must be set'

if blocks_per_halving is not None or initial_token_units_per_block != 0 or minimum_token_units_per_block != 0:
raise ValueError('PoA networks do not support block rewards')

return consensus_algorithm


_VALIDATORS = dict(
_parse_hex_str=pydantic.validator(
'P2PKH_VERSION_BYTE',
Expand All @@ -494,19 +516,22 @@ def _parse_hex_str(hex_str: Union[str, bytes]) -> bytes:
'GENESIS_TX2_HASH',
pre=True,
allow_reuse=True
)(_parse_hex_str),
)(parse_hex_str),
_parse_soft_voided_tx_id=pydantic.validator(
'SOFT_VOIDED_TX_IDS',
pre=True,
allow_reuse=True,
each_item=True
)(_parse_hex_str),
)(parse_hex_str),
_parse_checkpoints=pydantic.validator(
'CHECKPOINTS',
pre=True
)(_parse_checkpoints),
_parse_blueprints=pydantic.validator(
'BLUEPRINTS',
pre=True
)(_parse_blueprints)
)(_parse_blueprints),
_validate_consensus_algorithm=pydantic.validator(
'CONSENSUS_ALGORITHM'
)(_validate_consensus_algorithm),
)
86 changes: 86 additions & 0 deletions hathor/consensus/consensus_settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# Copyright 2024 Hathor Labs
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from abc import ABC, abstractmethod
from enum import Enum, unique
from typing import Annotated, Literal, TypeAlias

from pydantic import Field, validator
from typing_extensions import override

from hathor.transaction import TxVersion
from hathor.utils.pydantic import BaseModel


@unique
class ConsensusType(str, Enum):
PROOF_OF_WORK = 'PROOF_OF_WORK'
PROOF_OF_AUTHORITY = 'PROOF_OF_AUTHORITY'


class _BaseConsensusSettings(ABC, BaseModel):
type: ConsensusType

def is_pow(self) -> bool:
"""Return whether this is a Proof-of-Work consensus."""
return self.type is ConsensusType.PROOF_OF_WORK

def is_poa(self) -> bool:
"""Return whether this is a Proof-of-Authority consensus."""
return self.type is ConsensusType.PROOF_OF_AUTHORITY

@abstractmethod
def _get_valid_vertex_versions(self) -> set[TxVersion]:
"""Return a set of `TxVersion`s that are valid in for this consensus type."""
raise NotImplementedError

def is_vertex_version_valid(self, version: TxVersion) -> bool:
"""Return whether a `TxVersion` is valid for this consensus type."""
return version in self._get_valid_vertex_versions()


class PowSettings(_BaseConsensusSettings):
type: Literal[ConsensusType.PROOF_OF_WORK] = ConsensusType.PROOF_OF_WORK

@override
def _get_valid_vertex_versions(self) -> set[TxVersion]:
return {
TxVersion.REGULAR_BLOCK,
TxVersion.REGULAR_TRANSACTION,
TxVersion.TOKEN_CREATION_TRANSACTION,
TxVersion.MERGE_MINED_BLOCK
}


class PoaSettings(_BaseConsensusSettings):
type: Literal[ConsensusType.PROOF_OF_AUTHORITY] = ConsensusType.PROOF_OF_AUTHORITY

# A list of Proof-of-Authority signer public keys that have permission to produce blocks.
signers: tuple[bytes, ...] = ()

@validator('signers', each_item=True)
def parse_hex_str(cls, hex_str: str | bytes) -> bytes:
from hathor.conf.settings import parse_hex_str
return parse_hex_str(hex_str)

@override
def _get_valid_vertex_versions(self) -> set[TxVersion]:
return {
TxVersion.POA_BLOCK,
TxVersion.REGULAR_TRANSACTION,
TxVersion.TOKEN_CREATION_TRANSACTION,
}


ConsensusSettings: TypeAlias = Annotated[PowSettings | PoaSettings, Field(discriminator='type')]
8 changes: 8 additions & 0 deletions hathor/consensus/poa/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from .poa import BLOCK_WEIGHT_IN_TURN, BLOCK_WEIGHT_OUT_OF_TURN, SIGNER_ID_LEN, get_hashed_poa_data

__all__ = [
'BLOCK_WEIGHT_IN_TURN',
'BLOCK_WEIGHT_OUT_OF_TURN',
'SIGNER_ID_LEN',
'get_hashed_poa_data',
]
36 changes: 36 additions & 0 deletions hathor/consensus/poa/poa.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Copyright 2024 Hathor Labs
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import annotations

import hashlib
from typing import TYPE_CHECKING

from hathor.transaction import Block

if TYPE_CHECKING:
from hathor.transaction.poa import PoaBlock

BLOCK_WEIGHT_IN_TURN = 2.0
BLOCK_WEIGHT_OUT_OF_TURN = 1.0
SIGNER_ID_LEN = 2


def get_hashed_poa_data(block: PoaBlock) -> bytes:
"""Get the data to be signed for the Proof-of-Authority."""
poa_data = block.get_funds_struct()
poa_data += Block.get_graph_struct(block) # We call Block's to exclude poa fields
poa_data += block.get_struct_nonce()
hashed_poa_data = hashlib.sha256(poa_data).digest()
return hashed_poa_data
Loading