{
    "Function": "checkSignatures",
    "File": "src/contracts/middleware/BLSSignatureChecker.sol",
    "Parent Contracts": [],
    "High-Level Calls": [
        "BN254",
        "IQuorumRegistry",
        "IBLSRegistry",
        "IQuorumRegistry",
        "MiddlewareUtils",
        "IQuorumRegistry"
    ],
    "Internal Calls": [
        "require(bool,string)",
        "calldataload(uint256)",
        "mstore(uint256,uint256)",
        "abi.encodePacked()",
        "mstore(uint256,uint256)",
        "keccak256(bytes)",
        "calldataload(uint256)",
        "mstore(uint256,uint256)",
        "mstore(uint256,uint256)",
        "calldataload(uint256)",
        "staticcall(uint256,uint256,uint256,uint256,uint256,uint256)",
        "mstore(uint256,uint256)",
        "require(bool,string)",
        "_validateOperatorStake",
        "calldataload(uint256)",
        "mstore(uint256,uint256)",
        "calldataload(uint256)",
        "abi.encodePacked()",
        "require(bool,string)",
        "gas()",
        "require(bool,string)",
        "gas()",
        "calldataload(uint256)",
        "_validateOperatorStake",
        "keccak256(bytes)",
        "staticcall(uint256,uint256,uint256,uint256,uint256,uint256)",
        "calldataload(uint256)",
        "calldataload(uint256)",
        "gas()",
        "calldataload(uint256)",
        "mstore(uint256,uint256)",
        "staticcall(uint256,uint256,uint256,uint256,uint256,uint256)",
        "calldataload(uint256)",
        "mstore(uint256,uint256)",
        "require(bool,string)",
        "mstore(uint256,uint256)",
        "_validateOperatorStake",
        "keccak256(bytes)",
        "calldataload(uint256)",
        "calldataload(uint256)",
        "require(bool,string)",
        "keccak256(bytes)",
        "require(bool,string)",
        "staticcall(uint256,uint256,uint256,uint256,uint256,uint256)",
        "gas()",
        "calldataload(uint256)",
        "abi.encodePacked()",
        "invalid()",
        "calldataload(uint256)",
        "require(bool,string)",
        "staticcall(uint256,uint256,uint256,uint256,uint256,uint256)",
        "mstore(uint256,uint256)",
        "gas()",
        "staticcall(uint256,uint256,uint256,uint256,uint256,uint256)",
        "calldataload(uint256)",
        "calldataload(uint256)",
        "staticcall(uint256,uint256,uint256,uint256,uint256,uint256)",
        "require(bool,string)",
        "mstore(uint256,uint256)",
        "calldataload(uint256)",
        "gas()",
        "calldataload(uint256)",
        "calldataload(uint256)",
        "abi.encodePacked()",
        "gas()",
        "require(bool,string)",
        "mstore(uint256,uint256)",
        "calldataload(uint256)"
    ],
    "Library Calls": [
        "computeSignatoryRecordHash",
        "hashToG1"
    ],
    "Low-Level Calls": [],
    "Code": "function checkSignatures(bytes calldata data)\n        public\n        returns (\n            uint32 taskNumberToConfirm,\n            uint32 referenceBlockNumber,\n            bytes32 msgHash,\n            SignatoryTotals memory signedTotals,\n            bytes32 compressedSignatoryRecord\n        )\n    {\n        // temporary variable used to hold various numbers\n        uint256 placeholder;\n\n        uint256 pointer;\n        \n        assembly {\n            pointer := data.offset\n            /**\n             * Get the 32 bytes immediately after the function signature and length + offset encoding of 'bytes\n             * calldata' input type, which represents the msgHash for which the disperser is calling `checkSignatures`\n             */\n            msgHash := calldataload(pointer)\n            \n            // Get the 6 bytes immediately after the above, which represent the index of the totalStake in the 'totalStakeHistory' array\n            placeholder := shr(BIT_SHIFT_totalStakeIndex, calldataload(add(pointer, CALLDATA_OFFSET_totalStakeIndex)))\n        }\n\n        // fetch the 4 byte referenceBlockNumber, the block number from which stakes are going to be read from\n        assembly {\n            referenceBlockNumber :=\n                shr(BIT_SHIFT_referenceBlockNumber, calldataload(add(pointer, CALLDATA_OFFSET_referenceBlockNumber)))\n        }\n\n        // get information on total stakes\n        IQuorumRegistry.OperatorStake memory localStakeObject = registry.getTotalStakeFromIndex(placeholder);\n\n        // check that the returned OperatorStake object is the most recent for the referenceBlockNumber\n        _validateOperatorStake(localStakeObject, referenceBlockNumber);\n\n        // copy total stakes amounts to `signedTotals` -- the 'signedStake' amounts are decreased later, to reflect non-signers\n        signedTotals.totalStakeFirstQuorum = localStakeObject.firstQuorumStake;\n        signedTotals.signedStakeFirstQuorum = localStakeObject.firstQuorumStake;\n        signedTotals.totalStakeSecondQuorum = localStakeObject.secondQuorumStake;\n        signedTotals.signedStakeSecondQuorum = localStakeObject.secondQuorumStake;\n\n        assembly {\n            //fetch the task number to avoid replay signing on same taskhash for different datastore\n            taskNumberToConfirm :=\n                shr(BIT_SHIFT_taskNumberToConfirm, calldataload(add(pointer, CALLDATA_OFFSET_taskNumberToConfirm)))\n            // get the 4 bytes immediately after the above, which represent the\n            // number of operators that aren't present in the quorum\n            // slither-disable-next-line write-after-write\n            placeholder := shr(BIT_SHIFT_numberNonSigners, calldataload(add(pointer, CALLDATA_OFFSET_numberNonSigners)))\n        }\n\n        // we have read (32 + 6 + 4 + 4 + 4) = 50 bytes of calldata so far\n        pointer += CALLDATA_OFFSET_NonsignerPubkeys;\n\n        // to be used for holding the pub key hashes of the operators that aren't part of the quorum\n        bytes32[] memory pubkeyHashes = new bytes32[](placeholder);\n        // intialize some memory eventually to be the input for call to ecPairing precompile contract\n        uint256[12] memory input;\n        // used for verifying that precompile calls are successful\n        bool success;\n\n        /**\n         * @dev The next step involves computing the aggregated pub key of all the operators\n         * that are not part of the quorum for this specific taskNumber.\n         */\n\n        /**\n         * @dev loading pubkey for the first operator that is not part of the quorum as listed in the calldata;\n         * Note that this need not be a special case and *could* be subsumed in the for loop below.\n         * However, this implementation saves one ecAdd operation, which would be performed in the i=0 iteration otherwise.\n         * @dev Recall that `placeholder` here is the number of operators *not* included in the quorum\n         * @dev (input[0], input[1]) is the aggregated non singer public key\n         */\n        if (placeholder != 0) {\n            //load compressed pubkey and the index in the stakes array into memory\n            uint32 stakeIndex;\n            assembly {\n                /**\n                 * @notice retrieving the pubkey of the node in Jacobian coordinates\n                 */\n                // pk.X\n                mstore(input, calldataload(pointer))\n                // pk.Y\n                mstore(add(input, 32), calldataload(add(pointer, 32)))\n\n                /**\n                 * @notice retrieving the index of the stake of the operator in pubkeyHashToStakeHistory in\n                 * Registry.sol that was recorded at the time of pre-commit.\n                 */\n                stakeIndex := shr(BIT_SHIFT_stakeIndex, calldataload(add(pointer, BYTE_LENGTH_G1_POINT)))\n            }\n            // We have read (32 + 32 + 4) = 68 additional bytes of calldata in the above assembly block.\n            // Update pointer accordingly.\n            unchecked {\n                pointer += BYTE_LENGTH_NON_SIGNER_INFO;\n            }\n\n            // get pubkeyHash and add it to pubkeyHashes of operators that aren't part of the quorum.\n            bytes32 pubkeyHash = keccak256(abi.encodePacked(input[0], input[1]));\n\n\n            pubkeyHashes[0] = pubkeyHash;\n\n            // querying the VoteWeigher for getting information on the operator's stake\n            // at the time of pre-commit\n            localStakeObject = registry.getStakeFromPubkeyHashAndIndex(pubkeyHash, stakeIndex);\n\n            // check that the returned OperatorStake object is the most recent for the referenceBlockNumber\n            _validateOperatorStake(localStakeObject, referenceBlockNumber);\n\n            // subtract operator stakes from totals\n            signedTotals.signedStakeFirstQuorum -= localStakeObject.firstQuorumStake;\n            signedTotals.signedStakeSecondQuorum -= localStakeObject.secondQuorumStake;\n        }\n\n        /**\n         * @dev store each non signer's public key in (input[2], input[3]) and add them to the aggregate non signer public key\n         * @dev keep track of the aggreagate non signing stake too\n         */\n        for (uint256 i = 1; i < placeholder;) {\n            //load compressed pubkey and the index in the stakes array into memory\n            uint32 stakeIndex;\n            assembly {\n                /// @notice retrieving the pubkey of the operator that is not part of the quorum\n                mstore(add(input, 64), calldataload(pointer))\n                mstore(add(input, 96), calldataload(add(pointer, 32)))\n\n                /**\n                 * @notice retrieving the index of the stake of the operator in pubkeyHashToStakeHistory in\n                 * Registry.sol that was recorded at the time of pre-commit.\n                 */\n                // slither-disable-next-line variable-scope\n                stakeIndex := shr(BIT_SHIFT_stakeIndex, calldataload(add(pointer, BYTE_LENGTH_G1_POINT)))\n            }\n\n            // We have read (32 + 32 + 4) = 68 additional bytes of calldata in the above assembly block.\n            // Update pointer accordingly.\n            unchecked {\n                pointer += BYTE_LENGTH_NON_SIGNER_INFO;\n            }\n\n            // get pubkeyHash and add it to pubkeyHashes of operators that aren't part of the quorum.\n            bytes32 pubkeyHash = keccak256(abi.encodePacked(input[2], input[3]));\n\n            //pubkeys should be ordered in ascending order of hash to make proofs of signing or\n            // non signing constant time\n            /**\n             * @dev this invariant is used in forceOperatorToDisclose in ServiceManager.sol\n             */\n            require(uint256(pubkeyHash) > uint256(pubkeyHashes[i - 1]), \"BLSSignatureChecker.checkSignatures: Pubkey hashes must be in ascending order\");\n\n            // recording the pubkey hash\n            pubkeyHashes[i] = pubkeyHash;\n\n            // querying the VoteWeigher for getting information on the operator's stake\n            // at the time of pre-commit\n            localStakeObject = registry.getStakeFromPubkeyHashAndIndex(pubkeyHash, stakeIndex);\n\n            // check that the returned OperatorStake object is the most recent for the referenceBlockNumber\n            _validateOperatorStake(localStakeObject, referenceBlockNumber);\n\n            //subtract validator stakes from totals\n            signedTotals.signedStakeFirstQuorum -= localStakeObject.firstQuorumStake;\n            signedTotals.signedStakeSecondQuorum -= localStakeObject.secondQuorumStake;\n            \n            // call to ecAdd\n            // aggregateNonSignerPublicKey = aggregateNonSignerPublicKey + nonSignerPublicKey\n            // (input[0], input[1])        = (input[0], input[1])        + (input[2], input[3])\n            // solium-disable-next-line security/no-inline-assembly\n            assembly {\n                success := staticcall(sub(gas(), 2000), 6, input, 0x80, input, 0x40)\n                // Use \"invalid\" to make gas estimation work\n                switch success\n                case 0 {\n                    invalid()\n                }\n            }\n            require(success, \"BLSSignatureChecker.checkSignatures: non signer addition failed\");\n\n            unchecked {\n                ++i;\n            }\n        }\n        // usage of a scoped block here minorly decreases gas usage\n        {\n            uint32 apkIndex;\n            assembly {\n                //get next 32 bits which would be the apkIndex of apkUpdates in Registry.sol\n                apkIndex := shr(BIT_SHIFT_apkIndex, calldataload(pointer))\n                // Update pointer to account for the 4 bytes specifying the apkIndex\n                pointer := add(pointer, BYTE_LENGTH_apkIndex)\n\n                /**\n                 * @notice Get the aggregated publickey at the moment when pre-commit happened\n                 * @dev Aggregated pubkey given as part of calldata instead of being retrieved from voteWeigher reduces number of SLOADs\n                 * @dev (input[2], input[3]) is the apk\n                 */\n                mstore(add(input, 64), calldataload(pointer))\n                mstore(add(input, 96), calldataload(add(pointer, 32)))\n            }\n\n            // We have read (32 + 32) = 64 additional bytes of calldata in the above assembly block.\n            // Update pointer accordingly.\n            unchecked {\n                pointer += BYTE_LENGTH_G1_POINT;\n            }\n\n            // make sure the caller has provided the correct aggPubKey\n            require(\n                IBLSRegistry(address(registry)).getCorrectApkHash(apkIndex, referenceBlockNumber) == keccak256(abi.encodePacked(input[2], input[3])),\n                \"BLSSignatureChecker.checkSignatures: Incorrect apk provided\"\n            );\n\n            \n        }\n\n        // if at least 1 non-signer\n        if (placeholder != 0) {\n            /**\n             * @notice need to subtract aggNonSignerPubkey from the apk to get aggregate signature of all\n             * operators that are part of the quorum\n             */\n            // negate aggNonSignerPubkey\n            input[1] = (BN254.FP_MODULUS - input[1]) % BN254.FP_MODULUS;\n\n            // call to ecAdd\n            // singerPublicKey      = -aggregateNonSignerPublicKey + apk\n            // (input[2], input[3]) = (input[0], input[1])         + (input[2], input[3])\n            // solium-disable-next-line security/no-inline-assembly\n            assembly {\n                success := staticcall(sub(gas(), 2000), 6, input, 0x80, add(input, 0x40), 0x40)\n            }\n            require(success, \"BLSSignatureChecker.checkSignatures: aggregate non signer addition failed\");\n\n            // emit log_named_uint(\"agg new pubkey\", input[2]);\n            // emit log_named_uint(\"agg new pubkey\", input[3]);\n            \n        }\n\n        // Now, (input[2], input[3]) is the signingPubkey\n\n        // compute H(M) in G1\n        (input[6], input[7]) = BN254.hashToG1(msgHash);\n\n        // emit log_named_uint(\"msgHash G1\", input[6]);\n        // emit log_named_uint(\"msgHash G1\", pointer);\n\n\n        // Load the G2 public key into (input[8], input[9], input[10], input[11])\n        assembly {\n            mstore(add(input, 288), calldataload(pointer)) //input[9] = pkG2.X1\n            mstore(add(input, 256), calldataload(add(pointer, 32))) //input[8] = pkG2.X0\n            mstore(add(input, 352), calldataload(add(pointer, 64))) //input[11] = pkG2.Y1\n            mstore(add(input, 320), calldataload(add(pointer, 96))) //input[10] = pkG2.Y0\n        }\n\n        unchecked {\n            pointer += BYTE_LENGTH_G2_POINT;\n        }\n\n        // Load the G1 signature, sigma, into (input[0], input[1])\n        assembly {\n            mstore(input, calldataload(pointer))\n            mstore(add(input, 32), calldataload(add(pointer, 32)))\n        }\n\n        unchecked {\n            pointer += BYTE_LENGTH_G1_POINT;\n        }\n\n        // generate random challenge for public key equality \n        // gamma = keccak(simga.X, sigma.Y, signingPublicKey.X, signingPublicKey.Y, H(m).X, H(m).Y, \n        //         signingPublicKeyG2.X1, signingPublicKeyG2.X0, signingPublicKeyG2.Y1, signingPublicKeyG2.Y0)\n        input[4] = uint256(keccak256(abi.encodePacked(input[0], input[1], input[2], input[3], input[6], input[7], input[8], input[9], input[10], input[11])));\n\n        // call ecMul\n        // (input[2], input[3]) = (input[2], input[3]) * input[4] = signingPublicKey * gamma\n        // solium-disable-next-line security/no-inline-assembly\n        assembly {\n            success := staticcall(sub(gas(), 2000), 7, add(input, 0x40), 0x60, add(input, 0x40), 0x40)\n        }\n        require(success, \"BLSSignatureChecker.checkSignatures: aggregate signer public key random shift failed\");\n        \n\n\n        // call ecAdd\n        // (input[0], input[1]) = (input[0], input[1]) + (input[2], input[3]) = sigma + gamma * signingPublicKey\n        // solium-disable-next-line security/no-inline-assembly\n        assembly {\n            success := staticcall(sub(gas(), 2000), 6, input, 0x80, input, 0x40)\n        }\n        require(success, \"BLSSignatureChecker.checkSignatures: aggregate signer public key and signature addition failed\");\n\n        // (input[2], input[3]) = g1, the G1 generator\n        input[2] = 1;\n        input[3] = 2;\n\n        // call ecMul\n        // (input[4], input[5]) = (input[2], input[3]) * input[4] = g1 * gamma \n        // solium-disable-next-line security/no-inline-assembly\n        assembly {\n            success := staticcall(sub(gas(), 2000), 7, add(input, 0x40), 0x60, add(input, 0x80), 0x40)\n        }\n        require(success, \"BLSSignatureChecker.checkSignatures: generator random shift failed\");\n\n        // (input[6], input[7]) = (input[4], input[5]) + (input[6], input[7]) = g1 * gamma + H(m)\n        // solium-disable-next-line security/no-inline-assembly\n        assembly {\n            success := staticcall(sub(gas(), 2000), 6, add(input, 0x80), 0x80, add(input, 0xC0), 0x40)\n        }\n        require(success, \"BLSSignatureChecker.checkSignatures: generator random shift and G1 hash addition failed\");\n\n        // insert negated coordinates of the generator for G2\n        input[2] = BN254.nG2x1;\n        input[3] = BN254.nG2x0;\n        input[4] = BN254.nG2y1;\n        input[5] = BN254.nG2y0;\n\n        // in summary\n        // (input[0], input[1]) =  sigma + gamma * signingPublicKey\n        // (input[2], input[3], input[4], input[5]) = negated generator of G2\n        // (input[6], input[7]) = g1 * gamma + H(m)\n        // (input[8], input[9], input[10], input[11]) = public key in G2\n        \n        \n        /**\n         * @notice now we verify that e(sigma + gamma * pk, -g2)e(H(m) + gamma * g1, pkG2) == 1\n         */\n\n        assembly {\n            // check the pairing; if incorrect, revert                \n            // staticcall address 8 (ecPairing precompile), forward all gas, send 384 bytes (0x180 in hex) = 12 (32-byte) inputs.\n            // store the return data in input[0], and copy only 32 bytes of return data (since precompile returns boolean)\n            success := staticcall(sub(gas(), 2000), 8, input, 0x180, input, 0x20)\n        }\n        require(success, \"BLSSignatureChecker.checkSignatures: pairing precompile call failed\");\n        // check that the provided signature is correct\n        require(input[0] == 1, \"BLSSignatureChecker.checkSignatures: Pairing unsuccessful\");\n\n        emit SignatoryRecord(\n            msgHash,\n            taskNumberToConfirm,\n            signedTotals.signedStakeFirstQuorum,\n            signedTotals.signedStakeSecondQuorum,\n            pubkeyHashes\n        );\n\n        // set compressedSignatoryRecord variable used for fraudproofs\n        compressedSignatoryRecord = MiddlewareUtils.computeSignatoryRecordHash(\n            taskNumberToConfirm,\n            pubkeyHashes,\n            signedTotals.signedStakeFirstQuorum,\n            signedTotals.signedStakeSecondQuorum\n        );\n\n        // return taskNumber, referenceBlockNumber, msgHash, total stakes that signed, and a hash of the signatories\n        return (taskNumberToConfirm, referenceBlockNumber, msgHash, signedTotals, compressedSignatoryRecord);\n    }"
}