ci: refactor Gitea workflows to use environment variables for workspace paths
Some checks failed
Blockchain Synchronization Verification / sync-verification (push) Failing after 3s
Cross-Chain Functionality Tests / test-cross-chain-sync (push) Successful in 3s
Cross-Chain Functionality Tests / test-cross-chain-transactions (push) Successful in 3s
Cross-Chain Functionality Tests / test-multi-chain-consensus (push) Successful in 2s
Cross-Node Transaction Testing / transaction-test (push) Successful in 3s
Deploy to Testnet / deploy-testnet (push) Successful in 1m17s
Documentation Validation / validate-docs (push) Failing after 11s
Documentation Validation / validate-policies-strict (push) Successful in 4s
Integration Tests / test-service-integration (push) Failing after 42s
Multi-Chain Island Architecture Tests / test-multi-chain-island (push) Failing after 3s
Multi-Node Blockchain Health Monitoring / health-check (push) Successful in 3s
Multi-Node Stress Testing / stress-test (push) Successful in 4s
P2P Network Verification / p2p-verification (push) Has been cancelled
Python Tests / test-python (push) Has been cancelled
Security Scanning / security-scan (push) Has been cancelled
Node Failover Simulation / failover-test (push) Failing after 1h35m21s
Cross-Chain Functionality Tests / aggregate-results (push) Successful in 8s

- Added WORKSPACE env variable to all workflow jobs
- Changed hardcoded workspace paths to use ${{ env.WORKSPACE }}
- Added pull_request path filters to blockchain-sync-verification.yml
- Updated cross-chain-tests.yml path filters to apps/blockchain-node/** and scripts/multi-node/**
- Removed ait-devnet from default chains in cross-chain-tests.yml
- Disabled test-cross-chain-bridge job (test file not implemented)
- Removed test-cross-chain-bridge from aggregate
This commit is contained in:
aitbc
2026-05-11 14:26:44 +02:00
parent 3105189d4c
commit 99205f97b0
15 changed files with 345 additions and 1310 deletions

View File

@@ -1,256 +0,0 @@
---
description: Security & Audit Workflow for AITBC Platform
---
# Security & Audit Workflow
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
- Documentation of system architecture
- List of third-party dependencies
- Smart contract source code
- Circom circuit source code
- Budget for third-party security audit (if applicable)
## Steps
### 1. Professional Third-Party Security Audit
1. **Select security audit firm**
- Research reputable blockchain security firms
- Evaluate expertise in: smart contracts, ZK proofs, zero-knowledge systems
- Compare pricing and timelines
- Check references and past audits
2. **Prepare audit scope**
- Define components to audit:
- Smart contracts (Solidity)
- ZK circuits (Circom)
- Coordinator API (Python/FastAPI)
- Blockchain node (Python)
- Wallet daemon (Python)
- Define audit timeline and deliverables
- Prepare architecture documentation
- Provide threat model documentation
3. **Engage audit firm**
- Sign NDAs and contracts
- Provide access to code repositories
- Schedule kickoff meeting
- Define communication channels
4. **Review audit findings**
- Receive audit report
- Categorize findings by severity (Critical, High, Medium, Low)
- Review each finding with engineering team
- Estimate remediation effort
5. **Implement security fixes**
- Create issue tickets for each finding
- Prioritize Critical and High findings
- Implement fixes with proper testing
- Document remediation steps
6. **Re-audit**
- Submit fixed code for re-audit
- Verify all findings are resolved
- Obtain final audit report
- Publish audit summary (if appropriate)
### 2. Circom Circuit Security Review
1. **Circuit code review**
- Review all Circom circuits in `apps/zk-circuits/`
- Check for common vulnerabilities:
- Arithmetic overflow/underflow
- Incorrect constraint definitions
- Side-channel attacks
- Privacy leaks
- Verify circuit correctness with test vectors
2. **Constraint analysis**
- Analyze constraint complexity
- Check for unnecessary constraints
- Verify witness generation correctness
- Test circuit with edge cases
3. **Proving system review**
- Review Groth16 proving key generation
- Verify trusted setup ceremony process
- Check verification key security
- Test proof generation and verification
4. **Performance optimization**
- Analyze circuit size and proving time
- Optimize constraint count
- Implement circuit caching
- Benchmark proving performance
### 3. ZK Proof Implementation Audit
1. **API endpoint security**
- Review ZK proof endpoints in coordinator API
- Check input validation
- Verify proof verification logic
- Test with malicious inputs
2. **Circuit integration review**
- Review integration of Circom circuits with Python
- Check witness generation security
- Verify proof serialization/deserialization
- Test proof verification pipeline
3. **Privacy verification**
- Verify zero-knowledge properties
- Check that sensitive data is not leaked
- Test with privacy-sensitive scenarios
- Verify confidentiality guarantees
4. **Error handling**
- Review error messages for information leaks
- Test error paths
- Verify graceful degradation
- Check logging sensitivity
### 4. Token Economy and Attack Vector Review
**COMPLETED** (2026-05-11)
1. **Economic model analysis**
- ✅ 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**
- ✅ Reviewed staking mechanisms
- ✅ Checked reward distribution logic
- ✅ Verified slashing conditions
- ✅ Analyzed governance token economics
3. **Market manipulation prevention**
- ✅ Reviewed marketplace pricing mechanisms
- ✅ Checked for oracle manipulation risks
- ✅ Verified liquidity protection
- ✅ Analyzed arbitrage opportunities
4. **Game theory analysis**
- ✅ 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
1. **Create security findings document**
- Document: `docs/security/audit-findings.md`
- Structure by component and severity
- Include: description, impact, remediation, status
- Track remediation progress
2. **Create remediation plan**
- Prioritize findings by severity
- Assign owners and timelines
- Create issue tickets
- Track progress in project management tool
3. **Implement fixes**
- Fix Critical findings first
- Add comprehensive tests for fixes
- Perform regression testing
- Update documentation
4. **Security hardening**
- Implement defense in depth
- Add additional security layers
- Improve monitoring and alerting
- Update security policies
5. **Post-audit improvements**
- Update development practices
- Add security testing to CI/CD
- Implement security training
- Establish security review process
## Verification
- [ ] Third-party audit firm selected and engaged
- [ ] Audit scope defined and documented
- [ ] Circom circuits reviewed and optimized
- [ ] ZK proof implementation audited
- [ ] Token economy analyzed for attack vectors
- [ ] Security findings documented
- [ ] Critical and High findings remediated
- [ ] Re-audit completed and findings resolved
- [ ] Security hardening implemented
- [ ] Security practices updated
## Troubleshooting
- **Audit firm unavailable**: Expand search to include more firms, consider remote audit firms
- **Circuit review finds issues**: Consult Circom community, review best practices, consider circuit redesign
- **Economic model vulnerabilities**: Consult economic experts, consider simulation testing, adjust incentives
- **Remediation blocked**: Escalate to management, prioritize critical fixes, consider temporary mitigations
## Related Files
**Source Code:**
- `apps/zk-circuits/*.circom`
- `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

@@ -1,314 +0,0 @@
---
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

@@ -1,454 +0,0 @@
---
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