Skip to content
Closed
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
108 changes: 108 additions & 0 deletions .cursor/components/bls_lagrange.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# BLS Lagrange Component

## Overview
The `bls_lagrange` component implements BLS (Boneh-Lynn-Shacham) threshold signature schemes using Lagrange interpolation for secret sharing. This component is part of the Anchor project by Sigma Prime and provides cryptographic primitives for distributed signature generation.

## Location
- **Path**: `anchor/common/bls_lagrange/`
- **Type**: Rust library crate
- **Version**: 0.1.0

## Purpose
This component enables:
1. **Secret Key Splitting**: Split a master BLS secret key into multiple shares using Shamir's Secret Sharing
2. **Threshold Signatures**: Combine partial signatures from a threshold number of participants to reconstruct the original signature
3. **Lagrange Interpolation**: Use mathematical interpolation to recover secrets from partial shares

## Key Features

### Dual Implementation Support
- **BLST Backend** (`blst.rs`): High-performance implementation using the BLST library with manual Lagrange interpolation
- **Blsful Backend** (`blsful.rs`): Alternative implementation using blstrs_plus and vsss-rs libraries

### Configuration Features
- `default = ["blst_single_thread"]`: Default to single-threaded BLST
- `blsful`: Enable blsful backend with vsss-rs support
- `blst`: Enable BLST backend
- `blst_single_thread`: Single-threaded BLST variant

### Core Functionality
- **Key Splitting**: `split()` and `split_with_rng()` functions to create threshold shares
- **Signature Combination**: `combine_signatures()` to reconstruct signatures from partial shares
- **KeyId Management**: Secure handling of participant identifiers with zero-protection

## API Structure

### Main Types
- `KeyId`: Represents a participant identifier (non-zero u64 with cryptographic scalar representation)
- `Error`: Comprehensive error handling for various failure modes

### Key Functions
```rust
// Split a secret key into threshold shares
pub fn split(key: &SecretKey, threshold: u64, ids: impl IntoIterator<Item = KeyId>) -> Result<Vec<(KeyId, SecretKey)>, Error>

// Combine partial signatures to reconstruct the original signature
pub fn combine_signatures(signatures: &[Signature], ids: &[KeyId]) -> Result<Signature, Error>
```

### Error Types
- `InternalError`: Cryptographic operation failures
- `InvalidThreshold`: Threshold parameter validation errors
- `LessThanTwoSignatures`: Insufficient signatures for combination
- `NotOneIdPerSignature`: Mismatch between signatures and IDs
- `ZeroId`: Invalid zero participant ID
- `ZeroKey`: Invalid zero secret key
- `RepeatedId`: Duplicate participant IDs
- `InvalidSignature`: Signature validation failures

## Implementation Details

### BLST Backend (`blst.rs`)
- Direct implementation of Lagrange interpolation algorithm
- Manual polynomial evaluation using Horner's method
- Optimized scalar arithmetic using unsafe BLST operations
- Single-threaded and multi-threaded variants available
- Performance-focused with manual memory management

### Blsful Backend (`blsful.rs`)
- Uses `vsss-rs` crate for secret sharing primitives
- Higher-level abstractions with built-in error handling
- Automatic participant ID generation and validation
- Type-safe scalar field operations using `blstrs_plus`

## Security Considerations
- All secret keys are automatically zeroized on drop
- Participant IDs must be non-zero to prevent secret exposure
- Threshold must be ≥ 2 for meaningful security
- Duplicate participant IDs are detected and rejected
- Invalid signatures are validated before processing

## Testing
Comprehensive test suite includes:
- Basic threshold signature functionality
- Edge case validation (zero keys, invalid thresholds, etc.)
- Error condition testing
- Performance benchmarking
- Cryptographic correctness verification

## Dependencies
- `bls`: Workspace BLS signature implementation
- `blst`: Optional BLST cryptographic library
- `blstrs_plus`: Optional alternative BLS implementation
- `vsss-rs`: Optional Verifiable Secret Sharing library
- `rand`: Cryptographic random number generation
- `zeroize`: Secure memory clearing

## Integration
This component is used within the Anchor ecosystem for:
- Distributed validator key management
- Threshold signature schemes in consensus protocols
- Multi-party cryptographic operations
- Secure secret sharing for validator operations

## Performance Notes
- BLST backend optimized for high-performance scenarios
- Single-threaded variant available for embedded or constrained environments
- Benchmarking utilities included for performance validation
- Memory-efficient implementation with automatic cleanup
15 changes: 15 additions & 0 deletions .cursor/rules/code_standards.mdc
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Code Standards

This file defines coding standards and conventions for this project.

## Code Style
- Follow language-specific best practices
- Maintain consistency with existing code
- Use meaningful names for variables and functions

## Documentation
- Document public APIs and interfaces
- Include examples where helpful
- Keep documentation up to date

_This file will be auto-generated and customized by Claude AI._
15 changes: 15 additions & 0 deletions .cursor/rules/development_workflow.mdc
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Development Workflow

This file outlines the development workflow and processes for this project.

## Workflow
- Feature branch development
- Code review requirements
- Testing standards

## Tools and Processes
- Build and deployment procedures
- Quality assurance practices
- Change management

_This file will be auto-generated and customized by Claude AI._
15 changes: 15 additions & 0 deletions .cursor/rules/project_architecture.mdc
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Project Architecture

This file contains project-specific architecture guidelines and patterns.

## Overview
- Project structure and organization
- Module dependencies and relationships
- Key architectural decisions

## Guidelines
- Follow established patterns in the codebase
- Maintain consistency with existing architecture
- Document significant architectural changes

_This file will be auto-generated and customized by Claude AI._
1 change: 1 addition & 0 deletions .roo
158 changes: 158 additions & 0 deletions AI_DOCS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
# Anchor SSV - AI Documentation

## Project Overview

Anchor is an open-source implementation of the Secret Shared Validator (SSV) protocol written in Rust. It enables distributed validator operations across multiple operators to enhance Ethereum validator resilience and decentralization.

### Key Characteristics
- **Language**: Rust
- **Domain**: Ethereum Consensus Layer, Distributed Validator Technology
- **Architecture**: Modular, service-oriented design
- **Consensus**: QBFT (Istanbul BFT variant)
- **Network**: libp2p-based P2P networking

## Component Architecture

### Core Components

#### 1. Client (`anchor/client/`)
- **Purpose**: Main orchestration component
- **Key Files**: `lib.rs`, `cli.rs`, `config.rs`, `key.rs`, `notifier.rs`
- **Documentation**: [Client AI Docs](anchor/client/src/AI_DOCS.md)

#### 2. Network Layer (`anchor/network/`)
- **Purpose**: P2P networking and peer management
- **Key Modules**:
- Handshake protocol ([docs](anchor/network/src/handshake/AI_DOCS.md))
- Peer management ([docs](anchor/network/src/peer_manager/AI_DOCS.md))
- Scoring system ([docs](anchor/network/src/scoring/AI_DOCS.md))
- **Documentation**: [Network AI Docs](anchor/network/src/AI_DOCS.md)

#### 3. Consensus (`anchor/qbft_manager/`, `anchor/common/qbft/`)
- **Purpose**: Byzantine fault-tolerant consensus protocol
- **Documentation**:
- [QBFT Manager AI Docs](anchor/qbft_manager/src/AI_DOCS.md)
- [QBFT Common AI Docs](anchor/common/qbft/AI_DOCS.md)

#### 4. Message Processing
- **Message Receiver** ([docs](anchor/message_receiver/src/AI_DOCS.md))
- **Message Sender** ([docs](anchor/message_sender/src/AI_DOCS.md))
- **Message Validator** ([docs](anchor/message_validator/src/AI_DOCS.md))
- **Processor** ([docs](anchor/processor/src/AI_DOCS.md))

#### 5. Signature Operations
- **Signature Collector** ([docs](anchor/signature_collector/src/AI_DOCS.md))
- **BLS Lagrange** ([docs](anchor/common/bls_lagrange/))

#### 6. Validator Management
- **Validator Store** ([docs](anchor/validator_store/src/AI_DOCS.md))
- **Duties Tracker** ([docs](anchor/duties_tracker/src/AI_DOCS.md))
- **Subnet Service** ([docs](anchor/subnet_service/src/AI_DOCS.md))

#### 7. Ethereum Integration
- **Eth Module** ([docs](anchor/eth/src/AI_DOCS.md))
- **SSV Types** ([docs](anchor/common/ssv_types/AI_DOCS.md))

#### 8. Data & Storage
- **Database** ([docs](anchor/database/src/AI_DOCS.md))
- **Key Generation** ([docs](anchor/keygen/src/AI_DOCS.md))
- **Key Splitting** ([docs](anchor/keysplit/src/AI_DOCS.md))

#### 9. Infrastructure
- **HTTP API** ([docs](anchor/http_api/src/AI_DOCS.md))
- **HTTP Metrics** ([docs](anchor/http_metrics/src/AI_DOCS.md))
- **Logging** ([docs](anchor/logging/src/AI_DOCS.md))

## Data Flow Overview

```
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Beacon Node │────│ Anchor Client │────│ SSV Network │
│ (Ethereum) │ │ (Orchestrator) │ │ (P2P Peers) │
└─────────────────┘ └─────────────────┘ └─────────────────┘
┌─────────────────┐
│ QBFT Consensus │
│ (Byzantine │
│ Fault Tolerant)│
└─────────────────┘
┌─────────────────┐
│ Signature │
│ Aggregation │
└─────────────────┘
```

## Development Guidelines

### Code Standards
- Follow Rust best practices and idioms
- Use `thiserror` for error handling
- Implement comprehensive testing
- Follow existing logging patterns with `tracing`
- Use workspace dependencies for consistency

### Testing Strategy
- Unit tests for individual components
- Integration tests for cross-component functionality
- Property-based testing where applicable
- Network simulation tests for distributed scenarios

### Security Considerations
- Slashing protection is critical - never compromise validator safety
- Secure handling of cryptographic keys
- Message validation and authentication
- Network security and peer verification

## Key External Dependencies

- **Lighthouse**: Ethereum consensus client dependencies
- **libp2p**: Peer-to-peer networking
- **tokio**: Async runtime
- **alloy**: Ethereum types and utilities
- **blst/blstrs**: BLS signature library
- **rusqlite**: SQLite database interface

## Monitoring & Observability

- Prometheus metrics available via HTTP metrics endpoint
- Structured logging with configurable levels
- Health checks and service status monitoring
- Performance metrics and resource tracking

## Build & Development

```bash
# Build entire workspace
cargo build --release

# Run tests
cargo test

# Run specific component tests
cargo test -p database

# Generate documentation
cargo doc --open
```

## AI Documentation Structure

Each component includes:
- `AI_DOCS.md`: Comprehensive technical documentation
- `COMPONENT_SPEC.md`: Formal specification and interfaces
- `USAGE_EXAMPLES.md`: Practical usage examples and patterns

This documentation framework enables AI assistants to:
- Understand component relationships and dependencies
- Identify appropriate patterns for new features
- Maintain consistency with existing architecture
- Implement secure and compliant code changes

## Related Resources

- [Anchor Book](https://anchor-book.sigmaprime.io): User documentation
- [SSV Protocol](https://docs.ssv.network/): Protocol specification
- [Lighthouse](https://lighthouse-book.sigmaprime.io/): Ethereum consensus client
1 change: 1 addition & 0 deletions ai_docs
Loading
Loading