Skip to content

Security: BuildsWithKing/ethos-reputation-launch

Security

docs/SECURITY.md

Security Considerations

Overview

This document outlines the security architecture, potential vulnerabilities, and mitigation strategies for the Ethos Reputation Launch system. While this is a hackathon project demonstrating reputation-gated NFT launches, it implements professional security patterns and best practices.


Table of Contents


Security Model

The system operates under a trust-minimized but not trustless model:

  • Onchain logic is trustless (immutable smart contracts)
  • Oracle component requires trust (king/admin sets scores)
  • Emergency recovery requires trust (king can transfer NFTs)

This hybrid model balances hackathon simplicity with reasonable security for a demonstration system.


Trust Assumptions

Centralized Components

Users must trust:

  1. King (Contract Owner)

    • Will not set malicious reputation scores
    • Will only use emergency NFT transfer for legitimate recovery
    • Will not pause contracts arbitrarily
    • Will not abuse admin privileges
  2. Admin (Score Setter)

    • Will accurately fetch scores from Ethos API
    • Will not manipulate scores for personal gain
    • Will set scores in timely manner

Decentralized Components

Users do NOT need to trust:

  1. Smart Contract Logic

    • Minting rules are enforced programmatically
    • Tier calculations are deterministic
    • Token claims are guaranteed for NFT holders
    • Soulbound property is enforced by code
  2. Immutability

    • Contracts cannot be upgraded
    • Rules cannot be changed after deployment
    • Tier thresholds are fixed at deployment

Security Features

1. Reentrancy Protection

Implementation: KingReentrancyGuard module

Protected Functions:

  • ReputationNFT.mint()
  • ReputationToken.claimTokens()

How it works:

    /// @dev Restricts a function from being reentered.
    modifier nonReentrant() {
        // Revert if locked.
        if (s_isLocked) {
            revert NoReentrant();
        }

        // Lock before executing the function.
        s_isLocked = true;
        _;

        // Unlock after the execution.
        s_isLocked = false;
    }

Prevents:

  • Recursive calls draining funds
  • State manipulation via callback attacks

Test Coverage:

// Tested with malicious contracts attempting reentrancy
// All attempts properly blocked

2. Access Control

Implementation: Kingable and role-based permissions

Role Hierarchy:

King (Full Control)
├── Can pause/unpause contracts
├── Can set reputation scores
├── Can transfer NFTs (emergency recovery)
├── Can update reward amounts
└── Can assign/revoke admin role

Admin (Limited Control)
├── Can set reputation scores
└── Cannot pause or transfer NFTs

Users (No Admin Rights)
├── Can mint NFTs (if eligible)
├── Can claim tokens (if NFT owner)
└── Cannot transfer NFTs (soulbound)

Function Access Matrix:

Function King Admin User
setEthosScore()
transferFrom() (NFT)
pauseContract()
setTiersClaimableTokens()
mint() ✓ (if eligible)
claimTokens() ✓ (if owner)

3. Emergency Pause

Implementation: KingablePausable module

Pausable Contracts:

  • ReputationNFT (can pause minting)
  • ReputationToken (can pause claiming)

Usage:

// Pause minting
function pauseContract() external onlyKing {
    // Call the internal `_pause` function.
    _pause();
}

// Resume minting
function activateContract() external onlyKing {
    // Call the internal `_activate` function.
    _activate();
}

When to use:

  • Critical vulnerability discovered
  • Oracle compromise detected
  • Suspicious activity observed
  • Planned maintenance

Important: Pausing does NOT affect:

  • NFT ownership (users still own their NFTs)
  • Token balances (claimed tokens remain)
  • View functions (data still readable)

4. Input Validation

Zero Address Checks:

// Via KingCheckAddressLib
KingCheckAddressLib.ensureNonZero(address);

Applied to:

  • Contract constructor parameters
  • Function arguments expecting addresses

Array Length Validation:

// In setEthosScoreBatch
if (users.length != scores.length) {
    revert EthosIntegration__LengthMisMatch();
}

Tier Threshold Validation:

// In TierManager
// Check: silver tier must be greater than the minimum
if (silver_ <= minimum_) {
    revert TierManager__InvalidSilverThreshold();
}

// Check: gold tier must be greater than the silver tier
if (gold_ <= silver_) {
    revert TierManager__InvalidGoldThreshold();
}

Prevents:

  • Locking funds in zero address
  • Array mismatch attacks
  • Invalid configuration states

5. Soulbound Enforcement

Implementation: Override all ERC721 transfer functions

Code:

function transferFrom(address from, address to, uint256 tokenId) 
    public virtual override 
{
    if(msg.sender == s_king) {
        _transfer(from, to, tokenId);  // Emergency recovery
    } else {
        revert ReputationNFT__TokenIsSoulbound();
    }
}

Security Implications:

  • Users cannot sell/transfer NFTs
  • Prevents multi-wallet farming
  • King maintains emergency transfer capability
  • No marketplace compatibility (intentional)

Test Coverage:

// All transfer attempts by non-king addresses revert
// King transfers succeed (for emergency recovery)

6. One-Time Claims

Implementation: Mapping tracks claim status

Code:

mapping(address => bool) public s_hasClaimed;

function claimTokens(uint256 nftId) external {
    // Check: One-time claim only.
    if (s_hasClaimed[msg.sender]) {
        revert ReputationToken__AlreadyClaimed();
    }
    // ... mint tokens
}

Prevents:

  • Double-spending tokens
  • Infinite minting exploits

Edge Case Handling:

  • NFT transfer after claim doesn't grant new claim
  • New owner of transferred NFT cannot claim (original minter already claimed)

Known Limitations

Hackathon Version Limitations

  1. Centralized Oracle ⚠️

    • Issue: King/admin manually sets scores
    • Risk: Malicious/incorrect score setting
    • Mitigation: Trust assumption on king/admin
    • Production Fix: Chainlink Functions or UMA oracle
  2. No Score Refresh ⚠️

    • Issue: Tier locked at mint, never updates
    • Risk: Users keep tier even if reputation drops
    • Mitigation: Snapshot-based design (intentional)
    • Production Fix: Optional tier refresh mechanism
  3. No Burning ⚠️

    • Issue: NFTs cannot be destroyed
    • Risk: Permanent association with wallet
    • Mitigation: Emergency transfer by king
    • Production Fix: Add burning function
  4. Single Admin ⚠️

    • Issue: Admin is single point of failure
    • Risk: Admin key compromise or loss
    • Mitigation: Trust assumption
    • Production Fix: Multi-sig for admin operations
  5. No Upgrade Path ⚠️

    • Issue: Contracts are immutable
    • Risk: Cannot fix bugs post-deployment
    • Mitigation: Thorough testing pre-deployment
    • Production Fix: UUPS proxy pattern

Potential Attack Vectors

1. Oracle Manipulation

Attack: Malicious admin sets fake high scores for accomplices.

Impact:

  • Undeserving users mint NFTs
  • Illegitimate token claims
  • System integrity compromised

Likelihood: Medium (requires admin compromise)

Mitigations:

  • Trust assumption on admin
  • Event emissions allow public monitoring
  • Production: Multi-sig required for score setting
  • Production: Delay + dispute period

Detection:

// Monitor ScoreUpdated events
event ScoreUpdated(address indexed user, uint256 score);

2. King Compromise

Attack: King's private key is stolen.

Impact:

  • Attacker can pause contracts
  • Attacker can transfer all NFTs
  • Attacker can set arbitrary scores
  • Complete system takeover

Likelihood: Low (depends on key security)

Mitigations:

  • Hardware wallet for king
  • Multi-sig wallet in production
  • Time-locks on critical operations
  • Emergency recovery procedures

If Detected:

  1. Deploy new contracts immediately
  2. Announce compromise publicly
  3. Assist users with migration
  4. Investigate root cause

3. Score Gaming

Attack: User temporarily boosts Ethos score, mints NFT, then drops score.

Impact:

  • User gains tier benefits without maintaining reputation
  • Undermines system fairness

Likelihood: Medium (depends on Ethos score mechanics)

Mitigations:

  • Current: Snapshot-based design (tier locked at mint)
  • Production: Time-weighted average scores
  • Production: Reputation decay mechanism
  • Production: Periodic tier verification

4. Frontrunning

Attack: Attacker observes score-setting transaction in mempool, frontruns mint.

Impact:

  • Minimal (score must be set anyway)
  • User still gets NFT
  • No financial loss

Likelihood: Low (no real incentive)

Mitigations:

  • Public minting (no advantage to frontrun)
  • No price discovery (fixed tiers)
  • Mempool privacy in production (Flashbots)

5. Grief Attacks

Attack: Malicious admin sets score = 799 for victim (just below minimum).

Impact:

  • Victim cannot mint NFT
  • Requires legitimate score update

Likelihood: Low (requires malicious admin)

Mitigations:

  • Trust assumption on admin
  • Event monitoring detects suspicious scores
  • King can override admin score
  • Production: Multi-sig prevents single admin grief

6. Integer Overflow/Underflow

Attack: Manipulate arithmetic to overflow/underflow variables.

Impact:

  • Could bypass checks
  • Could mint incorrect amounts

Likelihood: Very Low (Solidity ^0.8.0 has built-in checks)

Mitigations:

  • Solidity ^0.8.30 (automatic checks)
  • Unchecked only where safe (loop increments)
  • Extensive test coverage

Test Coverage:

// All arithmetic operations tested
// Boundary conditions verified
// No unchecked blocks except safe loop increments

Mitigation Strategies

Current Mitigations

  1. Custom Errors - Gas-efficient, clear error messages
  2. Reentrancy Guards - On all state-changing functions
  3. Access Control - Role-based permissions
  4. Pausability - Emergency stop mechanism
  5. Input Validation - Comprehensive checks
  6. Event Emission - Transparent on-chain logging
  7. Immutability - No upgrade risk
  8. Test Coverage - 98.71% line coverage

Production Recommendations

  1. Multi-Sig Governance

    // Use Gnosis Safe or similar
    address king = 0xGnosisSafeAddress;
  2. Chainlink Oracle Integration

    // Decentralized score fetching
    function requestScore(address user) external {
        bytes32 requestId = sendChainlinkRequest(...);
    }
  3. Time-Locks

    // Add delay to critical operations
    function setEthosScore(...) external onlyKing {
        require(block.timestamp >= unlockTime, "Timelocked");
        // ...
    }
  4. Rate Limiting

    // Prevent spam attacks
    mapping(address => uint256) lastMintTime;
    require(block.timestamp - lastMintTime[user] >= COOLDOWN);
  5. Professional Audit

    • Trail of Bits
    • OpenZeppelin
    • Consensys Diligence

Audit Findings

Status: No professional audit conducted (hackathon project)

Self-Audit Results:

  • ✅ No critical vulnerabilities found
  • ✅ All reentrancy risks mitigated
  • ✅ Access control properly implemented
  • ✅ Input validation comprehensive
  • ⚠️ Centralization risks documented

Test Coverage: 98.71%

Recommended Actions:

  • Professional audit before mainnet
  • Bug bounty program
  • Formal verification for critical functions

Emergency Procedures

Scenario 1: Critical Vulnerability Discovered

Immediate Actions:

  1. Pause all contracts (pauseContract())
  2. Announce on official channels
  3. Document the vulnerability
  4. Develop fix
  5. Test extensively
  6. Deploy new contracts
  7. Assist with migration

Communication Template:

CRITICAL SECURITY UPDATE

We have discovered a vulnerability in [contract name].
All operations have been paused.
User funds are SAFE.
Migration plan will be announced within 24 hours.
Updates: [link]

Scenario 2: Oracle Compromise

Immediate Actions:

  1. Revoke admin permissions (assignAdmin(newAdmin))
  2. Pause score-dependent operations
  3. Audit recent score updates
  4. Identify affected users
  5. Deploy new EthosIntegration contract
  6. Re-set legitimate scores
  7. Resume operations

Recovery Steps:

// 1. Remove compromised admin
ethosIntegration.assignAdmin(newAdmin);

// 2. Deploy new integration
EthosIntegration newIntegration = new EthosIntegration(king, newAdmin);

// 3. Deploy new NFT pointing to new integration
ReputationNFT newNFT = new ReputationNFT(..., address(newIntegration), ...);

Scenario 3: Mass User Wallet Loss

Immediate Actions:

  1. Verify legitimate wallet loss (not theft)
  2. Confirm new wallet ownership
  3. Use king emergency transfer
  4. Document all transfers
  5. Announce publicly

Transfer Process:

// King transfers NFT from lost wallet to new wallet
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
    // Check if the caller is the king.
    if (msg.sender == s_king) {
        _transfer(from, to, tokenId);
    } else {
        revert ReputationNFT__TokenIsSoulbound();
    }

Security Best Practices for Users

  1. Wallet Security

    • Use hardware wallet if possible
    • Never share private keys
    • Backup seed phrases securely
    • Verify contract addresses
  2. Transaction Safety

    • Always verify contract address before interacting
    • Check transaction details before signing
    • Start with small test transactions
    • Confirm on block explorer
  3. Awareness

    • Understand soulbound property (cannot transfer)
    • Know that tier is locked at mint
    • Recognize official communication channels
    • Report suspicious activity

Security Best Practices for Administrators

  1. Key Management

    • Use hardware wallet for king/admin
    • Never expose private keys
    • Rotate keys periodically
    • Use multi-sig in production
  2. Score Setting

    • Verify scores from official Ethos API
    • Double-check addresses before setting
    • Use batch operations when possible
    • Monitor for anomalies
  3. Monitoring

    • Watch for unusual mint patterns
    • Monitor score update events
    • Track contract interactions
    • Alert on suspicious activity
  4. Incident Response

    • Have pause procedures ready
    • Document all emergency actions
    • Communicate transparently
    • Preserve evidence for investigation

Code Review Checklist

Before deployment, verify:

  • All functions have appropriate access control
  • All state-changing functions have reentrancy guards
  • All inputs are validated
  • All addresses are checked for zero
  • All events are emitted correctly
  • All errors are handled properly
  • No hardcoded addresses
  • No TODO comments in production code
  • Test coverage above 95%
  • No unchecked arithmetic except safe cases
  • All dependencies are latest stable versions
  • Deployment scripts are tested
  • Emergency procedures documented

Reporting Security Issues

Please DO NOT open public GitHub issues for security vulnerabilities.

Instead, report via:

Include:

  • Description of vulnerability
  • Steps to reproduce
  • Potential impact
  • Suggested fix (if any)

Response Time:

  • Critical: < 24 hours
  • High: < 48 hours
  • Medium: < 1 week
  • Low: < 2 weeks

Bug Bounty Not Available


Security Roadmap

Phase 1: Pre-Deployment (Current)

  • Comprehensive test suite
  • Self-audit completed
  • Known limitations documented
  • Community review period
  • Final security checklist

Phase 2: Post-Hackathon

  • External code review
  • Formal verification of critical functions
  • Bug bounty program
  • Incident response plan
  • Monitoring infrastructure

Phase 3: Production Preparation

  • Professional security audit
  • Multi-sig implementation
  • Chainlink oracle integration
  • Time-locks on critical functions
  • Upgrade mechanism (if needed)

Additional Resources


Remember: Security is a continuous process, not a one-time check. Stay vigilant, keep learning, and always prioritize user safety.

There aren't any published security advisories