consensus: integrate state root computation and validation with state transition system
Some checks failed
Integration Tests / test-service-integration (push) Has been cancelled
Python Tests / test-python (push) Has been cancelled
Security Scanning / security-scan (push) Has been cancelled
Documentation Validation / validate-docs (push) Has been cancelled

- Add _compute_state_root helper function to compute Merkle Patricia Trie state root from account state
- Replace direct balance/nonce updates with state_transition.apply_transaction in block proposal
- Compute and set state_root for both regular blocks and genesis block
- Add state root verification in sync.py after importing blocks
- Add application-layer database validation with DatabaseOperationValidator class
This commit is contained in:
aitbc
2026-04-13 19:16:54 +02:00
parent b3bec1041c
commit b74dfd76e3
12 changed files with 1065 additions and 24 deletions

View File

@@ -8,11 +8,11 @@ from typing import Callable, ContextManager, Optional
from sqlmodel import Session, select
from ..logger import get_logger
from ..metrics import metrics_registry
from ..gossip import gossip_broker
from ..state.merkle_patricia_trie import StateManager
from ..state.state_transition import get_state_transition
from ..config import ProposerConfig
from ..models import Block, Account
from ..gossip import gossip_broker
_METRIC_KEY_SANITIZE = re.compile(r"[^a-zA-Z0-9_]")
@@ -22,6 +22,25 @@ def _sanitize_metric_suffix(value: str) -> str:
return sanitized or "unknown"
def _compute_state_root(session: Session, chain_id: str) -> str:
"""Compute state root from current account state."""
state_manager = StateManager()
# Get all accounts for this chain
accounts = session.exec(
select(Account).where(Account.chain_id == chain_id)
).all()
# Convert to dictionary
account_dict = {acc.address: acc for acc in accounts}
# Compute state root
root = state_manager.compute_state_root(account_dict)
# Return as hex string
return '0x' + root.hex()
import time
@@ -200,10 +219,22 @@ class PoAProposer:
else:
self._logger.info(f"[PROPOSE] Recipient account exists for {recipient}")
# Update balances
sender_account.balance -= total_cost
sender_account.nonce += 1
recipient_account.balance += value
# Apply state transition through validated transaction
state_transition = get_state_transition()
tx_data = {
"from": sender,
"to": recipient,
"value": value,
"fee": fee,
"nonce": sender_account.nonce
}
success, error_msg = state_transition.apply_transaction(
session, self._config.chain_id, tx_data, tx.tx_hash
)
if not success:
self._logger.warning(f"[PROPOSE] Failed to apply transaction {tx.tx_hash}: {error_msg}")
continue
# Check if transaction already exists in database
existing_tx = session.exec(
@@ -256,7 +287,7 @@ class PoAProposer:
proposer=self._config.proposer_id,
timestamp=timestamp,
tx_count=len(processed_txs),
state_root=None,
state_root=_compute_state_root(session, self._config.chain_id),
)
session.add(block)
session.commit()
@@ -327,7 +358,7 @@ class PoAProposer:
proposer="genesis", # Use "genesis" as the proposer for genesis block to avoid hash conflicts
timestamp=timestamp,
tx_count=0,
state_root=None,
state_root=_compute_state_root(session, self._config.chain_id),
)
session.add(genesis)
try: