šŸŽ‰ 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
šŸ’¼ Servicesā„¹ļø Aboutāœ‰ļø ContactView Pricing Plansfrom $10

Blockchain Networking

Network Layer🟢 Free Lesson

Blockchain Networking

P2P protocols, gossip protocol, node discovery, block propagation, network topology, eclipse attacks, and Sybil resistance.

Overview

Blockchain networking enables decentralized communication between nodes. The network layer is critical for maintaining consensus, propagating transactions, and ensuring all nodes have consistent views of the blockchain.

Peer-to-Peer Architecture

P2P Network Models

P2P Network TopologiesFull MeshO(n²) connectionsStar NetworkCentral point of failureGossip NetworkO(n log n) messagesNetwork Comparison• Full Mesh: Best latency, worst scalability• Star: Easy management, single point of failure• Gossip: Scales well, eventual consistencyBlockchain Choice: Gossip + random peersBitcoin: ~8 connections per nodeEthereum: ~25 connections per node

P2P Implementation

python
import asyncio
import hashlib
import time
from typing import Dict, List, Set, Optional
from dataclasses import dataclass
from collections import deque

@dataclass
class Peer:
    """Represents a network peer."""
    node_id: str
    address: str
    port: int
    last_seen: float
    latency: float = 0.0
    is_valid: bool = True

class P2PNetwork:
    """Simplified P2P network layer."""

    MAX_PEERS = 50
    MIN_PEERS = 8
    PEER_TIMEOUT = 300  # 5 minutes

    def __init__(self, node_id: str, port: int):
        self.node_id = node_id
        self.port = port
        self.peers: Dict[str, Peer] = {}
        self.known_nodes: Set[str] = set()
        self.message_queue = deque()

    async def connect_to_bootstrap(self, bootstrap_nodes: List[str]):
        """Connect to bootstrap nodes."""
        for addr in bootstrap_nodes:
            try:
                await self.add_peer(addr)
            except Exception as e:
                print(f"Failed to connect to {addr}: {e}")

    async def add_peer(self, address: str, port: int = 8333) -> bool:
        """Add a new peer."""
        if len(self.peers) >= self.MAX_PEERS:
            return False

        node_id = hashlib.sha256(address.encode()).hexdigest()[:16]

        peer = Peer(
            node_id=node_id,
            address=address,
            port=port,
            last_seen=time.time()
        )

        self.peers[node_id] = peer
        return True

    def remove_peer(self, node_id: str):
        """Remove a peer."""
        if node_id in self.peers:
            del self.peers[node_id]

    async def broadcast(self, message: dict, exclude: Optional[str] = None):
        """Broadcast message to all peers."""
        for peer_id, peer in self.peers.items():
            if peer_id != exclude and peer.is_valid:
                await self.send_to_peer(peer, message)

    async def send_to_peer(self, peer: Peer, message: dict):
        """Send message to specific peer."""
        try:
            # Simulated network call
            await asyncio.sleep(0.01)
            peer.last_seen = time.time()
        except Exception:
            peer.is_valid = False

    def get_peers_to_connect(self) -> List[str]:
        """Get addresses of peers to connect to."""
        # Bitcoin's AddrMan-style peer selection
        addresses = []
        for peer in self.peers.values():
            if peer.is_valid:
                addresses.append(f"{peer.address}:{peer.port}")
        return addresses[:self.MIN_PEERS]

    def cleanup_stale_peers(self):
        """Remove peers that haven't been seen recently."""
        current_time = time.time()
        stale = [
            node_id for node_id, peer in self.peers.items()
            if current_time - peer.last_seen > self.PEER_TIMEOUT
        ]
        for node_id in stale:
            self.remove_peer(node_id)

# Example usage
async def main():
    network = P2PNetwork("node_1", 8333)
    await network.connect_to_bootstrap([
        "192.168.1.100",
        "192.168.1.101"
    ])
    print(f"Connected to {len(network.peers)} peers")

asyncio.run(main())

Gossip Protocol

Gossip protocols enable efficient message propagation across the network.

Epidemic Spread Model

Architecture Diagram
Round 1: Node A → Node B, C
Round 2: Node A → Node D, Node B → Node E, Node C → Node F
Round 3: Continue until all nodes receive message

Convergence Time: O(log n) rounds

Gossip Implementation

python
import random
import hashlib
from typing import Dict, List, Set
from dataclasses import dataclass, field
from collections import defaultdict
import time

@dataclass
class GossipMessage:
    """Gossip protocol message."""
    message_id: str
    sender: str
    data: bytes
    timestamp: float
    ttl: int = 10  # Time to live (hops)

class GossipProtocol:
    """Gossip protocol implementation."""

    GOSSIP_FANOUT = 3  # Number of peers to gossip to
    GOSSIP_INTERVAL = 1.0  # Seconds between gossip rounds

    def __init__(self, node_id: str):
        self.node_id = node_id
        self.peers: Set[str] = set()
        self.seen_messages: Dict[str, float] = {}
        self.received_messages: List[GossipMessage] = []
        self.pending_gossip: List[GossipMessage] = []

    def add_peer(self, peer_id: str):
        """Add peer to gossip network."""
        self.peers.add(peer_id)

    def create_message(self, data: bytes) -> GossipMessage:
        """Create new gossip message."""
        message_id = hashlib.sha256(
            f"{self.node_id}:{time.time()}:{data}".encode()
        ).hexdigest()[:16]

        msg = GossipMessage(
            message_id=message_id,
            sender=self.node_id,
            data=data,
            timestamp=time.time()
        )

        self.seen_messages[message_id] = time.time()
        self.pending_gossip.append(msg)

        return msg

    def receive_message(self, message: GossipMessage) -> bool:
        """Receive gossip message. Returns True if new."""
        # Check if already seen
        if message.message_id in self.seen_messages:
            return False

        # Record as seen
        self.seen_messages[message.message_id] = time.time()
        self.received_messages.append(message)

        # Add to pending gossip
        message.ttl -= 1
        if message.ttl > 0:
            self.pending_gossip.append(message)

        return True

    def get_gossip_targets(self) -> List[str]:
        """Select random peers to gossip to."""
        available_peers = list(self.peers - {self.node_id})

        if len(available_peers) == 0:
            return []

        # Random selection
        targets = random.sample(
            available_peers,
            min(self.GOSSIP_FANOUT, len(available_peers))
        )

        return targets

    def run_gossip_round(self) -> Dict[str, List[GossipMessage]]:
        """Execute one round of gossip."""
        gossip_map = {}

        for message in self.pending_gossip:
            targets = self.get_gossip_targets()
            for target in targets:
                if target not in gossip_map:
                    gossip_map[target] = []
                gossip_map[target].append(message)

        self.pending_gossip.clear()
        return gossip_map

    def cleanup_old_messages(self, max_age: float = 3600):
        """Remove old seen messages."""
        current_time = time.time()
        to_remove = [
            msg_id for msg_id, timestamp in self.seen_messages.items()
            if current_time - timestamp > max_age
        ]
        for msg_id in to_remove:
            del self.seen_messages[msg_id]

# Simulation
def simulate_gossip(num_nodes: int = 100, num_messages: int = 5):
    """Simulate gossip protocol across network."""
    nodes = [GossipProtocol(f"node_{i}") for i in range(num_nodes)]

    # Connect all nodes
    for i in range(num_nodes):
        for j in range(num_nodes):
            if i != j:
                nodes[i].add_peer(f"node_{j}")

    # Originator sends message
    originator = nodes[0]
    msg = originator.create_message(b"Hello, Network!")

    # Run gossip rounds
    rounds = 0
    while any(node.received_messages == [] for node in nodes[1:]):
        for node in nodes:
            gossip_map = node.run_gossip_round()

            # Deliver messages
            for target, messages in gossip_map.items():
                target_node = next(
                    (n for n in nodes if n.node_id == target), None
                )
                if target_node:
                    for msg in messages:
                        target_node.receive_message(msg)

        rounds += 1
        if rounds > 100:
            break

    # Calculate statistics
    received_count = sum(1 for n in nodes[1:] if n.received_messages)
    print(f"Nodes reached: {received_count}/{num_nodes-1}")
    print(f"Rounds: {rounds}")
    print(f"Efficiency: {received_count / (rounds * num_nodes):.2%}")

simulate_gossip(50, 1)

Gossip Properties

PropertyDescription
Scalability rounds to reach all nodes
Fault toleranceTolerates node failures
Bandwidth total messages
LatencyLogarithmic in network size
RedundancyEach node receives message multiple times

Node Discovery

Bitcoin DNS Seeds

python
import socket
import dns.resolver
from typing import List

class BitcoinNodeDiscovery:
    """Bitcoin node discovery mechanisms."""

    DNS_SEEDS = [
        "seed.bitcoin.sipa.be",
        "dnsseed.bluematt.me",
        "dnsseed.bitcoin.dashjr-list-of-p2p-nodes.us",
        "seed.bitcoinstats.com",
        "seed.bitcoin.jonasschnelli.ch",
        "seed.btc.petertodd.net",
        "seed.bitcoin.sprovoost.nl",
    ]

    def discover_via_dns(self) -> List[str]:
        """Discover nodes via DNS seeds."""
        addresses = []

        for seed in self.DNS_SEEDS:
            try:
                resolver = dns.resolver.Resolver()
                resolver.timeout = 5
                result = resolver.resolve(seed, 'A')

                for rdata in result:
                    addresses.append(str(rdata))

            except Exception as e:
                print(f"DNS seed {seed} failed: {e}")

        return addresses[:100]  # Limit results

    def discover_via_hardcoded(self) -> List[str]:
        """Discover via hardcoded node list."""
        # In production, this would be maintained
        return [
            "127.0.0.1:8333",
            "192.168.1.100:8333",
        ]

    def getaddr_message(self) -> dict:
        """Create GETADDR message for peer discovery."""
        return {
            'command': 'getaddr',
            'timestamp': int(time.time())
        }

    def addr_message(self, addresses: List[str]) -> dict:
        """Create ADDR message with known addresses."""
        return {
            'command': 'addr',
            'addresses': addresses,
            'timestamp': int(time.time())
        }

# Example
discovery = BitcoinNodeDiscovery()
dns_addresses = discovery.discover_via_dns()
print(f"Discovered {len(dns_addresses)} addresses via DNS")

Ethereum Node Discovery (ENR)

python
class EthereumNodeRecord:
    """Ethereum Node Record (ENR) for node discovery."""

    def __init__(self):
        self.fields = {
            'secp256k1': None,  # Public key
            'ip': None,
            'tcp': None,
            'udp': None,
        }
        self.signature = None

    def encode(self) -> bytes:
        """Encode ENR to bytes."""
        # Simplified encoding
        data = ""
        for key, value in self.fields.items():
            if value is not None:
                data += f"{key}={value}&"
        return data.encode()

    @classmethod
    def decode(cls, data: bytes) -> 'EthereumNodeRecord':
        """Decode ENR from bytes."""
        enr = cls()
        # Simplified decoding
        return enr

class NodeDiscoveryV5:
    """Ethereum discv5 node discovery protocol."""

    def __init__(self, node_id: bytes):
        self.node_id = node_id
        self.known_nodes = {}
        self.routing_table = {}  # k-buckets

    def ping(self, target_node: bytes) -> bool:
        """Send PING message to node."""
        # Simulate ping
        return True

    def pong(self, target_node: bytes) -> dict:
        """Respond to PING with PONG."""
        return {
            'enr_seq': 1,
            'hash': hashlib.sha256(target_node).digest()[:16]
        }

    def find_node(self, target: bytes) -> list:
        """Find nodes closest to target ID."""
        # Find nodes in routing table closest to target
        closest_nodes = sorted(
            self.known_nodes.keys(),
            key=lambda x: int.from_bytes(
                bytes([a ^ b for a, b in zip(x, target)]), 'big'
            )
        )[:16]

        return closest_nodes

    def talk_req(self, target: bytes, msg_type: int, payload: bytes) -> bytes:
        """Send TALKREQ message."""
        return b"response"

Discovery Protocol Comparison

ProtocolMechanismLatencyScalability
Bitcoin DNSDNS seeds + addr msgsHighMedium
Ethereum discv5Kademlia DHTMediumHigh
LibP2PmDNS + DHTLowHigh
Tor OnionOnion routingVery HighMedium

Block Propagation

Compact Block Relay (BIP 152)

python
import hashlib
from typing import List, Dict
from dataclasses import dataclass

@dataclass
class TransactionShortID:
    """Compact block transaction short ID."""
    index: int
    short_id: int  # 6-byte truncated hash

class CompactBlock:
    """BIP 152 compact block."""

    def __init__(self, block_hash: bytes, nonce: int, short_ids: List[int]):
        self.block_hash = block_hash
        self.nonce = nonce
        self.short_ids = short_ids
        self.prefilled_txn = []

    def encode(self) -> bytes:
        """Encode compact block."""
        data = self.block_hash
        data += self.nonce.to_bytes(8, 'big')
        data += len(self.short_ids).to_bytes(2, 'big')
        for sid in self.short_ids:
            data += sid.to_bytes(6, 'big')
        return data

class CompactBlockRelay:
    """Compact block relay protocol."""

    def __init__(self):
        self.block_index = {}  # Hash -> transactions
        self.short_id_index = {}  # Short ID -> hash

    def create_compact_block(self, block: dict) -> CompactBlock:
        """Create compact block from full block."""
        nonce = int.from_bytes(hashlib.sha256(b"random").digest()[:8], 'big')

        short_ids = []
        for i, tx_hash in enumerate(block['transactions']):
            # Create short ID (6 bytes)
            full_hash = hashlib.sha256(
                tx_hash + nonce.to_bytes(8, 'big')
            ).digest()
            short_id = int.from_bytes(full_hash[:6], 'big')
            short_ids.append(short_id)

            # Store in index
            self.short_id_index[short_id] = tx_hash

        compact = CompactBlock(
            block_hash=block['hash'],
            nonce=nonce,
            short_ids=short_ids
        )

        return compact

    def reconstruct_block(self, compact: CompactBlock, 
                          available_txs: List[bytes]) -> dict:
        """Reconstruct block from compact block and available transactions."""
        transactions = []

        # Build short ID index from available transactions
        local_index = {}
        for tx in available_txs:
            full_hash = hashlib.sha256(
                tx + compact.nonce.to_bytes(8, 'big')
            ).digest()
            short_id = int.from_bytes(full_hash[:6], 'big')
            local_index[short_id] = tx

        # Match short IDs
        for short_id in compact.short_ids:
            if short_id in local_index:
                transactions.append(local_index[short_id])
            else:
                # Request missing transaction (GETBLOCKTXN)
                transactions.append(None)

        return {
            'hash': compact.block_hash,
            'transactions': transactions
        }

# Example
relay = CompactBlockRelay()
block = {
    'hash': hashlib.sha256(b"block").digest(),
    'transactions': [hashlib.sha256(f"tx{i}".encode()).digest() for i in range(10)]
}

compact = relay.create_compact_block(block)
print(f"Compact block: {len(compact.short_ids)} short IDs")
print(f"Original: {len(block['transactions'])} transactions")
print(f"Compression: {(1 - len(compact.short_ids) * 6 / (len(block['transactions']) * 32)) * 100:.1f}%")

Block Propagation Latency

MethodLatencyBandwidthUse Case
Full BlockHighHighInitial sync
Compact BlockLowLowRelay
Erasure CodingMediumVery LowPruned nodes
Block-onlyMediumMediumSPV nodes

Eclipse Attacks

Attack Description

An eclipse attack isolates a target node from the honest network by monopolizing its peer connections.

Eclipse Attack Implementation

python
import random
from typing import List, Dict, Set

class EclipseAttack:
    """Simulate eclipse attack."""

    def __init__(self, target_node: str):
        self.target = target_node
        self.attacker_nodes: Set[str] = set()
        self.target_peers: Set[str] = set()
        self.max_peers = 8  # Typical Bitcoin limit

    def add_attacker_node(self, node_id: str):
        """Add malicious node."""
        self.attacker_nodes.add(node_id)

    def execute_attack(self, honest_nodes: List[str]) -> bool:
        """Execute eclipse attack."""
        # Fill target's peer slots with attacker nodes
        for _ in range(self.max_peers):
            if self.attacker_nodes:
                attacker = random.choice(list(self.attacker_nodes))
                self.target_peers.add(attacker)

        # Check if eclipse achieved
        attacker_count = len(
            self.target_peers & self.attacker_nodes
        )

        return attacker_count >= self.max_peers

    def isolate_from_network(self) -> dict:
        """Simulate network isolation."""
        return {
            'target': self.target,
            'connected_to': list(self.target_peers),
            'attacker_nodes': list(self.attacker_nodes & self.target_peers),
            'honest_nodes': len(self.target_peers - self.attacker_nodes),
            'eclipseachieved': len(self.attacker_nodes & self.target_peers) >= self.max_peers
        }

    def feed_false_chain(self, fork_height: int) -> dict:
        """Feed false chain to eclipsed node."""
        return {
            'type': 'alternative_chain',
            'height': fork_height,
            'blocks': [f'fake_block_{i}' for i in range(fork_height)]
        }

# Simulation
attack = EclipseAttack("victim_node")

# Create honest and attacker nodes
honest_nodes = [f"honest_{i}" for i in range(100)]
attacker_nodes = [f"attacker_{i}" for i in range(10)]

for node in attacker_nodes:
    attack.add_attacker_node(node)

# Execute attack
success = attack.execute_attack(honest_nodes)
print(f"Eclipse attack {'succeeded' if success else 'failed'}")
print(f"Isolation status: {attack.isolate_from_network()}")

Eclipse Attack Prevention

TechniqueDescriptionEffectiveness
Diversified peersConnect to diverse networksHigh
Anchor nodesPersistent trusted peersHigh
Peer rotationRegularly rotate peersMedium
Geographic diversityConnect to different regionsMedium
IP validationVerify peer IP addressesLow

Sybil Resistance

Definition

Sybil resistance is the ability of a network to defend against attacks where a single entity creates multiple identities.

Sybil Resistance Mechanisms

python
import hashlib
import time
from typing import Dict, List, Optional

class SybilResistance:
    """Sybil resistance mechanisms."""

    def __init__(self):
        self.identity_costs: Dict[str, float] = {}
        self.stake_requirements: Dict[str, int] = {}

    def proof_of_work_sybil_resistance(self, identity: str) -> dict:
        """PoW-based Sybil resistance."""
        # Require work for each identity
        difficulty = 20  # Leading zeros required

        nonce = 0
        while True:
            data = f"{identity}:{nonce}".encode()
            hash_result = hashlib.sha256(data).hexdigest()

            if hash_result.startswith('0' * difficulty):
                return {
                    'identity': identity,
                    'nonce': nonce,
                    'hash': hash_result,
                    'cost': nonce  # Computational cost
                }
            nonce += 1

            if nonce > 1000000:  # Limit for simulation
                break

        return None

    def proof_of_stake_sybil_resistance(self, identity: str, stake: int) -> dict:
        """PoS-based Sybil resistance."""
        # Cost = locked capital
        min_stake = 32  # ETH equivalent

        if stake < min_stake:
            return {'error': 'Insufficient stake'}

        return {
            'identity': identity,
            'stake': stake,
            'cost': stake,  # Capital cost
            'slashing_risk': stake * 0.1  # 10% slashing
        }

    def reputation_based_resistance(self, identity: str, reputation: float) -> dict:
        """Reputation-based Sybil resistance."""
        # New identities have low reputation
        return {
            'identity': identity,
            'reputation': reputation,
            'influence': reputation ** 2,  # Quadratic influence
            'cost_to_attack': reputation * 1000
        }

    def rate_limiting(self, identity: str, action: str) -> bool:
        """Rate limiting as Sybil resistance."""
        # Track actions per identity
        if identity not in self.identity_costs:
            self.identity_costs[identity] = 0

        # Rate limit based on reputation/cost
        max_actions = 100
        if self.identity_costs[identity] >= max_actions:
            return False

        self.identity_costs[identity] += 1
        return True

# Example
resistance = SybilResistance()

# PoW resistance
pow_result = resistance.proof_of_work_sybil_resistance("attacker_1")
if pow_result:
    print(f"PoW cost: {pow_result['cost']} hashes")

# PoS resistance
pos_result = resistance.proof_of_stake_sybil_resistance("attacker_1", 32)
print(f"PoS cost: {pos_result['stake']} ETH")

Sybil Resistance Comparison

MechanismCost TypeCost LevelDecentralization
PoWComputationalHighHigh
PoSCapitalHighMedium
DPoSVotingMediumLow
PoAIdentityVariableLow
reputationHistoryMediumMedium

Network Topology Analysis

Degree Distribution

python
import random
import math
from collections import Counter

class NetworkTopology:
    """Analyze network topology."""

    def __init__(self, num_nodes: int):
        self.num_nodes = num_nodes
        self.adjacency = {i: set() for i in range(num_nodes)}

    def random_graph(self, avg_degree: float):
        """Generate random graph."""
        for i in range(self.num_nodes):
            num_connections = random.randint(
                max(1, int(avg_degree * 0.5)),
                min(self.num_nodes - 1, int(avg_degree * 1.5))
            )
            targets = random.sample(
                [j for j in range(self.num_nodes) if j != i],
                min(num_connections, self.num_nodes - 1)
            )
            for j in targets:
                self.adjacency[i].add(j)
                self.adjacency[j].add(i)

    def scale_free_graph(self, gamma: float = 2.5):
        """Generate scale-free graph (BarabĆ”si–Albert model)."""
        # Start with small complete graph
        for i in range(min(5, self.num_nodes)):
            for j in range(i + 1, min(5, self.num_nodes)):
                self.adjacency[i].add(j)
                self.adjacency[j].add(i)

        # Add nodes preferentially
        for i in range(5, self.num_nodes):
            # Preferential attachment
            degrees = [len(self.adjacency[j]) for j in range(i)]
            total_degree = sum(degrees) or 1

            targets = []
            for _ in range(min(3, i)):
                prob = [d / total_degree for d in degrees]
                target = random.choices(range(i), weights=prob, k=1)[0]
                targets.append(target)

            for target in targets:
                self.adjacency[i].add(target)
                self.adjacency[target].add(i)

    def small_world_graph(self, k: int = 6, beta: float = 0.3):
        """Generate small-world graph (Watts-Strogatz model)."""
        # Ring lattice
        for i in range(self.num_nodes):
            for j in range(1, k // 2 + 1):
                neighbor = (i + j) % self.num_nodes
                self.adjacency[i].add(neighbor)
                self.adjacency[neighbor].add(i)

        # Rewire with probability beta
        for i in range(self.num_nodes):
            neighbors = list(self.adjacency[i])
            for j in neighbors:
                if random.random() < beta:
                    # Rewire
                    new_target = random.randint(0, self.num_nodes - 1)
                    if new_target != i and new_target not in self.adjacency[i]:
                        self.adjacency[i].remove(j)
                        self.adjacency[j].remove(i)
                        self.adjacency[i].add(new_target)
                        self.adjacency[new_target].add(i)

    def analyze(self) -> dict:
        """Analyze network properties."""
        degrees = [len(self.adjacency[i]) for i in range(self.num_nodes)]
        avg_degree = sum(degrees) / len(degrees)

        # Clustering coefficient (approximate)
        triangles = 0
        triplets = 0
        for i in range(self.num_nodes):
            neighbors = list(self.adjacency[i])
            for j in range(len(neighbors)):
                for k in range(j + 1, len(neighbors)):
                    triplets += 1
                    if neighbors[k] in self.adjacency[neighbors[j]]:
                        triangles += 1

        clustering = (3 * triangles / triplets) if triplets > 0 else 0

        # Diameter (approximate with BFS)
        diameter = self._approximate_diameter()

        return {
            'num_nodes': self.num_nodes,
            'avg_degree': avg_degree,
            'min_degree': min(degrees),
            'max_degree': max(degrees),
            'clustering_coefficient': clustering,
            'diameter': diameter,
            'density': sum(degrees) / (self.num_nodes * (self.num_nodes - 1))
        }

    def _approximate_diameter(self, samples: int = 10) -> int:
        """Approximate diameter with random BFS."""
        max_dist = 0

        for _ in range(samples):
            start = random.randint(0, self.num_nodes - 1)
            visited = {start: 0}
            queue = [start]

            while queue:
                node = queue.pop(0)
                for neighbor in self.adjacency[node]:
                    if neighbor not in visited:
                        visited[neighbor] = visited[node] + 1
                        max_dist = max(max_dist, visited[neighbor])
                        queue.append(neighbor)

        return max_dist

# Analysis
topology = NetworkTopology(1000)

topology.random_graph(avg_degree=6)
random_stats = topology.analyze()
print(f"Random graph: avg_degree={random_stats['avg_degree']:.1f}, "
      f"clustering={random_stats['clustering_coefficient']:.3f}")

topology2 = NetworkTopology(1000)
topology2.scale_free_graph()
scale_free_stats = topology2.analyze()
print(f"Scale-free: avg_degree={scale_free_stats['avg_degree']:.1f}, "
      f"diameter={scale_free_stats['diameter']}")

Blockchain Network Properties

PropertyBitcoinEthereum
Nodes~15,000~10,000
Avg connections825
Diameter~6~5
Block propagation~2 sec~1 sec
Transaction relay~1 sec~0.5 sec

Trade-offs

Network Design Trade-offs

Trade-offOption AOption B
Connection countMore (better propagation)Less (lower overhead)
Gossip roundsMore (faster convergence)Less (lower bandwidth)
Peer selectionRandom (better diversity)Known (better trust)
Message validationFull (more secure)Partial (faster)

Scalability Solutions

SolutionDescriptionTrade-off
ShardingPartition networkComplexity
Layer 2Off-chain transactionsTrust assumptions
Relay networksBlock propagationCentralization
Compact blocksReduce bandwidthSynchronization

Real-World Examples

Bitcoin Network

  • 15,000+ reachable nodes
  • 8 average connections per node
  • ~2 seconds block propagation
  • BIP 152 compact block relay

Ethereum Network

  • 10,000+ nodes
  • 25 average connections
  • discv5 node discovery
  • libp2p networking stack

Lightning Network

  • ~15,000 nodes
  • ~35,000 channels
  • Onion routing for privacy
  • Gossip protocol for channel updates

Interview Questions

Q1: Explain how the gossip protocol achieves O(log n) convergence time.

Answer: Gossip protocols achieve logarithmic convergence through epidemic spreading:

  1. Fanout: Each node sends to random peers (typically 3-5)
  2. Exponential spread: New nodes receiving message also gossip
  3. Redundancy: Multiple paths ensure reliability

In round , approximately nodes receive the message. To reach nodes:

For and : rounds

Q2: What are the trade-offs between compact blocks and full blocks?

Answer:

AspectFull BlocksCompact Blocks
BandwidthHigh (~1MB)Low (~10KB)
LatencyHigherLower
ReconstructionNone neededRequires mempool
Missing txsN/AGETBLOCKTXN needed
PrivacyShows full blockHides full block initially
Use caseInitial syncBlock relay

Trade-off: Compact blocks save bandwidth but require nodes to maintain mempool and handle reconstruction failures.

Q3: How does Eclipse attack differ from Sybil attack?

Answer:

AspectEclipse AttackSybil Attack
GoalIsolate target nodeGain disproportionate influence
MethodMonopolize peer connectionsCreate multiple identities
TargetSingle nodeEntire network
DefenseDiversified peersCost (PoW/PoS)
ResultFalse view of chainConsensus manipulation

Eclipse attacks isolate a node by controlling all its connections, while Sybil attacks create fake identities to influence consensus.


Quiz Questions

Q1: What is the typical fanout parameter in Bitcoin's gossip protocol?

A) 1 B) 3 C) 10 D) 100

Answer: B) 3

Q2: Which node discovery mechanism does Ethereum use?

A) DNS seeds only B) Hardcoded IPs C) Kademlia DHT (discv5) D) Central registry

Answer: C) Kademlia DHT (discv5)

Q3: What is the main purpose of BIP 152 compact blocks?

A) Compress block headers B) Reduce block propagation bandwidth C) Encrypt block data D) Validate transactions faster

Answer: B) Reduce block propagation bandwidth


Practice

  1. Implement a gossip protocol simulation
  2. Analyze network topology metrics for different graph models
  3. Simulate eclipse attack and test prevention mechanisms
  4. Compare block propagation latency across different relay methods
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-09-22

—
ā˜†ā˜†ā˜†ā˜†ā˜†
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Need Expert Blockchain Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement