ZKMiningControllerSimple

Description:

Multi-signature wallet contract requiring multiple confirmations for transaction execution.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "sources": {
    "src/ZKMiningControllerSimple.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";

/**
 * @title ZK Mining Controller (Simplified)
 * @dev ZK-Proof based mining controller with reward distribution
 * @author ZKAEDI Team
 */
contract ZKMiningControllerSimple is Ownable, ReentrancyGuard, Pausable {
    // Mining session structure
    struct MiningSession {
        uint256 sessionId;
        address miner;
        uint256 startTime;
        uint256 endTime;
        uint256 blocksMined;
        uint256 rewardsEarned;
        uint256 difficulty;
        bool completed;
        string algorithm;
    }
    
    // ZK Proof structure
    struct ZKProof {
        bytes32 proofHash;
        uint256 blockNumber;
        address miner;
        uint256 timestamp;
        uint256 difficulty;
        bool verified;
        string algorithm;
    }
    
    // Mining statistics
    struct MinerStats {
        uint256 totalBlocks;
        uint256 totalRewards;
        uint256 totalSessions;
        uint256 averageDifficulty;
        uint256 lastMiningTime;
    }
    
    // State variables
    uint256 public totalRewards;
    uint256 public totalBlocks;
    uint256 public currentDifficulty;
    uint256 public rewardPerBlock;
    uint256 public sessionCounter;
    uint256 public constant MAX_DIFFICULTY = 1000000;
    uint256 public constant MIN_DIFFICULTY = 100;
    
    // Mappings
    mapping(address => uint256) public minerRewards;
    mapping(address => uint256) public minerBlocks;
    mapping(address => uint256) public minerSessions;
    mapping(address => MinerStats) public minerStats;
    mapping(uint256 => MiningSession) public sessions;
    mapping(bytes32 => ZKProof) public proofs;
    mapping(string => bool) public supportedAlgorithms;
    
    // Events
    event BlockMined(address indexed miner, uint256 blockNumber, uint256 reward, string algorithm);
    event RewardClaimed(address indexed miner, uint256 amount);
    event MiningSessionStarted(uint256 indexed sessionId, address indexed miner, string algorithm);
    event MiningSessionCompleted(uint256 indexed sessionId, address indexed miner, uint256 blocks, uint256 rewards);
    event ZKProofSubmitted(bytes32 indexed proofHash, address indexed miner, uint256 blockNumber, string algorithm);
    event DifficultyUpdated(uint256 oldDifficulty, uint256 newDifficulty);
    event RewardPerBlockUpdated(uint256 oldReward, uint256 newReward);
    event AlgorithmAdded(string algorithm);
    event AlgorithmRemoved(string algorithm);
    
    constructor() Ownable(msg.sender) {
        currentDifficulty = 1000;
        rewardPerBlock = 2 ether; // 2 ETH per block
        
        // Add supported algorithms
        supportedAlgorithms["SHA256"] = true;
        supportedAlgorithms["ZK-SNARK"] = true;
        supportedAlgorithms["Quantum-Resistant"] = true;
        supportedAlgorithms["Multi-Domain"] = true;
    }
    
    /**
     * @dev Submit ZK proof for block mining
     * @param proofHash Hash of the ZK proof
     * @param blockNumber Block number being mined
     * @param algorithm Mining algorithm used
     */
    function submitProof(bytes32 proofHash, uint256 blockNumber, string memory algorithm) 
        external 
        whenNotPaused 
        nonReentrant 
    {
        require(blockNumber > totalBlocks, "Invalid block number");
        require(!proofs[proofHash].verified, "Proof already verified");
        require(supportedAlgorithms[algorithm], "Unsupported algorithm");
        
        // Verify ZK proof (simplified for demo)
        require(_verifyZKProof(proofHash, blockNumber, msg.sender, algorithm), "Invalid ZK proof");
        
        totalBlocks = blockNumber;
        uint256 reward = calculateReward(algorithm);
        
        minerRewards[msg.sender] += reward;
        minerBlocks[msg.sender] += 1;
        totalRewards += reward;
        
        // Update miner stats
        MinerStats storage stats = minerStats[msg.sender];
        stats.totalBlocks += 1;
        stats.totalRewards += reward;
        stats.averageDifficulty = (stats.averageDifficulty + currentDifficulty) / 2;
        stats.lastMiningTime = block.timestamp;
        
        proofs[proofHash] = ZKProof({
            proofHash: proofHash,
            blockNumber: blockNumber,
            miner: msg.sender,
            timestamp: block.timestamp,
            difficulty: currentDifficulty,
            verified: true,
            algorithm: algorithm
        });
        
        emit BlockMined(msg.sender, blockNumber, reward, algorithm);
        emit ZKProofSubmitted(proofHash, msg.sender, blockNumber, algorithm);
    }
    
    /**
     * @dev Start a new mining session
     * @param algorithm Mining algorithm to use
     * @return sessionId The session ID
     */
    function startMiningSession(string memory algorithm) 
        external 
        whenNotPaused 
        returns (uint256) 
    {
        require(supportedAlgorithms[algorithm], "Unsupported algorithm");
        
        sessionCounter += 1;
        uint256 sessionId = sessionCounter;
        
        sessions[sessionId] = MiningSession({
            sessionId: sessionId,
            miner: msg.sender,
            startTime: block.timestamp,
            endTime: 0,
            blocksMined: 0,
            rewardsEarned: 0,
            difficulty: currentDifficulty,
            completed: false,
            algorithm: algorithm
        });
        
        minerSessions[msg.sender] += 1;
        minerStats[msg.sender].totalSessions += 1;
        
        emit MiningSessionStarted(sessionId, msg.sender, algorithm);
        
        return sessionId;
    }
    
    /**
     * @dev Complete a mining session
     * @param sessionId Session ID to complete
     * @param blocksMined Number of blocks mined
     */
    function completeMiningSession(uint256 sessionId, uint256 blocksMined) 
        external 
        whenNotPaused 
    {
        require(sessions[sessionId].miner == msg.sender, "Not your session");
        require(!sessions[sessionId].completed, "Session already completed");
        
        uint256 rewards = blocksMined * calculateReward(sessions[sessionId].algorithm);
        
        sessions[sessionId].endTime = block.timestamp;
        sessions[sessionId].blocksMined = blocksMined;
        sessions[sessionId].rewardsEarned = rewards;
        sessions[sessionId].completed = true;
        
        minerRewards[msg.sender] += rewards;
        minerBlocks[msg.sender] += blocksMined;
        totalRewards += rewards;
        totalBlocks += blocksMined;
        
        // Update miner stats
        MinerStats storage stats = minerStats[msg.sender];
        stats.totalBlocks += blocksMined;
        stats.totalRewards += rewards;
        stats.lastMiningTime = block.timestamp;
        
        emit MiningSessionCompleted(sessionId, msg.sender, blocksMined, rewards);
    }
    
    /**
     * @dev Claim mining rewards
     */
    function claimRewards() external nonReentrant {
        uint256 amount = minerRewards[msg.sender];
        require(amount > 0, "No rewards to claim");
        require(address(this).balance >= amount, "Insufficient contract balance");
        
        minerRewards[msg.sender] = 0;
        payable(msg.sender).transfer(amount);
        
        emit RewardClaimed(msg.sender, amount);
    }
    
    /**
     * @dev Calculate reward based on algorithm
     * @param algorithm Mining algorithm
     * @return reward Calculated reward
     */
    function calculateReward(string memory algorithm) public view returns (uint256) {
        uint256 baseReward = rewardPerBlock;
        
        // Algorithm-specific multipliers
        if (keccak256(bytes(algorithm)) == keccak256(bytes("ZK-SNARK"))) {
            return baseReward * 150 / 100; // 1.5x for ZK-SNARK
        } else if (keccak256(bytes(algorithm)) == keccak256(bytes("Quantum-Resistant"))) {
            return baseReward * 200 / 100; // 2x for Quantum-Resistant
        } else if (keccak256(bytes(algorithm)) == keccak256(bytes("Multi-Domain"))) {
            return baseReward * 175 / 100; // 1.75x for Multi-Domain
        }
        
        return baseReward; // Default for SHA256
    }
    
    // Admin functions
    function updateDifficulty(uint256 newDifficulty) external onlyOwner {
        require(newDifficulty >= MIN_DIFFICULTY && newDifficulty <= MAX_DIFFICULTY, "Invalid difficulty");
        uint256 oldDifficulty = currentDifficulty;
        currentDifficulty = newDifficulty;
        emit DifficultyUpdated(oldDifficulty, newDifficulty);
    }
    
    function updateRewardPerBlock(uint256 newReward) external onlyOwner {
        uint256 oldReward = rewardPerBlock;
        rewardPerBlock = newReward;
        emit RewardPerBlockUpdated(oldReward, newReward);
    }
    
    function addAlgorithm(string memory algorithm) external onlyOwner {
        supportedAlgorithms[algorithm] = true;
        emit AlgorithmAdded(algorithm);
    }
    
    function removeAlgorithm(string memory algorithm) external onlyOwner {
        supportedAlgorithms[algorithm] = false;
        emit AlgorithmRemoved(algorithm);
    }
    
    function pause() external onlyOwner {
        _pause();
    }
    
    function unpause() external onlyOwner {
        _unpause();
    }
    
    function deposit() external payable onlyOwner {
        // Allow owner to deposit ETH for rewards
    }
    
    function withdraw(uint256 amount) external onlyOwner {
        require(address(this).balance >= amount, "Insufficient balance");
        payable(owner()).transfer(amount);
    }
    
    // View functions
    function getMinerStats(address miner) external view returns (MinerStats memory) {
        return minerStats[miner];
    }
    
    function getSession(uint256 sessionId) external view returns (MiningSession memory) {
        return sessions[sessionId];
    }
    
    function getProof(bytes32 proofHash) external view returns (ZKProof memory) {
        return proofs[proofHash];
    }
    
    function isAlgorithmSupported(string memory algorithm) external view returns (bool) {
        return supportedAlgorithms[algorithm];
    }
    
    function getContractBalance() external view returns (uint256) {
        return address(this).balance;
    }
    
    // Internal functions
    function _verifyZKProof(bytes32 proofHash, uint256 blockNumber, address miner, string memory algorithm) 
        internal 
        pure 
        returns (bool) 
    {
        // Simplified ZK proof verification
        // In a real implementation, this would verify actual ZK-SNARK proofs
        return proofHash != bytes32(0) && blockNumber > 0 && miner != address(0) && bytes(algorithm).length > 0;
    }
    
    receive() external payable {
        // Allow contract to receive ETH
    }
}
"
    },
    "lib/openzeppelin-contracts/contracts/access/Ownable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}
"
    },
    "lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    uint256 private _status;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _status = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == ENTERED;
    }
}
"
    },
    "lib/openzeppelin-contracts/contracts/utils/Pausable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    bool private _paused;

    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}
"
    },
    "lib/openzeppelin-contracts/contracts/utils/Context.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}
"
    }
  },
  "settings": {
    "remappings": [
      "@openzeppelin/=lib/openzeppelin-contracts/",
      "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
      "forge-std/=lib/forge-std/src/",
      "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
      "openzeppelin-contracts/=lib/openzeppelin-contracts/"
    ],
    "optimizer": {
      "enabled": true,
      "runs": 200
    },
    "metadata": {
      "useLiteralContent": false,
      "bytecodeHash": "ipfs",
      "appendCBOR": true
    },
    "outputSelection": {
      "*": {
        "*": [
          "evm.bytecode",
          "evm.deployedBytecode",
          "devdoc",
          "userdoc",
          "metadata",
          "abi"
        ]
      }
    },
    "evmVersion": "shanghai",
    "viaIR": true
  }
}}

Tags:
Multisig, Upgradeable, Multi-Signature, Factory|addr:0x5cd346908cab679a159bd37436fddb1fdbe1f1ea|verified:true|block:23515290|tx:0x346d2e238b929baeb2fcb5a3b9737eeab27aa61708c6e3c0f3d3b67ca4ac6c8b|first_check:1759740628

Submitted on: 2025-10-06 10:50:30

Comments

Log in to comment.

No comments yet.