Skip to content

Commit

Permalink
Revert "feat(python): add storage operations to Python bindings"
Browse files Browse the repository at this point in the history
This reverts commit 66b575d.
  • Loading branch information
dirvine committed Nov 10, 2024
1 parent 66b575d commit 359029d
Show file tree
Hide file tree
Showing 4 changed files with 97 additions and 424 deletions.
103 changes: 31 additions & 72 deletions sn_node/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,100 +38,59 @@ maturin develop
To run the `safenode` binary, follow the instructions in the main project's usage guide.

### Python Usage

The Python module provides a comprehensive interface to run and manage Safe Network nodes. Here's a complete overview:

#### Basic Node Operations
The Python module provides a simple interface to run and manage Safe Network nodes. Here's a basic example:

```python
from safenode import SafeNode

# Example initial peers (note: these are example addresses and may not be active)
# You should use current active peers from the network
initial_peers = [
"/ip4/142.93.37.4/udp/40184/quic-v1/p2p/12D3KooWPC8q7QGZsmuTtCYxZ2s3FPXPZcS8LVKkayXkVFkqDEQB",
"/ip4/157.245.40.2/udp/33698/quic-v1/p2p/12D3KooWNyNNTGfwGf6fYyvrk4zp5EHxPhNDVNB25ZzEt2NXbCq2",
"/ip4/157.245.40.2/udp/33991/quic-v1/p2p/12D3KooWHPyZVAHqp2ebzKyxxsYzJYS7sNysfcLg2s1JLtbo6vhC"
]

# Create and start a node
node = SafeNode()
node.run(
rewards_address="0x1234567890123456789012345678901234567890", # Your EVM wallet address
evm_network="arbitrum_sepolia", # or "arbitrum_one" for mainnet
ip="0.0.0.0",
port=12000,
initial_peers=[
"/ip4/142.93.37.4/udp/40184/quic-v1/p2p/12D3KooWPC8q7QGZsmuTtCYxZ2s3FPXPZcS8LVKkayXkVFkqDEQB",
],
initial_peers=initial_peers,
local=False,
root_dir=None, # Uses default directory
home_network=False
)
```

#### Available Methods

Node Information:

- `peer_id()`: Get the node's peer ID
- `get_rewards_address()`: Get current rewards/wallet address
- `set_rewards_address(address: str)`: Set new rewards address (requires restart)
- `get_kbuckets()`: Get routing table information
- `get_all_record_addresses()`: Get all stored record addresses

Storage Operations:

- `store_record(key: str, value: bytes, record_type: str)`: Store data
- `key`: Hex string
- `value`: Bytes to store
- `record_type`: "chunk" or "scratchpad"
- `get_record(key: str) -> Optional[bytes]`: Retrieve stored data
- `delete_record(key: str) -> bool`: Delete stored data
- `get_stored_records_size() -> int`: Get total size of stored data
# Get node information
peer_id = node.peer_id()
print(f"Node peer ID: {peer_id}")

Directory Management:
# Get current rewards address
address = node.get_rewards_address()
print(f"Current rewards address: {address}")

- `get_root_dir() -> str`: Get current root directory path
- `get_default_root_dir(peer_id: Optional[str]) -> str`: Get default root directory
- `get_logs_dir() -> str`: Get logs directory path
- `get_data_dir() -> str`: Get data storage directory path

#### Storage Example

```python
# Store some data
key = "1234567890abcdef" # Hex string key
data = b"Hello, Safe Network!"
node.store_record(key, data, "chunk")

# Retrieve the data
stored_data = node.get_record(key)
if stored_data:
print(f"Retrieved: {stored_data.decode()}")

# Get storage info
size = node.get_stored_records_size()
print(f"Total storage used: {size} bytes")

# Delete data
if node.delete_record(key):
print("Data deleted successfully")
# Get network information
kbuckets = node.get_kbuckets()
for distance, peers in kbuckets:
print(f"Distance {distance}: {len(peers)} peers")
```

#### Directory Management Example

```python
# Get various directory paths
root_dir = node.get_root_dir()
logs_dir = node.get_logs_dir()
data_dir = node.get_data_dir()

# Get default directory for a specific peer
default_dir = SafeNode.get_default_root_dir(peer_id)
```
#### Available Methods
- `run()`: Start the node with configuration
- `peer_id()`: Get the node's peer ID
- `get_rewards_address()`: Get the current rewards/wallet address
- `set_rewards_address()`: Set a new rewards address (requires node restart)
- `get_all_record_addresses()`: Get all record addresses stored by the node
- `get_kbuckets()`: Get routing table information

#### Important Notes

- Initial peers list should contain currently active network peers
- Rewards address must be a valid EVM address
- Changing rewards address requires node restart
- Storage keys must be valid hex strings
- Record types are limited to 'chunk' and 'scratchpad'
- Directory paths are platform-specific
- Custom root directories can be set at node startup
- The initial peers list needs to contain currently active peers from the network
- The rewards address should be a valid EVM address
- Changing the rewards address requires restarting the node
- The node needs to connect to active peers to participate in the network

## Directory Structure

Expand Down
4 changes: 4 additions & 0 deletions sn_node/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ name = "safenode"
version = "0.112.3"
description = "SAFE Network Node"
requires-python = ">=3.8"
dependencies = [
"maturin>=1.7.4",
"pip>=24.3.1",
]

[tool.maturin]
features = ["extension-module"]
Expand Down
194 changes: 61 additions & 133 deletions sn_node/python/example.py
Original file line number Diff line number Diff line change
@@ -1,144 +1,72 @@
from safenode import SafeNode
import os

def print_section(title):
print(f"\n{'='*20} {title} {'='*20}")
# Create a new node instance
node = SafeNode()
initial_peers = ["/ip4/142.93.37.4/udp/40184/quic-v1/p2p/12D3KooWPC8q7QGZsmuTtCYxZ2s3FPXPZcS8LVKkayXkVFkqDEQB",
"/ip4/157.245.40.2/udp/33698/quic-v1/p2p/12D3KooWNyNNTGfwGf6fYyvrk4zp5EHxPhNDVNB25ZzEt2NXbCq2",
"/ip4/157.245.40.2/udp/33991/quic-v1/p2p/12D3KooWHPyZVAHqp2ebzKyxxsYzJYS7sNysfcLg2s1JLtbo6vhC"]
# Start the node with initial rewards address
initial_rewards_address = "0x1234567890123456789012345678901234567890"
print(f"Starting node with rewards address: {initial_rewards_address}")

# Example initial peers - note these may not be active
initial_peers = [
"/ip4/142.93.37.4/udp/40184/quic-v1/p2p/12D3KooWPC8q7QGZsmuTtCYxZ2s3FPXPZcS8LVKkayXkVFkqDEQB",
"/ip4/157.245.40.2/udp/33698/quic-v1/p2p/12D3KooWNyNNTGfwGf6fYyvrk4zp5EHxPhNDVNB25ZzEt2NXbCq2",
"/ip4/157.245.40.2/udp/33991/quic-v1/p2p/12D3KooWHPyZVAHqp2ebzKyxxsYzJYS7sNysfcLg2s1JLtbo6vhC"
]
node.run(
rewards_address=initial_rewards_address,
evm_network="arbitrum_sepolia",
ip="0.0.0.0",
port=12000,
initial_peers=initial_peers,
local=True,
root_dir=None,
home_network=False
)

def demonstrate_basic_node_operations():
print_section("Basic Node Operations")

# Create and start node
node = SafeNode()
initial_rewards_address = "0x1234567890123456789012345678901234567890"
print(f"Starting node with rewards address: {initial_rewards_address}")
# Get the current rewards address
current_address = node.get_rewards_address()
print(f"Current rewards address: {current_address}")

node.run(
rewards_address=initial_rewards_address,
evm_network="arbitrum_sepolia",
ip="0.0.0.0",
port=12000,
initial_peers=initial_peers,
local=True,
root_dir=None,
home_network=False
)
# Verify it matches what we set
assert current_address.lower() == initial_rewards_address.lower(), "Rewards address mismatch!"

# Get node information
peer_id = node.peer_id()
print(f"Node peer ID: {peer_id}")

current_address = node.get_rewards_address()
print(f"Current rewards address: {current_address}")

return node, peer_id
# Try to set a new rewards address (this will raise an error since it requires restart)
new_address = "0x9876543210987654321098765432109876543210"
try:
node.set_rewards_address(new_address)
print("This line won't be reached due to the error")
except RuntimeError as e:
print(f"Expected error when trying to change address: {e}")

def demonstrate_storage_operations(node):
print_section("Storage Operations")

# Store data
key = "1234567890abcdef" # Example hex key
data = b"Hello, Safe Network!"

try:
# Store a chunk
node.store_record(key, data, "chunk")
print(f"Successfully stored chunk with key: {key}")

# Retrieve the data
stored_data = node.get_record(key)
if stored_data:
print(f"Retrieved data: {stored_data.decode()}")

# Get storage stats
size = node.get_stored_records_size()
print(f"Total storage used: {size} bytes")

# List all stored records
addresses = node.get_all_record_addresses()
print(f"Stored record addresses: {addresses}")

# Delete the record
if node.delete_record(key):
print(f"Successfully deleted record: {key}")
except Exception as e:
print(f"Storage operation failed: {e}")
# Get the node's peer ID
peer_id = node.peer_id()
print(f"Node peer ID: {peer_id}")

def demonstrate_network_operations(node):
print_section("Network Operations")

try:
# Get routing table information
kbuckets = node.get_kbuckets()
print("\nRouting table information:")
for distance, peers in kbuckets:
print(f"Distance {distance}: {len(peers)} peers")
for peer in peers[:3]: # Show first 3 peers at each distance
print(f" - {peer}")
except Exception as e:
print(f"Network operation failed: {e}")
# Get all record addresses
addresses = node.get_all_record_addresses()
print(f"Record addresses: {addresses}")

def demonstrate_directory_management(node, peer_id):
print_section("Directory Management")

try:
# Get various directory paths
root_dir = node.get_root_dir()
print(f"Current root directory: {root_dir}")

logs_dir = node.get_logs_dir()
print(f"Logs directory: {logs_dir}")

data_dir = node.get_data_dir()
print(f"Data directory: {data_dir}")

# Get default directory for current peer
default_dir = SafeNode.get_default_root_dir(peer_id)
print(f"Default root directory for peer {peer_id}: {default_dir}")

# Demonstrate custom directory
custom_dir = os.path.join(os.path.expanduser("~"), "safenode-test")
print(f"\nStarting new node with custom directory: {custom_dir}")

new_node = SafeNode()
new_node.run(
rewards_address="0x1234567890123456789012345678901234567890",
evm_network="arbitrum_sepolia",
ip="0.0.0.0",
port=12001,
initial_peers=initial_peers,
local=True,
root_dir=custom_dir,
home_network=False
)

print(f"New node root directory: {new_node.get_root_dir()}")

except Exception as e:
print(f"Directory operation failed: {e}")
# Get kbuckets information
kbuckets = node.get_kbuckets()
for distance, peers in kbuckets:
print(f"Distance {distance}: {len(peers)} peers")

def main():
try:
# Basic setup and node operations
node, peer_id = demonstrate_basic_node_operations()

# Storage operations
demonstrate_storage_operations(node)

# Network operations
demonstrate_network_operations(node)

# Directory management
demonstrate_directory_management(node, peer_id)

except Exception as e:
print(f"Example failed with error: {e}")
# To actually change the rewards address, you would need to:
# 1. Stop the current node
# 2. Create a new node with the new address
print("\nDemonstrating rewards address change with node restart:")
node = SafeNode() # Create new instance
print(f"Starting node with new rewards address: {new_address}")

if __name__ == "__main__":
main()
node.run(
rewards_address=new_address,
evm_network="arbitrum_sepolia",
ip="0.0.0.0",
port=12000,
initial_peers=[],
local=True,
root_dir=None,
home_network=False
)

# Verify the new address was set
current_address = node.get_rewards_address()
print(f"New current rewards address: {current_address}")
assert current_address.lower() == new_address.lower(), "New rewards address mismatch!"
Loading

0 comments on commit 359029d

Please sign in to comment.