Skip to content

Commit d302f53

Browse files
authored
Merge branch 'main' into pnet
2 parents dc94042 + 124c87e commit d302f53

21 files changed

+2332
-197
lines changed

docs/gossipsub-1.2.rst

Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
GossipSub 1.2 Protocol Support
2+
==============================
3+
4+
Overview
5+
--------
6+
7+
Py-libp2p now supports the GossipSub 1.2 protocol specification, which introduces significant improvements for bandwidth efficiency and network performance. This document provides comprehensive information about the new features, configuration options, and best practices.
8+
9+
What's New in GossipSub 1.2
10+
----------------------------
11+
12+
GossipSub 1.2 introduces several key improvements over previous versions:
13+
14+
* **IDONTWANT Control Messages**: A new mechanism to inform peers not to send specific messages, reducing unnecessary bandwidth usage
15+
* **Enhanced Protocol ID**: Uses `/meshsub/1.2.0` protocol identifier
16+
* **Backward Compatibility**: Maintains full compatibility with GossipSub 1.1 and earlier versions
17+
* **Improved Memory Management**: Better handling of message tracking and cleanup
18+
19+
IDONTWANT Control Messages
20+
--------------------------
21+
22+
The most significant feature in GossipSub 1.2 is the introduction of IDONTWANT control messages. These messages allow peers to inform each other about messages they have already received, preventing duplicate message transmission and improving overall network efficiency.
23+
24+
How IDONTWANT Works
25+
~~~~~~~~~~~~~~~~~~~
26+
27+
1. **Message Reception**: When a peer receives a message, it can send an IDONTWANT control message to its mesh peers
28+
2. **Bandwidth Optimization**: Mesh peers will avoid sending the same message to the peer that sent the IDONTWANT
29+
3. **Memory Management**: The system tracks IDONTWANT messages with configurable limits to prevent memory exhaustion
30+
31+
Performance Benefits
32+
~~~~~~~~~~~~~~~~~~~~
33+
34+
IDONTWANT messages provide the most benefit in scenarios with:
35+
36+
* **Large Messages**: Significant bandwidth savings when preventing duplicate large message transmission
37+
* **High-Frequency Messaging**: Reduces network congestion in busy pubsub topics
38+
* **Mesh Networks**: Particularly effective in well-connected mesh topologies
39+
40+
Configuration Options
41+
---------------------
42+
43+
GossipSub 1.2 introduces new configuration parameters to control IDONTWANT behavior:
44+
45+
max_idontwant_messages
46+
~~~~~~~~~~~~~~~~~~~~~~
47+
48+
**Default Value**: 10
49+
50+
**Purpose**: Limits the number of message IDs tracked per peer in IDONTWANT lists to prevent memory exhaustion from malicious or misbehaving peers.
51+
52+
**DoS Prevention**: This parameter is crucial for preventing denial-of-service attacks where peers might send excessive IDONTWANT messages to consume memory resources.
53+
54+
**Rationale for Default Value**: The default value of 10 was chosen based on:
55+
- Analysis of typical message patterns in pubsub networks
56+
- Balance between memory usage and bandwidth optimization
57+
- Protection against potential DoS attacks
58+
- Compatibility with existing network topologies
59+
60+
**Performance Implications**:
61+
- **Small Messages**: IDONTWANT overhead may exceed benefits for very small messages
62+
- **Large Messages**: Significant bandwidth savings for messages larger than typical IDONTWANT control message size
63+
- **High-Frequency Scenarios**: Most beneficial when message frequency is high
64+
65+
Memory Management
66+
-----------------
67+
68+
GossipSub 1.2 implements aggressive cleanup of IDONTWANT entries during heartbeat intervals to prevent memory leaks.
69+
70+
Current Approach
71+
~~~~~~~~~~~~~~~~
72+
73+
The current implementation uses aggressive cleanup (clears all entries) which provides:
74+
75+
* **Simplicity**: Easy to understand and maintain
76+
* **Memory Safety**: Strong guarantees against memory leaks
77+
* **Suitable for Regular Heartbeats**: Works well for applications with consistent heartbeat intervals
78+
79+
Alternative Approaches
80+
~~~~~~~~~~~~~~~~~~~~~~
81+
82+
The JavaScript implementation uses time-based expiration, which offers:
83+
84+
* **More Sophisticated**: Tracks timestamps and only clears expired entries
85+
* **Better for Long-Running Applications**: More efficient for applications with infrequent heartbeats
86+
* **Future Enhancement**: Could be considered for GossipSub v1.3+ or as a separate optimization
87+
88+
Usage Examples
89+
--------------
90+
91+
Basic GossipSub 1.2 Setup
92+
~~~~~~~~~~~~~~~~~~~~~~~~~~
93+
94+
.. code-block:: python
95+
96+
from libp2p import new_node
97+
from libp2p.pubsub.gossipsub import GossipSub
98+
from libp2p.pubsub.pubsub import PubSub
99+
100+
# Create a new libp2p node
101+
node = await new_node()
102+
103+
# Initialize GossipSub with default settings
104+
gossipsub = GossipSub()
105+
106+
# Initialize PubSub with GossipSub
107+
pubsub = PubSub(gossipsub)
108+
109+
# Start the node
110+
await node.start()
111+
112+
Custom Configuration
113+
~~~~~~~~~~~~~~~~~~~~
114+
115+
.. code-block:: python
116+
117+
from libp2p.pubsub.gossipsub import GossipSub
118+
119+
# Configure GossipSub with custom IDONTWANT limits
120+
gossipsub = GossipSub(
121+
max_idontwant_messages=20, # Allow more IDONTWANT messages per peer
122+
# ... other parameters
123+
)
124+
125+
Protocol Compatibility
126+
----------------------
127+
128+
GossipSub 1.2 maintains full backward compatibility:
129+
130+
* **Protocol Negotiation**: Automatically negotiates the highest supported version
131+
* **Graceful Degradation**: Falls back to GossipSub 1.1 if peers don't support 1.2
132+
* **Mixed Networks**: Supports networks with both 1.1 and 1.2 peers
133+
134+
Migration Guide
135+
---------------
136+
137+
Upgrading from GossipSub 1.1 to 1.2 is straightforward:
138+
139+
1. **No Code Changes Required**: Existing applications work without modification
140+
2. **Automatic Protocol Detection**: The system automatically uses 1.2 when available
141+
3. **Configuration Optional**: Default settings work for most use cases
142+
4. **Performance Benefits**: Immediate bandwidth improvements in compatible networks
143+
144+
Best Practices
145+
--------------
146+
147+
Configuration Recommendations
148+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
149+
150+
* **Default Settings**: Start with default configuration unless you have specific requirements
151+
* **Monitor Memory Usage**: Keep an eye on memory consumption in long-running applications
152+
* **Network Analysis**: Consider your message size and frequency patterns when tuning parameters
153+
* **Security Considerations**: Be aware of potential DoS vectors and configure limits appropriately
154+
155+
Performance Optimization
156+
~~~~~~~~~~~~~~~~~~~~~~~~
157+
158+
* **Message Size**: IDONTWANT is most beneficial for messages larger than ~1KB
159+
* **Network Topology**: Works best in well-connected mesh networks
160+
* **Heartbeat Frequency**: Regular heartbeats ensure proper cleanup of IDONTWANT entries
161+
* **Peer Management**: Monitor peer behavior for excessive IDONTWANT usage
162+
163+
Troubleshooting
164+
---------------
165+
166+
Common Issues
167+
~~~~~~~~~~~~~
168+
169+
**High Memory Usage**
170+
- Check if `max_idontwant_messages` is set too high
171+
- Monitor for peers sending excessive IDONTWANT messages
172+
- Consider reducing the limit if memory usage is a concern
173+
174+
**Network Performance**
175+
- Verify that peers support GossipSub 1.2
176+
- Check network topology and connectivity
177+
- Monitor message sizes and frequency patterns
178+
179+
**Compatibility Issues**
180+
- Ensure all peers are using compatible libp2p versions
181+
- Check protocol negotiation logs
182+
- Verify network configuration and firewall settings
183+
184+
Specification References
185+
------------------------
186+
187+
* `GossipSub v1.2 Specification <https://github.com/libp2p/specs/blob/master/pubsub/gossipsub/gossipsub-v1.2.md>`_
188+
* `libp2p PubSub Specification <https://github.com/libp2p/specs/blob/master/pubsub/README.md>`_
189+
* `Py-libp2p GossipSub API Documentation <libp2p.pubsub.gossipsub>`_
190+
191+
Related Documentation
192+
---------------------
193+
194+
* :doc:`examples.pubsub` - Practical examples using GossipSub
195+
* :doc:`libp2p.pubsub` - Complete PubSub API documentation
196+
* :doc:`getting_started` - Getting started with Py-libp2p

docs/index.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ The Python implementation of the libp2p networking stack
1818

1919
Examples <examples>
2020
API <libp2p>
21+
GossipSub 1.2 <gossipsub-1.2>
2122

2223
.. toctree::
2324
:maxdepth: 1

docs/introduction.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ Current Capabilities
3333
Py-libp2p currently supports these core libp2p features:
3434

3535
* **Transports**: TCP, QUIC (near completion, in final testing phase)
36-
* **Protocols**: Gossipsub v1.1, Identify, Ping
36+
* **Protocols**: Gossipsub v1.1 and v1.2, Identify, Ping
3737
* **Security**: Noise protocol framework
3838
* **Connection Management**: Connection multiplexing
3939

docs/libp2p.pubsub.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
libp2p.pubsub package
22
=====================
33

4+
Py-libp2p provides a comprehensive PubSub implementation with support for both FloodSub and GossipSub protocols, including the latest GossipSub 1.2 specification with IDONTWANT control messages for improved bandwidth efficiency.
5+
6+
For detailed information about GossipSub 1.2 features and configuration, see :doc:`gossipsub-1.2`.
7+
48
Subpackages
59
-----------
610

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
# Mplex Stream Timeout and Deadline Example
2+
3+
This example demonstrates the new timeout and deadline features in MplexStream, including deadline validation, timeout handling, and real-world timeout scenarios.
4+
5+
## Features Demonstrated
6+
7+
### 🔍 Deadline Validation
8+
9+
- **Negative TTL values**: Returns `False` and doesn't modify deadlines
10+
- **Zero TTL values**: Returns `True` and sets immediate timeout
11+
- **Positive TTL values**: Returns `True` and sets timeout as expected
12+
13+
### ⏰ Timeout Scenarios
14+
15+
- **Normal operation**: Read/write with reasonable timeouts
16+
- **Short timeouts**: Demonstrates timeout behavior with very short deadlines
17+
- **Write timeouts**: Shows timeout handling for write operations
18+
- **Error handling**: Graceful handling of timeout exceptions
19+
20+
### 🛠️ New Methods Demonstrated
21+
22+
- `set_deadline(ttl)`: Sets both read and write deadlines
23+
- `set_read_deadline(ttl)`: Sets read deadline only
24+
- `set_write_deadline(ttl)`: Sets write deadline only
25+
- All methods now return `True`/`False` based on TTL validation
26+
27+
## Usage
28+
29+
The example requires a `--role` parameter to specify whether to run as server or client.
30+
31+
**Note**: Running without parameters will show the help message with all available options.
32+
33+
### 1. Start the Server
34+
35+
```bash
36+
python example_mplex_timeouts.py --role server --port 8000
37+
```
38+
39+
### 2. Start the Client
40+
41+
```bash
42+
python example_mplex_timeouts.py --role client --destination /ip4/127.0.0.1/tcp/8000/p2p/QmServerPeerID
43+
```
44+
45+
### 3. Run with Verbose Logging
46+
47+
```bash
48+
python example_mplex_timeouts.py --role server --port 8000 --verbose
49+
```
50+
51+
## What You'll See
52+
53+
The demo will show:
54+
55+
- ✅ Deadline validation results for different TTL values
56+
- ⏰ Timeout behavior with various deadline settings
57+
- 📤📥 Stream communication with timeout handling
58+
- 🔍 Error handling for invalid TTL values
59+
- 📊 Real-time demonstration of timeout features
60+
61+
## Key Improvements
62+
63+
This example showcases the refactored MplexStream implementation with:
64+
65+
- **Input validation**: Proper handling of negative TTL values
66+
- **Meaningful return values**: Methods return `True`/`False` based on success
67+
- **Unified timeout handling**: Consistent timeout behavior across read/write operations
68+
- **Better error messages**: Descriptive timeout error messages
69+
- **Comprehensive testing**: Edge cases and real-world scenarios
70+
71+
## Technical Details
72+
73+
The example uses:
74+
75+
- **Explicit mplex configuration**: `muxer_opt={MPLEX_PROTOCOL_ID: Mplex}`
76+
- **InsecureTransport**: Plaintext communication for demonstration purposes (not recommended for production)
77+
- **Trio async framework**: Non-blocking timeout operations
78+
- **Comprehensive logging**: Detailed output for understanding timeout behavior
79+
80+
This demonstrates how the new timeout features make MplexStream more robust and easier to use in production applications.

0 commit comments

Comments
 (0)