Skip to content

Conversation

@PeterGRutherford
Copy link
Contributor

  • Create DifficultyManager in lib-consensus
  • Move DifficultyConfig to lib-consensus
  • Update BlockchainConsensusCoordinator to use DifficultyManager
  • Update Blockchain to delegate difficulty adjustment to Coordinator
  • Add governance parameters for difficulty adjustment
  • Update documentation and architecture diagrams

- Create DifficultyManager in lib-consensus
- Move DifficultyConfig to lib-consensus
- Update BlockchainConsensusCoordinator to use DifficultyManager
- Update Blockchain to delegate difficulty adjustment to Coordinator
- Add governance parameters for difficulty adjustment
- Update documentation and architecture diagrams
Copilot AI review requested due to automatic review settings January 6, 2026 22:14
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR refactors difficulty adjustment ownership from lib-blockchain to lib-consensus, establishing the consensus layer as the authoritative source for difficulty policy. The changes implement a new DifficultyManager that encapsulates Bitcoin-style difficulty adjustment logic and makes parameters governable via DAO proposals.

Key Changes:

  • Created DifficultyManager and DifficultyConfig in lib-consensus with Bitcoin-compatible defaults
  • Updated BlockchainConsensusCoordinator to own and manage difficulty calculations
  • Modified Blockchain::adjust_difficulty() to delegate to consensus coordinator while maintaining backward compatibility
  • Extended DAO governance to support blockchain difficulty parameter updates

Reviewed changes

Copilot reviewed 12 out of 13 changed files in this pull request and generated 11 comments.

Show a summary per file
File Description
lib-consensus/src/lib.rs Adds difficulty module export and re-exports key types
lib-consensus/src/difficulty.rs New module implementing DifficultyManager with Bitcoin-style adjustment algorithm, validation, and DAO governance support
lib-consensus/src/dao/dao_types.rs Adds governance parameters for blockchain difficulty (InitialDifficulty, AdjustmentInterval, TargetTimespan)
lib-consensus/src/dao/dao_engine.rs Adds validation for blockchain difficulty parameters in DAO governance proposals
lib-consensus/docs/api-reference.md Documents DifficultyManager API, configuration options, and DAO integration patterns
lib-consensus/README.md Adds difficulty management section highlighting consensus ownership and DAO governance
lib-blockchain/src/lib.rs Re-exports difficulty types from lib-consensus for convenience
lib-blockchain/src/integration/consensus_integration.rs Integrates DifficultyManager into BlockchainConsensusCoordinator with delegation methods
lib-blockchain/src/blockchain.rs Delegates difficulty adjustment to consensus coordinator with legacy fallback
lib-blockchain/docs/architecture.md Updates architecture to include difficulty management coordination
lib-blockchain/docs/api-reference.md Documents that DIFFICULTY_ADJUSTMENT_INTERVAL is now a fallback constant
Cargo.toml Changes package.metadata to workspace.metadata (appears unrelated to PR scope)
Cargo.lock Adds new dependencies (rand_chacha, turmoil, rand_distr, libm) not mentioned in PR description

- Remove redundant height > 0 condition in should_adjust()
- Fix double lock acquisition in blockchain.rs adjust_difficulty()
- Add division by zero checks in legacy difficulty calculation
- Make config_mut() private to prevent bypassing validation
- Add min_timespan safeguard against integer division returning 0
- Document complete governance application flow for difficulty params
- Remove duplicate DifficultyManager documentation
- Add comprehensive tests for setter methods
- Add 4 new integration tests for difficulty manager
- Export initialize_consensus_integration_with_difficulty_config()

All tests passing. Fixes address security, correctness, and maintainability issues.
…culty-adjustment-ownership-to-lib-consensus

Resolved conflict in Cargo.toml by keeping [workspace.metadata.dev-tools]
@umwelt
Copy link
Contributor

umwelt commented Jan 9, 2026

Code review

Found 1 issue:

  1. Inconsistent error handling for zero actual_timespan between DifficultyManager and legacy fallback creates consensus risk

When the consensus coordinator path is used, DifficultyManager::adjust_difficulty() returns an error if actual_timespan == 0. However, when this error triggers the fallback to calculate_difficulty_legacy(), the legacy code silently returns the current difficulty unchanged for the same condition. This creates a window where different nodes could diverge on difficulty calculations:

  • Node A: coordinator succeeds, returns error (actual_timespan == 0)
  • Node B: coordinator fails, fallback silently handles it → different result
  • Result: potential chain fork

Both paths should handle zero timespan consistently—either both error out or both silently return current difficulty (but not mixed).

/// Validator information stored on-chain
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidatorInfo {
/// Validator identity ID
pub identity_id: String,
/// Staked amount (in micro-ZHTP)
pub stake: u64,
/// Storage provided (in bytes)
pub storage_provided: u64,

https://github.com/SOVEREIGN-NET/The-Sovereign-Network/blob/9350cf7350a953bf249d40878703cef8a265cad0/lib-consensus/src/difficulty.rs#L1184-L1192

…with legacy fallback

- Changed DifficultyManager::adjust_difficulty() to return Ok(None) instead of error when actual_timespan is zero
- This matches the behavior of calculate_difficulty_legacy() which silently returns current difficulty
- Both code paths now handle the edge case identically, preventing consensus divergence
- Added warning log to trace when this rare condition occurs

Fixes inconsistent error handling between coordinator and fallback paths that could cause chain forks when actual_timespan equals zero (identical block timestamps).
@sonarqubecloud
Copy link

sonarqubecloud bot commented Jan 9, 2026

@umwelt umwelt merged commit 2cbae63 into development Jan 9, 2026
4 checks passed
@umwelt umwelt deleted the fix/refactorlib-blockchain-move-difficulty-adjustment-ownership-to-lib-consensus branch January 9, 2026 21:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

refactor(lib-blockchain): Move difficulty adjustment ownership to lib-consensus

3 participants