> For the complete documentation index, see [llms.txt](https://docs.neurochain.ai/nc/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.neurochain.ai/nc/neurochainai-guides/architecture/validation-consensus.md).

# Validation & Consensus

This document describes the validator consensus mechanism in NCN Network v2, including preprocessing validation, completion validation, and the M-of-N signature scheme.

***

## Overview

Validators provide decentralized verification of inference requests and results, ensuring:

1. **Fair Pricing**: Payment amounts are correctly calculated
2. **Node Selection**: Compute nodes are capable and available
3. **Result Integrity**: Computation results are valid
4. **Payment Security**: Funds are distributed correctly

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                         Validator Consensus Flow                             │
│                                                                             │
│     Request               Preprocessing              Completion             │
│   ┌─────────┐            ┌─────────────┐           ┌─────────────┐          │
│   │ Gateway │───────────▶│  Validator  │──────────▶│  Validator  │          │
│   │         │            │  Consensus  │           │  Consensus  │          │
│   └─────────┘            │  (M-of-N)   │           │  (M-of-N)   │          │
│                          └──────┬──────┘           └──────┬──────┘          │
│                                 │                         │                 │
│                                 ▼                         ▼                 │
│                          ┌─────────────┐           ┌─────────────┐          │
│                          │   Payment   │           │   Payment   │          │
│                          │ Initiation  │           │Distribution │          │
│                          └─────────────┘           └─────────────┘          │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
```

***

## M-of-N Signature Scheme

### Configuration

| Parameter  | Default | Description                           |
| ---------- | ------- | ------------------------------------- |
| **N**      | 5       | Total validators selected per request |
| **M**      | 3       | Minimum signatures required           |
| **Quorum** | 60%     | M/N ratio                             |

### Why M-of-N?

* **Fault Tolerance**: Network continues if some validators offline
* **Byzantine Resistance**: Requires majority for malicious action
* **Availability**: Doesn't wait for slow validators
* **Decentralization**: No single point of failure

### Signature Aggregation

```
                    Selected Validators (N=5)
                    ┌───┬───┬───┬───┬───┐
                    │ V1│ V2│ V3│ V4│ V5│
                    └─┬─┴─┬─┴─┬─┴─┬─┴─┬─┘
                      │   │   │   │   │
     Sign request     │   │   │   │   │
                      ▼   ▼   ▼   ▼   ▼
                    ┌───┬───┬───┬───┬───┐
                    │ ✓ │ ✓ │ ✗ │ ✓ │ ✗ │  (3 of 5 = valid)
                    └───┴───┴───┴───┴───┘
                            │
                            ▼
                    ┌───────────────────┐
                    │ Aggregated Sigs   │
                    │ [sig1, sig2, sig4]│
                    └───────────────────┘
```

***

## Validator Pool

### ValidatorInfo Structure

```rust
pub struct ValidatorInfo {
    pub wallet_address: String,
    pub stake_amount: u128,
    pub validations_count: u64,
    pub successful_validations: u64,
    pub failed_validations: u64,
    pub reputation_score: u32,        // 0-100
    pub is_active: bool,
    pub slash_count: u32,
    pub last_validation_timestamp: i64,
}
```

### Validator Registration

```
                    Blockchain                    P2P Registry
                        │                             │
    Stake tokens        │                             │
    ────────────────────▶                             │
                        │                             │
    Register validator  │                             │
    ────────────────────────────────────────────────────▶
                        │                             │
                        │    Sync validators          │
                        │◀────────────────────────────│
                        │    (periodic)               │
```

### Selection Strategies

| Strategy        | Description                 | Use Case          |
| --------------- | --------------------------- | ----------------- |
| **Random**      | Uniform random selection    | Default           |
| **Reputation**  | Highest reputation first    | Quality priority  |
| **Stake**       | Highest stake first         | Economic security |
| **Performance** | Best success rate           | Reliability       |
| **Weighted**    | Stake + reputation weighted | Balanced          |

### Selection Algorithm

```rust
fn select_validators(&self, count: usize, strategy: SelectionStrategy) -> Vec<ValidatorInfo> {
    let active_validators: Vec<_> = self.validators
        .values()
        .filter(|v| v.is_active && v.reputation_score >= MIN_REPUTATION)
        .collect();
    
    match strategy {
        SelectionStrategy::Random => {
            active_validators.choose_multiple(&mut rng, count).collect()
        }
        SelectionStrategy::Reputation => {
            active_validators
                .sorted_by(|a, b| b.reputation_score.cmp(&a.reputation_score))
                .take(count)
                .collect()
        }
        SelectionStrategy::WeightedRandom => {
            // Weight by stake * reputation
            weighted_sample(active_validators, count, |v| {
                v.stake_amount * v.reputation_score as u128
            })
        }
    }
}
```

***

## Preprocessing Validation

### Purpose

Verify request setup before client payment:

* Gateway legitimacy
* Compute node availability
* Payment calculation correctness
* Request parameter validity

### Process

```
Gateway                    P2P Registry              Validators
  │                            │                         │
  │ 1. RequestPreprocessing    │                         │
  │───────────────────────────▶│                         │
  │                            │                         │
  │                            │ 2. Verify gateway       │
  │                            │    - Registered?        │
  │                            │    - Reputation >= min? │
  │                            │                         │
  │                            │ 3. Verify compute node  │
  │                            │    - Registered?        │
  │                            │    - Available?         │
  │                            │    - Supports model?    │
  │                            │                         │
  │                            │ 4. Calculate payment    │
  │                            │    - Compute price      │
  │                            │    - Gateway gas        │
  │                            │    - Validator reward   │
  │                            │                         │
  │                            │ 5. Select N validators  │
  │                            │───────────────────────────▶│
  │                            │                         │
  │                            │ 6. Request signatures   │
  │                            │───────────────────────────▶│
  │                            │                         │
  │                            │                         │ 7. Validate
  │                            │                         │    & Sign
  │                            │                         │
  │                            │ 8. Collect M signatures │
  │                            │◀───────────────────────────│
  │                            │                         │
  │ 9. PreprocessingValidation │                         │
  │◀───────────────────────────│                         │
```

### Validation Message

Validators sign a deterministic message:

```
message = SHA256(
    request_id ||
    gateway_wallet ||
    compute_node_id ||
    compute_node_wallet ||
    payment_tree_hash ||
    expiry_timestamp
)
```

### PreprocessingValidation Structure

```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;
}
```

***

## Completion Validation

### Purpose

Verify computation results after execution:

* Compute node signature validity
* Result format correctness
* Computation time reasonableness
* Result integrity

### Process

```
Gateway                    P2P Registry              Validators
  │                            │                         │
  │ 1. RequestCompletion       │                         │
  │───────────────────────────▶│                         │
  │   (InferenceResponse)      │                         │
  │                            │                         │
  │                            │ 2. Verify request exists│
  │                            │    - In mempool?        │
  │                            │    - Not completed?     │
  │                            │                         │
  │                            │ 3. Verify compute sig   │
  │                            │    - Valid signature?   │
  │                            │    - Correct signer?    │
  │                            │                         │
  │                            │ 4. Verify result        │
  │                            │    - Format valid?      │
  │                            │    - Hash matches?      │
  │                            │    - Time reasonable?   │
  │                            │                         │
  │                            │ 5. Select N validators  │
  │                            │───────────────────────────▶│
  │                            │                         │
  │                            │ 6. Request signatures   │
  │                            │───────────────────────────▶│
  │                            │                         │
  │                            │                         │ 7. Validate
  │                            │                         │    & Sign
  │                            │                         │
  │                            │ 8. Collect M signatures │
  │                            │◀───────────────────────────│
  │                            │                         │
  │ 9. CompletionValidation    │                         │
  │◀───────────────────────────│                         │
```

### Completion Message

Validators sign:

```
message = SHA256(
    request_id ||
    compute_node_signature ||
    result_hash ||
    completion_timestamp ||
    computation_time_ms
)
```

### CompletionValidation Structure

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

message ComputeCompletion {
  string request_id = 1;
  string compute_node_signature = 2;
  bytes result_hash = 3;
  int64 completion_timestamp = 4;
  uint64 computation_time_ms = 5;
}
```

***

## Reputation System

### Reputation Score

Each validator has a reputation score (0-100):

```
reputation = base_reputation + performance_bonus - slash_penalty
```

| Factor                   | Impact     |
| ------------------------ | ---------- |
| Successful validation    | +1 point   |
| Failed validation        | -2 points  |
| Timeout (no response)    | -5 points  |
| Slashing event           | -20 points |
| Minimum stake maintained | Required   |

### Reputation Updates

```rust
fn update_reputation(&mut self, validator: &str, approved: bool) {
    if let Some(v) = self.validators.get_mut(validator) {
        if approved {
            v.successful_validations += 1;
            v.reputation_score = min(100, v.reputation_score + 1);
        } else {
            v.failed_validations += 1;
            v.reputation_score = max(0, v.reputation_score.saturating_sub(2));
        }
        v.validations_count += 1;
        v.last_validation_timestamp = current_time();
    }
}
```

### Minimum Reputation

Validators below minimum reputation (default: 20) are:

* Excluded from selection
* Must stake more or wait for recovery
* Can appeal through governance

***

## Slashing Conditions

### Slashable Offenses

| Offense                         | Severity | Penalty    |
| ------------------------------- | -------- | ---------- |
| **Invalid signature**           | High     | 50% stake  |
| **Colluding with compute node** | Critical | 100% stake |
| **Approving invalid result**    | High     | 30% stake  |
| **Prolonged downtime**          | Medium   | 10% stake  |
| **Front-running requests**      | High     | 50% stake  |

### Slashing Process

```
Detection                 Verification              Execution
┌─────────────┐          ┌─────────────┐          ┌─────────────┐
│  Monitor    │─────────▶│  Committee  │─────────▶│  Contract   │
│  detects    │          │  reviews    │          │  slashes    │
│  violation  │          │  evidence   │          │  stake      │
└─────────────┘          └─────────────┘          └─────────────┘
```

### Slash Implementation

```rust
fn slash_validator(&mut self, address: &str, reason: &str) -> bool {
    if let Some(v) = self.validators.get_mut(address) {
        v.slash_count += 1;
        v.reputation_score = max(0, v.reputation_score.saturating_sub(20));
        
        if v.slash_count >= MAX_SLASHES {
            v.is_active = false;
        }
        
        log::warn!("Slashed validator {}: {}", address, reason);
        true
    } else {
        false
    }
}
```

***

## Validator Rotation

### Purpose

Prevent validator centralization and ensure fairness.

### Rotation Schedule

```rust
fn rotate_validators(&mut self) {
    // Deactivate low-reputation validators
    for v in self.validators.values_mut() {
        if v.reputation_score < MIN_REPUTATION_THRESHOLD {
            v.is_active = false;
        }
    }
    
    // Reactivate validators with recovered reputation
    for v in self.validators.values_mut() {
        if !v.is_active && v.reputation_score >= REACTIVATION_THRESHOLD {
            v.is_active = true;
        }
    }
}
```

### Rotation Frequency

| Event               | Trigger               |
| ------------------- | --------------------- |
| Hourly rotation     | Time-based            |
| Reputation check    | After each validation |
| Stake change        | On-chain event        |
| Manual intervention | Governance action     |

***

## Mempool

### Purpose

Temporary storage for pending validations:

```
┌─────────────────────────────────────────────────────────┐
│                        Mempool                           │
│                                                         │
│  ┌─────────────────────────────────────────────────┐    │
│  │           Pending Requests                       │    │
│  │  req1: { request, timestamp, status }           │    │
│  │  req2: { request, timestamp, status }           │    │
│  └─────────────────────────────────────────────────┘    │
│                                                         │
│  ┌─────────────────────────────────────────────────┐    │
│  │       Preprocessing Validations                  │    │
│  │  req1: { validation, signatures[], timestamp }  │    │
│  └─────────────────────────────────────────────────┘    │
│                                                         │
│  ┌─────────────────────────────────────────────────┐    │
│  │        Completion Validations                    │    │
│  │  req1: { completion, signatures[], timestamp }  │    │
│  └─────────────────────────────────────────────────┘    │
│                                                         │
└─────────────────────────────────────────────────────────┘
```

### TTL (Time-to-Live)

| Entry Type      | Default TTL | Purpose             |
| --------------- | ----------- | ------------------- |
| Pending Request | 10 min      | Await preprocessing |
| Preprocessing   | 15 min      | Await payment       |
| Completion      | 5 min       | Await finalization  |

### Cleanup

```rust
fn cleanup_expired(&mut self) -> CleanupStats {
    let now = current_timestamp();
    
    // Remove expired entries
    self.pending_requests.retain(|_, e| !e.is_expired(now, PENDING_TTL));
    self.preprocessing_validations.retain(|_, e| !e.is_expired(now, PREPROC_TTL));
    self.completion_validations.retain(|_, e| !e.is_expired(now, COMPLETION_TTL));
}
```

***

## Configuration

### Validator Settings

```bash
# Validator identity
VALIDATOR_PRIVATE_KEY=0x...
VALIDATOR_ADDRESS=0x...

# Pool settings
MIN_VALIDATORS_FOR_CONSENSUS=3
MAX_VALIDATORS_TO_SELECT=5
MIN_REPUTATION_THRESHOLD=20

# Timing
VALIDATION_TIMEOUT_SECS=30
SIGNATURE_COLLECTION_TIMEOUT_MS=5000
```

### Sync Settings

```bash
# Blockchain sync
VALIDATOR_SYNC_ENABLED=true
VALIDATOR_SYNC_INTERVAL=60
VALIDATOR_REGISTRY_CONTRACT=0x...
```

***

## Monitoring

### Key Metrics

| Metric                            | Description                 |
| --------------------------------- | --------------------------- |
| `validators_active`               | Currently active validators |
| `validators_total`                | Total registered validators |
| `validations_preprocessing_total` | Preprocessing validations   |
| `validations_completion_total`    | Completion validations      |
| `consensus_reached_total`         | Successful consensus        |
| `consensus_failed_total`          | Failed consensus            |
| `average_reputation`              | Mean reputation score       |

### Health Checks

```bash
# Check validator pool status
curl http://registry:50050/health

# Response
{
  "status": "healthy",
  "validators": {
    "active": 10,
    "total": 15,
    "average_reputation": 85
  },
  "mempool": {
    "pending_requests": 5,
    "preprocessing": 3,
    "completion": 1
  }
}
```

***

## Next Steps

* [Payment Flow](/nc/neurochainai-guides/architecture/payment-flow.md) - Payment mechanics
* [Security Model](/nc/neurochainai-guides/architecture/security-model.md) - Security architecture
* [P2P Registry](/nc/neurochainai-guides/components/p2p-registry.md) - Registry implementation
