Blockchain Governance
On-chain vs off-chain governance, voting mechanisms, proposal systems, hard fork coordination, and governance attacks.
Overview
Blockchain governance determines how protocols evolve, upgrades are implemented, and disputes are resolved. Effective governance balances decentralization with decision-making efficiency.
Governance Models
Governance Spectrum
Governance Model Comparison
| Model | Decision Speed | Decentralization | Implementation |
|---|---|---|---|
| Off-chain | Slow | High | Social consensus |
| Hybrid | Medium | Medium | Mixed |
| On-chain | Fast | Variable | Smart contracts |
| Autonomous | Variable | Low | Fully automated |
On-Chain Governance
Tezos Governance
Tezos pioneered self-amending blockchain with formal on-chain governance.
from dataclasses import dataclass
from typing import List, Dict, Optional
import time
@dataclass
class Proposal:
"""Governance proposal."""
proposal_id: str
author: str
title: str
description: str
code_changes: dict
timestamp: float
votes_for: int = 0
votes_against: int = 0
status: str = "voting" # testing, voting, accepted, rejected
class TezosGovernance:
"""Tezos-style on-chain governance."""
VOTING_PERIOD = 23 # days
PROPOSAL_DEPOSIT = 10000 # tez
def __init__(self, total_voting_power: int):
self.total_voting_power = total_voting_power
self.proposals: List[Proposal] = []
self.current_period = 0
self.period_start = time.time()
def submit_proposal(self, author: str, title: str,
description: str, code_changes: dict) -> Proposal:
"""Submit new governance proposal."""
proposal = Proposal(
proposal_id=f"prop_{len(self.proposals)}",
author=author,
title=title,
description=description,
code_changes=code_changes,
timestamp=time.time()
)
self.proposals.append(proposal)
return proposal
def vote(self, proposal_id: str, voter: str,
voting_power: int, vote: str) -> bool:
"""Cast vote on proposal."""
proposal = self._get_proposal(proposal_id)
if not proposal:
return False
if time.time() - self.period_start > self.VOTING_PERIOD * 86400:
print("Voting period ended")
return False
if vote == "for":
proposal.votes_for += voting_power
elif vote == "against":
proposal.votes_against += voting_power
else:
return False
return True
def check_proposal(self, proposal_id: str) -> dict:
"""Check proposal status."""
proposal = self._get_proposal(proposal_id)
if not proposal:
return {'error': 'Proposal not found'}
total_votes = proposal.votes_for + proposal.votes_against
quorum = self.total_voting_power * 0.3 # 30% quorum
if total_votes < quorum:
status = "insufficient_votes"
elif proposal.votes_for > proposal.votes_against:
status = "accepted"
else:
status = "rejected"
return {
'proposal_id': proposal_id,
'status': status,
'votes_for': proposal.votes_for,
'votes_against': proposal.votes_against,
'total_votes': total_votes,
'quorum': quorum,
'participation': total_votes / self.total_voting_power
}
def promote_proposal(self, proposal_id: str) -> bool:
"""Promote accepted proposal to testing phase."""
status = self.check_proposal(proposal_id)
if status['status'] != 'accepted':
return False
proposal = self._get_proposal(proposal_id)
proposal.status = "testing"
return True
def activate_proposal(self, proposal_id: str) -> bool:
"""Activate proposal after successful testing."""
proposal = self._get_proposal(proposal_id)
if not proposal or proposal.status != "testing":
return False
# In reality, this would execute code changes
proposal.status = "activated"
return True
def _get_proposal(self, proposal_id: str) -> Optional[Proposal]:
for prop in self.proposals:
if prop.proposal_id == proposal_id:
return prop
return None
# Example
governance = TezosGovernance(total_voting_power=1000000)
# Submit proposal
proposal = governance.submit_proposal(
author="tz1abc...",
title="Increase block size",
description="Proposal to increase block size from 1MB to 2MB",
code_changes={'parameter': 'max_block_size', 'new_value': 2000000}
)
# Cast votes
governance.vote(proposal.proposal_id, "tz1voter1", 100000, "for")
governance.vote(proposal.proposal_id, "tz1voter2", 80000, "for")
governance.vote(proposal.proposal_id, "tz1voter3", 50000, "against")
# Check status
status = governance.check_proposal(proposal.proposal_id)
print(f"Proposal status: {status}")
Tezos Governance Flow
Phase 1: Proposal
βββ Submit proposal with code
βββ Deposit required (10k tez)
βββ Community discussion
Phase 2: Exploration (23 days)
βββ Voting begins
βββ 30% quorum required
βββ Supermajority (2/3) needed
Phase 3: Testing (23 days)
βββ Proposal on testnet
βββ Technical validation
βββ Community feedback
Phase 4: Promotion (23 days)
βββ Final vote
βββ 30% quorum
βββ Supermajority required
Phase 5: Activation
βββ Automatic amendment
βββ No hard fork needed
βββ Self-amending protocol
Off-Chain Governance
Bitcoin Improvement Proposals (BIPs)
from dataclasses import dataclass
from typing import List, Optional
from enum import Enum
class BIPStatus(Enum):
DRAFT = "draft"
PROPOSED = "proposed"
ACCEPTED = "accepted"
REJECTED = "rejected"
FINAL = "final"
ACTIVE = "active"
REPLACED = "replaced"
@dataclass
class BIP:
"""Bitcoin Improvement Proposal."""
bip_number: int
title: str
author: str
status: BIPStatus
category: str # Standards, Informational, Process
created: float
description: str
class BIPRegistry:
"""Manage Bitcoin Improvement Proposals."""
def __init__(self):
self.proposals: dict[int, BIP] = {}
self.next_number = 1
def submit_bip(self, title: str, author: str,
category: str, description: str) -> BIP:
"""Submit new BIP."""
bip = BIP(
bip_number=self.next_number,
title=title,
author=author,
status=BIPStatus.DRAFT,
category=category,
created=time.time(),
description=description
)
self.proposals[self.next_number] = bip
self.next_number += 1
return bip
def update_status(self, bip_number: int, new_status: BIPStatus) -> bool:
"""Update BIP status."""
if bip_number not in self.proposals:
return False
self.proposals[bip_number].status = new_status
return True
def get_active_bips(self) -> List[BIP]:
"""Get all active BIPs."""
return [
bip for bip in self.proposals.values()
if bip.status in [BIPStatus.ACTIVE, BIPStatus.FINAL]
]
def get_bip_process(self) -> dict:
"""Describe BIP process."""
return {
'stages': [
'Idea β Draft β Proposed β Accepted β Final β Active',
'Community discussion on mailing list',
'Core developer review',
'Rough consensus required',
'No formal vote (social consensus)'
],
'key_points': [
'No formal voting mechanism',
'Relies on social consensus',
'Miners signal via block version',
'Developers propose, nodes accept/reject',
'Fork if no consensus'
]
}
# Example
registry = BIPRegistry()
# Submit BIPs
bip1 = registry.submit_bip(
title="Segregated Witness",
author="Eric Lombrozo",
category="Standards",
description="Segregate witness data from transaction data"
)
bip2 = registry.submit_bip(
title="Pay to Script Hash",
author="Gavin Andresen",
category="Standards",
description="Define new transaction type"
)
print(f"Submitted BIP-{bip1.bip_number}: {bip1.title}")
print(f"Submitted BIP-{bip2.bip_number}: {bip2.title}")
Bitcoin Governance Process
BIP Process:
1. Idea discussed on mailing list
2. BIP draft submitted to repository
3. Core developers review
4. Community discussion (months/years)
5. Implementation in reference client
6. Miners signal support (90% threshold)
7. Activation (flag day or BIP 9)
Key Points:
- No formal voting
- Social consensus required
- "Rough consensus and running code"
- Forks are last resort
Voting Mechanisms
Token Voting
from dataclasses import dataclass
from typing import List, Dict
import math
@dataclass
class Voter:
"""DAO voter."""
address: str
token_balance: int
voting_power: int
delegation: Optional[str] = None
class TokenVoting:
"""Token-weighted voting system."""
def __init__(self, quorum: float = 0.25, threshold: float = 0.5):
self.quorum = quorum # Minimum participation
self.threshold = threshold # Approval threshold
self.voters: Dict[str, Voter] = {}
self.proposals: dict = {}
self.votes: Dict[str, Dict[str, int]] = {} # proposal -> voter -> vote
def register_voter(self, address: str, token_balance: int):
"""Register voter with token balance."""
voting_power = self._calculate_voting_power(token_balance)
self.voters[address] = Voter(
address=address,
token_balance=token_balance,
voting_power=voting_power
)
def _calculate_voting_power(self, tokens: int) -> int:
"""Calculate voting power (can be quadratic)."""
# Linear voting (1 token = 1 vote)
return tokens
# Quadratic voting (sqrt of tokens)
# return int(math.sqrt(tokens))
def create_proposal(self, proposal_id: str, title: str,
description: str) -> dict:
"""Create new proposal."""
self.proposals[proposal_id] = {
'id': proposal_id,
'title': title,
'description': description,
'votes_for': 0,
'votes_against': 0,
'total_voting_power': 0
}
self.votes[proposal_id] = {}
return self.proposals[proposal_id]
def vote(self, proposal_id: str, voter_address: str,
support: bool) -> bool:
"""Cast vote."""
if proposal_id not in self.proposals:
return False
if voter_address not in self.voters:
return False
voter = self.voters[voter_address]
# Check if already voted
if voter_address in self.votes[proposal_id]:
return False
# Record vote
self.votes[proposal_id][voter_address] = 1 if support else 0
# Update proposal totals
if support:
self.proposals[proposal_id]['votes_for'] += voter.voting_power
else:
self.proposals[proposal_id]['votes_against'] += voter.voting_power
self.proposals[proposal_id]['total_voting_power'] += voter.voting_power
return True
def tally_results(self, proposal_id: str) -> dict:
"""Tally votes and determine outcome."""
if proposal_id not in self.proposals:
return {'error': 'Proposal not found'}
proposal = self.proposals[proposal_id]
# Calculate total possible voting power
total_power = sum(v.voting_power for v in self.voters.values())
# Calculate participation
participation = proposal['total_voting_power'] / total_power
# Determine outcome
if participation < self.quorum:
outcome = "quorum_not_reached"
elif proposal['votes_for'] > proposal['votes_against']:
outcome = "passed"
else:
outcome = "rejected"
return {
'proposal_id': proposal_id,
'outcome': outcome,
'votes_for': proposal['votes_for'],
'votes_against': proposal['votes_against'],
'participation': participation,
'quorum': self.quorum,
'threshold': self.threshold
}
# Example
voting = TokenVoting(quorum=0.25, threshold=0.5)
# Register voters
voting.register_voter("0xAlice", 10000)
voting.register_voter("0xBob", 5000)
voting.register_voter("0xCharlie", 3000)
# Create proposal
voting.create_proposal("prop_1", "Increase gas limit",
"Proposal to increase block gas limit")
# Cast votes
voting.vote("prop_1", "0xAlice", support=True)
voting.vote("prop_1", "0xBob", support=True)
voting.vote("prop_1", "0xCharlie", support=False)
# Tally results
results = voting.tally_results("prop_1")
print(f"Proposal outcome: {results}")
Voting Mechanism Comparison
| Mechanism | Description | Pros | Cons |
|---|---|---|---|
| Token-weighted | 1 token = 1 vote | Simple | Plutocratic |
| Quadratic | βtokens = votes | Fairer | Sybil vulnerable |
| Reputation-weighted | Based on contribution | Meritocratic | Hard to measure |
| Conviction voting | Time-weighted | Long-term focus | Slow |
| Holographic | Multiple criteria | Comprehensive | Complex |
Proposal Systems
Governor Contract (Compound Style)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract CompoundGovernor {
struct Proposal {
uint256 id;
address proposer;
uint256 startBlock;
uint256 endBlock;
uint256 forVotes;
uint256 againstVotes;
bool canceled;
bool executed;
mapping(address => VoteReceipt) receipts;
}
struct VoteReceipt {
bool hasVoted;
Vote vote;
uint256 votes;
}
enum Vote { Against, For, Abstain }
uint256 public votingDelay = 1; // 1 block
uint256 public votingPeriod = 50400; // ~1 week
uint256 public proposalThreshold = 10000e18; // 10k tokens
uint256 public quorumPercentage = 4; // 4%
mapping(uint256 => Proposal) public proposals;
uint256 public proposalCount;
function propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) public returns (uint256) {
require(
getVotes(msg.sender) > proposalThreshold,
"Below proposal threshold"
);
uint256 proposalId = proposalCount++;
Proposal storage proposal = proposals[proposalId];
proposal.id = proposalId;
proposal.proposer = msg.sender;
proposal.startBlock = block.number + votingDelay;
proposal.endBlock = block.number + votingDelay + votingPeriod;
return proposalId;
}
function castVote(uint256 proposalId, Vote vote) public {
return _castVote(msg.sender, proposalId, vote, "");
}
function _castVote(
address voter,
uint256 proposalId,
Vote vote,
bytes memory reason
) internal {
Proposal storage proposal = proposals[proposalId];
require(block.number >= proposal.startBlock, "Voting not started");
require(block.number <= proposal.endBlock, "Voting ended");
require(!proposal.receipts[voter].hasVoted, "Already voted");
uint256 votes = getVotes(voter);
proposal.receipts[voter] = VoteReceipt({
hasVoted: true,
vote: vote,
votes: votes
});
if (vote == Vote.For) {
proposal.forVotes += votes;
} else if (vote == Vote.Against) {
proposal.againstVotes += votes;
}
}
function execute(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public payable returns (uint256) {
uint256 proposalId = proposalCount - 1;
Proposal storage proposal = proposals[proposalId];
require(proposal.forVotes > proposal.againstVotes, "Not passed");
require(!proposal.executed, "Already executed");
require(block.number > proposal.endBlock, "Voting not ended");
proposal.executed = true;
for (uint256 i = 0; i < targets.length; i++) {
(bool success, ) = targets[i].call{value: values[i]}(calldatas[i]);
require(success, "Execution failed");
}
return proposalId;
}
function getVotes(address account) public view returns (uint256) {
// Return voting power
return 0; // Placeholder
}
}
Proposal Lifecycle
Proposal Lifecycle:
1. Discussion
βββ Forum posts
βββ Community feedback
βββ Core dev review
2. Submission
βββ On-chain proposal
βββ Deposit requirement
βββ Metadata stored
3. Voting Period
βββ Token holders vote
βββ Quorum tracking
βββ Real-time results
4. Execution
βββ If passed
βββ Time lock delay
βββ Smart contract execution
5. Monitoring
βββ Execution verification
βββ Impact assessment
βββ Community feedback
Hard Fork Coordination
Fork Process
from dataclasses import dataclass
from typing import List, Dict
import time
@dataclass
class ForkProposal:
"""Hard fork proposal."""
fork_id: str
name: str
activation_block: int
changes: dict
requires_unanimity: bool
support_threshold: float
class ForkCoordinator:
"""Coordinate hard forks."""
def __init__(self):
self.proposals: Dict[str, ForkProposal] = {}
self.signals: Dict[str, Dict[str, bool]] = {} # fork -> node -> signal
def propose_fork(self, fork_id: str, name: str,
activation_block: int, changes: dict) -> ForkProposal:
"""Propose new hard fork."""
proposal = ForkProposal(
fork_id=fork_id,
name=name,
activation_block=activation_block,
changes=changes,
requires_unanimity=False,
support_threshold=0.95 # 95% support needed
)
self.proposals[fork_id] = proposal
self.signals[fork_id] = {}
return proposal
def signal_support(self, fork_id: str, node_id: str, support: bool):
"""Node signals support for fork."""
if fork_id not in self.signals:
return False
self.signals[fork_id][node_id] = support
return True
def check_readiness(self, fork_id: str, total_nodes: int) -> dict:
"""Check if fork has enough support."""
if fork_id not in self.proposals:
return {'error': 'Fork not found'}
signals = self.signals.get(fork_id, {})
support_count = sum(1 for s in signals.values() if s)
support_ratio = support_count / total_nodes
proposal = self.proposals[fork_id]
return {
'fork_id': fork_id,
'name': proposal.name,
'activation_block': proposal.activation_block,
'support_ratio': support_ratio,
'threshold': proposal.support_threshold,
'ready': support_ratio >= proposal.support_threshold,
'supporting_nodes': support_count,
'total_nodes': total_nodes
}
def execute_fork(self, fork_id: str, current_block: int) -> dict:
"""Execute hard fork at activation block."""
proposal = self.proposals[fork_id]
if current_block != proposal.activation_block:
return {'error': 'Not activation block'}
# In reality, this would apply protocol changes
return {
'fork_id': fork_id,
'activated': True,
'block': current_block,
'changes': proposal.changes
}
# Example
coordinator = ForkCoordinator()
# Propose fork
fork = coordinator.propose_fork(
fork_id="berlin",
name="Berlin Hard Fork",
activation_block=12244000,
changes={
'EIP-2565': 'ModExp pricing',
'EIP-2929': 'Gas cost increases',
'EIP-2718': 'Typed transactions',
'EIP-2930': 'Access lists'
}
)
# Signal support
for i in range(100):
coordinator.signal_support("berlin", f"node_{i}", support=True)
# Check readiness
readiness = coordinator.check_readiness("berlin", total_nodes=100)
print(f"Fork readiness: {readiness}")
Hard Fork Coordination
Coordination Process:
1. Planning (6-12 months)
βββ EIP selection
βββ Testing
βββ Documentation
2. Signaling (2-3 months)
βββ Miners/validators signal
βββ Core nodes update
βββ Support threshold tracking
3. Activation
βββ Block number reached
βββ Protocol changes apply
βββ Network splits if not unanimous
4. Post-Fork
βββ Monitor for issues
βββ Community support
βββ Legacy chain handling
Governance Attacks
Attack Vectors
class GovernanceAttack:
"""Common governance attack vectors."""
def __init__(self, governance_system):
self.governance = governance_system
def flash_loan_attack(self, attacker: str, proposal_id: str) -> dict:
"""Flash loan governance attack."""
# 1. Take flash loan of governance tokens
flash_loan_amount = 1000000 # Tokens
# 2. Create and pass malicious proposal
self.governance.register_voter(attacker, flash_loan_amount)
self.governance.vote(proposal_id, attacker, support=True)
# 3. Repay flash loan
# (In reality, this happens in one transaction)
return {
'attack_type': 'flash_loan',
'tokens_borrowed': flash_loan_amount,
'proposal_passed': True,
'attacker': attacker
}
def bribery_attack(self, proposal_id: str,
bribe_per_vote: float) -> dict:
"""Bribe voters to vote a certain way."""
# Calculate total bribe cost
total_voters = len(self.governance.voters)
total_bribe = total_voters * bribe_per_vote
return {
'attack_type': 'bribery',
'bribe_per_vote': bribe_per_vote,
'total_cost': total_bribe,
'affected_voters': total_voters
}
def vote_buying(self, voter_address: str,
offer_price: float) -> dict:
"""Buy votes from voter."""
voter = self.governance.voters.get(voter_address)
if not voter:
return {'error': 'Voter not found'}
cost = voter.voting_power * offer_price
return {
'attack_type': 'vote_buying',
'voter': voter_address,
'voting_power': voter.voting_power,
'cost': cost,
'price_per_vote': offer_price
}
def proposal_spam(self, num_proposals: int) -> dict:
"""Spam governance with proposals."""
# Create many proposals to overwhelm voters
for i in range(num_proposals):
self.governance.create_proposal(
f"spam_{i}",
f"Spam proposal {i}",
"Intentionally low-quality proposal"
)
return {
'attack_type': 'proposal_spam',
'proposals_created': num_proposals
}
def sybil_attack(self, attacker: str,
num_identities: int) -> dict:
"""Create multiple identities to gain voting power."""
# Split tokens across multiple addresses
tokens_per_identity = 1000
total_tokens = num_identities * tokens_per_identity
for i in range(num_identities):
fake_address = f"{attacker}_sybil_{i}"
self.governance.register_voter(fake_address, tokens_per_identity)
return {
'attack_type': 'sybil',
'identities_created': num_identities,
'total_voting_power': total_tokens
}
Attack Prevention
| Attack | Prevention | Trade-off |
|---|---|---|
| Flash loan | Time-lock voting | Slower governance |
| Bribery | Commit-reveal | Reduced transparency |
| Vote buying | Quadratic voting | Reduced efficiency |
| Proposal spam | Deposit requirement | Barrier to participation |
| Sybil | Identity verification | Reduced privacy |
Trade-offs
Governance Design Trade-offs
| Trade-off | Option A | Option B |
|---|---|---|
| Speed | Fast decisions | Careful deliberation |
| Participation | Low barrier | Qualified voters |
| Decentralization | Wide input | Expert decisions |
| Finality | Quick execution | Appeal period |
| Privacy | Transparent votes | Secret ballots |
On-Chain vs Off-Chain
| Aspect | On-Chain | Off-Chain |
|---|---|---|
| Transparency | Full | Partial |
| Enforcement | Automatic | Social |
| Speed | Fast | Slow |
| Cost | Gas fees | Free |
| Participation | Token holders | Community |
| Finality | Immediate | Gradual |
Real-World Examples
Ethereum Governance
- EIP Process: Off-chain discussion, core dev calls
- Social layer: Twitter, forums, conferences
- No formal voting: Rough consensus
- Execution: Core client updates
MakerDAO Governance
- MKR token voting: On-chain proposals
- Executive votes: Parameter changes
- Polling votes: Signal direction
- ~50k MKR voters: Active participation
Compound Finance
- Governor contract: On-chain execution
- COMP token voting: Token-weighted
- Delegation: Voters can delegate
- Time-locks: 48-hour delay
Interview Questions
Q1: What are the trade-offs between on-chain and off-chain governance?
Answer:
| Aspect | On-Chain | Off-Chain |
|---|---|---|
| Transparency | Full (on-chain records) | Partial (forums, calls) |
| Enforcement | Automatic (smart contracts) | Social (voluntary compliance) |
| Speed | Fast (block-based) | Slow (discussion-based) |
| Cost | Gas fees for voting | Free to discuss |
| Participation | Token holders only | Anyone |
| Finality | Immediate | Gradual consensus |
| Flexibility | Rigid (code is law) | Flexible (social norms) |
Trade-off: On-chain governance is more transparent and enforceable but less flexible and excludes non-token holders. Off-chain governance is more inclusive but relies on social coordination.
Q2: How do flash loan governance attacks work and how can they be prevented?
Answer:
Attack mechanism:
- Attacker takes flash loan of governance tokens
- Creates malicious proposal
- Votes with borrowed tokens
- Passes proposal and executes changes
- Repays flash loan in same transaction
Prevention mechanisms:
- Time-lock voting: Require tokens to be held for N blocks before voting
- Vote escrow: Lock tokens for extended period (veCRV model)
- Delegation: Require delegation before voting power activates
- Quorum requirements: Higher participation thresholds
- Proposal delay: Multiple days between proposal and voting
Example: Compound requires 3-day voting delay + 7-day voting period.
Q3: What is the role of rough consensus in blockchain governance?
Answer: Rough consensus is Bitcoin/Ethereum's governance philosophy:
Key principles:
- No formal voting: Decisions emerge from discussion
- Running code: Implementation demonstrates viability
- Social consensus: Community agreement matters most
- Fork choice: Dissenters can fork the protocol
How it works:
- Core developers propose changes (EIPs/BIPs)
- Community discusses on forums, social media
- Miners/validators signal support
- If majority runs new code, it becomes consensus
- If not, hard fork occurs
Advantages:
- Flexible and adaptive
- Prevents capture by special interests
- Values technical merit over voting power
Disadvantages:
- Uncertain decision process
- Requires active community participation
- Can lead to contentious forks
Quiz Questions
Q1: What is the minimum participation required in Tezos governance?
A) 10% B) 30% C) 50% D) 67%
Answer: B) 30%
Q2: Which governance mechanism allows voters to influence multiple proposals with a single vote?
A) Token-weighted voting B) Conviction voting C) Delegation D) Vote escrow
Answer: B) Conviction voting
Q3: What is the primary purpose of time-locks in governance?
A) Increase voting power B) Prevent flash loan attacks C) Reduce gas costs D) Improve transparency
Answer: B) Prevent flash loan attacks
Practice
- Implement a simple on-chain governance system
- Simulate a flash loan governance attack
- Compare different voting mechanisms (token-weighted vs quadratic)
- Design a governance system for a DAO with multiple token types