Class SyncManager

java.lang.Object
com.privatechain.network.sync.SyncManager
All Implemented Interfaces:
ChainSyncer

public final class SyncManager extends Object implements ChainSyncer
Synchronizes the local blockchain with the P2P network on node startup and after partition recovery (FR-NET-04, design.md §4.3).

Algorithm

  1. Broadcast GET_STATUS to all connected peers.
  2. Collect STATUS responses (chainHeight per peer).
  3. Find the peer with max(chainHeight).
  4. If that height is greater than the local chain: fetch the missing blocks from that peer via BlockFetcher.
  5. Validate and append each fetched block via Blockchain.addBlock(Block).
  6. If the peer's chain is shorter or equal: local chain is already up-to-date.

Fork handling

If during sync a received block fails Blockchain.addBlock(Block) (e.g., because its previousHash does not match the local tip), ForkResolver is consulted. A full chain replacement is outside the scope of this milestone and is noted as a backlog item (T-B04).

Thread safety

syncChain() is designed to be called from the node-startup thread. Concurrent calls are allowed but each call proceeds independently; Blockchain.addBlock(com.privatechain.core.model.Block) is thread-safe via its internal ReentrantLock.

Since:
1.0.0
See Also:
  • Constructor Details

    • SyncManager

      public SyncManager(String localNodeId, Blockchain blockchain, PeerManager peerManager, BlockFetcher blockFetcher, ForkResolver forkResolver, MessageCodec codec, NodeClient nodeClient)
      Constructs a SyncManager with all required dependencies.
      Parameters:
      localNodeId - this node's stable logical identifier (non-null, non-blank)
      blockchain - the local chain manager (non-null)
      peerManager - the peer lifecycle manager (non-null)
      blockFetcher - the block downloader (non-null)
      forkResolver - the fork-selection arbiter (non-null)
      codec - message codec for GET_STATUS/STATUS messages (non-null)
      nodeClient - outbound TCP client (non-null)
      Throws:
      NullPointerException - if any parameter is null
      IllegalArgumentException - if localNodeId is blank
  • Method Details

    • syncChain

      public int syncChain()
      Performs chain synchronization against the connected peer network.

      This method implements the peer-sync flow described in design.md §4.3:

      1. Query all connected peers for their chain heights via GET_STATUS.
      2. Select the peer with the greatest height as the sync source.
      3. Fetch and apply any missing blocks from that peer.

      If no peers are connected, or if all peers have equal/lower chain heights, this method returns immediately without modifying the local chain.

      Specified by:
      syncChain in interface ChainSyncer
      Returns:
      the number of blocks appended to the local chain during this sync session