# Protocol Buffers

Complete reference for NCN Network v2 Protocol Buffer definitions.

***

## Overview

NCN Network uses Protocol Buffers (protobuf) for all gRPC communication. The definitions are in `proto/common_types.proto`.

***

## Services

### GatewayClientService

Client-facing service exposed by Gateway nodes.

```protobuf
service GatewayClientService {
  // Submit an inference task
  rpc SubmitInferenceTask(InferenceRequest) returns (InferenceTaskStatus);
  
  // Subscribe to task updates (streaming)
  rpc SubscribeToTaskUpdates(TaskID) returns (stream InferenceResponse);
  
  // Get current task status
  rpc GetTaskStatus(TaskID) returns (InferenceTaskStatus);
  
  // Cancel a task
  rpc CancelTask(TaskID) returns (Ack);
  
  // Confirm payment was made
  rpc ConfirmPayment(TransactionConfirmation) returns (Ack);
  
  // Get supported models
  rpc GetSupportedModels(Empty) returns (stream ModelInfo);
}
```

### GatewayComputeService

Compute node-facing service exposed by Gateway nodes.

```protobuf
service GatewayComputeService {
  // Register compute node
  rpc RegisterComputeNode(NodeInfo) returns (Ack);
  
  // Update heartbeat
  rpc UpdateHeartbeat(HeartbeatRequest) returns (Ack);
  
  // Receive task stream
  rpc ReceiveTask(NodeInfo) returns (stream InferenceRequest);
  
  // Submit completed result
  rpc SubmitResult(InferenceResponse) returns (Ack);
  
  // Get task by ID
  rpc GetTask(TaskID) returns (InferenceRequest);
}
```

### P2PRegistryService

Registry service for node discovery and validation.

```protobuf
service P2PRegistryService {
  // Node management
  rpc RegisterNode(NodeInfo) returns (Ack);
  rpc UpdateNodeHeartbeat(UpdateNodeHeartbeatRequest) returns (Ack);
  rpc DeregisterNode(WalletAddress) returns (Ack);
  rpc DiscoverNodes(DiscoverNodesRequest) returns (stream NodeInfo);
  
  // Validation
  rpc RequestPreprocessingValidation(InferenceRequest) returns (PreprocessingValidation);
  rpc RequestCompletionValidation(InferenceResponse) returns (CompletionValidation);
  
  // Subnet management
  rpc EstimateSubnetFee(EstimateSubnetFeeRequest) returns (EstimateSubnetFeeResponse);
  rpc CreateSubnet(CreateSubnetRequest) returns (CreateSubnetResponse);
  rpc GetSubnet(GetSubnetRequest) returns (GetSubnetResponse);
  rpc ListSubnets(Empty) returns (stream SubnetMetadata);
  
  // Validator management
  rpc RegisterValidator(RegisterValidatorRequest) returns (RegisterValidatorResponse);
  rpc UnregisterValidator(UnregisterValidatorRequest) returns (Ack);
  rpc GetValidatorInfo(ValidatorAddressRequest) returns (ValidatorInfoResponse);
  rpc ListValidators(ListValidatorsRequest) returns (stream ValidatorInfoMessage);
}
```

***

## Core Messages

### InferenceRequest

Request for model inference.

```protobuf
message InferenceRequest {
  string request_id = 1;           // Unique request identifier
  string model_uuid = 2;           // Model to use
  string input_data = 3;           // JSON-encoded input
  string originator_client_id = 4; // Client wallet address
  
  // Payment information (optional)
  optional PreprocessingValidation preprocessing_validation = 5;
  optional TransactionConfirmation transaction_confirmation = 6;
  optional int64 assigned_timestamp = 7;
  optional string assigned_compute_node_id = 8;
}
```

### InferenceResponse

Response from model inference.

```protobuf
message InferenceResponse {
  string request_id = 1;
  string model_uuid = 2;
  string output_data = 3;          // JSON-encoded output
  string status = 4;               // "completed", "failed", "processing"
  string error_message = 5;
  
  // Compute node attestation
  optional ComputeCompletion compute_completion = 6;
  
  // Validation
  optional CompletionValidation completion_validation = 7;
}
```

### NodeInfo

Information about a network node.

```protobuf
message NodeInfo {
  string node_id = 1;              // Unique node identifier
  string node_type = 2;            // "compute", "gateway", "validator"
  string ip_address = 3;           // Node IP address
  uint32 port = 4;                 // Node port
  repeated string capabilities = 5; // Supported features
  string wallet_address = 6;       // Node's wallet address
  int64 last_heartbeat = 7;        // Unix timestamp
  
  // Model support
  repeated ModelData supported_models = 8;
  
  // Subnet membership
  optional uint64 subnet_id = 9;
}
```

***

## Payment Messages

### PaymentTree

Payment distribution specification.

```protobuf
message PaymentTree {
  string compute_price_wei = 1;    // Wei for compute node
  string gateway_gas_wei = 2;      // Wei for gateway
  string validator_reward_wei = 3; // Wei for validators
  string treasury_fee_wei = 4;     // Wei for treasury
}
```

### PreprocessingValidation

Validator approval for payment initiation.

```protobuf
message PreprocessingValidation {
  string request_id = 1;
  string gateway_wallet = 2;
  string compute_node_id = 3;
  string compute_node_wallet = 4;
  PaymentTree payment_tree = 5;
  repeated ValidatorSignature validator_signatures = 6;
  int64 expiry_timestamp = 7;
}
```

### TransactionConfirmation

Blockchain transaction confirmation.

```protobuf
message TransactionConfirmation {
  string request_id = 1;
  string tx_hash = 2;              // Transaction hash
  uint64 block_number = 3;         // Confirmation block
  uint64 confirmations = 4;        // Number of confirmations
  string originator_wallet = 5;    // Payer address
  string amount_wei = 6;           // Amount paid
  int64 timestamp = 7;             // Confirmation time
}
```

### ComputeCompletion

Compute node's result attestation.

```protobuf
message ComputeCompletion {
  string request_id = 1;
  string compute_node_signature = 2; // Signature over result
  bytes result_hash = 3;             // SHA-256 of result
  int64 completion_timestamp = 4;
  uint64 computation_time_ms = 5;
}
```

### CompletionValidation

Validator approval for payment distribution.

```protobuf
message CompletionValidation {
  string request_id = 1;
  repeated ValidatorSignature validator_signatures = 2;
  ComputeCompletion compute_completion = 3;
}
```

### ValidatorSignature

Individual validator signature.

```protobuf
message ValidatorSignature {
  string validator_address = 1;    // Validator wallet
  string signature = 2;            // Hex-encoded signature
  int64 timestamp = 3;             // Signature time
}
```

***

## Subnet Messages

### SubnetMetadata

Subnet configuration and status.

```protobuf
message SubnetMetadata {
  uint64 subnet_id = 1;
  string gateway_address = 2;
  int64 created_at = 3;
  repeated ModelDescriptor models = 4;
  repeated ValidatorSignature validated_by = 5;
  string network_fee_wei = 6;
  string payment_tx = 7;
  string status = 9;               // "pending", "active", "deprecated"
}
```

### ModelDescriptor

Model specification in subnet.

```protobuf
message ModelDescriptor {
  string model_uuid = 1;           // Unique model ID
  string source = 2;               // "huggingface", "path", "url"
  string path = 3;                 // Model path/URL
  string name = 4;                 // Display name
  string category = 5;             // "text", "audio", "vision"
  string description = 6;          // Model description
  int64 max_tokens = 7;            // Max tokens supported
  string version = 8;              // Model version
  string input_format = 9;         // Expected input format
  string output_format = 10;       // Output format
}
```

### CreateSubnetRequest

Request to create a new subnet.

```protobuf
message CreateSubnetRequest {
  string gateway_address = 1;
  repeated ModelDescriptor models = 2;
  string fee_quote_id = 3;         // From EstimateSubnetFee
  string payment_tx = 4;           // Transaction hash
  bytes config_hash = 5;           // Hash of configuration
}
```

***

## Status Messages

### InferenceTaskStatus

Current status of an inference task.

```protobuf
message InferenceTaskStatus {
  string request_id = 1;
  string status = 2;               // "queued", "processing", "completed", "failed"
  string error_message = 3;
  
  // Payment status
  optional PaymentStatus payment_status = 4;
  optional PreprocessingValidation preprocessing_validation = 5;
}
```

### PaymentStatus

Status of payment flow.

```protobuf
message PaymentStatus {
  bool required = 1;               // Is payment required?
  bool preprocessing_complete = 2; // Validation received?
  bool payment_confirmed = 3;      // Transaction confirmed?
  bool completion_validated = 4;   // Result validated?
  
  PaymentTree payment_tree = 5;    // Payment amounts
  string contract_address = 6;     // Contract to pay
}
```

***

## Utility Messages

### TaskID

```protobuf
message TaskID {
  string id = 1;
}
```

### Ack

```protobuf
message Ack {
  bool success = 1;
  string message = 2;
}
```

### Empty

```protobuf
message Empty {}
```

### WalletAddress

```protobuf
message WalletAddress {
  string address = 1;
}
```

***

## Error Handling

### gRPC Status Codes

| Code                    | Meaning      | When Used              |
| ----------------------- | ------------ | ---------------------- |
| OK (0)                  | Success      | Request completed      |
| CANCELLED (1)           | Cancelled    | Task cancelled         |
| INVALID\_ARGUMENT (3)   | Bad input    | Invalid request format |
| NOT\_FOUND (5)          | Not found    | Unknown task/model     |
| ALREADY\_EXISTS (6)     | Duplicate    | Request ID exists      |
| RESOURCE\_EXHAUSTED (8) | Rate limited | Too many requests      |
| INTERNAL (13)           | Server error | Processing error       |
| UNAVAILABLE (14)        | Service down | Node unavailable       |

***

## Code Generation

### Rust (tonic)

```bash
# Build generates automatically with build.rs
cargo build
```

### Python

```bash
pip install grpcio-tools
python -m grpc_tools.protoc \
  -I./proto \
  --python_out=./generated \
  --grpc_python_out=./generated \
  proto/common_types.proto
```

### Go

```bash
protoc \
  --go_out=./generated \
  --go-grpc_out=./generated \
  proto/common_types.proto
```

### JavaScript

```bash
npm install grpc-tools
grpc_tools_node_protoc \
  --js_out=import_style=commonjs:./generated \
  --grpc_out=./generated \
  proto/common_types.proto
```

***

## Related Documentation

* [Gateway gRPC API](https://github.com/NeuroChainAi/docs-guides/blob/main/api-reference/gateway-grpc.md) - Gateway service details
* [Registry gRPC API](https://github.com/NeuroChainAi/docs-guides/blob/main/api-reference/registry-grpc.md) - Registry service details
* [HTTP Endpoints](https://github.com/NeuroChainAi/docs-guides/blob/main/api-reference/http-endpoints.md) - REST API reference


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.neurochain.ai/nc/neurochainai-guides/api-reference/protobuf.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
