Skip to content

[P7] Implement Network & Protocol API methods (6 endpoints) #24

@umwelt

Description

@umwelt

Overview

Implement all Network and Protocol API methods in the TypeScript client to match the ZHTP node's network monitoring and protocol information endpoints.

Related to: #17 - Comprehensive API Implementation Guide
Priority: P7 - MEDIUM (Important for network visibility and monitoring)
Estimated Effort: Small-Medium (3-5 hours)

Background

The ZHTP node has 6 endpoints for network monitoring and protocol information:

  • Network status and peer discovery (3 endpoints)
  • Protocol information (2 endpoints)
  • Gas pricing (1 endpoint)

These are essential for network health monitoring, peer discovery, and transaction cost estimation.

Required Methods

Network Status (3 endpoints)

1. getNetworkPeers() ❓ UNKNOWN

Endpoint: GET /api/v1/blockchain/network/peers

Expected Response:

{
  status: "success",
  peers: [
    {
      peer_id: "...",
      address: "192.168.1.100:8080",
      reputation: 95,
      last_seen: 1234567890,
      connection_type: "inbound" | "outbound"
    }
  ],
  total_peers: 10,
  max_peers: 50
}

Action: Check if exists, implement if missing

Note: Old path /mesh/peers is aliased to this endpoint for backward compatibility

2. getNetworkStatus() ❓ UNKNOWN

Endpoint: GET /api/v1/blockchain/network/status

Expected Response:

{
  status: "success",
  network_id: "mainnet" | "testnet",
  connected_peers: 10,
  syncing: false,
  sync_progress: 100,
  current_block: 12345,
  latest_block: 12345
}

Action: Check if exists, implement if missing

3. connectToPeer() ❌ MISSING

Endpoint: POST /api/v1/blockchain/network/connect

Request:

{
  peer_address: string, // "ip:port" or "did:zhtp:..."
  bootstrap?: boolean
}

Expected Response:

{
  status: "success",
  connected: true,
  peer_id: "..."
}

Action: Implement new method

Protocol Information (2 endpoints)

4. getProtocolInfo() ❓ UNKNOWN

Endpoint: GET /api/v1/protocol/info

Expected Response:

{
  status: "success",
  protocol_version: "1.0.0",
  node_version: "0.1.0",
  supported_features: ["zkp", "web4", "dao", "guardians"],
  chain_id: "sovereign-mainnet",
  genesis_hash: "..."
}

Action: Check if exists, implement if missing

Note: Old path /node/status is aliased to this endpoint for backward compatibility

5. getProtocolMetrics() ❌ MISSING

Endpoint: GET /api/v1/protocol/metrics

Expected Response:

{
  status: "success",
  uptime: 86400, // seconds
  total_requests: 10000,
  requests_per_second: 10,
  memory_usage: 512, // MB
  cpu_usage: 25, // percentage
  disk_usage: 1024 // MB
}

Action: Implement new method

Gas Pricing (1 endpoint)

6. getGasInfo() ❌ MISSING

Endpoint: GET /api/v1/network/gas

Expected Response:

{
  status: "success",
  gas_price: 150, // base + priority
  estimated_cost: 3150000, // gas_price * 21000
  base_fee: 100,
  priority_fee: 50
}

Action: Implement new method

Use Case: For estimating transaction costs and wallet fee estimation

Implementation Checklist

Phase 1: Check Existing Methods

  • Check if getNetworkPeers() exists
  • Check if getNetworkStatus() exists
  • Check if getProtocolInfo() exists

Phase 2: Implement Missing Methods

  • Implement connectToPeer() (if missing)
  • Implement getProtocolMetrics() (if missing)
  • Implement getGasInfo() (if missing)
  • Implement any other missing methods from Phase 1

Phase 3: Backward Compatibility

  • Verify /mesh/peers path works (should be aliased)
  • Verify /node/status path works (should be aliased)
  • Consider adding method aliases for backward compatibility if needed

Phase 4: Testing

  • Test peer discovery and listing
  • Test network status monitoring
  • Test peer connection (use testnet!)
  • Test protocol info retrieval
  • Test metrics monitoring
  • Test gas price queries
  • Test error handling (network errors, timeout, etc.)

Phase 5: Documentation

  • Add JSDoc comments to all methods
  • Document network connection types
  • Create usage examples:
    • Network health monitoring
    • Peer discovery and connection
    • Gas price tracking
    • Protocol version checking
  • Update main README with network monitoring examples

Files to Modify

  • src/core/zhtp-api-methods.ts - Add/verify network methods
  • src/core/types.ts - Add network-related type definitions
  • src/core/zhtp-api-client.ts - Export new methods

Success Criteria

  • All 6 network/protocol endpoints have corresponding TypeScript methods
  • All methods use /api/v1 paths
  • Backward compatibility with legacy paths maintained
  • Response types match node implementation
  • All methods handle errors properly (network errors, timeouts, etc.)
  • Full test coverage for network functionality
  • Documentation complete with usage examples

Use Cases

Network Monitoring Dashboard

// Get network health
const status = await client.getNetworkStatus();
const peers = await client.getNetworkPeers();
const metrics = await client.getProtocolMetrics();

console.log(`Connected to ${status.connected_peers} peers`);
console.log(`Sync progress: ${status.sync_progress}%`);
console.log(`Node uptime: ${metrics.uptime} seconds`);

Transaction Cost Estimation

// Get current gas prices before sending transaction
const gasInfo = await client.getGasInfo();
const transactionCost = gasInfo.estimated_cost;

console.log(`Estimated transaction cost: ${transactionCost} wei`);
console.log(`Base fee: ${gasInfo.base_fee}, Priority fee: ${gasInfo.priority_fee}`);

Peer Discovery and Connection

// Find and connect to new peers
const peers = await client.getNetworkPeers();

if (peers.total_peers < peers.max_peers) {
  await client.connectToPeer({
    peer_address: "bootstrap.sovereign.network:8080",
    bootstrap: true
  });
}

Priority Rationale

Network and protocol methods are important for:

  • Network Health Monitoring: Essential for node operators and advanced users
  • Gas Price Discovery: Critical for wallet fee estimation
  • Peer Management: Important for network connectivity and resilience
  • Protocol Compatibility: Helps clients ensure they're compatible with the node

While not as critical as identity/wallet functionality, these methods are important for building production-ready applications and monitoring tools.

Dependencies

  • Session authentication (may not be required for some read-only endpoints)
  • Error handling utilities (already implemented)
  • Network utilities for handling connection errors

Related Issues

Testing Notes

Network Testing: When testing peer connection functionality, use testnet nodes to avoid disrupting mainnet. Consider implementing connection timeout handling and retry logic.

Gas Price Monitoring: Consider implementing periodic gas price polling for real-time fee estimation in wallet UIs.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions