Skip to content

Commit fef6e77

Browse files
committed
implement persistent peerstore with Protocol Buffer serialization, context managers, and configurable sync
1 parent 7c54a12 commit fef6e77

File tree

15 files changed

+1403
-184
lines changed

15 files changed

+1403
-184
lines changed
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Example usage of persistent peerstore with safe serialization.
4+
5+
This example demonstrates how to use the new persistent peerstore implementation
6+
with Protocol Buffer serialization instead of unsafe pickle.
7+
"""
8+
9+
import asyncio
10+
from pathlib import Path
11+
import tempfile
12+
13+
from multiaddr import Multiaddr
14+
15+
from libp2p.peer.id import ID
16+
from libp2p.peer.persistent import (
17+
create_async_peerstore,
18+
create_sync_peerstore,
19+
)
20+
21+
22+
async def async_example():
23+
"""Demonstrate async persistent peerstore usage."""
24+
print("=== Async Persistent Peerstore Example ===")
25+
26+
with tempfile.TemporaryDirectory() as temp_dir:
27+
db_path = Path(temp_dir) / "async_peers.db"
28+
29+
# Create peerstore with safe serialization and configurable sync
30+
async with create_async_peerstore(
31+
db_path=db_path,
32+
backend="sqlite",
33+
sync_interval=0.5, # Sync every 0.5 seconds
34+
auto_sync=True
35+
) as peerstore:
36+
37+
# Create a test peer
38+
peer_id = ID.from_base58("QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN")
39+
40+
# Add some addresses
41+
addr1 = Multiaddr("/ip4/127.0.0.1/tcp/4001")
42+
addr2 = Multiaddr("/ip6/::1/tcp/4001")
43+
44+
await peerstore.add_addrs_async(peer_id, [addr1, addr2], 3600)
45+
46+
# Add protocols
47+
await peerstore.add_protocols_async(peer_id, ["/ipfs/ping/1.0.0", "/ipfs/id/1.0.0"])
48+
49+
# Add metadata
50+
await peerstore.put_async(peer_id, "agent", "py-libp2p-example")
51+
52+
print(f"Added peer {peer_id}")
53+
print(f"Addresses: {await peerstore.addrs_async(peer_id)}")
54+
print(f"Protocols: {await peerstore.get_protocols_async(peer_id)}")
55+
print(f"Metadata: {await peerstore.get_async(peer_id, 'agent')}")
56+
57+
print("Peerstore closed safely using context manager")
58+
59+
60+
def sync_example():
61+
"""Demonstrate sync persistent peerstore usage."""
62+
print("\n=== Sync Persistent Peerstore Example ===")
63+
64+
with tempfile.TemporaryDirectory() as temp_dir:
65+
db_path = Path(temp_dir) / "sync_peers.db"
66+
67+
# Create peerstore with safe serialization and configurable sync
68+
with create_sync_peerstore(
69+
db_path=db_path,
70+
backend="sqlite",
71+
sync_interval=1.0, # Sync every 1 second
72+
auto_sync=False # Manual sync control
73+
) as peerstore:
74+
75+
# Create a test peer
76+
peer_id = ID.from_base58("QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN")
77+
78+
# Add some addresses
79+
addr1 = Multiaddr("/ip4/192.168.1.100/tcp/4001")
80+
addr2 = Multiaddr("/ip4/10.0.0.1/tcp/4001")
81+
82+
peerstore.add_addrs(peer_id, [addr1, addr2], 7200)
83+
84+
# Add protocols
85+
peerstore.add_protocols(peer_id, ["/libp2p/circuit/relay/0.1.0"])
86+
87+
# Add metadata
88+
peerstore.put(peer_id, "version", "1.0.0")
89+
90+
# Manual sync since auto_sync=False
91+
peerstore.datastore.sync(b"")
92+
93+
print(f"Added peer {peer_id}")
94+
print(f"Addresses: {peerstore.addrs(peer_id)}")
95+
print(f"Protocols: {peerstore.get_protocols(peer_id)}")
96+
print(f"Metadata: {peerstore.get(peer_id, 'version')}")
97+
98+
print("Peerstore closed safely using context manager")
99+
100+
101+
def security_example():
102+
"""Demonstrate security improvements."""
103+
print("\n=== Security Improvements ===")
104+
print("✅ Replaced unsafe pickle with Protocol Buffers")
105+
print("✅ Added context manager support for proper resource cleanup")
106+
print("✅ Improved SQLite thread safety with WAL mode")
107+
print("✅ Added configurable sync for better performance")
108+
print("✅ Enhanced error handling with specific exceptions")
109+
print("✅ Added proper file permissions (0600) for database files")
110+
111+
112+
if __name__ == "__main__":
113+
# Run async example
114+
asyncio.run(async_example())
115+
116+
# Run sync example
117+
sync_example()
118+
119+
# Show security improvements
120+
security_example()
121+
122+
print("\n🎉 All examples completed successfully!")
123+
print("The persistent peerstore now uses safe Protocol Buffer serialization")
124+
print("and provides better resource management and performance control.")

0 commit comments

Comments
 (0)