Skip to content

cryptix-network/fastchain-fork-resolver

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 

Repository files navigation

Cryptix Fastchain ForkResolver

  • Copyright @Cryptis (Cryptix-Network.org)

Cryptix Fastchain ForkResolver is a robust, deterministic component designed for blockchain systems to handle chain forks, orphan blocks, and reorganizations (reorgs). It is optimized for mainnet environments, emphasizing security, performance, and resistance to common attacks such as fork bombs, DoS via orphans, and Byzantine faults. Built in Rust, it integrates seamlessly with storage backends, state management, and mempools, ensuring efficient resolution of chain divergences while maintaining determinism for reproducibility. The ForkResolver is designed for high-throughput chains with high BPS. It can easily handle true 10 BPS through fast response and action times. The ForkResolver is designed for high-throughput chains with high BPS. It can easily handle true 10 BPS through fast response and execution times. However, actual performance depends on factors such as hardware, network latency, storage backend (e.g., RocksDB), and chain configuration. The resolver would certainly be able to handle very fast block times.

Overview

In decentralized blockchain networks, forks occur when multiple valid blocks compete for inclusion in the canonical chain. ForkResolver detects, evaluates, and resolves these forks by comparing chain work, validating completeness, and performing safe reorgs. It includes advanced features like orphan block management with rate limiting, missing block tracking for P2P synchronization, and bloom filters for transaction deduplication. The design prioritizes determinism (using block heights and timestamps instead of system time) to support consistent behavior across nodes.

This library is suitable for blockchain implementations requiring high reliability, such as those inspired by Bitcoin or Ethereum, and is prepared for integration with P2P layers (e.g., via libp2p).

Key Features

  • Fork Detection and Resolution:

    • Identifies forks by tracing alternative chains back to a common ancestor.
    • Builds partial or complete alternative chains, detecting gaps and requesting missing blocks.
    • Supports dynamic maximum reorg depth based on expected block time, with configurable limits to prevent deep reorgs.
  • Chain Comparison and Selection:

    • Compares chains using cumulative work, with thresholds for work and height advantages.
    • Validates cumulative work for Byzantine protection and enforces checkpoints to prevent invalid reorgs.
    • Rejects incomplete chains below a minimum length threshold for security.
  • Orphan Block Management:

    • Stores and prunes orphan blocks deterministically using block timestamps and a priority heap (O(log n) operations).
    • Enforces global capacity limits, per-parent limits to mitigate fork bombs, and per-peer rate limiting.
    • Provides methods to connect orphans to the main chain and retrieve statistics (e.g., utilization in permille).
  • Missing Block Tracking:

    • Tracks and prioritizes requests for missing blocks (e.g., parents in forks or orphans) with deterministic exponential backoff based on block heights.
    • Supports prioritization by reason (e.g., fork chain parents > orphans > chain gaps) and retry limits for DoS protection.
    • Integrates with P2P layers by exposing next-request methods; marks blocks as received or failed.
  • Transaction Handling:

    • Uses a bloom filter for fast probabilistic checks of transaction existence in recent chain history.
    • Validates transactions during reorgs, including nonce, balance, signature, and gas checks.
    • Reinjects valid transactions from reverted blocks into the mempool post-reorg.
  • Performance Optimizations:

    • LRU caching for block retrieval to reduce storage I/O.
    • Batch processing for reorgs to minimize state mutations.
    • Deterministic pruning and cleanup routines to manage memory usage.
  • Security Measures:

    • Timestamp validation using Median Time Past (MTP) with slack for minor dfastchains.
    • Protection against memory exhaustion, rate-limited inputs, and invalid chains.
    • Configurable constants for mainnet tuning (e.g., max orphans, retry intervals).

Architecture

ForkResolver comprises several interconnected components:

  • ForkResolver Struct: Central manager integrating storage, state, orphan manager, and trackers.
  • OrphanBlockManager: Handles orphan storage with thread-safe RwLock, priority queues, and peer trackers.
  • MissingBlockTracker: Manages requests for absent blocks with a priority queue for deterministic ordering.
  • TxBloomFilter: Probabilistic filter for quick transaction existence checks, rebuilt periodically.
  • BlockCache: LRU cache for frequent block accesses.

The system is designed to be extensible, with hooks for mempool integration and P2P request loops.

Usage

Installation

Add to your Cargo.toml:

[dependencies]
fastchain-fork-resolver = "0.1.0"  

Basic Example

use fork_resolver::{ForkResolver, Storage, State};
use std::sync::Arc;
use parking_lot::RwLock;

fn main() {
    let storage = Arc::new(Storage::new(/* config */));
    let state = Arc::new(RwLock::new(State::new()));
    let mut resolver = ForkResolver::new(storage, state);

    // Set mempool if available
    // resolver.set_mempool(Arc::new(RwLock::new(Mempool::new())));

    // Add a checkpoint
    resolver.add_checkpoint(1000, [/* block hash */]);

    // Handle an incoming block
    let block = /* incoming block */;
    if let Err(e) = resolver.handle_fork(&block) {
        eprintln!("Fork handling error: {}", e);
    }

    // Request next missing block for P2P
    if let Some(missing_hash) = resolver.get_next_missing_block_request() {
        // Send request to peers
    }
}

Integration information

Things to consider for high BPS:

Storage latency LRU caching helps, but large chains or slow databases can be limiting factors.

Transaction validation With a very high number of transactions per block, CPU can become the bottleneck.

Network latency At a true 10 BPS, the P2P layer must deliver extremely fast results → a resolver alone is insufficient.

Deep orphan/fork scenarios Extremely deep forks increase heap/hashmap operations → the minimum overhead per block increases.

Configuration

Constants are defined in fastchain_blockchain_core::constants and can be tuned via environment variables or build flags. Key tunables include:

  • MAX_ORPHAN_CAPACITY: Global orphan limit.
  • ORPHAN_RATE_LIMIT_PER_PEER: Per-peer orphan submission rate.
  • TX_BLOOM_REBUILD_INTERVAL: Bloom filter rebuild frequency.
  • MAX_REORG_DEPTH: Maximum allowed reorg depth.

Contributing

Contributions are welcome! Please submit pull requests for bug fixes, features, or documentation improvements. Ensure all changes maintain determinism and include tests.

License

MIT License.

About

fastchain-fork-resolver

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages