ci: standardize pytest invocation and add security scanning
Some checks failed
Blockchain Synchronization Verification / sync-verification (push) Failing after 8s
CLI Tests / test-cli (push) Successful in 10s
Contract Performance Benchmarks / benchmark-gas-usage (push) Successful in 1m22s
Contract Performance Benchmarks / benchmark-execution-time (push) Successful in 1m11s
Contract Performance Benchmarks / benchmark-throughput (push) Successful in 1m13s
Cross-Chain Functionality Tests / test-cross-chain-sync (push) Failing after 5s
Cross-Chain Functionality Tests / test-cross-chain-transactions (push) Successful in 5s
Cross-Chain Functionality Tests / test-cross-chain-bridge (push) Has been skipped
Cross-Chain Functionality Tests / test-multi-chain-consensus (push) Failing after 3s
Cross-Chain Functionality Tests / aggregate-results (push) Has been skipped
Cross-Node Transaction Testing / transaction-test (push) Successful in 5s
Deploy to Testnet / deploy-testnet (push) Successful in 1m14s
Contract Performance Benchmarks / compare-benchmarks (push) Has been cancelled
Documentation Validation / validate-docs (push) Failing after 10s
Multi-Node Stress Testing / stress-test (push) Has been cancelled
Node Failover Simulation / failover-test (push) Has been cancelled
Security Scanning / security-scan (push) Has been cancelled
Smart Contract Tests / test-solidity (map[name:aitbc-contracts path:contracts]) (push) Has been cancelled
Smart Contract Tests / test-solidity (map[name:aitbc-token path:packages/solidity/aitbc-token]) (push) Has been cancelled
Smart Contract Tests / test-foundry (push) Has been cancelled
Smart Contract Tests / lint-solidity (push) Has been cancelled
Smart Contract Tests / deploy-contracts (push) Has been cancelled
Documentation Validation / validate-policies-strict (push) Successful in 3s
Integration Tests / test-service-integration (push) Failing after 45s
Multi-Chain Island Architecture Tests / test-multi-chain-island (push) Failing after 2s
Multi-Node Blockchain Health Monitoring / health-check (push) Successful in 5s
P2P Network Verification / p2p-verification (push) Successful in 3s
Production Tests / Production Integration Tests (push) Failing after 7s
Python Tests / test-python (push) Failing after 46s
Staking Tests / test-staking-service (push) Failing after 2s
Staking Tests / test-staking-integration (push) Has been skipped
Staking Tests / test-staking-contract (push) Has been skipped
Staking Tests / run-staking-test-runner (push) Has been skipped
Systemd Sync / sync-systemd (push) Successful in 21s
API Endpoint Tests / test-api-endpoints (push) Failing after 12m19s

- Changed pytest calls to use `venv/bin/python -m pytest` with explicit config
- Added `--rootdir "$PWD"` and `--import-mode=importlib` for consistent imports
- Fixed PYTHONPATH to use absolute paths with $PWD prefix
- Added smart contract security scanning for Solidity files
- Added Circom circuit security checks for ZK proof circuits
- Added ZK proof implementation security validation
- Added contracts/** to security scanning workflow
This commit is contained in:
aitbc
2026-05-11 13:46:42 +02:00
parent eeed0c61a3
commit e4f1a96172
141 changed files with 63860 additions and 2869 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -1,153 +0,0 @@
---
description: Deployment Automation Workflow for AITBC Services
---
# Deployment Automation Workflow
This workflow covers the automation of AITBC service deployment with one-command setup.
## Prerequisites
- Linux server with systemd support
- Python 3.13+ installed
- SSH access to target servers
- Domain name configured (for SSL certificates)
## Steps
### 1. System Service One-Command Setup (systemd)
1. **Create systemd service templates**
- Create service files for each AITBC component:
- `aitbc-coordinator-api.service`
- `aitbc-blockchain-node.service`
- `aitbc-wallet.service`
- `aitbc-gpu-miner.service`
- `aitbc-agent-daemon.service`
- Store templates in `systemd/` directory
- Include proper dependencies and restart policies
2. **Configure service dependencies**
- Define startup order (blockchain → coordinator → wallet → miners)
- Add `After=` and `Requires=` directives
- Configure automatic restart on failure
- Set resource limits (CPU, memory)
3. **Create service management script**
- Script: `scripts/service/manage-services.sh`
- Commands: start, stop, restart, status, logs
- Handle multiple services with dependency ordering
- Include health checks before starting dependent services
### 2. One-Command Deployment Script (`./deploy.sh`)
1. **Create main deployment script**
- Script: `scripts/deploy/deploy.sh`
- Make executable: `chmod +x scripts/deploy/deploy.sh`
- Include error handling and rollback capability
2. **Deployment script functionality**
```bash
# Main deployment steps
- Check system prerequisites
- Install dependencies (Python, system packages)
- Clone or update repository
- Create virtual environment
- Install Python dependencies
- Configure environment variables
- Initialize databases
- Start systemd services
- Run health checks
- Display deployment status
```
3. **Add rollback capability**
- Backup previous deployment
- Rollback on failure
- Restore previous configuration
- Restart services with old version
### 3. Environment Configuration Templates (.env.example)
1. **Create .env.example template**
- File: `.env.example` at project root
- Include all required environment variables
- Add comments explaining each variable
- Group variables by service/component
2. **Template sections**
```bash
# Blockchain Configuration
CHAIN_ID=ait-mainnet
BLOCKCHAIN_RPC_PORT=8006
# Coordinator API
COORDINATOR_API_PORT=8001
COORDINATOR_API_HOST=0.0.0.0
DATABASE_URL=postgresql://user:pass@localhost/aitbc
# Wallet
WALLET_DAEMON_PORT=8000
WALLET_PASSWORD=your_secure_password
# GPU Miner
MINER_API_KEY=your_api_key
MINER_GPU_DEVICE=0
```
3. **Create validation script**
- Script: `scripts/deploy/validate-env.sh`
- Check all required variables are set
- Validate variable formats (ports, URLs)
- Test database connectivity
- Verify API keys are valid format
### 4. Service Health Checks and Monitoring
1. **Create health check endpoints**
- Add `/health/live` endpoint to each service
- Add `/health/ready` endpoint for readiness checks
- Return JSON with service status and dependencies
2. **Create monitoring script**
- Script: `scripts/monitoring/health-check.sh`
- Check all service health endpoints
- Monitor service resource usage (CPU, memory, disk)
- Alert on service failures
- Log health check results
3. **Integrate with systemd**
- Add `ExecStartPost=` for health checks
- Configure restart on health check failure
- Use systemd notify for service readiness
### 5. Manual SSL Certificate Handling
- SSL certificate provisioning and renewal are handled manually outside this workflow.
- Configure nginx with manually issued certificates as needed.
## Verification
- [ ] All systemd services start in correct order
- [ ] Deployment script completes successfully
- [ ] .env.example template is complete
- [ ] Health checks pass for all services
- [ ] SSL certificates are configured manually and services are accessible via HTTPS
- [ ] Rollback capability tested
## Troubleshooting
- **Service fails to start**: Check logs with `journalctl -u service-name`, verify dependencies
- **Deployment script fails**: Check error logs, verify prerequisites, test individual steps
- **Health checks fail**: Verify service is running, check endpoint configuration
- **SSL configuration fails**: Check domain DNS, verify nginx config, and confirm the manually issued certificate paths
- **Environment validation fails**: Verify all required variables are set, check formats
## Related Files
- `systemd/*.service`
- `scripts/deploy/deploy.sh`
- `.env.example`
- `scripts/deploy/validate-env.sh`
- `scripts/monitoring/health-check.sh`
- `nginx/nginx.conf`

View File

@@ -1,215 +0,0 @@
---
description: Distribution & Binaries Workflow for Debian Stable Miner
---
# Distribution & Binaries Workflow
This workflow covers the creation and distribution of Debian stable miner binaries.
## Prerequisites
- Debian stable build machine
- PyInstaller or similar packaging tool
- GitHub Releases configured
- Code signing certificates (for production)
- vLLM integration requirements
## Steps
### 1. Debian Stable Miner Binary
1. **Set up build environment for Debian stable**
- Debian stable (bookworm) build machine
- Python 3.13+ with PyInstaller
- CUDA Toolkit (for GPU support)
- System dependencies: build-essential, python3-dev, python3-venv
2. **Create PyInstaller spec files**
- File: `scripts/gpu/miner.spec`
- Define entry point: `scripts/gpu/gpu_miner_host.py`
- Include all dependencies
- Configure hidden imports
- Set icon and metadata
3. **Build binary for Debian stable**
```bash
# Debian stable
pyinstaller --onefile --name aitbc-miner-debian scripts/gpu/miner.spec
```
4. **Test binary**
- Run binary on Debian stable
- Verify GPU detection works
- Test job submission and processing
- Verify logging and error handling
5. **Package binary with dependencies**
- Create installation script for Debian stable
- Include README with Debian-specific instructions
- Bundle configuration templates
- Add verification checksums
### 2. vLLM Integration for Optimized LLM Inference
1. **Research vLLM integration**
- Review vLLM documentation
- Analyze compatibility with existing Ollama integration
- Evaluate performance benefits
- Check hardware requirements
2. **Implement vLLM integration**
- Add vLLM dependency to requirements
- Create vLLM service wrapper
- Implement model loading with vLLM
- Add vLLM-specific configuration options
3. **Test vLLM integration**
- Benchmark performance vs Ollama
- Test with various LLM models
- Verify GPU utilization
- Check memory usage
4. **Create fallback mechanism**
- Implement Ollama as fallback
- Add automatic model selection
- Configure graceful degradation
- Document vLLM vs Ollama trade-offs
### 3. Binary Distribution via GitHub Releases
1. **Create GitHub Actions workflow**
- File: `.github/workflows/build-binaries.yml`
- Trigger on version tags (e.g., `v*.*.*`)
- Build for Debian stable
- Upload artifacts to workflow
2. **Configure automatic release creation**
- Use GitHub Actions to create release on tag
- Attach binaries as release assets
- Generate release notes from CHANGELOG
- Sign binaries (if code signing available)
3. **Create release process**
```bash
# Tag release
git tag -a v0.1.0 -m "Release v0.1.0"
git push origin v0.1.0
# GitHub Actions will:
# 1. Build binary for Debian stable
# 2. Create GitHub Release
# 3. Attach binaries as assets
```
4. **Test release process**
- Create test release tag
- Verify automatic build works
- Check release creation
- Verify asset attachments
- Test download and installation
### 4. Automatic Binary Building in CI/CD
1. **Enhance existing CI/CD pipeline**
- Add binary build step to existing workflows
- Configure build for Debian stable
- Cache build dependencies
- Optimize build times
2. **Set up build agent**
- Configure GitHub Actions runner
- Use self-hosted runner for Debian stable builds
3. **Add build notifications**
- Notify on build failures
- Send build status to Slack/Email
- Track build metrics
- Monitor build queue times
4. **Implement build artifacts**
- Store build artifacts for debugging
- Keep last N builds
- Configure artifact retention policy
- Enable artifact download for testing
### 5. Installation Guides and Verification Instructions
1. **Create Debian stable installation guide**
- Debian: `docs/installation/debian-miner.md`
2. **Installation guide sections**
- System requirements
- Prerequisites (GPU drivers, CUDA)
- Download instructions
- Installation steps
- Configuration
- Verification
- Troubleshooting
3. **Create verification script**
- Script: `scripts/installation/verify-install.sh`
- Check binary integrity with checksums
- Verify GPU detection
- Test basic functionality
- Output verification report
4. **Add checksums to releases**
- Generate SHA256 checksums for each binary
- Include checksums in release notes
- Provide verification instructions
- Automate checksum generation
### 6. Binary Signature Verification
1. **Set up code signing**
- Obtain code signing certificates
- Configure signing tools
- Set up certificate storage (GitHub Secrets)
- Test signing process
2. **Sign binaries**
- Sign Linux binaries with GPG
- Sign Windows binaries with Authenticode
- Sign macOS binaries with Apple Developer ID
- Add signatures to release assets
3. **Create verification instructions**
- Document signature verification process
- Provide GPG public key
- Include verification commands
- Add to installation guides
4. **Automate signing in CI/CD**
- Add signing step to build workflow
- Configure certificate access
- Test signed binary distribution
- Verify signature verification works
## Verification
- [ ] Binary builds successfully for Debian stable
- [ ] Binary runs correctly on Debian stable
- [ ] vLLM integration tested and documented
- [ ] GitHub Actions workflow builds binary automatically
- [ ] Releases created automatically on tags
- [ ] Installation guide complete for Debian stable
- [ ] Verification scripts work correctly
- [ ] Code signing configured and tested
- [ ] Signature verification documented
## Troubleshooting
- **Build fails on Debian stable**: Check Debian-specific dependencies, verify Python version, test build locally
- **Binary doesn't run**: Check PyInstaller spec file, verify dependencies, test on clean Debian system
- **vLLM integration fails**: Check vLLM version compatibility, verify GPU drivers, test with simple model
- **Release creation fails**: Check GitHub token permissions, verify workflow configuration, test with manual release
- **Signature verification fails**: Check certificate validity, verify signing process, test verification commands
## Related Files
- `scripts/gpu/miner.spec`
- `scripts/gpu/gpu_miner_host.py`
- `.github/workflows/build-binaries.yml`
- `docs/installation/debian-miner.md`
- `scripts/installation/verify-install.sh`

View File

@@ -1,245 +0,0 @@
---
description: Documentation Workflow for AITBC Platform
---
# Documentation Workflow
This workflow covers the creation and enhancement of comprehensive documentation for the AITBC platform.
## Prerequisites
- Access to all source code
- Understanding of system architecture
- Technical writing resources
- Documentation tools (mkdocs, Sphinx, or similar)
- Video recording tools (for tutorials)
## Steps
### 1. Complete API Reference Documentation
1. **Review existing API documentation**
- Check current API documentation in `docs/api/`
- Identify missing endpoints
- Review OpenAPI/Swagger specifications
- Check for outdated information
2. **Enhance OpenAPI documentation**
- Add detailed descriptions to all endpoints
- Include request/response schemas
- Add example requests and responses
- Document authentication requirements
- Include error codes and handling
3. **Generate API reference from code**
- Use tools like FastAPI's automatic documentation
- Generate OpenAPI specification
- Export to multiple formats (HTML, JSON, YAML)
- Integrate with documentation site
4. **Create API usage examples**
- Python SDK examples
- JavaScript/TypeScript SDK examples
- cURL examples for all endpoints
- Integration examples
5. **Document WebSocket endpoints**
- Document real-time communication protocols
- Include message formats
- Add connection examples
- Document event types
### 2. Comprehensive Deployment Guide
1. **Create deployment guide structure**
- File: `docs/deployment/comprehensive-guide.md`
- Include sections for different deployment scenarios
- Add troubleshooting sections
- Include best practices
2. **Deployment scenarios**
- Local development setup
- Single-server production deployment
- Multi-server deployment
- Cloud deployment (AWS, GCP, Azure)
- Docker containerized deployment
3. **Deployment steps**
- System requirements
- Prerequisites installation
- Environment configuration
- Service installation
- Database setup
- SSL/TLS configuration
- Service startup
- Health checks
4. **Configuration reference**
- Document all environment variables
- Include default values
- Add configuration examples
- Document security considerations
5. **Troubleshooting section**
- Common deployment issues
- Service startup problems
- Database connection issues
- Network configuration
- Performance tuning
### 3. Security Best Practices Guide
1. **Create security guide**
- File: `docs/security/best-practices.md`
- Cover all security aspects
- Include code examples
- Add checklist for production
2. **Security topics**
- API key management
- Password policies
- SSL/TLS configuration
- Firewall rules
- Network security
- Database security
- Secret management
- Access control
3. **Code security**
- Input validation
- Output encoding
- SQL injection prevention
- XSS prevention
- CSRF protection
- Rate limiting
- Authentication best practices
4. **Operational security**
- Logging and monitoring
- Incident response
- Security audits
- Penetration testing
- Vulnerability scanning
### 4. Troubleshooting and FAQ
1. **Create troubleshooting guide**
- File: `docs/troubleshooting/comprehensive-guide.md`
- Organize by component
- Include common issues
- Add resolution steps
2. **Component-specific troubleshooting**
- Blockchain node issues
- Coordinator API issues
- Wallet daemon issues
- GPU miner issues
- Agent daemon issues
- Network issues
3. **Common issues**
- Service startup failures
- Database connection errors
- GPU detection issues
- Performance problems
- Memory leaks
- Network timeouts
4. **FAQ section**
- File: `docs/faq/README.md`
- Include frequently asked questions
- Add answers with examples
- Organize by topic
- Include links to detailed documentation
### 5. Video Tutorials for Key Workflows
1. **Identify key workflows**
- Initial setup and installation
- Miner configuration and startup
- Job submission and monitoring
- Wallet creation and management
- API integration examples
- Troubleshooting common issues
2. **Create tutorial scripts**
- Write scripts for each tutorial
- Include step-by-step instructions
- Add code examples
- Include expected outputs
3. **Record video tutorials**
- Use screen recording software
- Include voice narration
- Add captions
- Keep videos concise (5-15 minutes)
4. **Post-process videos**
- Edit for clarity
- Add chapter markers
- Include on-screen text
- Optimize for web playback
5. **Publish videos**
- Upload to YouTube or platform
- Create video thumbnails
- Add descriptions and tags
- Link from documentation
6. **Integrate with documentation**
- Embed videos in documentation
- Add video links to relevant sections
- Include video transcripts
- Add video search capability
## Documentation Tools Setup
### 1. Choose documentation framework
- **mkdocs**: Static site generator, Python-based
- **Sphinx**: Python documentation generator
- **Docusaurus**: React-based documentation site
- **Hugo**: Fast static site generator
### 2. Configure documentation build
- Set up CI/CD for documentation builds
- Configure automatic deployment
- Add documentation testing
- Implement link checking
### 3. Documentation standards
- Create style guide
- Define template structure
- Add contribution guidelines
- Set up review process
## Verification
- [ ] API reference complete for all endpoints
- [ ] Deployment guide covers all scenarios
- [ ] Security best practices documented
- [ ] Troubleshooting guide comprehensive
- [ ] FAQ covers common questions
- [ ] Video tutorials created for key workflows
- [ ] Documentation builds successfully
- [ ] Documentation deployed to public site
- [ ] Internal links validated
- [ ] External links checked
## Troubleshooting
- **API documentation incomplete**: Review code, add missing endpoints, test examples
- **Deployment guide unclear**: Test deployment steps, add more details, include screenshots
- **Security guide outdated**: Review latest security practices, update with new threats
- **Video quality poor**: Re-record with better audio/lighting, improve script
- **Documentation build fails**: Check syntax, verify links, fix formatting
## Related Files
- `docs/api/`
- `docs/deployment/`
- `docs/security/`
- `docs/troubleshooting/`
- `docs/faq/`
- `docs/tutorials/`
- `mkdocs.yml` or equivalent
- `.github/workflows/docs.yml`

View File

@@ -1,127 +0,0 @@
---
description: Package Publishing Workflow for aitbc-sdk and aitbc-crypto
---
# Package Publishing Workflow
This workflow covers the packaging and publishing of AITBC SDKs to PyPI and npm.
## Prerequisites
- Active PyPI account with publishing permissions
- Active npm account with publishing permissions
- Gitea Actions configured for the repository
- Version management strategy defined
## Steps
### 1. PyPI Package Setup for aitbc-sdk
1. **Verify package structure**
- Ensure `packages/py/aitbc-sdk/` has proper package structure
- Check `pyproject.toml` configuration
- Verify package metadata (name, version, description, authors)
2. **Configure PyPI publishing**
- Add PyPI API token to Gitea repository secrets (`PYPI_API_TOKEN`)
- Create Gitea Actions workflow for PyPI publishing
- Configure automatic publishing on version tags
3. **Test package installation**
- Build package locally: `cd packages/py/aitbc-sdk && python -m build`
- Test installation from built wheel
- Verify imports work correctly
4. **Publish to PyPI**
- Create and push version tag (e.g., `v0.1.0`)
- Gitea Actions will automatically publish to PyPI
- Verify package appears on PyPI
- Test installation from PyPI: `pip install aitbc-sdk`
### 2. PyPI Package Setup for aitbc-crypto
1. **Verify package structure**
- Ensure `packages/py/aitbc-crypto/` has proper package structure
- Check `pyproject.toml` configuration
- Verify package metadata
2. **Configure PyPI publishing**
- Use existing PyPI token from aitbc-sdk
- Create Gitea Actions workflow for aitbc-crypto publishing
- Configure automatic publishing on version tags
3. **Test package installation**
- Build package locally: `cd packages/py/aitbc-crypto && python -m build`
- Test installation from built wheel
- Verify cryptographic operations work correctly
4. **Publish to PyPI**
- Create and push version tag
- Gitea Actions will automatically publish
- Verify package appears on PyPI
- Test installation from PyPI: `pip install aitbc-crypto`
### 3. npm Package Setup for JavaScript/TypeScript SDK
1. **Verify package structure**
- Ensure `packages/js/aitbc-sdk/` has proper package structure
- Check `package.json` configuration
- Verify package metadata (name, version, description, author)
2. **Configure npm publishing**
- Add npm authentication token to Gitea repository secrets (`NPM_TOKEN`)
- Create Gitea Actions workflow for npm publishing
- Configure `.npmrc` for proper authentication
3. **Test package build**
- Build package locally: `cd packages/js/aitbc-sdk && npm run build`
- Test TypeScript compilation
- Verify type definitions (.d.ts files) are generated
4. **Publish to npm**
- Create and push version tag
- Gitea Actions will automatically publish to npm
- Verify package appears on npm registry
- Test installation from npm: `npm install aitbc-sdk`
### 4. Version Management
1. **Define semantic versioning strategy**
- Follow SemVer (MAJOR.MINOR.PATCH)
- MAJOR: Breaking changes
- MINOR: New features, backward compatible
- PATCH: Bug fixes, backward compatible
2. **Configure version management**
- Set up automated version bumping in Gitea Actions
- Create version tags for releases
- Maintain CHANGELOG.md with release notes
3. **Version synchronization**
- Ensure aitbc-sdk and aitbc-crypto versions are synchronized
- Coordinate Python and JavaScript SDK releases
- Document version compatibility matrix
## Verification
- [ ] aitbc-sdk published to PyPI and installable
- [ ] aitbc-crypto published to PyPI and installable
- [ ] aitbc-sdk published to npm and installable
- [ ] Gitea Actions workflows successfully publish on tags
- [ ] Version management strategy documented
- [ ] CHANGELOG.md maintained with release notes
## Troubleshooting
- **PyPI publishing fails**: Check PyPI token permissions, verify package name availability
- **npm publishing fails**: Verify npm token, check package name availability, ensure `.npmrc` is configured
- **Build fails locally**: Check dependencies, verify Python/Node.js versions
- **Installation test fails**: Verify package structure, check imports/exports
## Related Files
- `packages/py/aitbc-sdk/pyproject.toml`
- `packages/py/aitbc-crypto/pyproject.toml`
- `packages/js/aitbc-sdk/package.json`
- `.gitea/workflows/publish-python.yml`
- `.gitea/workflows/publish-js.yml`

View File

@@ -1,274 +0,0 @@
---
description: Quality Assurance Workflow for AITBC Platform
---
# Quality Assurance Workflow
This workflow covers comprehensive testing and quality assurance for the AITBC platform.
## Prerequisites
- Test environment matching production (Debian stable)
- Test data and fixtures
- Load testing tools (k6, locust, or similar)
- Security testing tools (OWASP ZAP, Burp Suite)
- CI/CD pipeline with test automation
## Steps
### 1. End-to-End Testing of All Components
1. **Define test scenarios**
- User registration and wallet creation
- Job submission and processing
- Payment and receipt generation
- Miner registration and operation
- Agent communication
- Blockchain transactions
- API interactions
2. **Create test suite**
- File: `tests/e2e/test_complete_system.py`
- Use test frameworks (pytest, playwright)
- Include setup and teardown procedures
- Mock external dependencies when needed
3. **Test individual components**
- **Blockchain Node**: Block creation, transaction processing, consensus
- **Coordinator API**: Job submission, matching, payments
- **Wallet Daemon**: Key management, transaction signing
- **GPU Miner**: Job processing, GPU utilization
- **Agent Daemon**: Agent communication, task execution
- **Exchange**: Trading, order matching
4. **Test component integration**
- Test data flow between components
- Verify API contracts
- Test error handling across components
- Validate state synchronization
5. **Automate E2E tests**
- Integrate with CI/CD pipeline
- Run on every PR
- Schedule nightly runs
- Generate test reports
### 2. Load Testing for Production Readiness
1. **Define load testing scenarios**
- Normal traffic patterns
- Peak traffic patterns
- Stress testing (beyond expected load)
- Sustained load testing
2. **Set up load testing tools**
- Install k6 or locust
- Configure test scenarios
- Set up monitoring during tests
- Configure alerting thresholds
3. **Create load test scripts**
- File: `tests/load/test_api_load.py`
- Define user behavior patterns
- Configure request rates
- Set up test data
- Define success criteria
4. **Test individual services**
- **Coordinator API**: Request rate limits, response times
- **Blockchain Node**: Block processing rate, transaction throughput
- **Exchange**: Order processing rate, matching speed
- **Marketplace**: Listing/browsing performance
5. **Test system under load**
- Run load tests on staging environment
- Monitor resource usage (CPU, memory, disk, network)
- Identify bottlenecks
- Test auto-scaling (if applicable)
6. **Analyze results**
- Document performance baselines
- Identify performance degradation points
- Create optimization plans
- Define SLA targets
### 3. Debian Stable Compatibility Validation
1. **Define target platform**
- **Operating System**: Debian stable (bookworm)
- **Python Versions**: 3.13, 3.14
- **GPU Hardware**: NVIDIA (various generations with CUDA)
2. **Set up test environment**
- Debian stable virtual machine
- Physical hardware for GPU testing
- Containerized environments
3. **Test Python compatibility**
- Test on Python 3.13 and 3.14
- Verify dependency compatibility
- Test with pip package manager
- Check for deprecated features
4. **Test OS compatibility**
- Install and run on Debian stable
- Verify service startup
- Test systemd services
- Verify package dependencies
5. **Test GPU compatibility**
- Test with NVIDIA GPUs (CUDA)
- Test with various GPU generations
- Verify GPU detection and utilization
- Test CUDA toolkit compatibility
### 4. Disaster Recovery Procedure Testing
1. **Define disaster scenarios**
- Database corruption
- Service failure
- Network partition
- Data center outage
- Security breach
- Ransomware attack
2. **Create backup procedures**
- Database backup strategy
- Configuration backup
- Code repository backup
- Blockchain state backup
- Wallet key backup
3. **Test backup restoration**
- Restore database from backup
- Verify data integrity
- Test service recovery
- Measure recovery time
- Document recovery procedures
4. **Test failover mechanisms**
- Test service failover
- Test database failover
- Test network failover
- Verify automatic recovery
- Measure failover time
5. **Create disaster recovery plan**
- File: `docs/operations/disaster-recovery.md`
- Include contact information
- Define escalation procedures
- Document recovery steps
- Include communication plan
6. **Conduct disaster recovery drills**
- Schedule regular drills
- Test different scenarios
- Document lessons learned
- Update procedures based on findings
### 5. Security Penetration Testing
1. **Define testing scope**
- Web applications (coordinator API, exchange, marketplace)
- APIs (REST, WebSocket)
- Smart contracts
- Network infrastructure
- Authentication and authorization
2. **Set up security testing tools**
- OWASP ZAP (web application security)
- Burp Suite (web application security)
- Nmap (network scanning)
- Nikto (web server scanning)
- SQLMap (SQL injection testing)
3. **Conduct vulnerability scanning**
- Automated vulnerability scans
- Dependency vulnerability checks (Snyk, Dependabot)
- Secret scanning (GitGuardian, truffleHog)
- Container scanning (Trivy, Clair)
4. **Manual penetration testing**
- Test authentication bypass
- Test authorization bypass
- Test input validation
- Test session management
- Test API security
- Test smart contract vulnerabilities
5. **Test common vulnerabilities**
- OWASP Top 10 (injection, broken auth, XSS, etc.)
- CWE/SANS Top 25
- Smart contract vulnerabilities (reentrancy, overflow, etc.)
- Blockchain-specific vulnerabilities
6. **Document findings**
- File: `docs/security/penetration-test-report.md`
- Categorize by severity
- Include proof of concept
- Provide remediation steps
- Track remediation progress
7. **Remediate vulnerabilities**
- Fix Critical and High findings
- Add security tests to CI/CD
- Implement security best practices
- Conduct re-testing
## Quality Metrics
### 1. Test Coverage
- Unit test coverage: >80%
- Integration test coverage: >70%
- E2E test coverage: >60%
- Code coverage tracked in CI/CD
### 2. Performance Metrics
- API response time: <200ms (p95)
- Block processing time: <1s
- Job processing time: <5s
- System uptime: >99.9%
### 3. Security Metrics
- Critical vulnerabilities: 0
- High vulnerabilities: 0
- Medium vulnerabilities: <5
- Dependency vulnerabilities: 0 (Critical/High)
### 4. Quality Metrics
- Bug escape rate: <5%
- Test flakiness: <2%
- Documentation coverage: >90%
- Code review coverage: 100%
## Verification
- [ ] E2E test suite complete and passing
- [ ] Load testing completed and baselines defined
- [ ] Debian stable testing completed
- [ ] Disaster recovery procedures tested
- [ ] Security penetration testing completed
- [ ] All Critical/High vulnerabilities remediated
- [ ] Quality metrics meet targets
- [ ] CI/CD pipeline includes all tests
- [ ] Test reports generated and reviewed
- [ ] Quality assurance process documented
## Troubleshooting
- **E2E tests flaky**: Review test dependencies, add proper waits, isolate tests, use test fixtures
- **Load tests fail**: Check resource limits, verify test environment, optimize code, scale infrastructure
- **Debian stable tests fail**: Check Debian-specific code, verify dependencies, test on actual Debian system
- **Disaster recovery fails**: Verify backup integrity, test restoration procedures, check documentation
- **Security tests find vulnerabilities**: Prioritize by severity, implement fixes, re-test, document lessons
## Related Files
- `tests/e2e/`
- `tests/load/`
- `tests/security/`
- `tests/integration/`
- `docs/operations/disaster-recovery.md`
- `docs/security/penetration-test-report.md`
- `.gitea/workflows/test.yml`
- `.gitea/workflows/security-scan.yml`

View File

@@ -6,6 +6,39 @@ description: Security & Audit Workflow for AITBC Platform
This workflow covers comprehensive security auditing and review for the AITBC platform.
## Status Summary
**Initial Audit Phase:** ✅ Completed (2026-05-11)
The initial internal security audit has been completed with the following deliverables:
- Security findings documented (20 findings: 3 Critical, 10 High, 7 Medium)
- Threat model created
- Economic analysis completed
- Remediation plan developed
- CI/CD security scanning enhanced
**Remediation Implementation:** ✅ Partially Completed (2026-05-11)
- **Phase 1 (Critical):** ✅ Complete (3/3 findings resolved)
- ECDSA verification bypass - Mitigated
- Mock ZK proof verification - Resolved
- Unlimited token minting - Resolved
- **Phase 2 (High):** 🔄 Partial (5/10 findings resolved, 5 deferred)
- ✅ Circom circuit constraints (3 findings) - Resolved
- ✅ ZK proof implementation security (5 findings) - Resolved/Mitigated
- ⏸️ Smart contract economic security (5 findings) - Deferred to dedicated sprint
- **Phase 3 (Medium):** ⏸️ Deferred (0/7 findings resolved, 7 deferred)
- All Medium findings require smart contract upgrades
- Deferred to dedicated smart contract security sprint
**Smart Contract Security Sprint:** ⏳ Not Started
- Scope: 8 deferred findings (5 High, 3 Medium)
- Components: AgentStaking.sol, AIServiceAMM.sol, EscrowService.sol
- Requires: Contract development, testing, migration strategy, governance approval
**Third-Party Audit:** Not yet initiated - pending completion of non-smart-contract remediations
## Prerequisites
- Access to all source code repositories
@@ -117,32 +150,36 @@ This workflow covers comprehensive security auditing and review for the AITBC pl
### 4. Token Economy and Attack Vector Review
**COMPLETED** (2026-05-11)
1. **Economic model analysis**
- Review token distribution and vesting
- Analyze incentive mechanisms
- Check for economic attack vectors:
- Reviewed token distribution and vesting
- Analyzed incentive mechanisms
- Checked for economic attack vectors:
- Pump and dump
- Front-running
- MEV extraction
- Sybil attacks
2. **Smart contract economic security**
- Review staking mechanisms
- Check reward distribution logic
- Verify slashing conditions
- Analyze governance token economics
- Reviewed staking mechanisms
- Checked reward distribution logic
- Verified slashing conditions
- Analyzed governance token economics
3. **Market manipulation prevention**
- Review marketplace pricing mechanisms
- Check for oracle manipulation risks
- Verify liquidity protection
- Analyze arbitrage opportunities
- Reviewed marketplace pricing mechanisms
- Checked for oracle manipulation risks
- Verified liquidity protection
- Analyzed arbitrage opportunities
4. **Game theory analysis**
- Analyze Nash equilibria
- Check for dominant strategies
- Verify incentive alignment
- Test economic simulations
- Analyzed Nash equilibria
- Checked for dominant strategies
- Verified incentive alignment
- Test economic simulations (pending)
**Findings:** 9 issues documented in `docs/security/audit-findings.md`
### 5. Security Findings Documentation and Remediation
@@ -198,9 +235,22 @@ This workflow covers comprehensive security auditing and review for the AITBC pl
## Related Files
**Source Code:**
- `apps/zk-circuits/*.circom`
- `apps/coordinator-api/src/app/routers/zk.py`
- `contracts/`
- `docs/security/audit-findings.md`
- `docs/security/threat-model.md`
- `docs/security/economic-analysis.md`
- `apps/coordinator-api/src/app/routers/zk_applications.py`
- `apps/coordinator-api/src/app/routers/ml_zk_proofs.py`
- `apps/coordinator-api/src/app/services/zk_proofs.py`
- `apps/coordinator-api/src/app/services/zk_memory_verification.py`
- `contracts/contracts/AIToken.sol`
- `contracts/contracts/AgentStaking.sol`
- `contracts/contracts/AIServiceAMM.sol`
- `contracts/contracts/EscrowService.sol`
**Security Documentation:**
- `docs/security/audit-findings.md` - All 20 security findings
- `docs/security/threat-model.md` - Comprehensive threat model
- `docs/security/economic-analysis.md` - Economic security analysis
- `docs/security/remediation-plan.md` - 3-phase remediation plan
**CI/CD:**
- `.gitea/workflows/security-scanning.yml` - Enhanced security scanning workflow

View File

@@ -0,0 +1,314 @@
---
description: Smart Contract Security Sprint - Dedicated remediation for contract-level findings
---
# Smart Contract Security Sprint
This document outlines the dedicated security sprint for addressing smart contract-level security findings deferred from the initial remediation phase.
## Sprint Overview
**Status:** ⏳ Not Started
**Sprint Duration:** 2-3 weeks
**Scope:** 8 security findings (5 High, 3 Medium)
**Components:** AgentStaking.sol, AIServiceAMM.sol, EscrowService.sol, AIToken.sol
## Deferred Findings
### High Severity (5 findings)
#### 1. No Slashing Mechanism in AgentStaking.sol
**Finding ID:** SC-H-01
**Component:** contracts/contracts/AgentStaking.sol
**Status:** Open
**Description:**
The contract has a `SLASHED` status enum but no actual slashing implementation. Malicious agents can act without consequences.
**Required Changes:**
- Implement slashing logic based on performance metrics
- Add slashing conditions (e.g., accuracy below threshold, missed jobs)
- Add slashing governance mechanism
- Implement appeal process for slashed agents
- Add slashing rewards to reporters
**Testing:**
- Unit tests for slashing conditions
- Integration tests for slashing execution
- Governance tests for slashing approval
#### 2. Lack of Oracle Manipulation Protection in AgentStaking.sol
**Finding ID:** SC-H-02
**Component:** contracts/contracts/AgentStaking.sol
**Status:** Open
**Description:**
The `updateAgentPerformance` function (line 429) lacks oracle authorization checks. Any caller can update performance metrics.
**Required Changes:**
- Add authorized oracle list with governance control
- Implement oracle signature verification
- Add time delay for performance updates
- Implement oracle rotation mechanism
- Add oracle reputation scoring
**Testing:**
- Oracle authorization tests
- Performance update validation tests
- Oracle rotation tests
#### 3. AMM Vulnerable to Flash Loan Attacks in AIServiceAMM.sol
**Finding ID:** SC-H-03
**Component:** contracts/contracts/AIServiceAMM.sol
**Status:** Open
**Description:**
The AMM lacks TWAP (Time-Weighted Average Price) protection against flash loan manipulation.
**Required Changes:**
- Implement TWAP price oracle
- Add price deviation limits
- Implement flash loan detection
- Add minimum time delay for swaps
- Implement circuit breaker for abnormal price movements
**Testing:**
- Flash loan simulation tests
- Price manipulation tests
- TWAP validation tests
#### 4. No Front-Running Protection in AIServiceAMM.sol
**Finding ID:** SC-H-04
**Component:** contracts/contracts/AIServiceAMM.sol
**Status:** Open
**Description:**
The AMM lacks front-running protection for trades.
**Required Changes:**
- Implement commit-reveal scheme
- Add minimum block delay for trade execution
- Implement trade batching
- Add maximum price deviation protection
- Consider MEV-resistant design patterns
**Testing:**
- Front-running simulation tests
- Commit-reveal tests
- Trade batching tests
#### 5. Emergency Withdraw Without Timelock in AIServiceAMM.sol
**Finding ID:** SC-H-05
**Component:** contracts/contracts/AIServiceAMM.sol
**Status:** Open
**Description:**
Emergency withdraw functions lack time delays, allowing immediate fund extraction.
**Required Changes:**
- Add time delay (e.g., 48 hours) for emergency withdraw
- Implement governance approval requirement
- Add notification system for pending emergency actions
- Implement multi-signature requirement
- Add cancel mechanism for pending emergency actions
**Testing:**
- Time delay tests
- Governance approval tests
- Multi-sig tests
### Medium Severity (3 findings)
#### 6. Oracle Single Point of Failure in EscrowService.sol
**Finding ID:** SC-M-01
**Component:** contracts/contracts/EscrowService.sol
**Status:** Open
**Description:**
Conditional release mechanism relies on single oracle verification (line 437).
**Required Changes:**
- Implement multi-oracle verification with threshold (e.g., 2/3)
- Add oracle reputation system
- Implement dispute resolution for oracle decisions
- Add time delay after oracle verification before release
- Consider decentralized oracle network integration
**Testing:**
- Multi-oracle threshold tests
- Dispute resolution tests
- Time delay tests
#### 7. No Minimum Voting Threshold for Emergency Release in EscrowService.sol
**Finding ID:** SC-M-02
**Component:** contracts/contracts/EscrowService.sol
**Status:** Open
**Description:**
Emergency release voting only requires 3 total votes and simple majority (line 612).
**Required Changes:**
- Implement percentage-based threshold (e.g., 66% of total arbiters)
- Add minimum quorum requirement based on escrow amount
- Implement arbiter staking to prevent sybil attacks
- Add voting weight based on arbiter reputation
- Implement time lock after approval before execution
**Testing:**
- Threshold calculation tests
- Quorum requirement tests
- Arbiter staking tests
#### 8. No Rate Limiting on Staking Operations in AgentStaking.sol
**Finding ID:** SC-M-03
**Component:** contracts/contracts/AgentStaking.sol
**Status:** Open
**Description:**
Staking contract has no rate limiting on operations.
**Required Changes:**
- Add rate limiting on stake creation (e.g., max 10 stakes/day)
- Implement minimum stake amounts
- Add maximum number of stakes per user
- Implement gas optimization for batch operations
- Add cooldown periods between operations
**Testing:**
- Rate limiting tests
- Minimum stake tests
- Maximum stake count tests
## Sprint Timeline
### Week 1: Planning and Development
- **Day 1-2:** Sprint planning, design review, test strategy
- **Day 3-5:** Implement High severity findings (SC-H-01, SC-H-02)
- **Day 6-7:** Unit testing for implemented fixes
### Week 2: Development and Testing
- **Day 8-10:** Implement remaining High severity findings (SC-H-03, SC-H-04, SC-H-05)
- **Day 11-12:** Implement Medium severity findings (SC-M-01, SC-M-02, SC-M-03)
- **Day 13-14:** Integration testing
### Week 3: Review and Deployment
- **Day 15-16:** Code review, security review
- **Day 17-18:** Audit preparation, documentation
- **Day 19-20:** Deployment to testnet, final testing
## Migration Strategy
### For Existing Deployments
**Option A: Contract Upgrade via Proxy**
- Deploy new implementation contracts
- Update proxy to point to new implementation
- Migrate state if necessary
- Requires governance approval
**Option B: New Deployment**
- Deploy new contracts
- Migrate users/stakes to new contracts
- Deprecate old contracts
- More complex but cleaner
**Recommended:** Option A for minimal disruption
### Testing Strategy
1. **Unit Tests**
- Test each fix individually
- Test edge cases and boundary conditions
- Test failure modes
2. **Integration Tests**
- Test contract interactions
- Test governance flows
- Test upgrade mechanisms
3. **Security Tests**
- Re-run security scanning on new code
- Manual security review
- Third-party audit (if budget allows)
4. **Performance Tests**
- Gas cost analysis
- Benchmark critical operations
- Optimize if necessary
## Risk Assessment
### High Risks
- **Contract upgrade failure:** Mitigate with thorough testing and rollback plan
- **State migration issues:** Mitigate with comprehensive migration tests
- **Governance approval delays:** Plan timeline accordingly
### Medium Risks
- **Gas cost increases:** Optimize critical paths
- **User confusion during migration:** Clear communication and documentation
- **Testing timeline overrun:** Buffer time in schedule
## Success Criteria
- All 8 findings resolved and tested
- Unit test coverage > 90% for modified contracts
- Integration tests passing
- Security review completed
- Migration to testnet successful
- Documentation updated
- Governance approval obtained
## Deliverables
1. **Code Changes**
- Modified smart contracts
- Migration scripts (if needed)
- Upgrade contracts (if using proxy pattern)
2. **Documentation**
- Updated contract documentation
- Migration guide
- API changes documentation
- Security review report
3. **Testing**
- Unit test suite
- Integration test suite
- Test results report
4. **Deployment**
- Testnet deployment
- Mainnet deployment plan
- Rollback plan
## Related Files
**Smart Contracts:**
- `contracts/contracts/AgentStaking.sol`
- `contracts/contracts/AIServiceAMM.sol`
- `contracts/contracts/EscrowService.sol`
- `contracts/contracts/AIToken.sol`
**Documentation:**
- `docs/security/audit-findings.md` - Original findings
- `docs/security/remediation-plan.md` - Overall remediation plan
- `contracts/docs/` - Contract documentation
**CI/CD:**
- `.gitea/workflows/smart-contract-tests.yml` - Contract testing workflow
- `contracts/deployments-aitbc-cascade.json` - Deployment configuration
## Verification Checklist
- [ ] Sprint planning completed
- [ ] Design review completed
- [ ] All 8 findings implemented
- [ ] Unit tests written and passing
- [ ] Integration tests written and passing
- [ ] Security review completed
- [ ] Gas cost analysis completed
- [ ] Migration strategy defined
- [ ] Testnet deployment successful
- [ ] Mainnet deployment plan approved
- [ ] Documentation updated
- [ ] Governance approval obtained

View File

@@ -0,0 +1,454 @@
---
description: Smart Contract Security Sprint Phase 1 - Implementation Plan for SC-H-01 and SC-H-02
---
# Smart Contract Security Sprint - Phase 1 Implementation Plan
**Date:** 2026-05-11
**Status:** In Progress
**Focus:** AgentStaking.sol security enhancements
## Findings to Implement
### SC-H-01: No Slashing Mechanism in AgentStaking.sol
**Current State:**
- Contract has `SLASHED` status enum (line 33)
- No actual slashing implementation
- Malicious agents can act without consequences
**Implementation Plan:**
**1. Add Slashing Conditions**
```solidity
// New state variables
struct SlashingCondition {
uint256 minAccuracyThreshold; // e.g., 50% minimum accuracy
uint256 maxMissedJobs; // e.g., 5 consecutive missed jobs
uint256 slashingPercentage; // e.g., 10% slash amount
}
mapping(address => SlashingCondition) public slashingConditions;
uint256 public defaultMinAccuracy = 50; // 50%
uint256 public defaultMaxMissedJobs = 5;
uint256 public defaultSlashingPercentage = 10; // 10%
```
**2. Implement Slashing Function**
```solidity
function slashStake(
uint256 _stakeId,
uint256 _slashingAmount,
string memory _reason
) external onlyOwner {
Stake storage stake = stakes[_stakeId];
require(stake.status == StakeStatus.ACTIVE, "Stake not active");
require(_slashingAmount <= stake.amount, "Invalid slash amount");
// Transfer slashed amount to treasury
uint256 slashAmount = (stake.amount * _slashingAmount) / 100;
stake.amount -= slashAmount;
// Update status to SLASHED
stake.status = StakeStatus.SLASHED;
// Transfer slashed tokens to treasury
aitbcToken.transfer(owner(), slashAmount);
emit StakeSlashed(_stakeId, stake.staker, slashAmount, _reason);
}
```
**3. Add Automatic Slashing Based on Performance**
```solidity
function checkAndSlashAgent(
address _agentWallet
) external onlyOwner {
AgentMetrics storage metrics = agentMetrics[_agentWallet];
// Check accuracy threshold
if (metrics.averageAccuracy < defaultMinAccuracy) {
_slashAllStakesForAgent(_agentWallet, defaultSlashingPercentage, "Low accuracy");
}
// Check missed jobs
uint256 missedJobs = metrics.totalSubmissions - metrics.successfulSubmissions;
if (missedJobs > defaultMaxMissedJobs) {
_slashAllStakesForAgent(_agentWallet, defaultSlashingPercentage, "Too many missed jobs");
}
}
function _slashAllStakesForAgent(
address _agentWallet,
uint256 _slashingPercentage,
string memory _reason
) internal {
uint256[] storage stakesForAgent = agentStakes[_agentWallet];
for (uint256 i = 0; i < stakesForAgent.length; i++) {
uint256 stakeId = stakesForAgent[i];
Stake storage stake = stakes[stakeId];
if (stake.status == StakeStatus.ACTIVE) {
uint256 slashAmount = (stake.amount * _slashingPercentage) / 100;
stake.amount -= slashAmount;
stake.status = StakeStatus.SLASHED;
aitbcToken.transfer(owner(), slashAmount);
emit StakeSlashed(stakeId, stake.staker, slashAmount, _reason);
}
}
}
```
**4. Add Appeal Process**
```solidity
struct SlashAppeal {
uint256 stakeId;
address appellant;
string memory reason;
uint256 appealTime;
bool resolved;
bool approved;
}
mapping(uint256 => SlashAppeal) public slashAppeals;
uint256 public appealCooldown = 7 days;
uint256 public appealWindow = 3 days;
function appealSlashing(uint256 _stakeId, string memory _reason) external {
Stake storage stake = stakes[_stakeId];
require(stake.staker == msg.sender, "Not your stake");
require(stake.status == StakeStatus.SLASHED, "Not slashed");
require(block.timestamp - stake.lastRewardTime < appealWindow, "Appeal window expired");
slashAppeals[_stakeId] = SlashAppeal({
stakeId: _stakeId,
appellant: msg.sender,
reason: _reason,
appealTime: block.timestamp,
resolved: false,
approved: false
});
emit SlashAppealFiled(_stakeId, msg.sender, _reason);
}
function resolveSlashAppeal(uint256 _stakeId, bool _approved) external onlyOwner {
SlashAppeal storage appeal = slashAppeals[_stakeId];
require(appeal.appellant != address(0), "No appeal found");
require(!appeal.resolved, "Already resolved");
appeal.resolved = true;
appeal.approved = _approved;
if (_approved) {
Stake storage stake = stakes[_stakeId];
stake.status = StakeStatus.ACTIVE;
emit SlashAppealApproved(_stakeId);
} else {
emit SlashAppealRejected(_stakeId);
}
}
```
**5. Add Slashing Rewards to Reporters**
```solidity
uint256 public slashReporterReward = 500; // 5% of slashed amount
function reportMaliciousAgent(
address _agentWallet,
string memory _evidence
) external {
require(agentMetrics[_agentWallet].agentWallet != address(0), "Agent not found");
// Check if agent should be slashed
if (agentMetrics[_agentWallet].averageAccuracy < defaultMinAccuracy) {
uint256 totalSlashed = _slashAllStakesForAgent(_agentWallet, defaultSlashingPercentage, "Reporter: " + _evidence);
uint256 reward = (totalSlashed * slashReporterReward) / 10000;
aitbcToken.transfer(msg.sender, reward);
emit MaliciousAgentReported(_agentWallet, msg.sender, reward);
}
}
```
### SC-H-02: Lack of Oracle Manipulation Protection in AgentStaking.sol
**Current State:**
- `updateAgentPerformance` function (line 429) lacks oracle authorization
- Any caller can update performance metrics
- No time delay for performance updates
**Implementation Plan:**
**1. Add Authorized Oracle List**
```solidity
mapping(address => bool) public authorizedOracles;
uint256 public oracleCount;
address[] public oracleList;
modifier onlyAuthorizedOracle() {
require(authorizedOracles[msg.sender], "Not authorized oracle");
_;
}
function addOracle(address _oracle) external onlyOwner {
require(_oracle != address(0), "Invalid oracle address");
require(!authorizedOracles[_oracle], "Oracle already authorized");
authorizedOracles[_oracle] = true;
oracleList.push(_oracle);
oracleCount++;
emit OracleAdded(_oracle);
}
function removeOracle(address _oracle) external onlyOwner {
require(authorizedOracles[_oracle], "Oracle not authorized");
authorizedOracles[_oracle] = false;
oracleCount--;
emit OracleRemoved(_oracle);
}
```
**2. Add Oracle Signature Verification**
```solidity
using ECDSA for bytes32;
using ECDSA for bytes;
struct PerformanceUpdate {
address agentWallet;
uint256 accuracy;
bool successful;
uint256 timestamp;
uint256 nonce;
}
mapping(address => uint256) public oracleNonces;
function updateAgentPerformanceWithSignature(
address _agentWallet,
uint256 _accuracy,
bool _successful,
uint256 _timestamp,
uint256 _nonce,
bytes memory _signature
) external onlyAuthorizedOracle {
require(block.timestamp <= _timestamp + 1 hours, "Signature expired");
require(oracleNonces[msg.sender] == _nonce, "Invalid nonce");
// Verify signature
bytes32 messageHash = keccak256(abi.encodePacked(_agentWallet, _accuracy, _successful, _timestamp, _nonce));
bytes32 ethSignedMessageHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", messageHash));
address signer = ethSignedMessageHash.recover(_signature);
require(signer == msg.sender, "Invalid signature");
// Update nonce
oracleNonces[msg.sender]++;
// Call original update function
_updateAgentPerformanceInternal(_agentWallet, _accuracy, _successful);
}
function _updateAgentPerformanceInternal(
address _agentWallet,
uint256 _accuracy,
bool _successful
) internal {
AgentMetrics storage metrics = agentMetrics[_agentWallet];
metrics.totalSubmissions++;
if (_successful) {
metrics.successfulSubmissions++;
}
uint256 totalAccuracy = metrics.averageAccuracy * (metrics.totalSubmissions - 1) + _accuracy;
metrics.averageAccuracy = totalAccuracy / metrics.totalSubmissions;
metrics.lastUpdateTime = block.timestamp;
PerformanceTier newTier = _calculateAgentTier(_agentWallet);
PerformanceTier oldTier = metrics.currentTier;
if (newTier != oldTier) {
metrics.currentTier = newTier;
uint256[] storage stakesForAgent = agentStakes[_agentWallet];
for (uint256 i = 0; i < stakesForAgent.length; i++) {
uint256 stakeId = stakesForAgent[i];
Stake storage stake = stakes[stakeId];
if (stake.status == StakeStatus.ACTIVE) {
stake.currentAPY = _calculateAPY(_agentWallet, stake.lockPeriod, newTier);
stake.agentTier = newTier;
}
}
emit AgentTierUpdated(_agentWallet, oldTier, newTier, metrics.tierScore);
}
}
```
**3. Add Time Delay for Performance Updates**
```solidity
uint256 public performanceUpdateDelay = 1 hours;
mapping(address => uint256) public lastPerformanceUpdateTime;
function updateAgentPerformance(
address _agentWallet,
uint256 _accuracy,
bool _successful
) external onlyAuthorizedOracle {
require(block.timestamp >= lastPerformanceUpdateTime[_agentWallet] + performanceUpdateDelay, "Update too frequent");
lastPerformanceUpdateTime[_agentWallet] = block.timestamp;
_updateAgentPerformanceInternal(_agentWallet, _accuracy, _successful);
}
```
**4. Implement Oracle Rotation Mechanism**
```solidity
uint256 public oracleRotationPeriod = 30 days;
uint256 public lastOracleRotation;
function rotateOracle(address _oldOracle, address _newOracle) external onlyOwner {
require(authorizedOracles[_oldOracle], "Old oracle not authorized");
require(!authorizedOracles[_newOracle], "New oracle already authorized");
require(block.timestamp >= lastOracleRotation + oracleRotationPeriod, "Rotation too soon");
authorizedOracles[_oldOracle] = false;
authorizedOracles[_newOracle] = true;
lastOracleRotation = block.timestamp;
emit OracleRotated(_oldOracle, _newOracle);
}
```
**5. Add Oracle Reputation Scoring**
```solidity
struct OracleReputation {
uint256 totalUpdates;
uint256 successfulUpdates;
uint256 disputedUpdates;
uint256 reputationScore; // 0-100
}
mapping(address => OracleReputation) public oracleReputations;
function updateOracleReputation(address _oracle, bool _successful) internal {
OracleReputation storage rep = oracleReputations[_oracle];
rep.totalUpdates++;
if (_successful) {
rep.successfulUpdates++;
rep.reputationScore = (rep.successfulUpdates * 100) / rep.totalUpdates;
} else {
rep.disputedUpdates++;
rep.reputationScore = (rep.successfulUpdates * 100) / rep.totalUpdates;
// Remove oracle if reputation falls below threshold
if (rep.reputationScore < 50) {
authorizedOracles[_oracle] = false;
emit OracleRemovedForLowReputation(_oracle, rep.reputationScore);
}
}
}
```
## Testing Strategy
### SC-H-01 Tests
1. **Slashing Condition Tests**
- Test slashing when accuracy below threshold
- Test slashing when missed jobs exceed limit
- Test no slashing when conditions not met
2. **Slashing Execution Tests**
- Test manual slashing by owner
- Test automatic slashing based on performance
- Test slashed stake status change
- Test token transfer to treasury
3. **Appeal Process Tests**
- Test appeal filing within window
- Test appeal rejection after window
- Test appeal approval by owner
- Test appeal rejection by owner
4. **Reporter Reward Tests**
- Test reward distribution for valid reports
- Test no reward for invalid reports
### SC-H-02 Tests
1. **Oracle Authorization Tests**
- Test only authorized oracles can update performance
- Test unauthorized callers are rejected
- Test oracle addition/removal by owner
2. **Signature Verification Tests**
- Test valid signature acceptance
- Test invalid signature rejection
- Test nonce validation
- Test timestamp validation
3. **Time Delay Tests**
- Test update delay enforcement
- Test immediate update rejection
- Test update after delay acceptance
4. **Oracle Rotation Tests**
- Test oracle rotation by owner
- Test rotation period enforcement
- Test old oracle removal
- Test new oracle authorization
5. **Reputation Tests**
- Test reputation score calculation
- Test low reputation removal
- Test reputation update on performance update
## Implementation Order
1. **SC-H-01: Slashing Mechanism**
- Add slashing condition structs and state variables
- Implement manual slashing function
- Implement automatic slashing based on performance
- Add appeal process
- Add reporter rewards
- Write unit tests
2. **SC-H-02: Oracle Protection**
- Add authorized oracle list
- Implement oracle signature verification
- Add time delay for performance updates
- Implement oracle rotation
- Add oracle reputation scoring
- Write unit tests
## Dependencies
- OpenZeppelin contracts (already imported)
- ECDSA library for signature verification
- No external dependencies required
## Risk Assessment
**High Risks:**
- Slashing mechanism could be abused if not properly tested
- Oracle manipulation could still occur if oracle list is compromised
**Mitigation:**
- Comprehensive unit and integration testing
- Governance controls for oracle management
- Reputation system to remove bad oracles
- Appeal process for unfair slashing
## Success Criteria
- Slashing mechanism implemented and tested
- Oracle protection implemented and tested
- Unit tests passing for both findings
- Integration tests passing
- Gas optimization reviewed
- Documentation updated