2. Security & IntegritySecurity & Integrity

2. Security & Integrity

The Fhenix-FairMarket protocol operates on a foundational security philosophy: “Trust in cryptographic proof, not in intermediaries.” Every architectural decision prioritizes mathematical privacy, economic finality, and capital preservation. The system implements a defense-in-depth strategy across cryptographic, economic, and operational layers, ensuring resilience against MEV extraction, sequencer failures, oracle manipulation, and smart contract vulnerabilities.

Version 2.0 replaces traditional trust assumptions with verifiable, mathematically bounded mechanisms, enforced through strict audit gates and zero-tolerance security policies at the CI/CD level.


2.1. Fully Homomorphic Encryption (FHE)

FHE forms the cryptographic bedrock of the protocol, enabling bid comparisons and settlement logic without ever decrypting sensitive values on-chain.

Core Implementation

  • Client-Side Encryption: Bids are encrypted locally using @cofhe/sdk ^1.2.0 before transmission. The plaintext value never traverses the network or enters the mempool.
  • Constant-Time Execution: Off-chain FHEOS coprocessors utilize FHE.select multiplexers, ensuring execution clocks remain identical regardless of input magnitude. This neutralizes timing side-channel attacks.
  • Solvency Pre-Validation: Before accepting a bid, the contract runs an encrypted solvency gate: FHE.lte(encryptedBid, FHE.asEuint32(escrowBalances[msg.sender])). Invalid bids revert instantly without consuming coprocessor resources or leaking balance information.

Security Guarantees

ThreatMitigation
Mempool Sniping / MEVBids arrive as opaque ciphertexts; validators cannot reorder or front-run based on value
Plaintext LeakageZero bid values in Events, Storage, or console.log; enforced by CI lint rules
SDK Version BreakageAll FHE calls routed through CofheAdapter.sol, isolating core logic from external library updates

2.2. O(1) On-chain Storage

Traditional FHE implementations store full ciphertext arrays on-chain, causing exponential gas growth and bloated state. Fhenix-FairMarket v2.0 enforces a strict O(1) storage model.

Technical Enforcement

  • Hash-Only Persistence: Only a bytes32 keccak256 hash of the ciphertext is pushed to ciphertextHashes[auctionId]. The full FHE object is never persisted.
  • State Decoupling: Heavy homomorphic operations (FHE.gt, FHE.select) are executed off-chain via DecryptionRequested events. The L2 chain acts solely as an immutable ledger and event broadcaster.
  • Gas Predictability: Each placeBid() transaction consumes a flat ~15k–25k gas, independent of auction size or bid count.

Architectural Impact

// Only hash stored. No FHE evaluation, no decryption, no loops.
ciphertextHashes[auctionId].push(keccak256(abi.encode(encryptedBid)));
emit BidPlaced(auctionId, msg.sender, keccak256(abi.encode(encryptedBid)));

This design ensures linear scalability, prevents state bloat, and eliminates gas-based DoS vectors during high-volume settlement windows.


2.3. Pull over Push Refund Pattern

Automated distribution (Push) of refunds to non-winning bidders introduces severe risks: Out-of-Gas (OOG) failures, reentrancy vulnerabilities, and cascading state rollbacks. The protocol mandates a Pull-based Settlement model.

Implementation Logic

  • State Update Precedence: hasWithdrawn[msg.sender] is set to true before the external call{value: amount} executes.
  • Individual Claim Path: Each participant invokes claimRefund() independently. The contract verifies eligibility, updates state, and releases funds.
  • Zero Loop Dependency: Refund distribution contains no for/while loops, ensuring transaction success is deterministic and immune to participant count.
function claimRefund(uint256 _auctionId) external {
 require(state == FINALIZED || state == CANCELLED || state == VOIDED);
 require(!hasWithdrawn[msg.sender]);
 
 uint256 amount = escrowBalances[msg.sender];
 escrowBalances[msg.sender] = 0;
 hasWithdrawn[msg.sender] = true; // State updated BEFORE transfer
 
 (bool success, ) = msg.sender.call{value: amount}("");
 require(success);
}

Security Benefits

  • Reentrancy Immunity: State mutation precedes value transfer, breaking classic reentrancy attack vectors.
  • OOG Elimination: No single transaction bears the gas burden of mass payouts. Failed claims do not block others.
  • Idempotency: hasWithdrawn mapping prevents double-claiming even under network retries or UI glitches.

2.4. Dynamic Dead Man’s Switch

Fixed timeouts are vulnerable to sequencer downtime, network congestion, and L2 rollup halts. The protocol replaces static deadlines with a Dynamic Dead Man’s Switch based on network volatility.

Technical Implementation

  • Moving Time Average: The resolution timeout is calculated dynamically: avgBlockTime = block.timestamp - lastBlockTimestamp. The threshold auto-adjusts using a 1.5x self-compensating factor.
  • Automatic Void Transition: If block.timestamp exceeds endTime + _getResolutionTimeout() without a valid AVS resolution, triggerFallbackVoid() executes automatically.
  • Full Liquidity Recovery: The auction transitions to VOIDED, the FHE engine is disabled, and 100% of escrowed funds are unlocked for immediate pull-refund.
function _getResolutionTimeout() internal view returns (uint256) {
 uint256 avgBlockTime = block.timestamp - lastBlockTimestamp;
 return avgBlockTime * 1.5; // Network volatility-aware threshold
}

Resilience Guarantees

  • Sequencer Failure Tolerance: Automatically activates during L2 outages, preventing indefinite fund lockup.
  • No Manual Intervention: Void execution is deterministic and permissionless; no admin keys required.
  • Funds Over Privacy: In extremis, capital recovery takes precedence over cryptographic settlement.

2.5. Fraud Proofs & Slashing

Replacing computationally expensive ZK-circuits, the protocol leverages EigenLayer Actively Validated Services (AVS) for decentralized, cryptoeconomic verification.

Verification Pipeline

  1. Threshold Consensus: Off-chain operators cryptographically sign the FHEOS result. submitResolution() only accepts the output once a quorum (e.g., 3/5) is reached.
  2. On-Chain Proof Verification: The smart contract cryptographically validates the aggregated avsProof before transitioning state to FINALIZED.
  3. Fraud Proof Challenge Window: Permissionless verifiers can submit a Fraud Proof if the aggregated signature mismatches the actual FHE computation.
  4. Automatic Slashing: Validated fraud triggers the EigenLayer slashing contract. Operator stake is deducted and routed to SlashedPot.sol for pro-rata user compensation.

Economic Security Model

ComponentRoleEnforcement
AVS OperatorsProvide decentralized verificationMust stake ETH/LSTs via EigenLayer
Fraud ProofsValidate off-chain resultsPermissionless challenge mechanism
SlashingPenalize collusion/incorrectnessAutomatic stake deduction to SlashedPot
On-Chain VerifierAccepts only valid proofsReverts on cryptographic mismatch

This model ensures fast finality, linear scalability, and robust economic alignment without heavy computational overhead.


2.6. Collateral-Pegged Escrow

The protocol enforces a Dummy Ceiling Deposit model to guarantee bid solvency and deter malicious spam without exposing actual bid values.

Mechanism

  • Public Escrow Lock: Bidders invoke lockEscrow() to deposit a publicly visible maximum ceiling (e.g., 5 ETH).
  • Encrypted Bid Validation: placeBid() runs FHE.lte(encryptedBid, escrowBalances[msg.sender]). If the encrypted value exceeds the public deposit, the transaction reverts.
  • NFTGuard Integration: During ACTIVE state, NFTGuard.sol locks the seller’s asset. Transfer is blocked until FINALIZED, CANCELLED, or VOIDED.
  • Cancellation Penalty: If a seller cancels an active auction (cancelAuction()), their deposit is confiscated and distributed pro-rata to bidders via SlashedPot.sol. The platform takes zero cut from penalties.

Security & Economic Alignment

  • Spam Mitigation: Requires upfront capital, eliminating sybil bidding and gas-wasting spam.
  • Seller Accountability: Financial penalty for withdrawal deters shill bidding and market manipulation.
  • Capital Preservation: All escrowed funds remain under user control until settlement, with automatic recovery paths on failure.

️ Threat Matrix & Mitigations

ThreatAttack VectorProtocol Mitigation
Bid Value LeakEvent emitting plaintext or storage exposureOnly bytes32 ciphertext hashes in Events/Storage; enforced by CI linting
Reentrancy in RefundclaimRefund() called before state updatehasWithdrawn set to true before call{value: amount}
Session Key TheftlocalStorage key cachingERC-4337 Ephemeral Keys (24h TTL, memory/Web Crypto only)
Sequencer ManipulationExploiting fixed timeout windowsMoving Time Average × 1.5 dynamic threshold
Fake AVS ResultCorrupt operator output or collusionEigenLayer Fraud Proof required before submitResolution()
Keeper Race ConditionMultiple keepers competing for closurenonce/blockhash gating + Redis distributed locks
Gas Exhaustion (DoS)Push-based payout loopsBatch queue max 10/block; all refunds are Pull-based
Upgrade ManipulationUnauthorized proxy upgradeUUPSUpgradeable + 48h Timelock + 5/9 Multisig

Emergency Protocol: Funds Over Privacy

In case of critical @cofhe/sdk vulnerability, EigenLayer network failure, or prolonged coprocessor outage, EmergencyHalt activates automatically or via multisig:

  1. Freeze FHE Engine: New encryption and bid submissions are permanently blocked.
  2. Open Public Refund Path: claimRefund() bypasses AVS verification, allowing immediate capital recovery.
  3. Return NFT to Seller: NFTGuard unlocks and transfers assets back to the original owner.
  4. Emit EmergencyHaltActivated: Full on-chain transparency for auditors and users.

Principle: Funds are protected before privacy in extreme emergency conditions.


Audit Readiness & P0 Checklist

The protocol enforces a strict Priority Classification for all security items. Progression to the next development phase is blocked until all P0 items pass.

PriorityDescriptionCriteria
P0Security-criticalMust be complete before any deployment
P1High importanceMust be complete before Mainnet launch
P2EnhancementTarget for v2.1 optimization

Mandatory P0 Verification Checklist

  • [] UUPS Proxy isolation — zero logic in storage contract, unauthorized upgrades revert
  • [] CofheAdapter abstraction — zero direct FHE imports in core contracts
  • [] State machine exhaustive — all 6 states reachable, no unauthorized transitions
  • [] FHE.lte solvency check — encrypted bid never exceeds escrowBalances[msg.sender]
  • [] Pull refund pattern — zero for/while loops in any payout function
  • [] Dynamic timeout — Moving Time Average not hardcoded; adapts to network conditions
  • [] triggerFallbackVoid() — 100% liquidity recovery on activation
  • [] No plaintext bids — zero bid values in Events or Storage (CI enforced)
  • [] AVS Fraud Proof — submitResolution() rejects without valid cryptographic proof
  • [] ERC-4337 session keys — no localStorage or cookie storage (ESLint rule enforced)
  • [] Sequential deployment — Adapters → Proxy → Factory ordering guaranteed
  • [] Environment secrets — zero keys in hardhat.config.ts or next.config.js

Next Steps

  • Proceed to 3. Market Mechanics to explore sealed-bid workflows, Vickrey pricing, and MEV protection.
  • Review Technical Components for contract-level references, function signatures, and deployment architecture.
  • Explore Developer Quickstart to run local security simulations and audit readiness tests.