# Common Types

The `common_types` crate provides shared types, utilities, and protocol definitions used across all NCN Network components.

***

## Overview

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                            common_types Crate                                │
│                                                                             │
│   ┌───────────────────────────────────────────────────────────────────┐     │
│   │                    Protocol Buffer Types                           │     │
│   │   Generated from proto/common_types.proto                          │     │
│   │   • InferenceRequest, InferenceResponse                            │     │
│   │   • NodeInfo, ModelData, PaymentTree                               │     │
│   │   • PreprocessingValidation, CompletionValidation                  │     │
│   │   • SubnetMetadata, ValidatorSignature                             │     │
│   └───────────────────────────────────────────────────────────────────┘     │
│                                                                             │
│   ┌───────────────────────────────────────────────────────────────────┐     │
│   │                    Cryptographic Utilities                         │     │
│   │   • compute_message_hash() - SHA-256 hashing                       │     │
│   │   • sign_message() - secp256k1 ECDSA signing                       │     │
│   │   • verify_signature() - Signature verification                    │     │
│   │   • recover_signer() - Address recovery                            │     │
│   └───────────────────────────────────────────────────────────────────┘     │
│                                                                             │
│   ┌───────────────────────────────────────────────────────────────────┐     │
│   │                    Payment Utilities                               │     │
│   │   • PaymentTree calculations                                       │     │
│   │   • Fee estimation                                                 │     │
│   │   • Wei/ETH conversions                                            │     │
│   └───────────────────────────────────────────────────────────────────┘     │
│                                                                             │
│   ┌───────────────────────────────────────────────────────────────────┐     │
│   │                    Type Conversions                                │     │
│   │   • Protobuf ↔ Native type conversions                             │     │
│   │   • Serialization/deserialization                                  │     │
│   └───────────────────────────────────────────────────────────────────┘     │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
```

***

## Crate Structure

```
common_types/
├── Cargo.toml
├── build.rs              # Protobuf code generation
└── src/
    ├── lib.rs            # Crate root, re-exports
    ├── crypto.rs         # Cryptographic utilities
    ├── payment.rs        # Payment helpers
    └── types.rs          # Type definitions
```

***

## Usage

### Add Dependency

```toml
# Cargo.toml
[dependencies]
common_types = { path = "../common_types" }
```

### Import Types

```rust
use common_types::{
    // Protobuf types
    InferenceRequest,
    InferenceResponse,
    NodeInfo,
    PaymentTree,
    PreprocessingValidation,
    CompletionValidation,
    ValidatorSignature,
    
    // Crypto utilities
    crypto::{
        compute_message_hash,
        sign_message,
        verify_signature,
        recover_signer,
    },
    
    // Payment utilities
    payment::{
        calculate_payment_tree,
        total_payment,
    },
};
```

***

## Protobuf Types

### Core Types

```rust
// Inference request
pub struct InferenceRequest {
    pub request_id: String,
    pub model_uuid: String,
    pub input_data: String,
    pub originator_client_id: String,
    pub preprocessing_validation: Option<PreprocessingValidation>,
    pub transaction_confirmation: Option<TransactionConfirmation>,
    pub assigned_timestamp: Option<i64>,
    pub assigned_compute_node_id: Option<String>,
}

// Inference response
pub struct InferenceResponse {
    pub request_id: String,
    pub model_uuid: String,
    pub output_data: String,
    pub status: String,
    pub error_message: String,
    pub compute_completion: Option<ComputeCompletion>,
    pub completion_validation: Option<CompletionValidation>,
}
```

### Payment Types

```rust
// Payment distribution
pub struct PaymentTree {
    pub compute_price_wei: String,
    pub gateway_gas_wei: String,
    pub validator_reward_wei: String,
    pub treasury_fee_wei: String,
}

// Validator signature
pub struct ValidatorSignature {
    pub validator_address: String,
    pub signature: String,
    pub timestamp: i64,
}
```

### Node Types

```rust
// Node information
pub struct NodeInfo {
    pub node_id: String,
    pub node_type: String,
    pub ip_address: String,
    pub port: u32,
    pub capabilities: Vec<String>,
    pub wallet_address: String,
    pub last_heartbeat: i64,
    pub supported_models: Vec<ModelData>,
    pub subnet_id: Option<u64>,
}

// Model data
pub struct ModelData {
    pub model_uuid: String,
    pub path: String,
    pub name: String,
    pub category: String,
}
```

***

## Cryptographic Utilities

### Message Hashing

```rust
use common_types::crypto::compute_message_hash;

// Hash message with Ethereum prefix
let message = "Hello, World!";
let hash = compute_message_hash(message);
// Returns: [u8; 32]
```

### Signing

```rust
use common_types::crypto::sign_message;

let private_key = "0x..."; // Private key hex
let message = "Hello, World!";
let signature = sign_message(private_key, message)?;
// Returns: "0x..." (hex-encoded signature)
```

### Verification

```rust
use common_types::crypto::{verify_signature, recover_signer};

let message = "Hello, World!";
let signature = "0x...";
let expected_address = "0x...";

// Verify signature matches expected address
let valid = verify_signature(message, signature, expected_address)?;

// Or recover the signer address
let recovered = recover_signer(message, signature)?;
assert_eq!(recovered, expected_address);
```

### Preprocessing Message

```rust
use common_types::crypto::compute_preprocessing_message;

let request_id = "req-123";
let gateway_wallet = "0x...";
let compute_node_id = "compute-1";
let compute_wallet = "0x...";
let payment_tree = PaymentTree { /* ... */ };
let expiry = 1704067200;

let message_hash = compute_preprocessing_message(
    request_id,
    gateway_wallet,
    compute_node_id,
    compute_wallet,
    &payment_tree,
    expiry,
);
```

### Completion Message

```rust
use common_types::crypto::compute_completion_message;

let request_id = "req-123";
let compute_signature = "0x...";
let result_hash = [0u8; 32];
let timestamp = 1704067200;
let computation_time = 1500;

let message_hash = compute_completion_message(
    request_id,
    compute_signature,
    &result_hash,
    timestamp,
    computation_time,
);
```

***

## Payment Utilities

### Calculate Payment Tree

```rust
use common_types::payment::calculate_payment_tree;

let base_price = 1_000_000_000_000_000_000u128; // 1 ETH
let gateway_rate = 0.10;  // 10%
let validator_rate = 0.05; // 5%
let treasury_rate = 0.05;  // 5%

let tree = calculate_payment_tree(
    base_price,
    gateway_rate,
    validator_rate,
    treasury_rate,
);

// tree.compute_price_wei = "800000000000000000"
// tree.gateway_gas_wei = "100000000000000000"
// tree.validator_reward_wei = "50000000000000000"
// tree.treasury_fee_wei = "50000000000000000"
```

### Total Payment

```rust
use common_types::payment::total_payment;

let tree = PaymentTree {
    compute_price_wei: "800000000000000000".to_string(),
    gateway_gas_wei: "100000000000000000".to_string(),
    validator_reward_wei: "50000000000000000".to_string(),
    treasury_fee_wei: "50000000000000000".to_string(),
};

let total = total_payment(&tree);
// total = 1000000000000000000 (1 ETH)
```

### Wei/ETH Conversion

```rust
use common_types::payment::{wei_to_eth, eth_to_wei};

let wei = 1_000_000_000_000_000_000u128;
let eth = wei_to_eth(wei);
// eth = 1.0

let eth = 2.5;
let wei = eth_to_wei(eth);
// wei = 2500000000000000000
```

***

## gRPC Services

### GatewayClientService Stub

```rust
use common_types::gateway_client_service_client::GatewayClientServiceClient;

let mut client = GatewayClientServiceClient::connect("http://localhost:50051").await?;

let request = InferenceRequest {
    request_id: "req-123".to_string(),
    model_uuid: "bark_semantic".to_string(),
    input_data: "{\"text\": \"Hello\"}".to_string(),
    originator_client_id: "client-1".to_string(),
    ..Default::default()
};

let response = client.submit_inference_task(request).await?;
```

### P2PRegistryService Stub

```rust
use common_types::p2p_registry_service_client::P2PRegistryServiceClient;

let mut client = P2PRegistryServiceClient::connect("http://localhost:50050").await?;

let request = DiscoverNodesRequest {
    node_type: "compute".to_string(),
    ..Default::default()
};

let mut stream = client.discover_nodes(request).await?.into_inner();
while let Some(node) = stream.next().await {
    println!("Found node: {:?}", node?);
}
```

***

## Building

### Build Protobuf

```bash
cargo build -p common_types
```

The `build.rs` script automatically generates Rust code from `proto/common_types.proto`.

### Regenerate Types

```bash
# If proto file changes, rebuild
cargo clean -p common_types
cargo build -p common_types
```

***

## Dependencies

```toml
[dependencies]
prost = "0.12"
tonic = { version = "0.10", features = ["gzip"] }
sha2 = "0.10"
secp256k1 = { version = "0.27", features = ["recovery"] }
hex = "0.4"

[build-dependencies]
tonic-build = "0.10"
```

***

## Related Documentation

* [Protobuf Reference](/nc/neurochainai-guides/api-reference/protobuf.md) - Proto file documentation
* [Cryptographic Signing](https://github.com/NeuroChainAi/docs-guides/blob/main/security/cryptographic-signing.md) - Signature details
* [Payment Flow](/nc/neurochainai-guides/architecture/payment-flow.md) - Payment architecture


---

# 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/components/common-types.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.
