Byzantine Fault Tolerance
PBFT, Tendermint, Casper FFG, fault models, quorum requirements, liveness vs safety, and FLP impossibility.
Overview
Byzantine Fault Tolerance (BFT) is the ability of a distributed system to continue functioning correctly even when some nodes fail or act maliciously. This is fundamental to blockchain security.
The Byzantine Generals Problem
Problem Statement
How can distributed parties reach agreement when some parties may be faulty or malicious?
Formal Definition
Given processes, where at most may be Byzantine (malicious), the system must satisfy:
- Agreement: All honest processes decide on the same value
- Validity: If all honest processes propose the same value, that value is decided
- Termination: All honest processes eventually decide
Impossibility Results
FLP Impossibility (1985):
In an asynchronous system with even one faulty process, no deterministic consensus algorithm can guarantee termination.
This impossibility result is circumvented in practice by:
- Randomization
- Partial synchrony assumptions
- Economic incentives (PoS)
- Synchrony assumptions (PoW)
Fault Models
Types of Faults
Fault Model Properties
| Fault Type | Behavior | Detection | Tolerance |
|---|---|---|---|
| Fail-Stop | Stops responding | Timeout | n > 2f |
| Crash | Halts, may recover | Timeout | n > 2f |
| Omission | Drops messages | Message logs | n > 3f |
| Byzantine | Arbitrary behavior | Verification | n > 3f |
Byzantine Generals Example
from enum import Enum
from typing import List, Dict, Set
class MessageType(Enum):
PROPOSE = "propose"
PREPARE = "prepare"
COMMIT = "commit"
class ByzantineNode:
"""Simulate Byzantine node behavior."""
def __init__(self, node_id: int, is_byzantine: bool = False):
self.id = node_id
self.is_byzantine = is_byzantine
self.received_messages = {}
self.sent_messages = set()
def send_message(self, msg_type: MessageType, value: int, recipients: List[int]) -> Dict[int, tuple]:
"""Send message, potentially Byzantine."""
messages = {}
for recipient in recipients:
if recipient == self.id:
continue
if self.is_byzantine:
# Byzantine behavior: send different values
messages[recipient] = (msg_type, value + self.id)
else:
messages[recipient] = (msg_type, value)
return messages
def receive_message(self, sender: int, msg_type: MessageType, value: int):
"""Receive and store message."""
if sender not in self.received_messages:
self.received_messages[sender] = {}
self.received_messages[sender][msg_type] = value
def get_received_values(self, msg_type: MessageType) -> List[int]:
"""Get all received values of a type."""
values = []
for sender, msgs in self.received_messages.items():
if msg_type in msgs:
values.append(msgs[msg_type])
return values
Practical Byzantine Fault Tolerance (PBFT)
PBFT achieves consensus in message complexity with nodes.
PBFT Protocol Phases
Client ā Primary ā All Nodes
Phase 1: Pre-prepare
Primary assigns sequence number to request
Broadcasts <PRE-PREPARE, v, n, d> to all replicas
Phase 2: Prepare
Each replica broadcasts <PREPARE, v, n, d, i>
Wait for 2f matching PREPARE messages
Phase 3: Commit
Each replica broadcasts <COMMIT, v, n, d, i>
Wait for 2f + 1 matching COMMIT messages
Execute request and send reply to client
View Change:
If primary fails, trigger view change
New primary elected via <VIEW-CHANGE> messages
PBFT Implementation
import hashlib
import time
from collections import defaultdict
from typing import List, Dict, Optional
class PBFTMessage:
"""PBFT protocol message."""
def __init__(self, msg_type: str, view: int, sequence: int,
digest: str, node_id: int, data: bytes = None):
self.type = msg_type
self.view = view
self.sequence = sequence
self.digest = digest
self.node_id = node_id
self.data = data
self.timestamp = time.time()
def to_bytes(self) -> bytes:
return f"{self.type}:{self.view}:{self.sequence}:{self.digest}:{self.node_id}".encode()
class PBFTNode:
"""PBFT consensus node."""
def __init__(self, node_id: int, total_nodes: int):
self.id = node_id
self.n = total_nodes
self.f = (self.n - 1) // 3 # Maximum Byzantine faults
self.view = 0
self.sequence = 0
self.log = []
self.prepares = defaultdict(dict)
self.commits = defaultdict(dict)
self.is_primary = (node_id == 0)
def handle_request(self, data: bytes) -> Optional[dict]:
"""Handle client request."""
if not self.is_primary:
return None
# Assign sequence number
self.sequence += 1
digest = hashlib.sha256(data).hexdigest()
# Create pre-prepare message
pre_prepare = PBFTMessage(
'pre-prepare', self.view, self.sequence, digest, self.id, data
)
return {
'type': 'pre-prepare',
'message': pre_prepare,
'data': data
}
def handle_pre_prepare(self, msg: PBFTMessage) -> Optional[dict]:
"""Handle pre-prepare message."""
# Verify message is from current primary
if msg.view != self.view:
return None
# Store pre-prepare
self.prepares[msg.sequence]['pre-prepare'] = msg
# Send prepare message
prepare = PBFTMessage(
'prepare', self.view, msg.sequence, msg.digest, self.id
)
return {
'type': 'prepare',
'message': prepare
}
def handle_prepare(self, msg: PBFTMessage) -> Optional[dict]:
"""Handle prepare message."""
# Store prepare
if msg.sequence not in self.prepares:
self.prepares[msg.sequence] = {}
self.prepares[msg.sequence][f'prepare-{msg.node_id}'] = msg
# Count prepares
prepare_count = sum(
1 for k in self.prepares[msg.sequence]
if k.startswith('prepare-')
)
# Need 2f prepares (including this node's)
if prepare_count >= 2 * self.f:
# Send commit message
commit = PBFTMessage(
'commit', self.view, msg.sequence, msg.digest, self.id
)
return {
'type': 'commit',
'message': commit
}
return None
def handle_commit(self, msg: PBFTMessage) -> Optional[dict]:
"""Handle commit message."""
# Store commit
if msg.sequence not in self.commits:
self.commits[msg.sequence] = {}
self.commits[msg.sequence][f'commit-{msg.node_id}'] = msg
# Count commits
commit_count = sum(
1 for k in self.commits[msg.sequence]
if k.startswith('commit-')
)
# Need 2f + 1 commits
if commit_count >= 2 * self.f + 1:
# Execute request
self.log.append(msg.sequence)
return {
'type': 'execute',
'sequence': msg.sequence,
'digest': msg.digest
}
return None
def trigger_view_change(self, new_view: int):
"""Trigger view change if primary is suspected faulty."""
view_change = PBFTMessage(
'view-change', new_view, 0, '', self.id
)
return view_change
# Simulate PBFT
def simulate_pbft(num_nodes: int = 4, byzantine_count: int = 1):
"""Simulate PBFT consensus."""
nodes = [PBFTNode(i, num_nodes) for i in range(num_nodes)]
# Mark some nodes as Byzantine
for i in range(byzantine_count):
nodes[-(i+1)].is_primary = False # Keep non-Byzantine as primary
# Client sends request
data = b"Transfer 100 tokens"
result = nodes[0].handle_request(data)
if not result:
print("Primary failed to handle request")
return
print(f"Primary sent pre-prepare: {result['message'].sequence}")
# Phase 1: Pre-prepare
for node in nodes[1:]:
prepare_msg = node.handle_pre_prepare(result['message'])
if prepare_msg:
print(f"Node {node.id} sent prepare")
# Phase 2: Prepare would continue...
# (simplified for brevity)
return nodes
nodes = simulate_pbft(4, 1)
print(f"Fault tolerance: f = {nodes[0].f}")
print(f"Required nodes: {3 * nodes[0].f + 1}")
PBFT Properties
| Property | Value |
|---|---|
| Message complexity | per consensus |
| Rounds | 3 (pre-prepare, prepare, commit) |
| Fault tolerance | |
| Communication | All-to-all |
| View changes | messages |
Tendermint
Tendermint is a BFT consensus engine used in Cosmos ecosystem.
Tendermint Protocol
Height H
āāā Round 0
ā āāā Propose: Validator proposes block
ā āāā Prevote: Validators vote on proposal
ā āāā Precommit: Validators confirm block
āāā Round 1 (if needed)
ā āāā Propose: New proposer
ā āāā Prevote
ā āāā Precommit
āāā Commit: Block finalized
Locking Rules:
1. Once you prevote for a block, you're locked on it
2. If locked, must propose/prevote for same block
3. Lock only releases on +2/3 prevotes for higher round
Tendermint Implementation
class TendermintValidator:
"""Tendermint validator."""
def __init__(self, validator_id: int, voting_power: int):
self.id = validator_id
self.voting_power = voting_power
self.signed_votes = {}
class TendermintRound:
"""Single round of Tendermint consensus."""
def __init__(self, height: int, round_num: int, validators: list):
self.height = height
self.round_num = round_num
self.validators = validators
self.total_power = sum(v.voting_power for v in validators)
self.proposal = None
self.prevotes = {}
self.precommits = {}
self.locked_value = None
self.locked_round = -1
self.valid_value = None
self.valid_round = -1
def get_proposer(self) -> TendermintValidator:
"""Select proposer using weighted round-robin."""
index = (self.height + self.round_num) % len(self.validators)
return self.validators[index]
def propose(self, block: dict):
"""Proposer creates block proposal."""
proposer = self.get_proposer()
self.proposal = {
'block': block,
'round': self.round_num,
'proposer': proposer.id
}
return self.proposal
def prevote(self, validator_id: int, block_hash: str):
"""Validator casts prevote."""
self.prevotes[validator_id] = {
'round': self.round_num,
'block_hash': block_hash,
'power': self._get_power(validator_id)
}
def check_prevote_quorum(self) -> bool:
"""Check if prevote quorum is reached."""
total_prevote_power = sum(
v['power'] for v in self.prevotes.values()
)
return total_prevote_power >= (2 * self.total_power) // 3 + 1
def precommit(self, validator_id: int, block_hash: str):
"""Validator casts precommit."""
self.precommits[validator_id] = {
'round': self.round_num,
'block_hash': block_hash,
'power': self._get_power(validator_id)
}
def check_precommit_quorum(self) -> bool:
"""Check if precommit quorum is reached."""
total_precommit_power = sum(
v['power'] for v in self.precommits.values()
)
return total_precommit_power >= (2 * self.total_power) // 3 + 1
def _get_power(self, validator_id: int) -> int:
for v in self.validators:
if v.id == validator_id:
return v.voting_power
return 0
class TendermintConsensus:
"""Full Tendermint consensus."""
def __init__(self, validators: list):
self.validators = validators
self.height = 0
self.round_num = 0
def run_height(self, blocks: list) -> dict:
"""Run consensus for a single height."""
round_state = TendermintRound(self.height, self.round_num, self.validators)
# Propose
proposal = round_state.propose(blocks[self.height])
# Simulate prevotes
for v in self.validators:
round_state.prevote(v.id, proposal['block']['hash'])
# Check prevote quorum
if not round_state.check_prevote_quorum():
print(f"Height {self.height}: No prevote quorum")
return None
# Simulate precommits
for v in self.validators:
round_state.precommit(v.id, proposal['block']['hash'])
# Check precommit quorum
if not round_state.check_precommit_quorum():
print(f"Height {self.height}: No precommit quorum")
return None
# Commit
self.height += 1
return {
'height': self.height - 1,
'block': proposal['block'],
'round': self.round_num,
'committed': True
}
# Example
validators = [
TendermintValidator(0, 33),
TendermintValidator(1, 33),
TendermintValidator(2, 34),
]
consensus = TendermintConsensus(validators)
blocks = [{'hash': f'block_{i}', 'data': f'Data {i}'} for i in range(3)]
for _ in range(3):
result = consensus.run_height(blocks)
if result:
print(f"Committed height {result['height']}: {result['block']['hash']}")
Tendermint Properties
| Property | Description |
|---|---|
| Finality | Instant (after +2/3 precommits) |
| Fork resolution | None (deterministic) |
| Message complexity | |
| Round complexity | expected |
| Locking | Prevents equivocation |
Casper FFG (Ethereum)
Casper FFG provides finality to Ethereum's PoS chain.
Casper FFG Protocol
Epoch E (32 slots)
āāā Checkpoint C1 (start)
āāā Checkpoint C2 (end)
ā
āāā Attestations
ā Validators vote on checkpoint
ā Need 2/3 stake for justification
ā
āāā Justification
ā Checkpoint becomes justified
ā When 2/3+ attest for it
ā
āāā Finalization
Checkpoint becomes finalized
When justified checkpoint is attested by 2/3+
Casper FFG Implementation
class CasperCheckpoint:
"""Casper FFG checkpoint."""
def __init__(self, epoch: int, block_root: str):
self.epoch = epoch
self.block_root = block_root
self.attestations = []
self.is_justified = False
self.is_finalized = False
def add_attestation(self, validator_id: int, stake: int):
"""Add validator attestation."""
self.attestations.append({
'validator': validator_id,
'stake': stake
})
def get_total_stake(self) -> int:
"""Get total attested stake."""
return sum(a['stake'] for a in self.attestations)
class CasperFFG:
"""Casper FFG finality gadget."""
EPOCH_LENGTH = 32 # slots per epoch
def __init__(self, validators: dict):
"""
Args:
validators: {validator_id: stake}
"""
self.validators = validators
self.total_stake = sum(validators.values())
self.checkpoints = {}
self.justified_checkpoint = None
self.finalized_checkpoint = None
def create_checkpoint(self, epoch: int, block_root: str) -> CasperCheckpoint:
"""Create new checkpoint."""
checkpoint = CasperCheckpoint(epoch, block_root)
self.checkpoints[epoch] = checkpoint
return checkpoint
def attest(self, epoch: int, validator_id: int):
"""Validator attests to checkpoint."""
if epoch not in self.checkpoints:
raise ValueError("Checkpoint doesn't exist")
checkpoint = self.checkpoints[epoch]
stake = self.validators[validator_id]
checkpoint.add_attestation(validator_id, stake)
# Check justification
if self._check_justification(checkpoint):
checkpoint.is_justified = True
self.justified_checkpoint = checkpoint
# Check finalization
if self._check_finalization(checkpoint):
checkpoint.is_finalized = True
self.finalized_checkpoint = checkpoint
return True
return False
def _check_justification(self, checkpoint: CasperCheckpoint) -> bool:
"""Check if checkpoint can be justified."""
attested_stake = checkpoint.get_total_stake()
return attested_stake >= (2 * self.total_stake) // 3
def _check_finalization(self, checkpoint: CasperCheckpoint) -> bool:
"""Check if justified checkpoint can be finalized."""
if not checkpoint.is_justified:
return False
# Check if next epoch's checkpoint is justified
next_epoch = checkpoint.epoch + 1
if next_epoch in self.checkpoints:
next_checkpoint = self.checkpoints[next_epoch]
if next_checkpoint.is_justified:
return True
return False
def get_finality_distance(self) -> int:
"""Get distance from finalized checkpoint."""
if not self.finalized_checkpoint:
return -1
current_epoch = max(self.checkpoints.keys())
return current_epoch - self.finalized_checkpoint.epoch
# Example
validators = {
0: 32000, # 32k ETH
1: 32000,
2: 32000,
3: 32000,
}
casper = CasperFFG(validators)
# Create checkpoints
for epoch in range(5):
checkpoint = casper.create_checkpoint(epoch, f'block_root_{epoch}')
# Simulate attestations
for v_id in validators:
casper.attest(epoch, v_id)
if checkpoint.is_justified:
print(f"Epoch {epoch}: Justified")
if checkpoint.is_finalized:
print(f"Epoch {epoch}: Finalized")
Casper FFG Slashing Conditions
| Condition | Description | Penalty |
|---|---|---|
| Surround voting | Vote that surrounds another | 1/32 stake |
| Double voting | Two votes same target | 1/32 stake |
Liveness vs Safety
Definitions
- Safety: Nothing bad happens (no conflicting finalized blocks)
- Liveness: Something good eventually happens (chain keeps growing)
Trade-off Analysis
class LivenessSafetyAnalyzer:
"""Analyze liveness-safety trade-offs."""
def analyze_consensus(self, mechanism: str) -> dict:
"""Analyze liveness and safety properties."""
properties = {
'PoW': {
'safety': 'Probabilistic - increases with confirmations',
'liveness': 'High - always makes progress',
'trade_off': 'Prioritizes liveness over safety',
'failure_mode': 'Chain reorganization',
'finality': 'Probabilistic (6 blocks)'
},
'PBFT': {
'safety': 'Strong - deterministic finality',
'liveness': 'Requires 2/3+ honest nodes',
'trade_off': 'Prioritizes safety over liveness',
'failure_mode': 'Halt if >1/3 Byzantine',
'finality': 'Immediate'
},
'Tendermint': {
'safety': 'Strong - instant finality',
'liveness': 'Requires 2/3+ voting power',
'trade_off': 'Prioritizes safety',
'failure_mode': 'Halt (no forks)',
'finality': 'Instant'
},
'Casper': {
'safety': 'Strong - economic finality',
'liveness': 'Requires 2/3+ stake',
'trade_off': 'Balanced with slashing',
'failure_mode': 'Halt or slashing',
'finality': '12-15 minutes'
}
}
return properties.get(mechanism, {})
def fischer_lynch_paterson(self) -> dict:
"""FLP impossibility result."""
return {
'theorem': 'No deterministic consensus in async system with even one faulty process',
'implications': [
'Cannot guarantee termination with faults',
'Must use randomized algorithms or synchrony assumptions',
'Blockchain consensus uses economic incentives to circumvent'
],
'solutions': [
'Partial synchrony (Tendermint)',
'Randomization (randcoin)',
'Economic penalties (Casper)',
'PoW longest chain (Bitcoin)'
]
}
Liveness-Safety Matrix
| Mechanism | Liveness Guarantee | Safety Guarantee | Failure Mode |
|---|---|---|---|
| PoW | High (chain always grows) | Probabilistic | Forks |
| PBFT | Conditional (2/3+ honest) | Strong (deterministic) | Halt |
| Tendermint | Conditional (2/3+ voting power) | Strong | Halt |
| Casper | Conditional (2/3+ stake) | Strong (economic) | Halt + Slashing |
| HotStuff | Conditional (2/3+ honest) | Strong | Halt |
Quorum Requirements
Quorum Certificate
A quorum certificate (QC) is a collection of votes from a quorum of validators.
class QuorumCertificate:
"""Quorum certificate for BFT consensus."""
def __init__(self, validators: dict):
"""
Args:
validators: {validator_id: voting_power}
"""
self.validators = validators
self.total_power = sum(validators.values())
self.votes = {}
@property
def quorum_threshold(self) -> int:
"""Required voting power for quorum."""
return (2 * self.total_power) // 3 + 1
@property
def intersection_threshold(self) -> int:
"""Any two quorums must intersect by this much."""
return (2 * self.total_power) // 3 + 1
def add_vote(self, validator_id: int, vote: dict):
"""Add vote to certificate."""
if validator_id not in self.validators:
raise ValueError("Unknown validator")
self.votes[validator_id] = vote
def is_quorum(self) -> bool:
"""Check if quorum is reached."""
voting_power = sum(
self.validators[vid] for vid in self.votes.keys()
)
return voting_power >= self.quorum_threshold
def get_quorum_intersection(self, other: 'QuorumCertificate') -> dict:
"""Calculate intersection with another quorum."""
common_validators = set(self.votes.keys()) & set(other.votes.keys())
intersection_power = sum(
self.validators[vid] for vid in common_validators
)
return {
'common_validators': len(common_validators),
'intersection_power': intersection_power,
'has_intersection': intersection_power >= self.intersection_threshold
}
# Example
validators = {i: 100 for i in range(10)}
qc = QuorumCertificate(validators)
# Add votes
for i in range(7):
qc.add_vote(i, {'block': 'test'})
print(f"Quorum reached: {qc.is_quorum()}")
print(f"Threshold: {qc.quorum_threshold}")
print(f"Current power: {sum(100 for _ in range(7))}")
Quorum Intersection Property
For safety, any two quorums must intersect with sufficient overlap:
Where:
- are quorums
- is total voting power
Real-World Examples
Bitcoin's Nakamoto Consensus
Bitcoin uses PoW as a BFT mechanism:
- Safety: Probabilistic (longest chain rule)
- Liveness: Always progresses (mining continues)
- Fault tolerance: 50% hash power
Cosmos/Tendermint
The Cosmos network uses Tendermint for IBC:
- Instant finality: No forks
- IBC: Cross-chain communication relies on finality
- Validators: Typically 100-150 validators
Ethereum's Hybrid Approach
Ethereum combines PoS with Casper FFG:
- Liveness: PoS block production (every 12 seconds)
- Safety: Casper FFG finality (every ~12 minutes)
- Slashing: Economic penalties for misbehavior
Trade-offs
PBFT vs PoW
| Aspect | PBFT | PoW |
|---|---|---|
| Scalability | Limited (O(n²)) | High |
| Finality | Instant | Probabilistic |
| Energy | Low | High |
| Fault tolerance | 1/3 Byzantine | 50% hash power |
| Message complexity | High | Low |
| Communication | All-to-all | Gossip |
Tendermint vs PBFT
| Aspect | Tendermint | PBFT |
|---|---|---|
| View changes | Round-robin | Explicit protocol |
| Locking | Yes | No |
| Message types | 3 | 3 |
| Complexity | Moderate | High |
| Use case | Blockchain | Traditional BFT |
Interview Questions
Q1: Explain why PBFT requires 3f+1 nodes for Byzantine fault tolerance.
Answer: In PBFT, we need 2f+1 matching messages for a decision. With n=3f+1:
- At most f nodes are Byzantine
- At least 2f+1 nodes are honest
- Two quorums of 2f+1 must intersect by at least f+1 nodes
- This guarantees at least one honest node in the intersection
- Prevents conflicting decisions
If n=2f+1, an adversary could control f nodes and with f+1 honest nodes, create two non-overlapping quorums.
Q2: How does Ethereum's Casper FFG handle the liveness-safety trade-off?
Answer: Casper FFG balances liveness and safety through:
Safety mechanism:
- 2/3+ stake required for justification/finalization
- Slashing conditions prevent equivocation
- Economic finality (reverting finalized blocks costs 1/3 stake)
Liveness mechanism:
- Validators can go offline without finalization halting
- Chain continues producing blocks (PoS)
- Finalization can be delayed but not prevented
Trade-off resolution:
- If 1/3+ validators go offline: chain halts (safety over liveness)
- If equivocation detected: slashing (economic penalty)
- Incentivizes honest behavior over extended periods
Q3: What is the significance of quorum intersection in BFT systems?
Answer: Quorum intersection ensures that any two quorums have enough overlap to guarantee consistency:
Properties:
- Any two quorums must share at least one honest node
- This prevents conflicting decisions
- Requires
Example: With n=100 validators (f=33):
- Quorum size: 67 validators
- Two quorums of 67 must overlap by at least 34 validators
- At most 33 are Byzantine, so at least 1 is honest
- This honest node prevents conflicting decisions
Without quorum intersection, the system could reach different decisions in different partitions.
Quiz Questions
Q1: What is the minimum number of nodes required for PBFT to tolerate f Byzantine faults?
A) 2f + 1 B) 3f + 1 C) 4f + 1 D) 2f
Answer: B) 3f + 1
Q2: In Tendermint, what prevents validators from voting for conflicting blocks in the same round?
A) Random selection B) Economic penalties C) Locking rules D) Message authentication
Answer: C) Locking rules
Q3: According to the FLP impossibility result, what must be sacrificed in an asynchronous system with faulty processes?
A) Safety B) Liveness C) Agreement D) Validity
Answer: B) Liveness
Practice
- Implement a simplified PBFT consensus simulation
- Simulate Tendermint's locking mechanism
- Analyze quorum intersection for different network sizes
- Compare finality times across BFT consensus mechanisms