Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ members = [
"node",
"pallets/template",
"pallets/task",
"pallets/verifier",
"runtime",
]
resolver = "2"
Expand Down
60 changes: 60 additions & 0 deletions pallets/verifier/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
[package]
name = "pallet-verifier"
description = "ZKP verification pallet for QuantumOS blockchain"
version = "0.1.0"
license = "Unlicense"
authors.workspace = true
homepage.workspace = true
repository.workspace = true
edition.workspace = true
publish = false

[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]

[dependencies]
codec = { features = ["derive"], workspace = true }
scale-info = { features = ["derive"], workspace = true }

# FRAME dependencies
frame-benchmarking = { optional = true, workspace = true }
frame-support.workspace = true
frame-system.workspace = true

# Substrate primitives
sp-runtime = { workspace = true }

# Local pallets
pallet-task = { path = "../task", default-features = false }

[dev-dependencies]
sp-core = { default-features = true, workspace = true }
sp-io = { default-features = true, workspace = true }
sp-runtime = { default-features = true, workspace = true }
pallet-balances = { default-features = true, workspace = true }
pallet-task = { path = "../task", default-features = true }

[features]
default = ["std"]
std = [
"codec/std",
"frame-benchmarking?/std",
"frame-support/std",
"frame-system/std",
"scale-info/std",
"sp-runtime/std",
"pallet-task/std",
]
runtime-benchmarks = [
"frame-benchmarking/runtime-benchmarks",
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
"pallet-task/runtime-benchmarks",
]
try-runtime = [
"frame-support/try-runtime",
"frame-system/try-runtime",
"sp-runtime/try-runtime",
"pallet-task/try-runtime",
]
251 changes: 251 additions & 0 deletions pallets/verifier/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,251 @@
# Pallet Verifier

A Substrate pallet for verifying zero-knowledge proofs (ZKP) attached to simulation task results in the QuantumOS blockchain.

## Overview

This pallet provides on-chain logic for verifying computational proofs submitted by miners. It integrates with `pallet-task` to complete the task lifecycle: miners submit proofs, verifiers validate them, and rewards are distributed accordingly.

## Features

- **Multi-Protocol Support**: Supports Groth16, PLONK, STARK, and custom proof systems
- **Proof Verification**: Validates zero-knowledge proofs for task results
- **Verification Keys**: Manages verification keys for different circuits
- **Miner Reputation**: Tracks verification success/failure rates
- **Penalty System**: Applies financial and reputation penalties for invalid proofs
- **Integration**: Seamlessly calls `pallet-task::verify_task` upon successful verification

## Proof Systems Supported

- **Groth16** (ID: 0) - SNARK proof system
- **PLONK** (ID: 1) - Universal SNARK
- **STARK** (ID: 2) - Transparent proof system
- **Custom** (ID: 3) - Custom verification logic

## Workflow

1. **Proof Submission**: Miner submits proof with task result
```rust
VerifierPallet::submit_proof(
origin,
task_id,
0, // Groth16
proof_data,
public_inputs
)
```

2. **Verification**: Off-chain worker or validator verifies the proof
```rust
VerifierPallet::verify_proof(origin, proof_id, is_valid)
```

3. **Success Path**:
- Proof marked as verified
- Miner reputation increases
- `pallet_task::verify_task` called
- Reward distributed to miner

4. **Failure Path**:
- Proof marked as failed
- Financial penalty applied
- Miner reputation decreases
- Task cancelled

## Storage

- **Proofs**: Map of proof ID to Proof metadata
- **NextProofId**: Counter for generating unique proof IDs
- **VerificationKeys**: Verification keys by circuit ID
- **TaskProofs**: Mapping from task ID to proof ID
- **MinerStats**: Verification statistics per miner
- **PendingVerifications**: Queue of proofs awaiting verification

## Dispatchable Functions

### `submit_proof`
Submits a zero-knowledge proof for a completed task.

**Parameters:**
- `origin`: Miner (must match task assignee)
- `task_id`: ID of the completed task
- `proof_system_id`: Type of proof system (0-3)
- `proof_data`: Serialized proof
- `public_inputs`: Public inputs to the proof

**Requirements:**
- Origin must be signed
- Task must exist and be in `Completed` status
- Submitter must be the assigned miner
- No proof already submitted for this task

### `verify_proof`
Verifies a submitted proof and processes the result.

**Parameters:**
- `origin`: Verifier (signed, typically validator or off-chain worker)
- `proof_id`: ID of the proof to verify
- `is_valid`: Whether the proof is valid

**Requirements:**
- Proof must exist and be in `Pending` status

**Effects on Success:**
- Updates miner stats (increases reputation)
- Calls `pallet_task::verify_task`
- Distributes reward to miner

**Effects on Failure:**
- Updates miner stats (decreases reputation)
- Applies financial penalty
- Cancels the task

### `register_verification_key`
Registers a verification key for a specific circuit.

**Parameters:**
- `origin`: Must be root
- `circuit_id`: Identifier for the circuit
- `proof_system_id`: Type of proof system (0-3)
- `key_data`: Serialized verification key

**Requirements:**
- Origin must be root or governance

### `toggle_verification_key`
Activates or deactivates a verification key.

**Parameters:**
- `origin`: Must be root
- `circuit_id`: Circuit identifier
- `is_active`: New activation status

**Requirements:**
- Origin must be root
- Verification key must exist

## Configuration

### Types

- `RuntimeEvent`: The overarching event type
- `VerifierWeightInfo`: Weight information for dispatchables
- `Currency`: Currency type for handling penalties

### Constants

- `MaxProofSize`: Maximum size of a proof (default: 4096 bytes)
- `MaxPublicInputSize`: Maximum size of public inputs (default: 512 bytes)
- `MaxCircuitIdLength`: Maximum length of circuit ID (default: 64 bytes)
- `MaxVerificationKeySize`: Maximum size of verification key (default: 2048 bytes)
- `InvalidProofPenalty`: Penalty for invalid proof (configurable)
- `ReputationDecreaseOnFailure`: Reputation points lost on failure (default: 10)
- `ReputationIncreaseOnSuccess`: Reputation points gained on success (default: 5)

## Events

- `ProofSubmitted`: A proof has been submitted
- `ProofVerified`: A proof has been verified successfully
- `ProofVerificationFailed`: Proof verification failed
- `VerificationKeyRegistered`: A verification key has been registered
- `VerificationKeyUpdated`: A verification key status has been updated
- `MinerPenalized`: A miner has been penalized for invalid proof

## Errors

- `ProofNotFound`: Proof does not exist
- `TaskNotFound`: Task does not exist
- `VerificationKeyNotFound`: Verification key not found
- `ProofTooLarge`: Proof data exceeds maximum size
- `PublicInputsTooLarge`: Public inputs exceed maximum size
- `CircuitIdTooLong`: Circuit ID exceeds maximum length
- `VerificationKeyTooLarge`: Verification key exceeds maximum size
- `NotAuthorized`: Caller not authorized for this operation
- `ProofAlreadyExists`: Proof already submitted for this task
- `InvalidTaskStatus`: Task not in correct status
- `VerificationFailed`: Proof verification failed
- `InvalidProofSystem`: Invalid proof system ID provided
- `VerificationKeyInactive`: Verification key is not active
- `TooManyPendingVerifications`: Pending verification queue is full
- `Overflow`: Arithmetic overflow occurred
- `SubmitterMismatch`: Proof submitter doesn't match task miner

## Miner Reputation System

The pallet tracks miner performance through a reputation system:

- **Range**: 0-100
- **Increase**: +5 points per successful verification
- **Decrease**: -10 points per failed verification
- **Impact**: Low reputation miners may face additional scrutiny or restrictions

## Integration with Other Pallets

### pallet-task
- Reads task status before accepting proofs
- Calls `verify_task` upon successful verification
- Calls `cancel_task` upon failed verification

### pallet-balances
- Applies financial penalties for invalid proofs
- Manages reward transfers (via pallet-task)

## Testing

Run the test suite:

```bash
cargo test
```

All 14 unit tests cover:
- Proof submission and validation
- Verification success and failure paths
- Verification key management
- Miner statistics tracking
- Access control and authorization
- Proof system type handling

## Example Usage

```rust
// 1. Register a verification key (root only)
VerifierPallet::register_verification_key(
Origin::root(),
b"spin_model_v1".to_vec(),
0, // Groth16
vkey_data
)?;

// 2. Miner submits proof after completing task
VerifierPallet::submit_proof(
Origin::signed(miner),
task_id,
0, // Groth16
proof_bytes,
public_inputs
)?;

// 3. Verifier checks the proof (off-chain or validator)
let is_valid = verify_zkp_offchain(&proof_data, &public_inputs, &vkey);

// 4. Submit verification result
VerifierPallet::verify_proof(
Origin::signed(verifier),
proof_id,
is_valid
)?;
```

## Future Enhancements

- Integration with actual ZKP libraries (bellman, plonk, winterfell)
- Off-chain workers for automatic verification
- Slashing mechanisms for malicious verifiers
- Circuit registry with versioning
- Batch verification for multiple proofs
- Decentralized verifier network

## License

Unlicense
Loading
Loading