Overview
Bitcoin Core’s P2P (peer-to-peer) layer handles all network communication between nodes. It manages peer connections, message exchange, block propagation, transaction relay, and network security. Primary files:src/net.cpp/src/net.h- Core networking (CConnman, CNode)src/net_processing.cpp/src/net_processing.h- Protocol message handlingsrc/protocol.cpp/src/protocol.h- Message format definitions
Network Architecture
Key Components
CConnman (Connection Manager)
Manages all network connections:- Socket management and I/O
- Connection establishment and cleanup
- Peer discovery and connection strategy
- Rate limiting and bandwidth management
CNode (Peer Connection)
Represents a single peer:PeerManager
Handles protocol-level logic:- Message processing
- Block and transaction relay
- Peer misbehavior tracking
- Inventory management
Connection Types
Bitcoin Core maintains different types of connections:Outbound Connections
Inbound Connections
Accepted from other peers:- Default max: 125 total connections
- After maxconnections reached, new inbound connections are rejected
- Exceptions for whitelisted peers
Peer Discovery
Address Manager (AddrMan)
Stores and manages peer addresses:- DNS seeds: Hardcoded DNS names that return peer IPs
- Seed nodes: Hardcoded IP addresses (fallback)
- ADDR messages: Peers share addresses
- Manual:
-addnode,-connectparameters
Address Selection
When choosing peers to connect to:- Prefer tried addresses (50% of the time)
- New addresses selected randomly from “new” table
- Group addresses by /16 subnet to ensure diversity
- Avoid connecting to same network group multiple times
Message Format
V1 Transport Protocol (Legacy)
Traditional Bitcoin message format:- Magic: Network identifier (0xD9B4BEF9 for mainnet)
- Command: Message type (e.g., “version”, “block”)
- Length: Payload size in bytes
- Checksum: SHA256(SHA256(payload))[0:4]
- Payload: Message-specific data
V2 Transport Protocol (BIP324)
Encrypted P2P messages (enabled by default since v27.0):- Encryption prevents passive surveillance
- Authentication prevents MITM attacks
- Pseudorandom length hides message boundaries
- More efficient than TLS
Core Protocol Messages
Handshake
1. version
First message exchanged:2. verack
Acknowledges version message:- Empty payload
- Both peers must exchange version/verack
- After verack, connection is established
Block Propagation
3. inv (inventory)
Announces available data:MSG_TX: TransactionMSG_BLOCK: BlockMSG_FILTERED_BLOCK: Filtered block (BIP37)MSG_CMPCT_BLOCK: Compact block (BIP152)MSG_WITNESS_TX: Transaction with witnessMSG_WITNESS_BLOCK: Block with witness
4. getdata
Requests data:5. block
Full block data:6. headers
Block headers (BIP130):- Initial block download (headers-first sync)
- Announcing new blocks without full data
Compact Blocks (BIP152)
Efficient block relay using short transaction IDs:7. cmpctblock
- ~95% bandwidth reduction (transactions already in mempool)
- Faster propagation (less data to transmit)
- Two modes: high-bandwidth and low-bandwidth
8. getblocktxn / blocktxn
Request/send missing transactions:Transaction Relay
9. tx
Full transaction:- Only relay if accepted to mempool
- Respect
-blocksonlymode - Rate limiting to prevent spam
10. wtxidrelay (BIP339)
Signals support for wtxid-based relay:- Announced in version message
- Uses witness transaction ID instead of txid
- Prevents witness stripping attacks
Address Exchange
11. addr
Share peer addresses:- Max 1000 addresses per message
- Tokens refill at 1 per second
- Prevents address flooding
12. addrv2 (BIP155)
Extended address format:- Supports Tor v3, I2P, CJDNS
- Variable-length network addresses
- Backward compatible with v1
Other Messages
13. ping / pong (BIP31)
Keep-alive and latency measurement:- Peer responds to ping with pong containing same nonce
- Used to detect dead connections
- Measures round-trip time
14. getaddr
Request peer addresses:- Empty message
- Peer responds with addr message
15. mempool (BIP35)
Request mempool inventory:- Returns inv messages for mempool transactions
- Only for NODE_BLOOM peers (privacy considerations)
16. feefilter (BIP133)
Announce minimum fee rate:17. sendheaders (BIP130)
Request direct header announcements:- After this message, peer sends headers instead of inv for new blocks
- Reduces latency (no getdata round-trip)
Message Processing Flow
Message Receive Loop
Message Send Loop
Peer Misbehavior
Misbehavior Scoring
Peers accumulate “misbehavior score” for protocol violations:- Invalid blocks/transactions: 100 points → ban
- Excessive inv messages: 20 points
- Duplicate headers: 10 points
- Protocol errors: varies
Ban Management
- Default: 24 hours
- Persisted to
banlist.dat - Manual bans via
setbanRPC
DoS Protection
Rate Limiting
Upload limits:-maxuploadtarget=<MiB>.
Per-peer limits:
- Inventory announcements: Token bucket
- Address messages: 1000 per message, rate limited
- Header messages: 2000 per message
Resource Limits
Connection limits:- Maximum in-flight blocks: Limited per peer
- Timeout stale requests
- Rotate between peers
Proof-of-Work Validation
All block headers validated before processing:- Prevents DoS via invalid high-difficulty headers
- Cheap to verify, expensive to generate
Advanced Features
Transaction Reconciliation (BIP330)
Sketch-based set reconciliation:- Use minisketch to find mempool differences
- Reduces bandwidth for transaction relay
- Experimental (disabled by default)
Orphan Transactions
Transactions with missing parents:- Store temporarily
- Request parent transactions
- Expire after timeout
Block Download Strategy
Headers-first synchronization:- Download headers to find best chain
- Parallel block download from multiple peers
- Validate blocks in order
- Disconnect peers providing invalid blocks
- Skip signature verification for old blocks
- Significantly faster initial sync
- Security based on accumulated proof-of-work
Network Privacy
Privacy Considerations
IP address exposure:- Clearnet: IP visible to all peers
- Tor: Hidden via Tor network
- I2P: Garlic routing for privacy
- CJDNS: Encrypted IPv6
- Dandelion routing (not yet implemented)
- Private transaction broadcast (BIP XXX)
- Tor/I2P for wallet transactions
Private Broadcast
Experimental feature for privacy-enhanced transaction relay:- Short-lived connections to privacy networks
- Broadcast transaction without revealing node IP
- Disconnect immediately after
Configuration Options
Network Settings
Bandwidth
Privacy
Performance Optimization
Compact Block Relay
High-bandwidth mode:- Enables immediate compact block announcements
- Reduces latency for miners and relays
- Limited to 3 peers
Header Pre-sync
Anti-DoS during initial sync:- Download headers from 2 peers in parallel
- Validate proof-of-work before committing
- Prevents resource exhaustion
Connection Management
Peer rotation:- Evict worst-performing peers
- Prefer diverse network groups
- Maintain block-relay-only connections for privacy