name
stringlengths
5
231
severity
stringclasses
3 values
description
stringlengths
107
68.2k
recommendation
stringlengths
12
8.75k
βŒ€
impact
stringlengths
3
11.2k
βŒ€
function
stringlengths
15
64.6k
Unpredictable behavior due to front running or general bad timing Pending
high
In a number of cases, administrators of contracts can update or upgrade things in the system without warning. This has the potential to violate a security goal of the system.\\nSpecifically, privileged roles could use front running to make malicious changes just ahead of incoming transactions, or purely accidental negative effects could occur due to unfortunate timing of changes.\\nSome instances of this are more important than others, but in general users of the system should have assurances about the behavior of the action they're about to take.\\nThe deployer of the `PerpetualGovernance`, `AMMGovernance`, and `GlobalConfig` contracts are set as administrators for the contracts through `WhitelistedRole`. The `WhitelistedAdminRole` can whitelist other accounts at any time and allow them to perform actions protected by the `onlyWhitelisted` decorator.\\nUpdating governance and global configuration parameters are not protected by a time-lock and take effect immediately. This, therefore, creates an opportunity for administrators to front-run users on the exchange by changing parameters for orders. It may also allow an administrator to temporarily lift restrictions for themselves (e.g. withdrawalLockBlockCount).\\n`GlobalConfig`\\n`withdrawalLockBlockCount` is queried when applying for withdrawal. This value can be set zero enabling allowing immediate withdrawal.\\n`brokerLockBlockCount` is queried when setting a new broker. This value can e set to zero effectively enabling immediate broker changes.\\n```\\nfunction setGlobalParameter(bytes32 key, uint256 value) public onlyWhitelistAdmin {\\n if (key == "withdrawalLockBlockCount") {\\n withdrawalLockBlockCount = value;\\n } else if (key == "brokerLockBlockCount") {\\n brokerLockBlockCount = value;\\n } else {\\n revert("key not exists");\\n }\\n emit UpdateGlobalParameter(key, value);\\n}\\n```\\n\\n`PerpetualGovernance`\\ne.g. Admin can front-run specific `matchOrder` calls and set arbitrary dev fees or curve parameters…\\n```\\nfunction setGovernanceParameter(bytes32 key, int256 value) public onlyWhitelistAdmin {\\n if (key == "initialMarginRate") {\\n governance.initialMarginRate = value.toUint256();\\n require(governance.initialMarginRate > 0, "require im > 0");\\n require(governance.initialMarginRate < 10\\*\\*18, "require im < 1");\\n require(governance.maintenanceMarginRate < governance.initialMarginRate, "require mm < im");\\n } else if (key == "maintenanceMarginRate") {\\n governance.maintenanceMarginRate = value.toUint256();\\n require(governance.maintenanceMarginRate > 0, "require mm > 0");\\n require(governance.maintenanceMarginRate < governance.initialMarginRate, "require mm < im");\\n require(governance.liquidationPenaltyRate < governance.maintenanceMarginRate, "require lpr < mm");\\n require(governance.penaltyFundRate < governance.maintenanceMarginRate, "require pfr < mm");\\n } else if (key == "liquidationPenaltyRate") {\\n governance.liquidationPenaltyRate = value.toUint256();\\n require(governance.liquidationPenaltyRate < governance.maintenanceMarginRate, "require lpr < mm");\\n } else if (key == "penaltyFundRate") {\\n governance.penaltyFundRate = value.toUint256();\\n require(governance.penaltyFundRate < governance.maintenanceMarginRate, "require pfr < mm");\\n } else if (key == "takerDevFeeRate") {\\n governance.takerDevFeeRate = value;\\n } else if (key == "makerDevFeeRate") {\\n governance.makerDevFeeRate = value;\\n } else if (key == "lotSize") {\\n require(\\n governance.tradingLotSize == 0 || governance.tradingLotSize.mod(value.toUint256()) == 0,\\n "require tls % ls == 0"\\n );\\n governance.lotSize = value.toUint256();\\n } else if (key == "tradingLotSize") {\\n require(governance.lotSize == 0 || value.toUint256().mod(governance.lotSize) == 0, "require tls % ls == 0");\\n governance.tradingLotSize = value.toUint256();\\n } else if (key == "longSocialLossPerContracts") {\\n require(status == LibTypes.Status.SETTLING, "wrong perpetual status");\\n socialLossPerContracts[uint256(LibTypes.Side.LONG)] = value;\\n } else if (key == "shortSocialLossPerContracts") {\\n require(status == LibTypes.Status.SETTLING, "wrong perpetual status");\\n socialLossPerContracts[uint256(LibTypes.Side.SHORT)] = value;\\n } else {\\n revert("key not exists");\\n }\\n emit UpdateGovernanceParameter(key, value);\\n}\\n```\\n\\nAdmin can set `devAddress` or even update to a new `amm` and `globalConfig`\\n```\\nfunction setGovernanceAddress(bytes32 key, address value) public onlyWhitelistAdmin {\\n require(value != address(0x0), "invalid address");\\n if (key == "dev") {\\n devAddress = value;\\n } else if (key == "amm") {\\n amm = IAMM(value);\\n } else if (key == "globalConfig") {\\n globalConfig = IGlobalConfig(value);\\n } else {\\n revert("key not exists");\\n }\\n emit UpdateGovernanceAddress(key, value);\\n}\\n```\\n\\n`AMMGovernance`\\n```\\nfunction setGovernanceParameter(bytes32 key, int256 value) public onlyWhitelistAdmin {\\n if (key == "poolFeeRate") {\\n governance.poolFeeRate = value.toUint256();\\n } else if (key == "poolDevFeeRate") {\\n governance.poolDevFeeRate = value.toUint256();\\n } else if (key == "emaAlpha") {\\n require(value > 0, "alpha should be > 0");\\n governance.emaAlpha = value;\\n emaAlpha2 = 10\\*\\*18 - governance.emaAlpha;\\n emaAlpha2Ln = emaAlpha2.wln();\\n } else if (key == "updatePremiumPrize") {\\n governance.updatePremiumPrize = value.toUint256();\\n } else if (key == "markPremiumLimit") {\\n governance.markPremiumLimit = value;\\n } else if (key == "fundingDampener") {\\n governance.fundingDampener = value;\\n } else {\\n revert("key not exists");\\n }\\n emit UpdateGovernanceParameter(key, value);\\n}\\n```\\n
The underlying issue is that users of the system can't be sure what the behavior of a function call will be, and this is because the behavior can change at any time.\\nWe recommend giving the user advance notice of changes with a time lock. For example, make all updates to system parameters or upgrades require two steps with a mandatory time window between them. The first step merely broadcasts to users that a particular change is coming, and the second step commits that change after a suitable waiting period.\\nAdditionally, users should verify the whitelist setup before using the contract system and monitor it for new additions to the whitelist. Documentation should clearly outline what roles are owned by whom to support suitability. Sane parameter bounds should be enforced (e.g. min. disallow block delay of zero )
null
```\\nfunction setGlobalParameter(bytes32 key, uint256 value) public onlyWhitelistAdmin {\\n if (key == "withdrawalLockBlockCount") {\\n withdrawalLockBlockCount = value;\\n } else if (key == "brokerLockBlockCount") {\\n brokerLockBlockCount = value;\\n } else {\\n revert("key not exists");\\n }\\n emit UpdateGlobalParameter(key, value);\\n}\\n```\\n
AMM - Governance is able to set an invalid alpha value Pending
medium
According to https://en.wikipedia.org/wiki/Moving_average\\nThe coefficient Ξ± represents the degree of weighting decrease, a constant smoothing factor between 0 and 1. A higher Ξ± discounts older observations faster.\\nHowever, the code does not check upper bounds. An admin may, therefore, set an invalid alpha that puts `emaAlpha2` out of bounds or negative.\\n```\\n} else if (key == "emaAlpha") {\\n require(value > 0, "alpha should be > 0");\\n governance.emaAlpha = value;\\n emaAlpha2 = 10\\*\\*18 - governance.emaAlpha;\\n emaAlpha2Ln = emaAlpha2.wln();\\n```\\n
Ensure that the system configuration is always within safe bounds. Document expected system variable types and their safe operating ranges. Enforce that bounds are checked every time a value is set. Enforce safe defaults when deploying contracts.\\nEnsure `emaAlpha` is `0 < value < 1 WAD`
null
```\\n} else if (key == "emaAlpha") {\\n require(value > 0, "alpha should be > 0");\\n governance.emaAlpha = value;\\n emaAlpha2 = 10\\*\\*18 - governance.emaAlpha;\\n emaAlpha2Ln = emaAlpha2.wln();\\n```\\n
Exchange - insufficient input validation in matchOrders Pending
medium
`matchOrders` does not check that that the sender has provided the same number of `amounts` as `makerOrderParams`. When fewer `amounts` exist than `makerOrderParams`, the method will revert because of an out-of-bounds array access. When fewer `makerOrderParams` exist than `amounts`, the method will succeed, and the additional values in `amounts` will be ignored.\\nAdditionally, the method allows the sender to provide no `makerOrderParams` at all, resulting in no state changes.\\n`matchOrders` also does not reject trades with an amount set to zero. Such orders should be rejected because they do not comply with the minimum `tradingLotSize` configured for the system. As a side-effect, events may be emitted for zero-amount trades and unexpected state changes may occur.\\n```\\nfunction matchOrders(\\n LibOrder.OrderParam memory takerOrderParam,\\n LibOrder.OrderParam[] memory makerOrderParams,\\n address \\_perpetual,\\n uint256[] memory amounts\\n) public {\\n```\\n\\n```\\nfunction matchOrderWithAMM(LibOrder.OrderParam memory takerOrderParam, address \\_perpetual, uint256 amount) public {\\n```\\n
Resolution\\nThis issue was addressed by following the recommendation to verify that `amounts.length > 0 && makerOrderParams.length == amounts.length`. However, the code does not abort if one of the `amounts` is zero which should never happen and therefore raise an exception due to it likely being an erroneous call. Additionally, the method now enforces that only a broker can interact with the interface.\\nRequire `makerOrderParams.length > 0 && amounts.length == makerOrderParams.length`\\nRequire that `amount` or any of the `amounts[i]` provided to `matchOrders` is `>=tradingLotSize`.
null
```\\nfunction matchOrders(\\n LibOrder.OrderParam memory takerOrderParam,\\n LibOrder.OrderParam[] memory makerOrderParams,\\n address \\_perpetual,\\n uint256[] memory amounts\\n) public {\\n```\\n
AMM - Liquidity provider may lose up to lotSize when removing liquidity Acknowledged
medium
When removing liquidity, the amount of collateral received is calculated from the `shareAmount` (ShareToken) of the liquidity provider. The liquidity removal process registers a trade on the amount, with the liquidity provider and `AMM` taking opposite sides. Because trading only accepts multiple of the `lotSize`, the leftover is discarded. The amount discarded may be up to `lotSize - 1`.\\nThe expectation is that this value should not be too high, but as `lotSize` can be set to arbitrary values by an admin, it is possible that this step discards significant value. Additionally, see issue 6.6 for how this can be exploited by an admin.\\nNote that similar behavior is present in `Perpetual.liquidateFrom`, where the `liquidatableAmount` calculated undergoes a similar modulo operation:\\n```\\nuint256 liquidatableAmount = totalPositionSize.sub(totalPositionSize.mod(governance.lotSize));\\nliquidationAmount = liquidationAmount.ceil(governance.lotSize).min(maxAmount).min(liquidatableAmount);\\n```\\n\\n`lotSize` can arbitrarily be set up to `pos_int256_max` as long as `tradingLotSize % `lotSize` == 0`\\n```\\n} else if (key == "lotSize") {\\n require(\\n governance.tradingLotSize == 0 || governance.tradingLotSize.mod(value.toUint256()) == 0,\\n "require tls % ls == 0"\\n );\\n governance.lotSize = value.toUint256();\\n} else if (key == "tradingLotSize") {\\n require(governance.lotSize == 0 || value.toUint256().mod(governance.lotSize) == 0, "require tls % ls == 0");\\n governance.tradingLotSize = value.toUint256();\\n```\\n\\n`amount` is derived from `shareAmount` rounded down to the next multiple of the `lotSize`. The leftover is discarded.\\n```\\nuint256 amount = shareAmount.wmul(oldPoolPositionSize).wdiv(shareToken.totalSupply());\\namount = amount.sub(amount.mod(perpetualProxy.lotSize()));\\n\\nperpetualProxy.transferBalanceOut(trader, price.wmul(amount).mul(2));\\nburnShareTokenFrom(trader, shareAmount);\\nuint256 opened = perpetualProxy.trade(trader, LibTypes.Side.LONG, price, amount);\\n```\\n
Ensure that documentation makes users aware of the fact that they may lose up to `lotsize-1` in value.\\nAlternatively, track accrued value and permit trades on values that exceed `lotSize`. Note that this may add significant complexity.\\nEnsure that similar system behavior, like the `liquidatableAmount` calculated in `Perpetual.liquidateFrom`, is also documented and communicated clearly to users.
null
```\\nuint256 liquidatableAmount = totalPositionSize.sub(totalPositionSize.mod(governance.lotSize));\\nliquidationAmount = liquidationAmount.ceil(governance.lotSize).min(maxAmount).min(liquidatableAmount);\\n```\\n
Oracle - Unchecked oracle response timestamp and integer over/underflow
medium
The external Chainlink oracle, which provides index price information to the system, introduces risk inherent to any dependency on third-party data sources. For example, the oracle could fall behind or otherwise fail to be maintained, resulting in outdated data being fed to the index price calculations of the AMM. Oracle reliance has historically resulted in crippled on-chain systems, and complications that lead to these outcomes can arise from things as simple as network congestion.\\nEnsuring that unexpected oracle return values are properly handled will reduce reliance on off-chain components and increase the resiliency of the smart contract system that depends on them.\\nThe `ChainlinkAdapter` and `InversedChainlinkAdapter` take the oracle's (int256) `latestAnswer` and convert the result using `chainlinkDecimalsAdapter`. This arithmetic operation can underflow/overflow if the Oracle provides a large enough answer:\\n```\\nint256 public constant chainlinkDecimalsAdapter = 10\\*\\*10;\\n\\nconstructor(address \\_feeder) public {\\n feeder = IChainlinkFeeder(\\_feeder);\\n}\\n\\nfunction price() public view returns (uint256 newPrice, uint256 timestamp) {\\n newPrice = (feeder.latestAnswer() \\* chainlinkDecimalsAdapter).toUint256();\\n timestamp = feeder.latestTimestamp();\\n}\\n```\\n\\n```\\nint256 public constant chainlinkDecimalsAdapter = 10\\*\\*10;\\n\\nconstructor(address \\_feeder) public {\\n feeder = IChainlinkFeeder(\\_feeder);\\n}\\n\\nfunction price() public view returns (uint256 newPrice, uint256 timestamp) {\\n newPrice = ONE.wdiv(feeder.latestAnswer() \\* chainlinkDecimalsAdapter).toUint256();\\n timestamp = feeder.latestTimestamp();\\n}\\n```\\n\\nThe oracle provides a timestamp for the `latestAnswer` that is not validated and may lead to old oracle timestamps being accepted (e.g. caused by congestion on the blockchain or a directed censorship attack).\\n```\\n timestamp = feeder.latestTimestamp();\\n}\\n```\\n
Use `SafeMath` for mathematical computations\\nVerify `latestAnswer` is within valid bounds (!=0)\\nVerify `latestTimestamp` is within accepted bounds (not in the future, was updated within a reasonable amount of time)\\nDeduplicate code by combining both Adapters into one as the only difference is that the `InversedChainlinkAdapter` returns `ONE.wdiv(price)`.
null
```\\nint256 public constant chainlinkDecimalsAdapter = 10\\*\\*10;\\n\\nconstructor(address \\_feeder) public {\\n feeder = IChainlinkFeeder(\\_feeder);\\n}\\n\\nfunction price() public view returns (uint256 newPrice, uint256 timestamp) {\\n newPrice = (feeder.latestAnswer() \\* chainlinkDecimalsAdapter).toUint256();\\n timestamp = feeder.latestTimestamp();\\n}\\n```\\n
Perpetual - Administrators can put the system into emergency mode indefinitely Pending
medium
There is no limitation on how long an administrator can put the `Perpetual` contract into emergency mode. Users cannot trade or withdraw funds in emergency mode and are effectively locked out until the admin chooses to put the contract in `SETTLED` mode.\\n```\\nfunction beginGlobalSettlement(uint256 price) public onlyWhitelistAdmin {\\n require(status != LibTypes.Status.SETTLED, "already settled");\\n settlementPrice = price;\\n status = LibTypes.Status.SETTLING;\\n emit BeginGlobalSettlement(price);\\n}\\n```\\n\\n```\\nfunction endGlobalSettlement() public onlyWhitelistAdmin {\\n require(status == LibTypes.Status.SETTLING, "wrong perpetual status");\\n\\n address guy = address(amm.perpetualProxy());\\n settleFor(guy);\\n status = LibTypes.Status.SETTLED;\\n\\n emit EndGlobalSettlement();\\n}\\n```\\n
Resolution\\nThe client provided the following statement addressing the issue:\\nIt should be solved by voting. Moreover, we add two roles who is able to disable withdrawing /pause the system.\\nThe duration of the emergency phase is still unrestricted.\\nSet a time-lock when entering emergency mode that allows anyone to set the system to `SETTLED` after a fixed amount of time.
null
```\\nfunction beginGlobalSettlement(uint256 price) public onlyWhitelistAdmin {\\n require(status != LibTypes.Status.SETTLED, "already settled");\\n settlementPrice = price;\\n status = LibTypes.Status.SETTLING;\\n emit BeginGlobalSettlement(price);\\n}\\n```\\n
Signed data may be usable cross-chain
medium
Signed order data may be re-usable cross-chain as the chain-id is not explicitly part of the signed data.\\nIt is also recommended to further harden the signature verification and validate that `v` and `s` are within expected bounds. `ecrecover()` returns `0x0` to indicate an error condition, therefore, a `signerAddress` or `recovered` address of `0x0` should explicitly be disallowed.\\nThe signed order data currently includes the EIP712 Domain Name `Mai Protocol` and the following information:\\n```\\nstruct Order {\\n address trader;\\n address broker;\\n address perpetual;\\n uint256 amount;\\n uint256 price;\\n /\\*\\*\\n \\* Data contains the following values packed into 32 bytes\\n \\* ╔════════════════════╀═══════════════════════════════════════════════════════════╗\\n \\* β•‘ β”‚ length(bytes) desc β•‘\\n \\* β•Ÿβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•’\\n \\* β•‘ version β”‚ 1 order version β•‘\\n \\* β•‘ side β”‚ 1 0: buy (long), 1: sell (short) β•‘\\n \\* β•‘ isMarketOrder β”‚ 1 0: limitOrder, 1: marketOrder β•‘\\n \\* β•‘ expiredAt β”‚ 5 order expiration time in seconds β•‘\\n \\* β•‘ asMakerFeeRate β”‚ 2 maker fee rate (base 100,000) β•‘\\n \\* β•‘ asTakerFeeRate β”‚ 2 taker fee rate (base 100,000) β•‘\\n \\* β•‘ (d) makerRebateRateβ”‚ 2 rebate rate for maker (base 100) β•‘\\n \\* β•‘ salt β”‚ 8 salt β•‘\\n \\* β•‘ isMakerOnly β”‚ 1 is maker only β•‘\\n \\* β•‘ isInversed β”‚ 1 is inversed contract β•‘\\n \\* β•‘ β”‚ 8 reserved β•‘\\n \\* β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•§β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•\\n \\*/\\n bytes32 data;\\n}\\n```\\n\\nSignature verification:\\n```\\nfunction isValidSignature(OrderSignature memory signature, bytes32 hash, address signerAddress)\\n internal\\n pure\\n returns (bool)\\n{\\n uint8 method = uint8(signature.config[1]);\\n address recovered;\\n uint8 v = uint8(signature.config[0]);\\n\\n if (method == uint8(SignatureMethod.ETH\\_SIGN)) {\\n recovered = ecrecover(\\n keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\\n32", hash)),\\n v,\\n signature.r,\\n signature.s\\n );\\n } else if (method == uint8(SignatureMethod.EIP712)) {\\n recovered = ecrecover(hash, v, signature.r, signature.s);\\n } else {\\n revert("invalid sign method");\\n }\\n\\n return signerAddress == recovered;\\n}\\n```\\n
Include the `chain-id` in the signature to avoid cross-chain validity of signatures\\nverify `s` is within valid bounds to avoid signature malleability\\n```\\nif (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {\\n revert("ECDSA: invalid signature 's' value");\\n }\\n```\\n\\nverify `v` is within valid bounds\\n```\\nif (v != 27 && v != 28) {\\n revert("ECDSA: invalid signature 'v' value");\\n}\\n```\\n\\nreturn invalid if the result of `ecrecover()` is `0x0`
null
```\\nstruct Order {\\n address trader;\\n address broker;\\n address perpetual;\\n uint256 amount;\\n uint256 price;\\n /\\*\\*\\n \\* Data contains the following values packed into 32 bytes\\n \\* ╔════════════════════╀═══════════════════════════════════════════════════════════╗\\n \\* β•‘ β”‚ length(bytes) desc β•‘\\n \\* β•Ÿβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β•’\\n \\* β•‘ version β”‚ 1 order version β•‘\\n \\* β•‘ side β”‚ 1 0: buy (long), 1: sell (short) β•‘\\n \\* β•‘ isMarketOrder β”‚ 1 0: limitOrder, 1: marketOrder β•‘\\n \\* β•‘ expiredAt β”‚ 5 order expiration time in seconds β•‘\\n \\* β•‘ asMakerFeeRate β”‚ 2 maker fee rate (base 100,000) β•‘\\n \\* β•‘ asTakerFeeRate β”‚ 2 taker fee rate (base 100,000) β•‘\\n \\* β•‘ (d) makerRebateRateβ”‚ 2 rebate rate for maker (base 100) β•‘\\n \\* β•‘ salt β”‚ 8 salt β•‘\\n \\* β•‘ isMakerOnly β”‚ 1 is maker only β•‘\\n \\* β•‘ isInversed β”‚ 1 is inversed contract β•‘\\n \\* β•‘ β”‚ 8 reserved β•‘\\n \\* β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•§β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•\\n \\*/\\n bytes32 data;\\n}\\n```\\n
Exchange - validateOrderParam does not check against SUPPORTED_ORDER_VERSION
medium
`validateOrderParam` verifies the signature and version of a provided order. Instead of checking against the contract constant `SUPPORTED_ORDER_VERSION` it, however, checks against a hardcoded version `2` in the method itself.\\nThis might be a problem if `SUPPORTED_ORDER_VERSION` is seen as the configuration parameter for the allowed version. Changing it would not change the allowed order version for `validateOrderParam` as this constant literal is never used.\\nAt the time of this audit, however, the `SUPPORTED_ORDER_VERSION` value equals the hardcoded value in the `validateOrderParam` method.\\n```\\nfunction validateOrderParam(IPerpetual perpetual, LibOrder.OrderParam memory orderParam)\\n internal\\n view\\n returns (bytes32)\\n{\\n address broker = perpetual.currentBroker(orderParam.trader);\\n require(broker == msg.sender, "invalid broker");\\n require(orderParam.getOrderVersion() == 2, "unsupported version");\\n require(orderParam.getExpiredAt() >= block.timestamp, "order expired");\\n\\n bytes32 orderHash = orderParam.getOrderHash(address(perpetual), broker);\\n require(orderParam.signature.isValidSignature(orderHash, orderParam.trader), "invalid signature");\\n require(filled[orderHash] < orderParam.amount, "fullfilled order");\\n\\n return orderHash;\\n}\\n```\\n
Check against `SUPPORTED_ORDER_VERSION` instead of the hardcoded value `2`.
null
```\\nfunction validateOrderParam(IPerpetual perpetual, LibOrder.OrderParam memory orderParam)\\n internal\\n view\\n returns (bytes32)\\n{\\n address broker = perpetual.currentBroker(orderParam.trader);\\n require(broker == msg.sender, "invalid broker");\\n require(orderParam.getOrderVersion() == 2, "unsupported version");\\n require(orderParam.getExpiredAt() >= block.timestamp, "order expired");\\n\\n bytes32 orderHash = orderParam.getOrderHash(address(perpetual), broker);\\n require(orderParam.signature.isValidSignature(orderHash, orderParam.trader), "invalid signature");\\n require(filled[orderHash] < orderParam.amount, "fullfilled order");\\n\\n return orderHash;\\n}\\n```\\n
LibMathSigned - wpowi returns an invalid result for a negative exponent Pending
medium
`LibMathSigned.wpowi(x,n)` calculates Wad value `x` (base) to the power of `n` (exponent). The exponent is declared as a signed int, however, the method returns wrong results when calculating `x ^(-n)`.\\nThe comment for the `wpowi` method suggests that `n` is a normal integer instead of a Wad-denominated value. This, however, is not being enforced.\\n`LibMathSigned.wpowi(8000000000000000000, 2) = 64000000000000000000`\\n(wrong) `LibMathSigned.wpowi(8000000000000000000, -2) = 64000000000000000000`\\n```\\n// x ^ n\\n// NOTE: n is a normal integer, do not shift 18 decimals\\n// solium-disable-next-line security/no-assign-params\\nfunction wpowi(int256 x, int256 n) internal pure returns (int256 z) {\\n z = n % 2 != 0 ? x : \\_WAD;\\n\\n for (n /= 2; n != 0; n /= 2) {\\n x = wmul(x, x);\\n\\n if (n % 2 != 0) {\\n z = wmul(z, x);\\n }\\n }\\n}\\n```\\n
Make `wpowi` support negative exponents or use the proper type for `n` (uint) and reject negative values.\\nEnforce that the exponent bounds are within sane ranges and less than a Wad to detect potential misuse where someone accidentally provides a Wad value as `n`.\\nAdd positive and negative unit-tests to fully cover this functionality.
null
```\\n// x ^ n\\n// NOTE: n is a normal integer, do not shift 18 decimals\\n// solium-disable-next-line security/no-assign-params\\nfunction wpowi(int256 x, int256 n) internal pure returns (int256 z) {\\n z = n % 2 != 0 ? x : \\_WAD;\\n\\n for (n /= 2; n != 0; n /= 2) {\\n x = wmul(x, x);\\n\\n if (n % 2 != 0) {\\n z = wmul(z, x);\\n }\\n }\\n}\\n```\\n
Outdated solidity version and floating pragma Pending
medium
Using an outdated compiler version can be problematic especially if there are publicly disclosed bugs and issues (see also https://github.com/ethereum/solidity/releases) that affect the current compiler version.\\nThe codebase specifies a floating version of `^0.5.2` and makes use of the experimental feature `ABIEncoderV2`.\\nIt should be noted, that `ABIEncoderV2` was subject to multiple bug-fixes up until the latest 0.6.xversion and contracts compiled with earlier versions are - for example - susceptible to the following issues:\\nImplicitConstructorCallvalueCheck\\nTupleAssignmentMultiStackSlotComponents\\nMemoryArrayCreationOverflow\\nprivateCanBeOverridden\\nYulOptimizerRedundantAssignmentBreakContinue0.5\\nABIEncoderV2CalldataStructsWithStaticallySizedAndDynamicallyEncodedMembers\\nSignedArrayStorageCopy\\nABIEncoderV2StorageArrayWithMultiSlotElement\\nDynamicConstructorArgumentsClippedABIV2\\nCodebase declares compiler version ^0.5.2:\\n```\\npragma solidity ^0.5.2;\\npragma experimental ABIEncoderV2; // to enable structure-type parameters\\n```\\n\\nAccording to etherscan.io, the currently deployed main-net `AMM` contract is compiled with solidity version 0.5.8:\\nhttps://etherscan.io/address/0xb95B9fb0539Ec84DeD2855Ed1C9C686Af9A4e8b3#code
It is recommended to settle on the latest stable 0.6.x or 0.5.x version of the Solidity compiler and lock the pragma version to a specifically tested compiler release.
null
```\\npragma solidity ^0.5.2;\\npragma experimental ABIEncoderV2; // to enable structure-type parameters\\n```\\n
AMM - ONE_WAD_U is never used
low
The const `ONE_WAD_U` is declared but never used. Avoid re-declaring the same constants in multiple source-units (and unit-test cases) as this will be hard to maintain.\\n```\\nuint256 private constant ONE\\_WAD\\_U = 10\\*\\*18;\\n```\\n
Remove unused code. Import the value from a shared resource. E.g.ONE_WAD is declared multiple times in `LibMathSigned`, `LibMathUnsigned`, `AMM`, hardcoded in checks in `PerpetualGovernance.setGovernanceParameter`, `AMMGovernance.setGovernanceParameter`.
null
```\\nuint256 private constant ONE\\_WAD\\_U = 10\\*\\*18;\\n```\\n
Perpetual - Variable shadowing in constructor
low
`Perpetual` inherits from `PerpetualGovernance` and `Collateral`, which declare state variables that are shadowed in the `Perpetual` constructor.\\nLocal constructor argument shadows `PerpetualGovernance.globalConfig`, `PerpetualGovernance.devAddress`, `Collateral.collateral`\\nNote: Confusing name: `Collateral` is an inherited contract and a state variable.\\n```\\nconstructor(address globalConfig, address devAddress, address collateral, uint256 collateralDecimals)\\n public\\n Position(collateral, collateralDecimals)\\n{\\n setGovernanceAddress("globalConfig", globalConfig);\\n setGovernanceAddress("dev", devAddress);\\n emit CreatePerpetual();\\n}\\n```\\n
Rename the parameter or state variable.
null
```\\nconstructor(address globalConfig, address devAddress, address collateral, uint256 collateralDecimals)\\n public\\n Position(collateral, collateralDecimals)\\n{\\n setGovernanceAddress("globalConfig", globalConfig);\\n setGovernanceAddress("dev", devAddress);\\n emit CreatePerpetual();\\n}\\n```\\n
Perpetual - The specified decimals for the collateral may not reflect the token's actual decimals Acknowledged
low
When initializing the `Perpetual` contract, the deployer can decide to use either `ETH`, or an ERC20-compliant collateral. In the latter case, the deployer must provide a nonzero address for the token, as well as the number of `decimals` used by the token:\\n```\\nconstructor(address \\_collateral, uint256 decimals) public {\\n require(decimals <= MAX\\_DECIMALS, "decimals out of range");\\n require(\\_collateral != address(0x0) || (\\_collateral == address(0x0) && decimals == 18), "invalid decimals");\\n\\n collateral = \\_collateral;\\n scaler = (decimals == MAX\\_DECIMALS ? 1 : 10\\*\\*(MAX\\_DECIMALS - decimals)).toInt256();\\n}\\n```\\n\\nThe provided `decimals` value is not checked for validity and can differ from the actual token's `decimals`.
Ensure to establish documentation that makes users aware of the fact that the decimals configured are not enforced to match the actual tokens decimals. This is to allow users to audit the system configuration and decide whether they want to participate in it.
null
```\\nconstructor(address \\_collateral, uint256 decimals) public {\\n require(decimals <= MAX\\_DECIMALS, "decimals out of range");\\n require(\\_collateral != address(0x0) || (\\_collateral == address(0x0) && decimals == 18), "invalid decimals");\\n\\n collateral = \\_collateral;\\n scaler = (decimals == MAX\\_DECIMALS ? 1 : 10\\*\\*(MAX\\_DECIMALS - decimals)).toInt256();\\n}\\n```\\n
AMM - Unchecked return value in ShareToken.mint Pending
low
`ShareToken` is an extension of the Openzeppelin ERC20Mintable pattern which exposes a method called `mint()` that allows accounts owning the minter role to mint new tokens. The return value of `ShareToken.mint()` is not checked.\\nSince the ERC20 standard does not define whether this method should return a value or revert it may be problematic to assume that all tokens revert. If, for example, an implementation is used that does not revert on error but returns a boolean error indicator instead the caller might falsely continue without the token minted.\\nWe would like to note that the functionality is intended to be used with the provided `ShareToken` and therefore the contract is safe to use assuming `ERC20Mintable.mint` reverts on error. The issue arises if the system is used with a different `ShareToken` implementation that is not implemented in the same way.\\nOpenzeppelin implementation\\n```\\nfunction mint(address account, uint256 amount) public onlyMinter returns (bool) {\\n \\_mint(account, amount);\\n return true;\\n}\\n```\\n\\nCall with unchecked return value\\n```\\nfunction mintShareTokenTo(address guy, uint256 amount) internal {\\n shareToken.mint(guy, amount);\\n}\\n```\\n
Consider wrapping the `mint` statement in a `require` clause, however, this way only tokens that are returning a boolean error indicator are supported. Document the specification requirements for the `ShareToken` and clearly state if the token is expected to revert or return an error indicator.\\nIt should also be documented that the Token exposes a `burn` method that does not adhere to the Openzeppelin `ERC20Burnable` implementation. The `ERC20Burnable` import is unused as noted in issue 6.23.
null
```\\nfunction mint(address account, uint256 amount) public onlyMinter returns (bool) {\\n \\_mint(account, amount);\\n return true;\\n}\\n```\\n
Perpetual - beginGlobalSettlement can be called multiple times Acknowledged
low
The system can be put into emergency mode by an admin calling `beginGlobalSettlement` and providing a fixed `settlementPrice`. The method can be invoked even when the contract is already in `SETTLING` (emergency) mode, allowing an admin to selectively adjust the settlement price again. This does not seem to be the intended behavior as calling the method again re-sets the status to `SETTLING`. Furthermore, it may affect users' behavior during the `SETTLING` phase.\\n```\\nfunction beginGlobalSettlement(uint256 price) public onlyWhitelistAdmin {\\n require(status != LibTypes.Status.SETTLED, "already settled");\\n settlementPrice = price;\\n status = LibTypes.Status.SETTLING;\\n emit BeginGlobalSettlement(price);\\n}\\n```\\n
Emergency mode should only be allowed to be set once
null
```\\nfunction beginGlobalSettlement(uint256 price) public onlyWhitelistAdmin {\\n require(status != LibTypes.Status.SETTLED, "already settled");\\n settlementPrice = price;\\n status = LibTypes.Status.SETTLING;\\n emit BeginGlobalSettlement(price);\\n}\\n```\\n
Exchange - OrderStatus is never used
low
The enum `OrderStatus` is declared but never used.\\n```\\nenum OrderStatus {EXPIRED, CANCELLED, FILLABLE, FULLY\\_FILLED}\\n```\\n
Resolution\\nThis issue was resolved by removing the unused code.\\nRemove unused code.
null
```\\nenum OrderStatus {EXPIRED, CANCELLED, FILLABLE, FULLY\\_FILLED}\\n```\\n
LibMath - Inaccurate declaration of _UINT256_MAX
low
`LibMathUnsigned` declares `_UINT256_MAX` as `2^255-1` while this value actually represents `_INT256_MAX`. This appears to just be a naming issue.\\n(UINT256_MAX/2-1 => pos INT256_MAX; 2**256/2-1==2**255-1)\\n```\\nlibrary LibMathUnsigned {\\n uint256 private constant \\_WAD = 10\\*\\*18;\\n uint256 private constant \\_UINT256\\_MAX = 2\\*\\*255 - 1;\\n```\\n
Rename `_UINT256_MAX` to `_INT256MAX` or `_SIGNED_INT256MAX`.
null
```\\nlibrary LibMathUnsigned {\\n uint256 private constant \\_WAD = 10\\*\\*18;\\n uint256 private constant \\_UINT256\\_MAX = 2\\*\\*255 - 1;\\n```\\n
LibMath - inconsistent assertion text and improve representation of literals with many digits Acknowledged
low
The assertion below states that `logE only accepts v <= 1e22 * 1e18` while the argument name is `x`. In addition to that we suggest representing large literals in scientific notation.\\n```\\nfunction wln(int256 x) internal pure returns (int256) {\\n require(x > 0, "logE of negative number");\\n require(x <= 10000000000000000000000000000000000000000, "logE only accepts v <= 1e22 \\* 1e18"); // in order to prevent using safe-math\\n int256 r = 0;\\n uint8 extra\\_digits = longer\\_digits - fixed\\_digits;\\n```\\n
Update the inconsistent assertion text `v` -> `x` and represent large literals in scientific notation as they are otherwise difficult to read and review.
null
```\\nfunction wln(int256 x) internal pure returns (int256) {\\n require(x > 0, "logE of negative number");\\n require(x <= 10000000000000000000000000000000000000000, "logE only accepts v <= 1e22 \\* 1e18"); // in order to prevent using safe-math\\n int256 r = 0;\\n uint8 extra\\_digits = longer\\_digits - fixed\\_digits;\\n```\\n
LibMath - roundHalfUp returns unfinished result
low
The method `LibMathSigned.roundHalfUp(int `x`, int y)` returns the value `x` rounded up to the base `y`. The method suggests that the result is the rounded value while that's not actually true. The result for a positive `x` is `x` + base/2 and `x` - base/2 for negative values. The rounding is not yet finished as this would require a final division by base `y` to manifest the rounding.\\nIt is assumed that the final rounding step is not executed for performance reasons. However, this might easily introduce errors when the caller assumes the result is rounded for base while it is not.\\n`roundHalfUp(-4700, 1000) = -4700` instead of `5000`\\n`roundHalfUp(4700, 1000) = 4700` instead of `5000`\\n```\\n// ROUND\\_HALF\\_UP rule helper. 0.5 β‰ˆ 1, 0.4 β‰ˆ 0, -0.5 β‰ˆ -1, -0.4 β‰ˆ 0\\nfunction roundHalfUp(int256 x, int256 y) internal pure returns (int256) {\\n require(y > 0, "roundHalfUp only supports y > 0");\\n if (x >= 0) {\\n return add(x, y / 2);\\n }\\n return sub(x, y / 2);\\n}\\n```\\n
We have verified the current code-base and the callers for `roundHalfUp` are correctly finishing the rounding step. However, it is recommended to finish the rounding within the method or document this behavior to prevent errors caused by code that falsely assumes that the returned value finished rounding.
null
```\\n// ROUND\\_HALF\\_UP rule helper. 0.5 β‰ˆ 1, 0.4 β‰ˆ 0, -0.5 β‰ˆ -1, -0.4 β‰ˆ 0\\nfunction roundHalfUp(int256 x, int256 y) internal pure returns (int256) {\\n require(y > 0, "roundHalfUp only supports y > 0");\\n if (x >= 0) {\\n return add(x, y / 2);\\n }\\n return sub(x, y / 2);\\n}\\n```\\n
LibMath/LibOrder - unused named return value
low
The following methods declare a named return value but explicitly return a value instead. The named return value is not used.\\n`LibMathSigned.min()`\\n`LibMathSigned.max()`\\n`LibMathUnsigned.min()`\\n`LibMathUnsigned.max()`\\n`LibOrder.getOrderHash()`\\n`LibOrder.hashOrder()`\\n```\\nfunction min(int256 x, int256 y) internal pure returns (int256 z) {\\n return x <= y ? x : y;\\n}\\n\\nfunction max(int256 x, int256 y) internal pure returns (int256 z) {\\n return x >= y ? x : y;\\n}\\n```\\n\\n```\\nfunction min(uint256 x, uint256 y) internal pure returns (uint256 z) {\\n return x <= y ? x : y;\\n}\\n\\nfunction max(uint256 x, uint256 y) internal pure returns (uint256 z) {\\n return x >= y ? x : y;\\n}\\n```\\n\\n```\\nfunction getOrderHash(Order memory order) internal pure returns (bytes32 orderHash) {\\n orderHash = LibEIP712.hashEIP712Message(hashOrder(order));\\n return orderHash;\\n}\\n```\\n\\n```\\nfunction hashOrder(Order memory order) internal pure returns (bytes32 result) {\\n bytes32 orderType = EIP712\\_ORDER\\_TYPE;\\n // solium-disable-next-line security/no-inline-assembly\\n assembly {\\n let start := sub(order, 32)\\n let tmp := mload(start)\\n mstore(start, orderType)\\n result := keccak256(start, 224)\\n mstore(start, tmp)\\n }\\n return result;\\n}\\n```\\n
Remove the named return value and explicitly return the value.
null
```\\nfunction min(int256 x, int256 y) internal pure returns (int256 z) {\\n return x <= y ? x : y;\\n}\\n\\nfunction max(int256 x, int256 y) internal pure returns (int256 z) {\\n return x >= y ? x : y;\\n}\\n```\\n
Commented code exists in BMath
low
```\\nuint tokenInRatio = bdiv(newTokenBalanceIn, tokenBalanceIn);\\n\\n// uint newPoolSupply = (ratioTi ^ weightTi) \\* poolSupply;\\nuint poolRatio = bpow(tokenInRatio, normalizedWeight);\\n```\\n\\n```\\nuint normalizedWeight = bdiv(tokenWeightOut, totalWeight);\\n// charge exit fee on the pool token side\\n// pAiAfterExitFee = pAi\\*(1-exitFee)\\nuint poolAmountInAfterExitFee = bmul(poolAmountIn, bsub(BONE, EXIT\\_FEE));\\n```\\n\\nAnd many more examples.
Remove the commented code, or address them properly. If the code is related to exit fee, which is considered to be 0 in this version, this style should be persistent in other contracts as well.
null
```\\nuint tokenInRatio = bdiv(newTokenBalanceIn, tokenBalanceIn);\\n\\n// uint newPoolSupply = (ratioTi ^ weightTi) \\* poolSupply;\\nuint poolRatio = bpow(tokenInRatio, normalizedWeight);\\n```\\n
Max weight requirement in rebind is inaccurate
low
`BPool.rebind` enforces `MIN_WEIGHT` and `MAX_WEIGHT` bounds on the passed-in `denorm` value:\\n```\\nfunction rebind(address token, uint balance, uint denorm)\\n public\\n \\_logs\\_\\n \\_lock\\_\\n{\\n\\n require(msg.sender == \\_controller, "ERR\\_NOT\\_CONTROLLER");\\n require(\\_records[token].bound, "ERR\\_NOT\\_BOUND");\\n require(!\\_finalized, "ERR\\_IS\\_FINALIZED");\\n\\n require(denorm >= MIN\\_WEIGHT, "ERR\\_MIN\\_WEIGHT");\\n require(denorm <= MAX\\_WEIGHT, "ERR\\_MAX\\_WEIGHT");\\n require(balance >= MIN\\_BALANCE, "ERR\\_MIN\\_BALANCE");\\n```\\n\\n`MIN_WEIGHT` is `1 BONE`, and `MAX_WEIGHT` is `50 BONE`.\\nThough a token weight of `50 BONE` may make sense in a single-token system, `BPool` is intended to be used with two to eight tokens. The sum of the weights of all tokens must not be greater than `50 BONE`.\\nThis implies that a weight of `50 BONE` for any single token is incorrect, given that at least one other token must be present.
`MAX_WEIGHT` for any single token should be `MAX_WEIGHT` - MIN_WEIGHT, or `49 BONE`.
null
```\\nfunction rebind(address token, uint balance, uint denorm)\\n public\\n \\_logs\\_\\n \\_lock\\_\\n{\\n\\n require(msg.sender == \\_controller, "ERR\\_NOT\\_CONTROLLER");\\n require(\\_records[token].bound, "ERR\\_NOT\\_BOUND");\\n require(!\\_finalized, "ERR\\_IS\\_FINALIZED");\\n\\n require(denorm >= MIN\\_WEIGHT, "ERR\\_MIN\\_WEIGHT");\\n require(denorm <= MAX\\_WEIGHT, "ERR\\_MAX\\_WEIGHT");\\n require(balance >= MIN\\_BALANCE, "ERR\\_MIN\\_BALANCE");\\n```\\n
Test code present in the code base
medium
Test code are present in the code base. This is mainly a reminder to fix those before production.\\n`rescuerAddress` and `freezerAddress` are not even in the function arguments.\\n```\\nwhitelistingAddress = \\_whitelistingAddress;\\nprojectAddress = \\_projectAddress;\\nfreezerAddress = \\_projectAddress; // TODO change, here only for testing\\nrescuerAddress = \\_projectAddress; // TODO change, here only for testing\\n```\\n
Resolution\\nFixed in lukso-network/[email protected]edb880c.\\nMake sure all the variable assignments are ready for production before deployment to production.
null
```\\nwhitelistingAddress = \\_whitelistingAddress;\\nprojectAddress = \\_projectAddress;\\nfreezerAddress = \\_projectAddress; // TODO change, here only for testing\\nrescuerAddress = \\_projectAddress; // TODO change, here only for testing\\n```\\n
frozenPeriod is subtracted twice for calculating the current price
medium
If the contract had been frozen, the current stage price will calculate the price by subtracting the `frozenPeriod` twice and result in wrong calculation.\\n`getCurrentBlockNumber()` subtracts `frozenPeriod` once, and then `getStageAtBlock()` will also subtract the same number again.\\n```\\nfunction getCurrentStage() public view returns (uint8) {\\n return getStageAtBlock(getCurrentBlockNumber());\\n}\\n```\\n\\n```\\nfunction getCurrentBlockNumber() public view returns (uint256) {\\n return uint256(block.number)\\n .sub(frozenPeriod); // make sure we deduct any frozenPeriod from calculations\\n}\\n```\\n\\n```\\nfunction getStageAtBlock(uint256 \\_blockNumber) public view returns (uint8) {\\n\\n uint256 blockNumber = \\_blockNumber.sub(frozenPeriod); // adjust the block by the frozen period\\n```\\n
Resolution\\nFound in parallel to the audit team and has been mitigated in lukso-network/[email protected]ebc4bce . The issue was further simplified by adding `getCurrentEffectiveBlockNumber()` in lukso-network/[email protected]e4c9ed5 to remove ambiguity when calculating current block number.\\nMake sure `frozenPeriod` calculation is done correctly. It could be solved by renaming `getCurrentBlockNumber()` to reflect the calculation done inside the function.\\ne.g. :\\n`getCurrentBlockNumber()` : gets current block number\\n`getCurrentEffectiveBlockNumber()` : calculates the effective block number deducting `frozenPeriod`
null
```\\nfunction getCurrentStage() public view returns (uint8) {\\n return getStageAtBlock(getCurrentBlockNumber());\\n}\\n```\\n
Gold order size should be limited
high
When a user submits an order to buy gold cards, it's possible to buy a huge amount of cards. `_commit` function uses less gas than `mineGolds`, which means that the user can successfully commit to buying this amount of cards and when it's time to collect them, `mineGolds` function may run out of gas because it iterates over all card IDs and mints them:\\n```\\n// Mint gold cards\\nskyweaverAssets.batchMint(\\_order.cardRecipient, \\_ids, amounts, "");\\n```\\n
Resolution\\nAddressed in horizon-games/SkyWeaver-contracts#9 by adding a limit for cold cards amount in one order.\\nLimit a maximum gold card amount in one order.
null
```\\n// Mint gold cards\\nskyweaverAssets.batchMint(\\_order.cardRecipient, \\_ids, amounts, "");\\n```\\n
Price and refund changes may cause failures
high
Price and refund for gold cards are used in 3 different places: commit, mint, refund.\\nWeave tokens spent during the commit phase\\n```\\nfunction \\_commit(uint256 \\_weaveAmount, GoldOrder memory \\_order)\\n internal\\n{\\n // Check if weave sent is sufficient for order\\n uint256 total\\_cost = \\_order.cardAmount.mul(goldPrice).add(\\_order.feeAmount);\\n uint256 refund\\_amount = \\_weaveAmount.sub(total\\_cost); // Will throw if insufficient amount received\\n```\\n\\nbut they are burned `rngDelay` blocks after\\n```\\n// Burn the non-refundable weave\\nuint256 weave\\_to\\_burn = (\\_order.cardAmount.mul(goldPrice)).sub(\\_order.cardAmount.mul(goldRefund));\\nweaveContract.burn(weaveID, weave\\_to\\_burn);\\n```\\n\\nIf the price is increased between these transactions, mining cards may fail because it should burn more `weave` tokens than there are tokens in the smart contract. Even if there are enough tokens during this particular transaction, someone may fail to melt a gold card later.\\nIf the price is decreased, some `weave` tokens will be stuck in the contract forever without being burned.
Store `goldPrice` and `goldRefund` in `GoldOrder`.
null
```\\nfunction \\_commit(uint256 \\_weaveAmount, GoldOrder memory \\_order)\\n internal\\n{\\n // Check if weave sent is sufficient for order\\n uint256 total\\_cost = \\_order.cardAmount.mul(goldPrice).add(\\_order.feeAmount);\\n uint256 refund\\_amount = \\_weaveAmount.sub(total\\_cost); // Will throw if insufficient amount received\\n```\\n
Re-entrancy attack allows to buy EternalHeroes cheaper
high
When buying eternal heroes in `_buy` function of `EternalHeroesFactory` contract, a buyer can do re-entracy before items are minted.\\n```\\nuint256 refundAmount = \\_arcAmount.sub(total\\_cost);\\nif (refundAmount > 0) {\\n arcadeumCoin.safeTransferFrom(address(this), \\_recipient, arcadeumCoinID, refundAmount, "");\\n}\\n\\n// Mint tokens to recipient\\nfactoryManager.batchMint(\\_recipient, \\_ids, amounts\\_to\\_mint, "");\\n```\\n\\nSince price should increase after every `N` items are minted, it's possible to buy more items with the old price.
Add re-entrancy protection or mint items before sending the refund.
null
```\\nuint256 refundAmount = \\_arcAmount.sub(total\\_cost);\\nif (refundAmount > 0) {\\n arcadeumCoin.safeTransferFrom(address(this), \\_recipient, arcadeumCoinID, refundAmount, "");\\n}\\n\\n// Mint tokens to recipient\\nfactoryManager.batchMint(\\_recipient, \\_ids, amounts\\_to\\_mint, "");\\n```\\n
Supply limitation misbehaviors
medium
In `SWSupplyManager` contract, the `owner` can limit supply for any token ID by setting maxSupply:\\n```\\nfunction setMaxSupplies(uint256[] calldata \\_ids, uint256[] calldata \\_newMaxSupplies) external onlyOwner() {\\n require(\\_ids.length == \\_newMaxSupplies.length, "SWSupplyManager#setMaxSupply: INVALID\\_ARRAYS\\_LENGTH");\\n\\n // Can only \\*decrease\\* a max supply\\n // Can't set max supply back to 0\\n for (uint256 i = 0; i < \\_ids.length; i++ ) {\\n if (maxSupply[\\_ids[i]] > 0) {\\n require(\\n 0 < \\_newMaxSupplies[i] && \\_newMaxSupplies[i] < maxSupply[\\_ids[i]],\\n "SWSupplyManager#setMaxSupply: INVALID\\_NEW\\_MAX\\_SUPPLY"\\n );\\n }\\n maxSupply[\\_ids[i]] = \\_newMaxSupplies[i];\\n }\\n\\n emit MaxSuppliesChanged(\\_ids, \\_newMaxSupplies);\\n}\\n```\\n\\nThe problem is that you can set `maxSupply` that is lower than `currentSupply`, which would be an unexpected state to have.\\nAlso, if some tokens are burned, their `currentSupply` is not decreasing:\\n```\\nfunction burn(\\n uint256 \\_id,\\n uint256 \\_amount)\\n external\\n{\\n \\_burn(msg.sender, \\_id, \\_amount);\\n}\\n```\\n\\nThis unexpected behaviour may lead to burning all of the tokens without being able to mint more.
Properly track `currentSupply` by modifying it in `burn` function. Consider having a following restriction `require(_newMaxSupplies[i] > currentSupply[_ids[i]])` in `setMaxSupplies` function.
null
```\\nfunction setMaxSupplies(uint256[] calldata \\_ids, uint256[] calldata \\_newMaxSupplies) external onlyOwner() {\\n require(\\_ids.length == \\_newMaxSupplies.length, "SWSupplyManager#setMaxSupply: INVALID\\_ARRAYS\\_LENGTH");\\n\\n // Can only \\*decrease\\* a max supply\\n // Can't set max supply back to 0\\n for (uint256 i = 0; i < \\_ids.length; i++ ) {\\n if (maxSupply[\\_ids[i]] > 0) {\\n require(\\n 0 < \\_newMaxSupplies[i] && \\_newMaxSupplies[i] < maxSupply[\\_ids[i]],\\n "SWSupplyManager#setMaxSupply: INVALID\\_NEW\\_MAX\\_SUPPLY"\\n );\\n }\\n maxSupply[\\_ids[i]] = \\_newMaxSupplies[i];\\n }\\n\\n emit MaxSuppliesChanged(\\_ids, \\_newMaxSupplies);\\n}\\n```\\n
importScore() in IexecMaintenanceDelegate can be used to wrongfully reset worker scores Acknowledged
medium
The import of worker scores from the previous PoCo system deployed on chain is made to be asynchronous. And, even though the pull pattern usually makes a system much more resilient, in this case, it opens up the possibility for an attack that undermines the trust-based game-theoretical balance the PoCo system relies on. As can be seen in the following function:\\n```\\nfunction importScore(address \\_worker)\\nexternal override\\n{\\n require(!m\\_v3\\_scoreImported[\\_worker], "score-already-imported");\\n m\\_workerScores[\\_worker] = m\\_workerScores[\\_worker].max(m\\_v3\\_iexecHub.viewScore(\\_worker));\\n m\\_v3\\_scoreImported[\\_worker] = true;\\n}\\n```\\n\\nA motivated attacker could attack the system providing bogus results for computation tasks therefore reducing his own reputation (mirrored by the low worker score that would follow).\\nAfter the fact, the attacker could reset its score to the previous high value attained in the previously deployed PoCo system (v3) and undo all the wrongdoings he had done at no reputational cost.
Resolution\\nUpdate from the iExec team:\\nIn order to perform this attack, one would first have to gain reputation on the new version, and lose it. They would then be able to restore its score from the old version.\\nWe feel the risk is acceptable for a few reasons:\\nIt can only be done once per worker\\nConsidering the score dynamics discussed in the β€œTrust in the PoCo” document, it is more interesting for a worker to import its reputation in the beginning rather then creating a new one, since bad contributions only remove part of the reputation\\nOnly a handful of workers have reputation in the old system (180), and their score is low (average 7, max 22)\\nWe might force the import all 180 workers with reputation >0. A script to identify the relevant addresses is already available.\\nCheck that each worker interacting with the PoCo system has already imported his score. Otherwise import it synchronously with a call at the time of their first interaction.
null
```\\nfunction importScore(address \\_worker)\\nexternal override\\n{\\n require(!m\\_v3\\_scoreImported[\\_worker], "score-already-imported");\\n m\\_workerScores[\\_worker] = m\\_workerScores[\\_worker].max(m\\_v3\\_iexecHub.viewScore(\\_worker));\\n m\\_v3\\_scoreImported[\\_worker] = true;\\n}\\n```\\n
Domain separator in iExecMaintenanceDelegate has a wrong version field Acknowledged
medium
The domain separator used to comply with the EIP712 standard in `iExecMaintenanceDelegate` has a wrong version field.\\n```\\nfunction \\_domain()\\ninternal view returns (IexecLibOrders\\_v5.EIP712Domain memory)\\n{\\n return IexecLibOrders\\_v5.EIP712Domain({\\n name: "iExecODB"\\n , version: "3.0-alpha"\\n , chainId: \\_chainId()\\n , verifyingContract: address(this)\\n });\\n}\\n```\\n\\nIn the above snippet we can see the code is still using the version field from an old version of the PoCo protocol, `"3.0-alpha"`.
Resolution\\nIssue was fixed in iExecBlockchainComputing/[email protected]ebee370\\nChange the version field to: `"5.0-alpha"`
null
```\\nfunction \\_domain()\\ninternal view returns (IexecLibOrders\\_v5.EIP712Domain memory)\\n{\\n return IexecLibOrders\\_v5.EIP712Domain({\\n name: "iExecODB"\\n , version: "3.0-alpha"\\n , chainId: \\_chainId()\\n , verifyingContract: address(this)\\n });\\n}\\n```\\n
The updateContract() method in ERC1538UpdateDelegate is incorrectly implemented
low
The `updateContract()` method in `ERC1538UpdateDelegate` does not behave as intended for some specific streams of bytes (meant to be parsed as function signatures).\\nThe mentioned function takes as input, among other things, a `string` (which is, canonically, a dynamically-sized `bytes` array) and tries to parse it as a conjunction of function signatures.\\nAs is evident in:\\n```\\nif (char == 0x3B) // 0x3B = ';'\\n```\\n\\nInside the function, `;` is being used as a β€œreserved” character, serving as a delimiter between each function signature.\\nHowever, if two semicolons are used in succession, the second one will not be checked and will be made part of the function signature being sent into the `_setFunc()` method.\\nExample of faulty input\\n`someFunc;;someOtherFuncWithSemiColon;`
Resolution\\nIssue was fixed in iExecBlockchainComputing/[email protected]e6be083\\nReplace the line that increases the `pos` counter at the end of the function:\\n```\\nstart = ++pos;\\n```\\n\\nWIth this line of code:\\n`start = pos + 1;`
null
```\\nif (char == 0x3B) // 0x3B = ';'\\n```\\n
TokenStaking.recoverStake allows instant stake undelegation
high
`TokenStaking.recoverStake` is used to recover stake that has been designated to be undelegated. It contains a single check to ensure that the undelegation period has passed:\\n```\\nfunction recoverStake(address \\_operator) public {\\n uint256 operatorParams = operators[\\_operator].packedParams;\\n require(\\n block.number > operatorParams.getUndelegationBlock().add(undelegationPeriod),\\n "Can not recover stake before undelegation period is over."\\n );\\n```\\n\\nHowever, if an undelegation period is never set, this will always return true, allowing any operator to instantly undelegate stake at any time.
Require that the undelegation period is nonzero before allowing an operator to recover stake.
null
```\\nfunction recoverStake(address \\_operator) public {\\n uint256 operatorParams = operators[\\_operator].packedParams;\\n require(\\n block.number > operatorParams.getUndelegationBlock().add(undelegationPeriod),\\n "Can not recover stake before undelegation period is over."\\n );\\n```\\n
tbtc - No access control in TBTCSystem.requestNewKeep
high
`TBTCSystem.requestNewKeep` is used by each new `Deposit` contract on creation. It calls `BondedECDSAKeepFactory.openKeep`, which sets the `Deposit` contract as the β€œowner,” a permissioned role within the created keep. `openKeep` also automatically allocates bonds from members registered to the application. The β€œapplication” from which member bonds are allocated is the tbtc system itself.\\nBecause `requestNewKeep` has no access controls, anyone can request that a keep be opened with `msg.sender` as the β€œowner,” and arbitrary signing threshold values:\\n```\\n/// @notice Request a new keep opening.\\n/// @param \\_m Minimum number of honest keep members required to sign.\\n/// @param \\_n Number of members in the keep.\\n/// @return Address of a new keep.\\nfunction requestNewKeep(uint256 \\_m, uint256 \\_n, uint256 \\_bond)\\n external\\n payable\\n returns (address)\\n{\\n IBondedECDSAKeepVendor \\_keepVendor = IBondedECDSAKeepVendor(keepVendor);\\n IBondedECDSAKeepFactory \\_keepFactory = IBondedECDSAKeepFactory(\\_keepVendor.selectFactory());\\n return \\_keepFactory.openKeep.value(msg.value)(\\_n, \\_m, msg.sender, \\_bond);\\n}\\n```\\n\\nGiven that the owner of a keep is able to seize signer bonds, close the keep, and more, having control of this role could be detrimental to group members.
Resolution\\nIssue addressed in keep-network/tbtc#514. Each call to `requestNewKeep` makes a check that `uint(msg.sender)` is an existing `TBTCDepositToken`. Because these tokens are only minted in `DepositFactory`, `msg.sender` would have to be one of the cloned deposit contracts.\\nAdd access control to `requestNewKeep`, so that it can only be called as a part of the `Deposit` creation and initialization process.
null
```\\n/// @notice Request a new keep opening.\\n/// @param \\_m Minimum number of honest keep members required to sign.\\n/// @param \\_n Number of members in the keep.\\n/// @return Address of a new keep.\\nfunction requestNewKeep(uint256 \\_m, uint256 \\_n, uint256 \\_bond)\\n external\\n payable\\n returns (address)\\n{\\n IBondedECDSAKeepVendor \\_keepVendor = IBondedECDSAKeepVendor(keepVendor);\\n IBondedECDSAKeepFactory \\_keepFactory = IBondedECDSAKeepFactory(\\_keepVendor.selectFactory());\\n return \\_keepFactory.openKeep.value(msg.value)(\\_n, \\_m, msg.sender, \\_bond);\\n}\\n```\\n
Unpredictable behavior due to front running or general bad timing
high
In a number of cases, administrators of contracts can update or upgrade things in the system without warning. This has the potential to violate a security goal of the system.\\nSpecifically, privileged roles could use front running to make malicious changes just ahead of incoming transactions, or purely accidental negative effects could occur due to unfortunate timing of changes.\\nSome instances of this are more important than others, but in general users of the system should have assurances about the behavior of the action they're about to take.\\nSystem Parameters\\nThe owner of the `TBTCSystem` contract can change system parameters at any time with changes taking effect immediately.\\n`setSignerFeeDivisor` - stored in the deposit contract when creating a new deposit. emits an event.\\n`setLotSizes` - stored in the deposit contract when creating a new deposit. emits an event.\\n`setCollateralizationThresholds` - stored in the deposit contract when creating a new deposit. emits an event.\\nThis also opens up an opportunity for malicious owner to:\\ninterfere with other participants deposit creation attempts (front-running transactions)\\ncraft a series of transactions that allow the owner to set parameters that are more beneficial to them, then create a deposit and reset the parameters to the systems' initial settings.\\n```\\n/// @notice Set the system signer fee divisor.\\n/// @param \\_signerFeeDivisor The signer fee divisor.\\nfunction setSignerFeeDivisor(uint256 \\_signerFeeDivisor)\\n external onlyOwner\\n{\\n require(\\_signerFeeDivisor > 9, "Signer fee divisor must be greater than 9, for a signer fee that is <= 10%.");\\n signerFeeDivisor = \\_signerFeeDivisor;\\n emit SignerFeeDivisorUpdated(\\_signerFeeDivisor);\\n}\\n```\\n\\nUpgradables\\nThe proxy pattern used in many places throughout the system allows the operator to set a new implementation which takes effect immediately.\\n```\\n/\\*\\*\\n \\* @dev Upgrade current implementation.\\n \\* @param \\_implementation Address of the new implementation contract.\\n \\*/\\nfunction upgradeTo(address \\_implementation)\\n public\\n onlyOwner\\n{\\n address currentImplementation = implementation();\\n require(\\_implementation != address(0), "Implementation address can't be zero.");\\n require(\\_implementation != currentImplementation, "Implementation address must be different from the current one.");\\n setImplementation(\\_implementation);\\n emit Upgraded(\\_implementation);\\n}\\n```\\n\\n```\\n/// @notice Upgrades the current vendor implementation.\\n/// @param \\_implementation Address of the new vendor implementation contract.\\nfunction upgradeTo(address \\_implementation) public onlyOwner {\\n address currentImplementation = implementation();\\n require(\\n \\_implementation != address(0),\\n "Implementation address can't be zero."\\n );\\n require(\\n \\_implementation != currentImplementation,\\n "Implementation address must be different from the current one."\\n );\\n setImplementation(\\_implementation);\\n emit Upgraded(\\_implementation);\\n}\\n```\\n\\nRegistry\\n```\\nfunction registerFactory(address payable \\_factory) external onlyOperatorContractUpgrader {\\n require(\\_factory != address(0), "Incorrect factory address");\\n require(\\n registry.isApprovedOperatorContract(\\_factory),\\n "Factory contract is not approved"\\n );\\n keepFactory = \\_factory;\\n}\\n```\\n
The underlying issue is that users of the system can't be sure what the behavior of a function call will be, and this is because the behavior can change at any time.\\nWe recommend giving the user advance notice of changes with a time lock. For example, make all upgrades require two steps with a mandatory time window between them. The first step merely broadcasts to users that a particular change is coming, and the second step commits that change after a suitable waiting period.
null
```\\n/// @notice Set the system signer fee divisor.\\n/// @param \\_signerFeeDivisor The signer fee divisor.\\nfunction setSignerFeeDivisor(uint256 \\_signerFeeDivisor)\\n external onlyOwner\\n{\\n require(\\_signerFeeDivisor > 9, "Signer fee divisor must be greater than 9, for a signer fee that is <= 10%.");\\n signerFeeDivisor = \\_signerFeeDivisor;\\n emit SignerFeeDivisorUpdated(\\_signerFeeDivisor);\\n}\\n```\\n
keep-core - reportRelayEntryTimeout creates an incentive for nodes to race for rewards potentially wasting gas and it creates an opportunity for front-running
high
The incentive on `reportRelayEntryTimeout` for being rewarded with 5% of the seized amount creates an incentive to call the method but might also kick off a race for front-running this call. This method is being called from the keep node which is unlikely to adjust the gasPrice and might always lose the race against a front-running bot collecting rewards for all timeouts and fraud proofs (issue 5.7)\\n```\\n/\\*\\*\\n \\* @dev Function used to inform about the fact the currently ongoing\\n \\* new relay entry generation operation timed out. As a result, the group\\n \\* which was supposed to produce a new relay entry is immediately\\n \\* terminated and a new group is selected to produce a new relay entry.\\n \\* All members of the group are punished by seizing minimum stake of\\n \\* their tokens. The submitter of the transaction is rewarded with a\\n \\* tattletale reward which is limited to min(1, 20 / group\\_size) of the\\n \\* maximum tattletale reward.\\n \\*/\\nfunction reportRelayEntryTimeout() public {\\n require(hasEntryTimedOut(), "Entry did not time out");\\n groups.reportRelayEntryTimeout(signingRequest.groupIndex, groupSize, minimumStake);\\n\\n // We could terminate the last active group. If that's the case,\\n // do not try to execute signing again because there is no group\\n // which can handle it.\\n if (numberOfGroups() > 0) {\\n signRelayEntry(\\n signingRequest.relayRequestId,\\n signingRequest.previousEntry,\\n signingRequest.serviceContract,\\n signingRequest.entryVerificationAndProfitFee,\\n signingRequest.callbackFee\\n );\\n }\\n}\\n```\\n
Make sure that `reportRelayEntryTimeout` throws as early as possible if the group was previously terminated (isGroupTerminated) to avoid that keep-nodes spend gas on a call that will fail. Depending on the reward for calling out the timeout this might create a front-running opportunity that cannot be resolved.
null
```\\n/\\*\\*\\n \\* @dev Function used to inform about the fact the currently ongoing\\n \\* new relay entry generation operation timed out. As a result, the group\\n \\* which was supposed to produce a new relay entry is immediately\\n \\* terminated and a new group is selected to produce a new relay entry.\\n \\* All members of the group are punished by seizing minimum stake of\\n \\* their tokens. The submitter of the transaction is rewarded with a\\n \\* tattletale reward which is limited to min(1, 20 / group\\_size) of the\\n \\* maximum tattletale reward.\\n \\*/\\nfunction reportRelayEntryTimeout() public {\\n require(hasEntryTimedOut(), "Entry did not time out");\\n groups.reportRelayEntryTimeout(signingRequest.groupIndex, groupSize, minimumStake);\\n\\n // We could terminate the last active group. If that's the case,\\n // do not try to execute signing again because there is no group\\n // which can handle it.\\n if (numberOfGroups() > 0) {\\n signRelayEntry(\\n signingRequest.relayRequestId,\\n signingRequest.previousEntry,\\n signingRequest.serviceContract,\\n signingRequest.entryVerificationAndProfitFee,\\n signingRequest.callbackFee\\n );\\n }\\n}\\n```\\n
keep-core - reportUnauthorizedSigning fraud proof is not bound to reporter and can be front-run
high
An attacker can monitor `reportUnauthorizedSigning()` for fraud reports and attempt to front-run the original call in an effort to be the first one reporting the fraud and be rewarded 5% of the total seized amount.\\n```\\n/\\*\\*\\n \\* @dev Reports unauthorized signing for the provided group. Must provide\\n \\* a valid signature of the group address as a message. Successful signature\\n \\* verification means the private key has been leaked and all group members\\n \\* should be punished by seizing their tokens. The submitter of this proof is\\n \\* rewarded with 5% of the total seized amount scaled by the reward adjustment\\n \\* parameter and the rest 95% is burned.\\n \\*/\\nfunction reportUnauthorizedSigning(\\n uint256 groupIndex,\\n bytes memory signedGroupPubKey\\n) public {\\n groups.reportUnauthorizedSigning(groupIndex, signedGroupPubKey, minimumStake);\\n}\\n```\\n
Require the reporter to include `msg.sender` in the signature proving the fraud or implement a two-step commit/reveal scheme to counter front-running opportunities by forcing a reporter to secretly commit the fraud parameters in one block and reveal them in another.
null
```\\n/\\*\\*\\n \\* @dev Reports unauthorized signing for the provided group. Must provide\\n \\* a valid signature of the group address as a message. Successful signature\\n \\* verification means the private key has been leaked and all group members\\n \\* should be punished by seizing their tokens. The submitter of this proof is\\n \\* rewarded with 5% of the total seized amount scaled by the reward adjustment\\n \\* parameter and the rest 95% is burned.\\n \\*/\\nfunction reportUnauthorizedSigning(\\n uint256 groupIndex,\\n bytes memory signedGroupPubKey\\n) public {\\n groups.reportUnauthorizedSigning(groupIndex, signedGroupPubKey, minimumStake);\\n}\\n```\\n
keep-core - operator contracts disabled via panic button can be re-enabled by RegistryKeeper
high
The Registry contract defines three administrative accounts: `Governance`, `registryKeeper`, and `panicButton`. All permissions are initially assigned to the deployer when the contract is created. The account acting like a super-admin, being allowed to re-assign administrative accounts - is `Governance`. `registryKeeper` is a lower privileged account maintaining the registry and `panicButton` is an emergency account that can disable operator contracts.\\nThe keep specification states the following:\\nPanic Button The Panic Button can disable malicious or malfunctioning contracts that have been previously approved by the Registry Keeper. When a contract is disabled by the Panic Button, its status on the registry changes to reflect this, and it becomes ineligible to penalize operators. Contracts disabled by the Panic Button can not be reactivated. The Panic Button can be rekeyed by Governance.\\nIt is assumed that the permissions are `Governance` > `panicButton` > `registryKeeper`, meaning that `panicButton` should be able to overrule `registryKeeper`, while `registryKeeper` cannot overrule `panicButton`.\\nWith the current implementation of the Registry the `registryKeeper` account can re-enable an operator contract that has previously been disabled by the `panicButton` account.\\nWe would also like to note the following:\\nThe contract should use enums instead of integer literals when working with contract states.\\nChanges to the contract take effect immediately, allowing an administrative account to selectively front-run calls to the Registry ACL and interfere with user activity.\\nThe operator contract state can be set to the current value without raising an error.\\nThe panic button can be called for operator contracts that are not yet active.\\n```\\nfunction approveOperatorContract(address operatorContract) public onlyRegistryKeeper {\\n operatorContracts[operatorContract] = 1;\\n}\\n\\nfunction disableOperatorContract(address operatorContract) public onlyPanicButton {\\n operatorContracts[operatorContract] = 2;\\n}\\n```\\n
The keep specification states:\\nThe Panic Button can be used to set the status of an APPROVED contract to DISABLED. Operator Contracts disabled with the Panic Button cannot be re-enabled, and disabled contracts may not punish operators nor be selected by service contracts to perform work.\\nAll three accounts are typically trusted. We recommend requiring the `Governance` or `paniceButton` accounts to reset the contract operator state before `registryKeeper` can change the state or disallow re-enabling of disabled operator contracts as stated in the specification.
null
```\\nfunction approveOperatorContract(address operatorContract) public onlyRegistryKeeper {\\n operatorContracts[operatorContract] = 1;\\n}\\n\\nfunction disableOperatorContract(address operatorContract) public onlyPanicButton {\\n operatorContracts[operatorContract] = 2;\\n}\\n```\\n
tbtc - State transitions are not always enforced
high
A deposit follows a complex state-machine that makes sure it is correctly funded before `TBTC` Tokens are minted. The deposit lifecycle starts with a set of states modeling a funding flow that - if successful - ultimately leads to the deposit being active, meaning that corresponding `TBTC` tokens exist for the deposits. A redemption flow allows to redeem `TBTC` for `BTC` and a liquidation flow handles fraud and abort conditions. Fraud cases in the funding flow are handled separately.\\nState transitions from one deposit state to another require someone calling the corresponding transition method on the deposit and actually spend gas on it. The incentive to call a transition varies and is analyzed in more detail in the security-specification section of this report.\\nThis issue assumes that participants are not always pushing forward through the state machine as soon as a new state becomes available, opening up the possibility of having multiple state transitions being a valid option for a deposit (e.g. pushing a deposit to active state even though a timeout should have been called on it).\\nA TDT holder can choose not to call out `notifySignerSetupFailure` hoping that the signing group still forms after the signer setup timeout passes.\\nthere is no incentive for the TDT holder to terminate its own deposit after a timeout.\\nthe deposit might end up never being in a final error state.\\nthere is no incentive for the signing group to terminate the deposit.\\nThis affects all states that can time out.\\nThe deposit can be pushed to active state even after `notifySignerSetupFailure`, `notifyFundingTimeout` have passed but nobody called it out.\\nThere is no timeout check in `retrieveSignerPubkey`, `provideBTCFundingProof`.\\n```\\n/// @notice we poll the Keep contract to retrieve our pubkey\\n/// @dev We store the pubkey as 2 bytestrings, X and Y.\\n/// @param \\_d deposit storage pointer\\n/// @return True if successful, otherwise revert\\nfunction retrieveSignerPubkey(DepositUtils.Deposit storage \\_d) public {\\n require(\\_d.inAwaitingSignerSetup(), "Not currently awaiting signer setup");\\n\\n bytes memory \\_publicKey = IBondedECDSAKeep(\\_d.keepAddress).getPublicKey();\\n require(\\_publicKey.length == 64, "public key not set or not 64-bytes long");\\n```\\n\\n```\\nfunction provideBTCFundingProof(\\n DepositUtils.Deposit storage \\_d,\\n bytes4 \\_txVersion,\\n bytes memory \\_txInputVector,\\n bytes memory \\_txOutputVector,\\n bytes4 \\_txLocktime,\\n uint8 \\_fundingOutputIndex,\\n bytes memory \\_merkleProof,\\n uint256 \\_txIndexInBlock,\\n bytes memory \\_bitcoinHeaders\\n) public returns (bool) {\\n\\n require(\\_d.inAwaitingBTCFundingProof(), "Not awaiting funding");\\n\\n bytes8 \\_valueBytes;\\n bytes memory \\_utxoOutpoint;\\n```\\n\\nMembers of the signing group might decide to call `notifyFraudFundingTimeout` in a race to avoid late submissions for `provideFraudBTCFundingProof` to succeed in order to contain funds lost due to fraud.\\nIt should be noted that even after the fraud funding timeout passed the TDT holder could `provideFraudBTCFundingProof` as it does not check for the timeout.\\nA malicious signing group observes BTC funding on the bitcoin chain in an attempt to commit fraud at the time the `provideBTCFundingProof` transition becomes available to front-run `provideFundingECDSAFraudProof` forcing the deposit into active state.\\nThe malicious users of the signing group can then try to report fraud, set themselves as `liquidationInitiator` to be awarded part of the signer bond (in addition to taking control of the BTC collateral).\\nThe TDT holders fraud-proof can be front-run, see issue 5.15\\nIf oracle price slippage occurs for one block (flash-crash type of event) someone could call an undercollateralization transition.\\nFor severe oracle errors deposits might be liquidated by calling `notifyUndercollateralizedLiquidation`. The TDT holder cannot exit liquidation in this case.\\nFor non-severe under collateralization someone could call `notifyCourtesyCall` to impose extra effort on TDT holders to `exitCourtesyCall` deposits.\\nA deposit term expiration courtesy call can be exit in the rare case where `_d.fundedAt + TBTCConstants.getDepositTerm() == block.timestamp`\\n```\\n/// @notice Goes from courtesy call to active\\n/// @dev Only callable if collateral is sufficient and the deposit is not expiring\\n/// @param \\_d deposit storage pointer\\nfunction exitCourtesyCall(DepositUtils.Deposit storage \\_d) public {\\n require(\\_d.inCourtesyCall(), "Not currently in courtesy call");\\n require(block.timestamp <= \\_d.fundedAt + TBTCConstants.getDepositTerm(), "Deposit is expiring");\\n require(getCollateralizationPercentage(\\_d) >= \\_d.undercollateralizedThresholdPercent, "Deposit is still undercollateralized");\\n \\_d.setActive();\\n \\_d.logExitedCourtesyCall();\\n}\\n```\\n\\n```\\n/// @notice Notifies the contract that its term limit has been reached\\n/// @dev This initiates a courtesy call\\n/// @param \\_d deposit storage pointer\\nfunction notifyDepositExpiryCourtesyCall(DepositUtils.Deposit storage \\_d) public {\\n require(\\_d.inActive(), "Deposit is not active");\\n require(block.timestamp >= \\_d.fundedAt + TBTCConstants.getDepositTerm(), "Deposit term not elapsed");\\n \\_d.setCourtesyCall();\\n \\_d.logCourtesyCalled();\\n \\_d.courtesyCallInitiated = block.timestamp;\\n}\\n```\\n\\nAllow exiting the courtesy call only if the deposit is not expired: `block.timestamp < _d.fundedAt + TBTCConstants.getDepositTerm()`
Ensure that there are no competing interests between participants of the system to favor one transition over the other, causing race conditions, front-running opportunities or stale deposits that are not pushed to end-states.\\nNote: Please find an analysis of incentives to call state transitions in the security section of this document.
null
```\\n/// @notice we poll the Keep contract to retrieve our pubkey\\n/// @dev We store the pubkey as 2 bytestrings, X and Y.\\n/// @param \\_d deposit storage pointer\\n/// @return True if successful, otherwise revert\\nfunction retrieveSignerPubkey(DepositUtils.Deposit storage \\_d) public {\\n require(\\_d.inAwaitingSignerSetup(), "Not currently awaiting signer setup");\\n\\n bytes memory \\_publicKey = IBondedECDSAKeep(\\_d.keepAddress).getPublicKey();\\n require(\\_publicKey.length == 64, "public key not set or not 64-bytes long");\\n```\\n
tbtc - Funder loses payment to keep if signing group is not established in time Pending
high
To create a new deposit, the funder has to pay for the creation of a keep. If establishing the keep does not succeed in time, fails or the signing group decides not to return a public key when `retrieveSignerPubkey` is called to transition from `awaiting_signer_setup` to `awaiting_btc_funding_proof` the signer setup fails. After a timeout of 3 hrs, anyone can force the deposit to transition from `awaiting_signer_setup` to `failed_setup` by calling `notifySignerSetupFailure`.\\nThe funder had to provide payment for the keep but the signing group failed to establish. Payment for the keep is not returned even though one could assume that the signing group tried to play unfairly. The signing group might intentionally try to cause this scenario to interfere with the system.\\n`retrieveSignerPubkey` fails if keep provided pubkey is empty or of an unexpected length\\n```\\n/// @notice we poll the Keep contract to retrieve our pubkey\\n/// @dev We store the pubkey as 2 bytestrings, X and Y.\\n/// @param \\_d deposit storage pointer\\n/// @return True if successful, otherwise revert\\nfunction retrieveSignerPubkey(DepositUtils.Deposit storage \\_d) public {\\n require(\\_d.inAwaitingSignerSetup(), "Not currently awaiting signer setup");\\n\\n bytes memory \\_publicKey = IBondedECDSAKeep(\\_d.keepAddress).getPublicKey();\\n require(\\_publicKey.length == 64, "public key not set or not 64-bytes long");\\n\\n \\_d.signingGroupPubkeyX = \\_publicKey.slice(0, 32).toBytes32();\\n \\_d.signingGroupPubkeyY = \\_publicKey.slice(32, 32).toBytes32();\\n require(\\_d.signingGroupPubkeyY != bytes32(0) && \\_d.signingGroupPubkeyX != bytes32(0), "Keep returned bad pubkey");\\n \\_d.fundingProofTimerStart = block.timestamp;\\n\\n \\_d.setAwaitingBTCFundingProof();\\n \\_d.logRegisteredPubkey(\\n \\_d.signingGroupPubkeyX,\\n \\_d.signingGroupPubkeyY);\\n}\\n```\\n\\n`notifySignerSetupFailure` can be called by anyone after a timeout of 3hrs\\n```\\n/// @notice Anyone may notify the contract that signing group setup has timed out\\n/// @dev We rely on the keep system punishes the signers in this case\\n/// @param \\_d deposit storage pointer\\nfunction notifySignerSetupFailure(DepositUtils.Deposit storage \\_d) public {\\n require(\\_d.inAwaitingSignerSetup(), "Not awaiting setup");\\n require(\\n block.timestamp > \\_d.signingGroupRequestedAt + TBTCConstants.getSigningGroupFormationTimeout(),\\n "Signing group formation timeout not yet elapsed"\\n );\\n \\_d.setFailedSetup();\\n \\_d.logSetupFailed();\\n\\n fundingTeardown(\\_d);\\n}\\n```\\n
It should be ensured that a keep group always establishes or otherwise the funder is refunded the fee for the keep.
null
```\\n/// @notice we poll the Keep contract to retrieve our pubkey\\n/// @dev We store the pubkey as 2 bytestrings, X and Y.\\n/// @param \\_d deposit storage pointer\\n/// @return True if successful, otherwise revert\\nfunction retrieveSignerPubkey(DepositUtils.Deposit storage \\_d) public {\\n require(\\_d.inAwaitingSignerSetup(), "Not currently awaiting signer setup");\\n\\n bytes memory \\_publicKey = IBondedECDSAKeep(\\_d.keepAddress).getPublicKey();\\n require(\\_publicKey.length == 64, "public key not set or not 64-bytes long");\\n\\n \\_d.signingGroupPubkeyX = \\_publicKey.slice(0, 32).toBytes32();\\n \\_d.signingGroupPubkeyY = \\_publicKey.slice(32, 32).toBytes32();\\n require(\\_d.signingGroupPubkeyY != bytes32(0) && \\_d.signingGroupPubkeyX != bytes32(0), "Keep returned bad pubkey");\\n \\_d.fundingProofTimerStart = block.timestamp;\\n\\n \\_d.setAwaitingBTCFundingProof();\\n \\_d.logRegisteredPubkey(\\n \\_d.signingGroupPubkeyX,\\n \\_d.signingGroupPubkeyY);\\n}\\n```\\n
bitcoin-spv - SPV proofs do not support transactions with larger numbers of inputs and outputs Pending
high
There is no explicit restriction on the number of inputs and outputs a Bitcoin transaction can have - as long as the transaction fits into a block. The number of inputs and outputs in a transaction is denoted by a leading β€œvarint” - a variable length integer. In `BTCUtils.validateVin` and `BTCUtils.validateVout`, the value of this varint is restricted to under `0xFD`, or 253:\\n```\\n/// @notice Checks that the vin passed up is properly formatted\\n/// @dev Consider a vin with a valid vout in its scriptsig\\n/// @param \\_vin Raw bytes length-prefixed input vector\\n/// @return True if it represents a validly formatted vin\\nfunction validateVin(bytes memory \\_vin) internal pure returns (bool) {\\n uint256 \\_offset = 1;\\n uint8 \\_nIns = uint8(\\_vin.slice(0, 1)[0]);\\n\\n // Not valid if it says there are too many or no inputs\\n if (\\_nIns >= 0xfd || \\_nIns == 0) {\\n return false;\\n }\\n```\\n\\nTransactions that include more than 252 inputs or outputs will not pass this validation, leading to some legitimate deposits being rejected by the tBTC system.\\nThe 252-item limit exists in a few forms throughout the system, outside of the aforementioned `BTCUtils.validateVin` and BTCUtils.validateVout:\\nBTCUtils.determineOutputLength:\\n```\\n/// @notice Determines the length of an output\\n/// @dev 5 types: WPKH, WSH, PKH, SH, and OP\\_RETURN\\n/// @param \\_output The output\\n/// @return The length indicated by the prefix, error if invalid length\\nfunction determineOutputLength(bytes memory \\_output) internal pure returns (uint256) {\\n uint8 \\_len = uint8(\\_output.slice(8, 1)[0]);\\n require(\\_len < 0xfd, "Multi-byte VarInts not supported");\\n\\n return \\_len + 8 + 1; // 8 byte value, 1 byte for \\_len itself\\n}\\n```\\n\\nDepositUtils.findAndParseFundingOutput:\\n```\\nfunction findAndParseFundingOutput(\\n DepositUtils.Deposit storage \\_d,\\n bytes memory \\_txOutputVector,\\n uint8 \\_fundingOutputIndex\\n) public view returns (bytes8) {\\n```\\n\\nDepositUtils.validateAndParseFundingSPVProof:\\n```\\nfunction validateAndParseFundingSPVProof(\\n DepositUtils.Deposit storage \\_d,\\n bytes4 \\_txVersion,\\n bytes memory \\_txInputVector,\\n bytes memory \\_txOutputVector,\\n bytes4 \\_txLocktime,\\n uint8 \\_fundingOutputIndex,\\n bytes memory \\_merkleProof,\\n uint256 \\_txIndexInBlock,\\n bytes memory \\_bitcoinHeaders\\n) public view returns (bytes8 \\_valueBytes, bytes memory \\_utxoOutpoint){\\n```\\n\\nDepositFunding.provideFraudBTCFundingProof:\\n```\\nfunction provideFraudBTCFundingProof(\\n DepositUtils.Deposit storage \\_d,\\n bytes4 \\_txVersion,\\n bytes memory \\_txInputVector,\\n bytes memory \\_txOutputVector,\\n bytes4 \\_txLocktime,\\n uint8 \\_fundingOutputIndex,\\n bytes memory \\_merkleProof,\\n uint256 \\_txIndexInBlock,\\n bytes memory \\_bitcoinHeaders\\n) public returns (bool) {\\n```\\n\\nDepositFunding.provideBTCFundingProof:\\n```\\nfunction provideBTCFundingProof(\\n DepositUtils.Deposit storage \\_d,\\n bytes4 \\_txVersion,\\n bytes memory \\_txInputVector,\\n bytes memory \\_txOutputVector,\\n bytes4 \\_txLocktime,\\n uint8 \\_fundingOutputIndex,\\n bytes memory \\_merkleProof,\\n uint256 \\_txIndexInBlock,\\n bytes memory \\_bitcoinHeaders\\n) public returns (bool) {\\n```\\n\\nDepositLiquidation.provideSPVFraudProof:\\n```\\nfunction provideSPVFraudProof(\\n DepositUtils.Deposit storage \\_d,\\n bytes4 \\_txVersion,\\n bytes memory \\_txInputVector,\\n bytes memory \\_txOutputVector,\\n bytes4 \\_txLocktime,\\n bytes memory \\_merkleProof,\\n uint256 \\_txIndexInBlock,\\n uint8 \\_targetInputIndex,\\n bytes memory \\_bitcoinHeaders\\n) public {\\n```\\n
Resolution\\nThe client provided the following statement:\\nBenchmarks and takeaways are being tracked in issue https://github.com/keep-network/tbtc/issues/556.\\nIncorporate varint parsing in `BTCUtils.validateVin` and `BTCUtils.validateVout`. Ensure that other components of the system reflect the removal of the 252-item limit.
null
```\\n/// @notice Checks that the vin passed up is properly formatted\\n/// @dev Consider a vin with a valid vout in its scriptsig\\n/// @param \\_vin Raw bytes length-prefixed input vector\\n/// @return True if it represents a validly formatted vin\\nfunction validateVin(bytes memory \\_vin) internal pure returns (bool) {\\n uint256 \\_offset = 1;\\n uint8 \\_nIns = uint8(\\_vin.slice(0, 1)[0]);\\n\\n // Not valid if it says there are too many or no inputs\\n if (\\_nIns >= 0xfd || \\_nIns == 0) {\\n return false;\\n }\\n```\\n
bitcoin-spv - multiple integer under-/overflows
high
The bitcoin-spv library allows for multiple integer under-/overflows while processing or converting potentially untrusted or user-provided data.\\n`uint8` underflow `uint256(uint8(_e - 3))`\\nNote: `_header[75]` will throw consuming all gas if out of bounds while the majority of the library usually uses `slice(start, 1)` to handle this more gracefully.\\n```\\n/// @dev Target is a 256 bit number encoded as a 3-byte mantissa and 1 byte exponent\\n/// @param \\_header The header\\n/// @return The target threshold\\nfunction extractTarget(bytes memory \\_header) internal pure returns (uint256) {\\n bytes memory \\_m = \\_header.slice(72, 3);\\n uint8 \\_e = uint8(\\_header[75]);\\n uint256 \\_mantissa = bytesToUint(reverseEndianness(\\_m));\\n uint \\_exponent = \\_e - 3;\\n\\n return \\_mantissa \\* (256 \\*\\* \\_exponent);\\n}\\n```\\n\\n`uint8` overflow `uint256(uint8(_len + 8 + 1))`\\nNote: might allow a specially crafted output to return an invalid determineOutputLength <= 9.\\nNote: while type `VarInt` is implemented for inputs, it is not for the output length.\\n```\\n/// @dev 5 types: WPKH, WSH, PKH, SH, and OP\\_RETURN\\n/// @param \\_output The output\\n/// @return The length indicated by the prefix, error if invalid length\\nfunction determineOutputLength(bytes memory \\_output) internal pure returns (uint256) {\\n uint8 \\_len = uint8(\\_output.slice(8, 1)[0]);\\n require(\\_len < 0xfd, "Multi-byte VarInts not supported");\\n\\n return \\_len + 8 + 1; // 8 byte value, 1 byte for \\_len itself\\n}\\n```\\n\\n`uint8` underflow `uint256(uint8(extractOutputScriptLen(_output)[0]) - 2)`\\n```\\n/// @dev Determines type by the length prefix and validates format\\n/// @param \\_output The output\\n/// @return The hash committed to by the pk\\_script, or null for errors\\nfunction extractHash(bytes memory \\_output) internal pure returns (bytes memory) {\\n if (uint8(\\_output.slice(9, 1)[0]) == 0) {\\n uint256 \\_len = uint8(extractOutputScriptLen(\\_output)[0]) - 2;\\n // Check for maliciously formatted witness outputs\\n if (uint8(\\_output.slice(10, 1)[0]) != uint8(\\_len)) {\\n return hex"";\\n }\\n return \\_output.slice(11, \\_len);\\n } else {\\n bytes32 \\_tag = \\_output.keccak256Slice(8, 3);\\n```\\n\\n`BytesLib` input validation multiple start+length overflow\\nNote: multiple occurrences. should check `start+length > start && bytes.length >= start+length`\\n```\\nfunction slice(bytes memory \\_bytes, uint \\_start, uint \\_length) internal pure returns (bytes memory res) {\\n require(\\_bytes.length >= (\\_start + \\_length), "Slice out of bounds");\\n```\\n\\n`BytesLib` input validation multiple start overflow\\n```\\nfunction toUint(bytes memory \\_bytes, uint \\_start) internal pure returns (uint256) {\\n require(\\_bytes.length >= (\\_start + 32), "Uint conversion out of bounds.");\\n```\\n\\n```\\nfunction toAddress(bytes memory \\_bytes, uint \\_start) internal pure returns (address) {\\n require(\\_bytes.length >= (\\_start + 20), "Address conversion out of bounds.");\\n```\\n\\n```\\nfunction slice(bytes memory \\_bytes, uint \\_start, uint \\_length) internal pure returns (bytes memory res) {\\n require(\\_bytes.length >= (\\_start + \\_length), "Slice out of bounds");\\n```\\n\\n```\\nfunction keccak256Slice(bytes memory \\_bytes, uint \\_start, uint \\_length) pure internal returns (bytes32 result) {\\n require(\\_bytes.length >= (\\_start + \\_length), "Slice out of bounds");\\n```\\n
We believe that a general-purpose parsing and verification library for bitcoin payments should be very strict when processing untrusted user input. With strict we mean, that it should rigorously validate provided input data and only proceed with the processing of the data if it is within a safe-to-use range for the method to return valid results. Relying on the caller to provide pre-validate data can be unsafe especially if the caller assumes that proper input validation is performed by the library.\\nGiven the risk profile for this library, we recommend a conservative approach that balances security instead of gas efficiency without relying on certain calls or instructions to throw on invalid input.\\nFor this issue specifically, we recommend proper input validation and explicit type expansion where necessary to prevent values from wrapping or processing data for arguments that are not within a safe-to-use range.
null
```\\n/// @dev Target is a 256 bit number encoded as a 3-byte mantissa and 1 byte exponent\\n/// @param \\_header The header\\n/// @return The target threshold\\nfunction extractTarget(bytes memory \\_header) internal pure returns (uint256) {\\n bytes memory \\_m = \\_header.slice(72, 3);\\n uint8 \\_e = uint8(\\_header[75]);\\n uint256 \\_mantissa = bytesToUint(reverseEndianness(\\_m));\\n uint \\_exponent = \\_e - 3;\\n\\n return \\_mantissa \\* (256 \\*\\* \\_exponent);\\n}\\n```\\n
tbtc - Unreachable state LIQUIDATION_IN_PROGRESS
high
According to the specification (overview, states, version 2020-02-06), a deposit can be in one of two liquidation_in_progress states.\\nLIQUIDATION_IN_PROGRESS\\nLIQUIDATION_IN_PROGRESS Liquidation due to undercollateralization or an abort has started Automatic (on-chain) liquidation was unsuccessful\\nFRAUD_LIQUIDATION_IN_PROGRESS\\nFRAUD_LIQUIDATION_IN_PROGRESS Liquidation due to fraud has started Automatic (on-chain) liquidation was unsuccessful\\nHowever, `LIQUIDATION_IN_PROGRESS` is unreachable and instead, `FRAUD_LIQUIDATION_IN_PROGRESS` is always called. This means that all non-fraud state transitions end up in the fraud liquidation path and will perform actions as if fraud was detected even though it might be caused by an undercollateralized notification or courtesy timeout.\\n`startSignerAbortLiquidation` transitions to `FRAUD_LIQUIDATION_IN_PROGRESS` on non-fraud events `notifyUndercollateralizedLiquidation` and `notifyCourtesyTimeout`\\n```\\n/// @notice Starts signer liquidation due to abort or undercollateralization\\n/// @dev We first attempt to liquidate on chain, then by auction\\n/// @param \\_d deposit storage pointer\\nfunction startSignerAbortLiquidation(DepositUtils.Deposit storage \\_d) internal {\\n \\_d.logStartedLiquidation(false);\\n // Reclaim used state for gas savings\\n \\_d.redemptionTeardown();\\n \\_d.seizeSignerBonds();\\n\\n \\_d.liquidationInitiated = block.timestamp; // Store the timestamp for auction\\n \\_d.liquidationInitiator = msg.sender;\\n \\_d.setFraudLiquidationInProgress();\\n}\\n```\\n
Verify state transitions and either remove `LIQUIDATION_IN_PROGRESS` if it is redundant or fix the state transitions for non-fraud liquidations.\\nNote that Deposit states can be simplified by removing redundant states by setting a flag (e.g. fraudLiquidation) in the deposit instead of adding a state to track the fraud liquidation path.\\nAccording to the specification, we assume the following state transitions are desired:\\n`LIQUIDATION_IN_PROGRESS`\\nIn case of liquidation due to undercollateralization or abort, the remaining bond value is split 50-50 between the account which triggered the liquidation and the signers.\\n`FRAUD_LIQUIDATION_IN_PROGRESS`\\nIn case of liquidation due to fraud, the remaining bond value in full goes to the account which triggered the liquidation by proving fraud.
null
```\\n/// @notice Starts signer liquidation due to abort or undercollateralization\\n/// @dev We first attempt to liquidate on chain, then by auction\\n/// @param \\_d deposit storage pointer\\nfunction startSignerAbortLiquidation(DepositUtils.Deposit storage \\_d) internal {\\n \\_d.logStartedLiquidation(false);\\n // Reclaim used state for gas savings\\n \\_d.redemptionTeardown();\\n \\_d.seizeSignerBonds();\\n\\n \\_d.liquidationInitiated = block.timestamp; // Store the timestamp for auction\\n \\_d.liquidationInitiator = msg.sender;\\n \\_d.setFraudLiquidationInProgress();\\n}\\n```\\n
tbtc - various deposit state transitions can be front-run (e.g. fraud proofs, timeouts) Won't Fix
high
An entity that can provide proof for fraudulent ECDSA signatures or SPV proofs in the liquidation flow is rewarded with part of the deposit contract ETH value.\\nSpecification: Liquidation Any signer bond left over after the deposit owner is compensated is distributed to the account responsible for reporting the misbehavior (for fraud) or between the signers and the account that triggered liquidation (for collateralization issues).\\nHowever, the methods under which proof is provided are not protected from front-running allowing anyone to observe transactions to provideECDSAFraudProof/ `provideSPVFraudProof` and submit the same proofs with providing a higher gas value.\\nPlease note that a similar issue exists for timeout states providing rewards for calling them out (i.e. they set the `liquidationInitiator` address).\\n`provideECDSAFraudProof` verifies the fraudulent proof\\n`r,s,v,signedDigest` appear to be the fraudulent signature. `_preimage` is the correct value.\\n```\\n/// @param \\_preimage The sha256 preimage of the digest\\nfunction provideECDSAFraudProof(\\n DepositUtils.Deposit storage \\_d,\\n uint8 \\_v,\\n bytes32 \\_r,\\n bytes32 \\_s,\\n bytes32 \\_signedDigest,\\n bytes memory \\_preimage\\n) public {\\n require(\\n !\\_d.inFunding() && !\\_d.inFundingFailure(),\\n "Use provideFundingECDSAFraudProof instead"\\n );\\n require(\\n !\\_d.inSignerLiquidation(),\\n "Signer liquidation already in progress"\\n );\\n require(!\\_d.inEndState(), "Contract has halted");\\n require(submitSignatureFraud(\\_d, \\_v, \\_r, \\_s, \\_signedDigest, \\_preimage), "Signature is not fraud");\\n startSignerFraudLiquidation(\\_d);\\n}\\n```\\n\\n`startSignerFraudLiquidation` sets the address that provides the proof as the beneficiary\\n```\\nfunction provideFundingECDSAFraudProof(\\n DepositUtils.Deposit storage \\_d,\\n uint8 \\_v,\\n bytes32 \\_r,\\n bytes32 \\_s,\\n bytes32 \\_signedDigest,\\n bytes memory \\_preimage\\n) public {\\n require(\\n \\_d.inAwaitingBTCFundingProof(),\\n "Signer fraud during funding flow only available while awaiting funding"\\n );\\n\\n bool \\_isFraud = \\_d.submitSignatureFraud(\\_v, \\_r, \\_s, \\_signedDigest, \\_preimage);\\n require(\\_isFraud, "Signature is not fraudulent");\\n \\_d.logFraudDuringSetup();\\n\\n // If the funding timeout has elapsed, punish the funder too!\\n if (block.timestamp > \\_d.fundingProofTimerStart + TBTCConstants.getFundingTimeout()) {\\n address(0).transfer(address(this).balance); // Burn it all down (fire emoji)\\n \\_d.setFailedSetup();\\n } else {\\n /\\* NB: This is reuse of the variable \\*/\\n \\_d.fundingProofTimerStart = block.timestamp;\\n \\_d.setFraudAwaitingBTCFundingProof();\\n }\\n}\\n```\\n\\n`purchaseSignerBondsAtAuction` pays out the funds\\n```\\n uint256 contractEthBalance = address(this).balance;\\n address payable initiator = \\_d.liquidationInitiator;\\n\\n if (initiator == address(0)){\\n initiator = address(0xdead);\\n }\\n if (contractEthBalance > 1) {\\n if (\\_wasFraud) {\\n initiator.transfer(contractEthBalance);\\n } else {\\n // There will always be a liquidation initiator.\\n uint256 split = contractEthBalance.div(2);\\n \\_d.pushFundsToKeepGroup(split);\\n initiator.transfer(split);\\n }\\n }\\n}\\n```\\n
For fraud proofs, it should be required that the reporter uses a commit/reveal scheme to lock in a proof in one block, and reveal the details in another.
null
```\\n/// @param \\_preimage The sha256 preimage of the digest\\nfunction provideECDSAFraudProof(\\n DepositUtils.Deposit storage \\_d,\\n uint8 \\_v,\\n bytes32 \\_r,\\n bytes32 \\_s,\\n bytes32 \\_signedDigest,\\n bytes memory \\_preimage\\n) public {\\n require(\\n !\\_d.inFunding() && !\\_d.inFundingFailure(),\\n "Use provideFundingECDSAFraudProof instead"\\n );\\n require(\\n !\\_d.inSignerLiquidation(),\\n "Signer liquidation already in progress"\\n );\\n require(!\\_d.inEndState(), "Contract has halted");\\n require(submitSignatureFraud(\\_d, \\_v, \\_r, \\_s, \\_signedDigest, \\_preimage), "Signature is not fraud");\\n startSignerFraudLiquidation(\\_d);\\n}\\n```\\n
tbtc - Anyone can emit log events due to missing access control
high
Access control for `DepositLog` is not implemented. `DepositLog` is inherited by `TBTCSystem` and its functionality is usually consumed by `Deposit` contracts to emit log events on `TBTCSystem`. Due to the missing access control, anyone can emit log events on `TBTCSystem`. Users, client-software or other components that rely on these events might be tricked into performing actions that were not authorized by the system.\\n```\\nfunction approvedToLog(address \\_caller) public pure returns (bool) {\\n /\\* TODO: auth via system \\*/\\n \\_caller;\\n return true;\\n}\\n```\\n
Log events are typically initiated by the Deposit contract. Make sure only Deposit contracts deployed by an approved factory can emit logs on TBTCSystem.
null
```\\nfunction approvedToLog(address \\_caller) public pure returns (bool) {\\n /\\* TODO: auth via system \\*/\\n \\_caller;\\n return true;\\n}\\n```\\n
DKGResultVerification.verify unsafe packing in signed data
medium
`DKGResultVerification.verify` allows the sender to arbitrarily move bytes between `groupPubKey` and misbehaved:\\n```\\nbytes32 resultHash = keccak256(abi.encodePacked(groupPubKey, misbehaved));\\n```\\n
Validate the expected length of both and add a salt between the two.
null
```\\nbytes32 resultHash = keccak256(abi.encodePacked(groupPubKey, misbehaved));\\n```\\n
keep-core - Service contract callbacks can be abused to call into other contracts
medium
`KeepRandomBeaconServiceImplV1` allows senders to specify an arbitrary method and contract that will receive a callback once the beacon generates a relay entry:\\n```\\n/\\*\\*\\n \\* @dev Creates a request to generate a new relay entry, which will include\\n \\* a random number (by signing the previous entry's random number).\\n \\* @param callbackContract Callback contract address. Callback is called once a new relay entry has been generated.\\n \\* @param callbackMethod Callback contract method signature. String representation of your method with a single\\n \\* uint256 input parameter i.e. "relayEntryCallback(uint256)".\\n \\* @param callbackGas Gas required for the callback.\\n \\* The customer needs to ensure they provide a sufficient callback gas\\n \\* to cover the gas fee of executing the callback. Any surplus is returned\\n \\* to the customer. If the callback gas amount turns to be not enough to\\n \\* execute the callback, callback execution is skipped.\\n \\* @return An uint256 representing uniquely generated relay request ID. It is also returned as part of the event.\\n \\*/\\nfunction requestRelayEntry(\\n address callbackContract,\\n string memory callbackMethod,\\n uint256 callbackGas\\n) public nonReentrant payable returns (uint256) {\\n```\\n\\nOnce an operator contract receives the relay entry, it calls executeCallback:\\n```\\n/\\*\\*\\n \\* @dev Executes customer specified callback for the relay entry request.\\n \\* @param requestId Request id tracked internally by this contract.\\n \\* @param entry The generated random number.\\n \\* @return Address to receive callback surplus.\\n \\*/\\nfunction executeCallback(uint256 requestId, uint256 entry) public returns (address payable surplusRecipient) {\\n require(\\n \\_operatorContracts.contains(msg.sender),\\n "Only authorized operator contract can call execute callback."\\n );\\n\\n require(\\n \\_callbacks[requestId].callbackContract != address(0),\\n "Callback contract not found"\\n );\\n\\n \\_callbacks[requestId].callbackContract.call(abi.encodeWithSignature(\\_callbacks[requestId].callbackMethod, entry));\\n\\n surplusRecipient = \\_callbacks[requestId].surplusRecipient;\\n delete \\_callbacks[requestId];\\n}\\n```\\n\\nArbitrary callbacks can be used to force the service contract to execute many functions within the keep contract system. Currently, the `KeepRandomBeaconOperator` includes an `onlyServiceContract` modifier:\\n```\\n/\\*\\*\\n \\* @dev Checks if sender is authorized.\\n \\*/\\nmodifier onlyServiceContract() {\\n require(\\n serviceContracts.contains(msg.sender),\\n "Caller is not an authorized contract"\\n );\\n \\_;\\n}\\n```\\n\\nThe functions it protects cannot be targeted by the aforementioned service contract callbacks due to Solidity's `CALLDATASIZE` checking. However, the presence of the modifier suggests that the service contract is expected to be a permissioned actor within some contracts.
Stick to a constant callback method signature, rather than allowing users to submit an arbitrary string. An example is `__beaconCallback__(uint256)`.\\nConsider disallowing arbitrary callback destinations. Instead, rely on contracts making requests directly, and default the callback destination to `msg.sender`. Ensure the sender is not an EOA.
null
```\\n/\\*\\*\\n \\* @dev Creates a request to generate a new relay entry, which will include\\n \\* a random number (by signing the previous entry's random number).\\n \\* @param callbackContract Callback contract address. Callback is called once a new relay entry has been generated.\\n \\* @param callbackMethod Callback contract method signature. String representation of your method with a single\\n \\* uint256 input parameter i.e. "relayEntryCallback(uint256)".\\n \\* @param callbackGas Gas required for the callback.\\n \\* The customer needs to ensure they provide a sufficient callback gas\\n \\* to cover the gas fee of executing the callback. Any surplus is returned\\n \\* to the customer. If the callback gas amount turns to be not enough to\\n \\* execute the callback, callback execution is skipped.\\n \\* @return An uint256 representing uniquely generated relay request ID. It is also returned as part of the event.\\n \\*/\\nfunction requestRelayEntry(\\n address callbackContract,\\n string memory callbackMethod,\\n uint256 callbackGas\\n) public nonReentrant payable returns (uint256) {\\n```\\n
tbtc - Disallow signatures with high-s values in DepositRedemption.provideRedemptionSignature
medium
`DepositRedemption.provideRedemptionSignature` is used by signers to publish a signature that can be used to redeem a deposit on Bitcoin. The function accepts a signature s value in the upper half of the secp256k1 curve:\\n```\\nfunction provideRedemptionSignature(\\n DepositUtils.Deposit storage \\_d,\\n uint8 \\_v,\\n bytes32 \\_r,\\n bytes32 \\_s\\n) public {\\n require(\\_d.inAwaitingWithdrawalSignature(), "Not currently awaiting a signature");\\n\\n // If we're outside of the signature window, we COULD punish signers here\\n // Instead, we consider this a no-harm-no-foul situation.\\n // The signers have not stolen funds. Most likely they've just inconvenienced someone\\n\\n // The signature must be valid on the pubkey\\n require(\\n \\_d.signerPubkey().checkSig(\\n \\_d.lastRequestedDigest,\\n \\_v, \\_r, \\_s\\n ),\\n "Invalid signature"\\n );\\n```\\n\\nAlthough `ecrecover` accepts signatures with these s values, they are no longer used in Bitcoin. As such, the signature will appear to be valid to the Ethereum smart contract, but will likely not be accepted on Bitcoin. If no users watching malleate the signature, the redemption process will likely enter a fee increase loop, incurring a cost on the deposit owner.
Ensure the passed-in s value is restricted to the lower half of the secp256k1 curve, as done in BondedECDSAKeep:\\n```\\n// Validate `s` value for a malleability concern described in EIP-2.\\n// Only signatures with `s` value in the lower half of the secp256k1\\n// curve's order are considered valid.\\nrequire(\\n uint256(\\_s) <=\\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,\\n "Malleable signature - s should be in the low half of secp256k1 curve's order"\\n);\\n```\\n
null
```\\nfunction provideRedemptionSignature(\\n DepositUtils.Deposit storage \\_d,\\n uint8 \\_v,\\n bytes32 \\_r,\\n bytes32 \\_s\\n) public {\\n require(\\_d.inAwaitingWithdrawalSignature(), "Not currently awaiting a signature");\\n\\n // If we're outside of the signature window, we COULD punish signers here\\n // Instead, we consider this a no-harm-no-foul situation.\\n // The signers have not stolen funds. Most likely they've just inconvenienced someone\\n\\n // The signature must be valid on the pubkey\\n require(\\n \\_d.signerPubkey().checkSig(\\n \\_d.lastRequestedDigest,\\n \\_v, \\_r, \\_s\\n ),\\n "Invalid signature"\\n );\\n```\\n
Consistent use of SafeERC20 for external tokens
medium
Use `SafeERC20` features to interact with potentially broken tokens used in the system. E.g. `TokenGrant.receiveApproval()` is using `safeTransferFrom` while other contracts aren't.\\n`TokenGrant.receiveApproval` using `safeTransferFrom`\\n```\\ntoken.safeTransferFrom(\\_from, address(this), \\_amount);\\n```\\n\\n`TokenStaking.receiveApproval` not using `safeTransferFrom` while `safeTransfer` is being used.\\n```\\ntoken.transferFrom(\\_from, address(this), \\_value);\\n```\\n\\n```\\ntoken.safeTransfer(owner, amount);\\n```\\n\\n```\\ntoken.transfer(tattletale, tattletaleReward);\\n```\\n\\n`distributeERC20ToMembers` not using `safeTransferFrom`\\n```\\ntoken.transferFrom(\\n msg.sender,\\n tokenStaking.magpieOf(members[i]),\\n dividend\\n);\\n```\\n
Consistently use `SafeERC20` to support potentially broken tokens external to the system.
null
```\\ntoken.safeTransferFrom(\\_from, address(this), \\_amount);\\n```\\n
Initialize implementations for proxy contracts and protect initialization methods
medium
It should be avoided that the implementation for proxy contracts can be initialized by third parties. This can be the case if the `initialize` function is unprotected. Since the implementation contract is not meant to be used directly without a proxy delegate-calling it is recommended to protect the initialization method of the implementation by initializing on deployment.\\nChanging the proxies implementation (upgradeTo()) to a version that does not protect the initialization method may allow someone to front-run and initialize the contract if it is not done within the same transaction.\\n`KeepVendor` delegates to `KeepVendorImplV1`. The implementations initialization method is unprotected.\\n```\\n/// @notice Initializes Keep Vendor contract implementation.\\n/// @param registryAddress Keep registry contract linked to this contract.\\nfunction initialize(\\n address registryAddress\\n)\\n public\\n{\\n require(!initialized(), "Contract is already initialized.");\\n \\_initialized["BondedECDSAKeepVendorImplV1"] = true;\\n registry = Registry(registryAddress);\\n}\\n```\\n\\n`KeepRandomBeaconServiceImplV1` and `KeepRandomBeaconServiceUpgradeExample`\\n```\\nfunction initialize(\\n uint256 priceFeedEstimate,\\n uint256 fluctuationMargin,\\n uint256 dkgContributionMargin,\\n uint256 withdrawalDelay,\\n address registry\\n)\\n public\\n{\\n require(!initialized(), "Contract is already initialized.");\\n \\_initialized["KeepRandomBeaconServiceImplV1"] = true;\\n \\_priceFeedEstimate = priceFeedEstimate;\\n \\_fluctuationMargin = fluctuationMargin;\\n \\_dkgContributionMargin = dkgContributionMargin;\\n \\_withdrawalDelay = withdrawalDelay;\\n \\_pendingWithdrawal = 0;\\n \\_previousEntry = \\_beaconSeed;\\n \\_registry = registry;\\n \\_baseCallbackGas = 18845;\\n}\\n```\\n\\n`Deposit` is deployed via `cloneFactory` delegating to a `masterDepositAddress` in `DepositFactory`. The `masterDepositAddress` (Deposit) might be left uninitialized.\\n```\\ncontract DepositFactoryAuthority {\\n\\n bool internal \\_initialized = false;\\n address internal \\_depositFactory;\\n\\n /// @notice Set the address of the System contract on contract initialization\\n function initialize(address \\_factory) public {\\n require(! \\_initialized, "Factory can only be initialized once.");\\n\\n \\_depositFactory = \\_factory;\\n \\_initialized = true;\\n }\\n```\\n
Initialize unprotected implementation contracts in the implementation's constructor. Protect initialization methods from being called by unauthorized parties or ensure that deployment of the proxy and initialization is performed in the same transaction.
null
```\\n/// @notice Initializes Keep Vendor contract implementation.\\n/// @param registryAddress Keep registry contract linked to this contract.\\nfunction initialize(\\n address registryAddress\\n)\\n public\\n{\\n require(!initialized(), "Contract is already initialized.");\\n \\_initialized["BondedECDSAKeepVendorImplV1"] = true;\\n registry = Registry(registryAddress);\\n}\\n```\\n
keep-tecdsa - If caller sends more than is contained in the signer subsidy pool, the value is burned
medium
The signer subsidy pool in `BondedECDSAKeepFactory` tracks funds sent to the contract. Each time a keep is opened, the subsidy pool is intended to be distributed to the members of the new keep:\\n```\\n// If subsidy pool is non-empty, distribute the value to signers but\\n// never distribute more than the payment for opening a keep.\\nuint256 signerSubsidy = subsidyPool < msg.value\\n ? subsidyPool\\n : msg.value;\\nif (signerSubsidy > 0) {\\n subsidyPool -= signerSubsidy;\\n keep.distributeETHToMembers.value(signerSubsidy)();\\n}\\n```\\n\\nThe tracking around subsidy pool increases is inconsistent, and can lead to sent value being burned. In the case that `subsidyPool` contains less Ether than is sent in `msg.value`, `msg.value` is unused and remains in the contract. It may or may not be added to `subsidyPool`, depending on the return status of the random beacon:\\n```\\n(bool success, ) = address(randomBeacon).call.gas(400000).value(msg.value)(\\n abi.encodeWithSignature(\\n "requestRelayEntry(address,string,uint256)",\\n address(this),\\n "setGroupSelectionSeed(uint256)",\\n callbackGas\\n )\\n);\\nif (!success) {\\n subsidyPool += msg.value; // beacon is busy\\n}\\n```\\n
Rather than tracking the `subsidyPool` individually, simply distribute `this.balance` to each new keep's members.
null
```\\n// If subsidy pool is non-empty, distribute the value to signers but\\n// never distribute more than the payment for opening a keep.\\nuint256 signerSubsidy = subsidyPool < msg.value\\n ? subsidyPool\\n : msg.value;\\nif (signerSubsidy > 0) {\\n subsidyPool -= signerSubsidy;\\n keep.distributeETHToMembers.value(signerSubsidy)();\\n}\\n```\\n
keep-core - TokenGrant and TokenStaking allow staking zero amount of tokens and front-running
medium
Tokens are staked via the callback `receiveApproval()` which is normally invoked when calling `approveAndCall()`. The method is not restricting who can initiate the staking of tokens and relies on the fact that the token transfer to the `TokenStaking` contract is pre-approved by the owner, otherwise, the call would revert.\\nHowever, `receiveApproval()` allows the staking of a zero amount of tokens. The only check performed on the number of tokens transferred is, that the token holders balance covers the amount to be transferred. This check is both relatively weak - having enough balance does not imply that tokens are approved for transfer - and does not cover the fact that someone can call the method with a zero amount of tokens.\\nThis way someone could create an arbitrary number of operators staking no tokens at all. This passes the token balance check, `token.transferFrom()` will succeed and an operator struct with a zero stake and arbitrary values for `operator, from, magpie, authorizer` can be set. Finally, an event is emitted for a zero stake.\\nAn attacker could front-run calls to `receiveApproval` to block staking of a legitimate operator by creating a zero stake entry for the operator before she is able to. This vector might allow someone to permanently inconvenience an operator's address. To recover from this situation one could be forced to `cancelStake` terminating the zero stake struct in order to call the contract with the correct stake again.\\nThe same issue exists for `TokenGrant`.\\n```\\n/\\*\\*\\n \\* @notice Receives approval of token transfer and stakes the approved amount.\\n \\* @dev Makes sure provided token contract is the same one linked to this contract.\\n \\* @param \\_from The owner of the tokens who approved them to transfer.\\n \\* @param \\_value Approved amount for the transfer and stake.\\n \\* @param \\_token Token contract address.\\n \\* @param \\_extraData Data for stake delegation. This byte array must have the\\n \\* following values concatenated: Magpie address (20 bytes) where the rewards for participation\\n \\* are sent, operator's (20 bytes) address, authorizer (20 bytes) address.\\n \\*/\\nfunction receiveApproval(address \\_from, uint256 \\_value, address \\_token, bytes memory \\_extraData) public {\\n require(ERC20Burnable(\\_token) == token, "Token contract must be the same one linked to this contract.");\\n require(\\_value <= token.balanceOf(\\_from), "Sender must have enough tokens.");\\n require(\\_extraData.length == 60, "Stake delegation data must be provided.");\\n\\n address payable magpie = address(uint160(\\_extraData.toAddress(0)));\\n address operator = \\_extraData.toAddress(20);\\n require(operators[operator].owner == address(0), "Operator address is already in use.");\\n address authorizer = \\_extraData.toAddress(40);\\n\\n // Transfer tokens to this contract.\\n token.transferFrom(\\_from, address(this), \\_value);\\n\\n operators[operator] = Operator(\\_value, block.number, 0, \\_from, magpie, authorizer);\\n ownerOperators[\\_from].push(operator);\\n\\n emit Staked(operator, \\_value);\\n}\\n```\\n
Require tokens to be staked and explicitly disallow the zero amount of tokens case. The balance check can be removed.\\nNote: Consider checking the calls return value or calling the contract via `SafeERC20` to support potentially broken tokens that do not revert in error cases (token.transferFrom).
null
```\\n/\\*\\*\\n \\* @notice Receives approval of token transfer and stakes the approved amount.\\n \\* @dev Makes sure provided token contract is the same one linked to this contract.\\n \\* @param \\_from The owner of the tokens who approved them to transfer.\\n \\* @param \\_value Approved amount for the transfer and stake.\\n \\* @param \\_token Token contract address.\\n \\* @param \\_extraData Data for stake delegation. This byte array must have the\\n \\* following values concatenated: Magpie address (20 bytes) where the rewards for participation\\n \\* are sent, operator's (20 bytes) address, authorizer (20 bytes) address.\\n \\*/\\nfunction receiveApproval(address \\_from, uint256 \\_value, address \\_token, bytes memory \\_extraData) public {\\n require(ERC20Burnable(\\_token) == token, "Token contract must be the same one linked to this contract.");\\n require(\\_value <= token.balanceOf(\\_from), "Sender must have enough tokens.");\\n require(\\_extraData.length == 60, "Stake delegation data must be provided.");\\n\\n address payable magpie = address(uint160(\\_extraData.toAddress(0)));\\n address operator = \\_extraData.toAddress(20);\\n require(operators[operator].owner == address(0), "Operator address is already in use.");\\n address authorizer = \\_extraData.toAddress(40);\\n\\n // Transfer tokens to this contract.\\n token.transferFrom(\\_from, address(this), \\_value);\\n\\n operators[operator] = Operator(\\_value, block.number, 0, \\_from, magpie, authorizer);\\n ownerOperators[\\_from].push(operator);\\n\\n emit Staked(operator, \\_value);\\n}\\n```\\n
tbtc - Inconsistency between increaseRedemptionFee and provideRedemptionProof may create un-provable redemptions
medium
`DepositRedemption.increaseRedemptionFee` is used by signers to approve a signable bitcoin transaction with a higher fee, in case the network is congested and miners are not approving the lower-fee transaction.\\nFee increases can be performed every 4 hours:\\n```\\nrequire(block.timestamp >= \\_d.withdrawalRequestTime + TBTCConstants.getIncreaseFeeTimer(), "Fee increase not yet permitted");\\n```\\n\\nIn addition, each increase must increment the fee by exactly the initial proposed fee:\\n```\\n// Check that we're incrementing the fee by exactly the redeemer's initial fee\\nuint256 \\_previousOutputValue = DepositUtils.bytes8LEToUint(\\_previousOutputValueBytes);\\n\\_newOutputValue = DepositUtils.bytes8LEToUint(\\_newOutputValueBytes);\\nrequire(\\_previousOutputValue.sub(\\_newOutputValue) == \\_d.initialRedemptionFee, "Not an allowed fee step");\\n```\\n\\nOutside of these two restrictions, there is no limit to the number of times `increaseRedemptionFee` can be called. Over a 20-hour period, for example, `increaseRedemptionFee` could be called 5 times, increasing the fee to `initialRedemptionFee * 5`. Over a 24-hour period, `increaseRedemptionFee` could be called 6 times, increasing the fee to `initialRedemptionFee * 6`.\\nEventually, it is expected that a transaction will be submitted and mined. At this point, anyone can call `DepositRedemption.provideRedemptionProof`, finalizing the redemption process and rewarding the signers. However, `provideRedemptionProof` will fail if the transaction fee is too high:\\n```\\nrequire((\\_d.utxoSize().sub(\\_fundingOutputValue)) <= \\_d.initialRedemptionFee \\* 5, "Fee unexpectedly very high");\\n```\\n\\nIn the case that `increaseRedemptionFee` is called 6 times and the signers provide a signature for this transaction, the transaction can be submitted and mined but `provideRedemptionProof` for this will always fail. Eventually, a redemption proof timeout will trigger the deposit into liquidation and the signers will be punished.
Because it is difficult to say with certainty that a 5x fee increase will always ensure a transaction's redeemability, the upper bound on fee bumps should be removed from `provideRedemptionProof`.\\nThis should be implemented in tandem with https://github.com/ConsenSys/thesis-tbtc-audit-2020-01/issues/38, so that signers cannot provide a proof that bypasses `increaseRedemptionFee` flow to spend the highest fee possible.
null
```\\nrequire(block.timestamp >= \\_d.withdrawalRequestTime + TBTCConstants.getIncreaseFeeTimer(), "Fee increase not yet permitted");\\n```\\n
keep-tecdsa - keep cannot be closed if a members bond was seized or fully reassigned
medium
A keep cannot be closed if the bonds have been completely reassigned or seized before, leaving at least one member with zero `lockedBonds`. In this case `closeKeep()` will throw in `freeMembersBonds()` because the requirement in `keepBonding.freeBond` is not satisfied anymore (lockedBonds[bondID] > 0). As a result of this, none of the potentially remaining bonds (reassign) are freed, the keep stays active even though it should be closed.\\n```\\n/// @notice Closes keep when owner decides that they no longer need it.\\n/// Releases bonds to the keep members. Keep can be closed only when\\n/// there is no signing in progress or requested signing process has timed out.\\n/// @dev The function can be called by the owner of the keep and only is the\\n/// keep has not been closed already.\\nfunction closeKeep() external onlyOwner onlyWhenActive {\\n require(\\n !isSigningInProgress() || hasSigningTimedOut(),\\n "Requested signing has not timed out yet"\\n );\\n\\n isActive = false;\\n\\n freeMembersBonds();\\n\\n emit KeepClosed();\\n}\\n\\n/// @notice Returns bonds to the keep members.\\nfunction freeMembersBonds() internal {\\n for (uint256 i = 0; i < members.length; i++) {\\n keepBonding.freeBond(members[i], uint256(address(this)));\\n }\\n}\\n```\\n\\n```\\n/// @notice Releases the bond and moves the bond value to the operator's\\n/// unbounded value pool.\\n/// @dev Function requires that caller is the holder of the bond which is\\n/// being released.\\n/// @param operator Address of the bonded operator.\\n/// @param referenceID Reference ID of the bond.\\nfunction freeBond(address operator, uint256 referenceID) public {\\n address holder = msg.sender;\\n bytes32 bondID = keccak256(\\n abi.encodePacked(operator, holder, referenceID)\\n );\\n\\n require(lockedBonds[bondID] > 0, "Bond not found");\\n\\n uint256 amount = lockedBonds[bondID];\\n lockedBonds[bondID] = 0;\\n unbondedValue[operator] = amount;\\n}\\n```\\n
Make sure the keep can be set to an end-state (closed/inactive) indicating its end-of-life even if the bond has been seized before. Avoid throwing an exception when freeing member bonds to avoid blocking the unlocking of bonds.
null
```\\n/// @notice Closes keep when owner decides that they no longer need it.\\n/// Releases bonds to the keep members. Keep can be closed only when\\n/// there is no signing in progress or requested signing process has timed out.\\n/// @dev The function can be called by the owner of the keep and only is the\\n/// keep has not been closed already.\\nfunction closeKeep() external onlyOwner onlyWhenActive {\\n require(\\n !isSigningInProgress() || hasSigningTimedOut(),\\n "Requested signing has not timed out yet"\\n );\\n\\n isActive = false;\\n\\n freeMembersBonds();\\n\\n emit KeepClosed();\\n}\\n\\n/// @notice Returns bonds to the keep members.\\nfunction freeMembersBonds() internal {\\n for (uint256 i = 0; i < members.length; i++) {\\n keepBonding.freeBond(members[i], uint256(address(this)));\\n }\\n}\\n```\\n
tbtc - provideFundingECDSAFraudProof attempts to burn non-existent funds
medium
The funding flow was recently changed from requiring the funder to provide a bond that stays in the Deposit contract to forwarding the funds to the keep, paying for the keep setup.\\nSo at a high level, the funding bond was designed to ensure that funders had some minimum skin in the game, so that DoSing signers/the system was expensive. The upside was that we could refund it in happy paths. Now that we've realized that opening the keep itself will cost enough to prevent DoS, the concept of refunding goes away entirely. We definitely missed cleaning up the funder handling in provideFundingECDSAFraudProof though.\\n```\\n// If the funding timeout has elapsed, punish the funder too!\\nif (block.timestamp > \\_d.fundingProofTimerStart + TBTCConstants.getFundingTimeout()) {\\n address(0).transfer(address(this).balance); // Burn it all down (fire emoji)\\n \\_d.setFailedSetup();\\n```\\n
Remove the line that attempts to punish the funder by burning the Deposit contract balance which is zero due to recent changes in how the payment provided with createNewDepositis handled.
null
```\\n// If the funding timeout has elapsed, punish the funder too!\\nif (block.timestamp > \\_d.fundingProofTimerStart + TBTCConstants.getFundingTimeout()) {\\n address(0).transfer(address(this).balance); // Burn it all down (fire emoji)\\n \\_d.setFailedSetup();\\n```\\n
bitcoin-spv - Bitcoin output script length is not checked in wpkhSpendSighash Won't Fix
medium
`CheckBitcoinSigs.wpkhSpendSighash` calculates the sighash of a Bitcoin transaction. Among its parameters, it accepts `bytes memory _outpoint`, which is a 36-byte UTXO id consisting of a 32-byte transaction hash and a 4-byte output index.\\nThe function in question should not accept an `_outpoint` that is not 36-bytes, but no length check is made:\\n```\\nfunction wpkhSpendSighash(\\n bytes memory \\_outpoint, // 36 byte UTXO id\\n bytes20 \\_inputPKH, // 20 byte hash160\\n bytes8 \\_inputValue, // 8-byte LE\\n bytes8 \\_outputValue, // 8-byte LE\\n bytes memory \\_outputScript // lenght-prefixed output script\\n) internal pure returns (bytes32) {\\n // Fixes elements to easily make a 1-in 1-out sighash digest\\n // Does not support timelocks\\n bytes memory \\_scriptCode = abi.encodePacked(\\n hex"1976a914", // length, dup, hash160, pkh\\_length\\n \\_inputPKH,\\n hex"88ac"); // equal, checksig\\n bytes32 \\_hashOutputs = abi.encodePacked(\\n \\_outputValue, // 8-byte LE\\n \\_outputScript).hash256();\\n bytes memory \\_sighashPreimage = abi.encodePacked(\\n hex"01000000", // version\\n \\_outpoint.hash256(), // hashPrevouts\\n hex"8cb9012517c817fead650287d61bdd9c68803b6bf9c64133dcab3e65b5a50cb9", // hashSequence(00000000)\\n \\_outpoint, // outpoint\\n \\_scriptCode, // p2wpkh script code\\n \\_inputValue, // value of the input in 8-byte LE\\n hex"00000000", // input nSequence\\n \\_hashOutputs, // hash of the single output\\n hex"00000000", // nLockTime\\n hex"01000000" // SIGHASH\\_ALL\\n );\\n return \\_sighashPreimage.hash256();\\n}\\n```\\n
Check that `_outpoint.length` is 36.
null
```\\nfunction wpkhSpendSighash(\\n bytes memory \\_outpoint, // 36 byte UTXO id\\n bytes20 \\_inputPKH, // 20 byte hash160\\n bytes8 \\_inputValue, // 8-byte LE\\n bytes8 \\_outputValue, // 8-byte LE\\n bytes memory \\_outputScript // lenght-prefixed output script\\n) internal pure returns (bytes32) {\\n // Fixes elements to easily make a 1-in 1-out sighash digest\\n // Does not support timelocks\\n bytes memory \\_scriptCode = abi.encodePacked(\\n hex"1976a914", // length, dup, hash160, pkh\\_length\\n \\_inputPKH,\\n hex"88ac"); // equal, checksig\\n bytes32 \\_hashOutputs = abi.encodePacked(\\n \\_outputValue, // 8-byte LE\\n \\_outputScript).hash256();\\n bytes memory \\_sighashPreimage = abi.encodePacked(\\n hex"01000000", // version\\n \\_outpoint.hash256(), // hashPrevouts\\n hex"8cb9012517c817fead650287d61bdd9c68803b6bf9c64133dcab3e65b5a50cb9", // hashSequence(00000000)\\n \\_outpoint, // outpoint\\n \\_scriptCode, // p2wpkh script code\\n \\_inputValue, // value of the input in 8-byte LE\\n hex"00000000", // input nSequence\\n \\_hashOutputs, // hash of the single output\\n hex"00000000", // nLockTime\\n hex"01000000" // SIGHASH\\_ALL\\n );\\n return \\_sighashPreimage.hash256();\\n}\\n```\\n
tbtc - liquidationInitiator can block purchaseSignerBondsAtAuction indefinitely
medium
When reporting a fraudulent proof the deposits `liquidationInitiator` is set to the entity reporting and proofing the fraud. The deposit that is in a `*_liquidation_in_progress` state can be bought by anyone at an auction calling `purchaseSignerBondsAtAuction`.\\nInstead of receiving a share of the funds the `liquidationInitiator` can decide to intentionally reject the funds by raising an exception causing `initiator.transfer(contractEthBalance)` to throw, blocking the auction and forcing the liquidation to fail. The deposit will stay in one of the `*_liquidation_in_progress` states.\\n```\\n/// @notice Closes an auction and purchases the signer bonds. Payout to buyer, funder, then signers if not fraud\\n/// @dev For interface, reading auctionValue will give a past value. the current is better\\n/// @param \\_d deposit storage pointer\\nfunction purchaseSignerBondsAtAuction(DepositUtils.Deposit storage \\_d) public {\\n bool \\_wasFraud = \\_d.inFraudLiquidationInProgress();\\n require(\\_d.inSignerLiquidation(), "No active auction");\\n\\n \\_d.setLiquidated();\\n \\_d.logLiquidated();\\n\\n // send the TBTC to the TDT holder. If the TDT holder is the Vending Machine, burn it to maintain the peg.\\n address tdtHolder = \\_d.depositOwner();\\n\\n TBTCToken \\_tbtcToken = TBTCToken(\\_d.TBTCToken);\\n\\n uint256 lotSizeTbtc = \\_d.lotSizeTbtc();\\n require(\\_tbtcToken.balanceOf(msg.sender) >= lotSizeTbtc, "Not enough TBTC to cover outstanding debt");\\n\\n if(tdtHolder == \\_d.VendingMachine){\\n \\_tbtcToken.burnFrom(msg.sender, lotSizeTbtc); // burn minimal amount to cover size\\n }\\n else{\\n \\_tbtcToken.transferFrom(msg.sender, tdtHolder, lotSizeTbtc);\\n }\\n\\n // Distribute funds to auction buyer\\n uint256 \\_valueToDistribute = \\_d.auctionValue();\\n msg.sender.transfer(\\_valueToDistribute);\\n\\n // Send any TBTC left to the Fee Rebate Token holder\\n \\_d.distributeFeeRebate();\\n\\n // For fraud, pay remainder to the liquidation initiator.\\n // For non-fraud, split 50-50 between initiator and signers. if the transfer amount is 1,\\n // division will yield a 0 value which causes a revert; instead, \\n // we simply ignore such a tiny amount and leave some wei dust in escrow\\n uint256 contractEthBalance = address(this).balance;\\n address payable initiator = \\_d.liquidationInitiator;\\n\\n if (initiator == address(0)){\\n initiator = address(0xdead);\\n }\\n if (contractEthBalance > 1) {\\n if (\\_wasFraud) {\\n initiator.transfer(contractEthBalance);\\n } else {\\n // There will always be a liquidation initiator.\\n uint256 split = contractEthBalance.div(2);\\n \\_d.pushFundsToKeepGroup(split);\\n initiator.transfer(split);\\n }\\n }\\n}\\n```\\n
Use a pull vs push funds pattern or use `address.send` instead of `address.transfer` which might leave some funds locked in the contract if it fails.
null
```\\n/// @notice Closes an auction and purchases the signer bonds. Payout to buyer, funder, then signers if not fraud\\n/// @dev For interface, reading auctionValue will give a past value. the current is better\\n/// @param \\_d deposit storage pointer\\nfunction purchaseSignerBondsAtAuction(DepositUtils.Deposit storage \\_d) public {\\n bool \\_wasFraud = \\_d.inFraudLiquidationInProgress();\\n require(\\_d.inSignerLiquidation(), "No active auction");\\n\\n \\_d.setLiquidated();\\n \\_d.logLiquidated();\\n\\n // send the TBTC to the TDT holder. If the TDT holder is the Vending Machine, burn it to maintain the peg.\\n address tdtHolder = \\_d.depositOwner();\\n\\n TBTCToken \\_tbtcToken = TBTCToken(\\_d.TBTCToken);\\n\\n uint256 lotSizeTbtc = \\_d.lotSizeTbtc();\\n require(\\_tbtcToken.balanceOf(msg.sender) >= lotSizeTbtc, "Not enough TBTC to cover outstanding debt");\\n\\n if(tdtHolder == \\_d.VendingMachine){\\n \\_tbtcToken.burnFrom(msg.sender, lotSizeTbtc); // burn minimal amount to cover size\\n }\\n else{\\n \\_tbtcToken.transferFrom(msg.sender, tdtHolder, lotSizeTbtc);\\n }\\n\\n // Distribute funds to auction buyer\\n uint256 \\_valueToDistribute = \\_d.auctionValue();\\n msg.sender.transfer(\\_valueToDistribute);\\n\\n // Send any TBTC left to the Fee Rebate Token holder\\n \\_d.distributeFeeRebate();\\n\\n // For fraud, pay remainder to the liquidation initiator.\\n // For non-fraud, split 50-50 between initiator and signers. if the transfer amount is 1,\\n // division will yield a 0 value which causes a revert; instead, \\n // we simply ignore such a tiny amount and leave some wei dust in escrow\\n uint256 contractEthBalance = address(this).balance;\\n address payable initiator = \\_d.liquidationInitiator;\\n\\n if (initiator == address(0)){\\n initiator = address(0xdead);\\n }\\n if (contractEthBalance > 1) {\\n if (\\_wasFraud) {\\n initiator.transfer(contractEthBalance);\\n } else {\\n // There will always be a liquidation initiator.\\n uint256 split = contractEthBalance.div(2);\\n \\_d.pushFundsToKeepGroup(split);\\n initiator.transfer(split);\\n }\\n }\\n}\\n```\\n
bitcoin-spv - verifyHash256Merkle allows existence proofs for the same leaf in multiple locations in the tree Won't Fix
medium
`BTCUtils.verifyHash256Merkle` is used by `ValidateSPV.prove` to validate a transaction's existence in a Bitcoin block. The function accepts as input a `_proof` and an `_index`. The `_proof` consists of, in order: the transaction hash, a list of intermediate nodes, and the merkle root.\\nThe proof is performed iteratively, and uses the `_index` to determine whether the next proof element represents a β€œleft branch” or a β€œright branch:”\\n```\\nuint \\_idx = \\_index;\\nbytes32 \\_root = \\_proof.slice(\\_proof.length - 32, 32).toBytes32();\\nbytes32 \\_current = \\_proof.slice(0, 32).toBytes32();\\n\\nfor (uint i = 1; i < (\\_proof.length.div(32)) - 1; i++) {\\n if (\\_idx % 2 == 1) {\\n \\_current = \\_hash256MerkleStep(\\_proof.slice(i \\* 32, 32), abi.encodePacked(\\_current));\\n } else {\\n \\_current = \\_hash256MerkleStep(abi.encodePacked(\\_current), \\_proof.slice(i \\* 32, 32));\\n }\\n \\_idx = \\_idx 1;\\n}\\nreturn \\_current == \\_root;\\n```\\n\\nIf `_idx` is even, the computed hash is placed before the next proof element. If `_idx` is odd, the computed hash is placed after the next proof element. After each iteration, `_idx` is decremented by `_idx /= 2`.\\nBecause `verifyHash256Merkle` makes no requirements on the size of `_proof` relative to `_index`, it is possible to pass in invalid values for `_index` that prove a transaction's existence in multiple locations in the tree.\\nBy modifying existing tests, we showed that any transaction can be proven to exist at least one alternate index. This alternate index is calculated as `(2 ** treeHeight) + prevIndex` - though other alternate indices are possible. The modified test is below:\\n```\\nit('verifies a bitcoin merkle root', async () => {\\n for (let i = 0; i < verifyHash256Merkle.length; i += 1) {\\n const res = await instance.verifyHash256Merkle(\\n verifyHash256Merkle[i].input.proof,\\n verifyHash256Merkle[i].input.index\\n ); // 0-indexed\\n assert.strictEqual(res, verifyHash256Merkle[i].output);\\n\\n // Now, attempt to use the same proof to verify the same leaf at\\n // a different index in the tree:\\n let pLen = verifyHash256Merkle[i].input.proof.length;\\n let height = ((pLen - 2) / 64) - 2;\\n\\n // Only attempt to verify roots that are meant to be verified\\n if (verifyHash256Merkle[i].output && height >= 1) {\\n let altIdx = (2 ** height) + verifyHash256Merkle[i].input.index;\\n\\n const resNext = await instance.verifyHash256Merkle(\\n verifyHash256Merkle[i].input.proof,\\n altIdx\\n );\\n\\n assert.strictEqual(resNext, verifyHash256Merkle[i].output);\\n\\n console.log('Verified transaction twice!');\\n }\\n }\\n});\\n```\\n
Use the length of `_proof` to determine the maximum allowed `_index`. `_index` should satisfy the following criterion: `_index` < 2 ** (_proof.length.div(32) - 2).\\nNote that subtraction by 2 accounts for the transaction hash and merkle root, which are assumed to be encoded in the proof along with the intermediate nodes.
null
```\\nuint \\_idx = \\_index;\\nbytes32 \\_root = \\_proof.slice(\\_proof.length - 32, 32).toBytes32();\\nbytes32 \\_current = \\_proof.slice(0, 32).toBytes32();\\n\\nfor (uint i = 1; i < (\\_proof.length.div(32)) - 1; i++) {\\n if (\\_idx % 2 == 1) {\\n \\_current = \\_hash256MerkleStep(\\_proof.slice(i \\* 32, 32), abi.encodePacked(\\_current));\\n } else {\\n \\_current = \\_hash256MerkleStep(abi.encodePacked(\\_current), \\_proof.slice(i \\* 32, 32));\\n }\\n \\_idx = \\_idx 1;\\n}\\nreturn \\_current == \\_root;\\n```\\n
keep-core - stake operator should not be eligible if undelegatedAt is set
low
An operator's stake should not be eligible if they stake an amount and immediately call `undelegate` in an attempt to indicate that they are going to recover their stake soon.\\n```\\nbool notUndelegated = block.number <= operator.undelegatedAt || operator.undelegatedAt == 0;\\n\\nif (isAuthorized && isActive && notUndelegated) {\\n balance = operator.amount;\\n}\\n```\\n
A stake that is entering undelegation is indicated by `operator.undelegatedAt` being non-zero. Change the `notUndelegated` check block.number <= `operator.undelegatedAt` || `operator.undelegatedAt` == 0 to `operator.undelegatedAT == 0` as any value being set indicates that undelegation is in progress.\\nEnforce that within the initialization period stake is canceled instead of being undelegated.
null
```\\nbool notUndelegated = block.number <= operator.undelegatedAt || operator.undelegatedAt == 0;\\n\\nif (isAuthorized && isActive && notUndelegated) {\\n balance = operator.amount;\\n}\\n```\\n
keep-core - Specification inconsistency: TokenStaking amount to be slashed/seized
low
The keep specification states that `slash` and `seize` affect at least the amount specified or the remaining stake of a member.\\nSlash each operator in the list misbehavers by the specified amount (or their remaining stake, whichever is lower).\\nPunish each operator in the list misbehavers by the specified amount or their remaining stake.\\nThe implementation, however, bails if one of the accounts does not have enough stake to be slashed or seized because of the use of `SafeMath.sub()`. This behavior is inconsistent with the specification which states that `min(amount, misbehaver.stake)` stake should be affected. The call to slash/seize will revert and no stakes are affected. At max, the staked amount of the lowest staker can be slashed/seized from every staker.\\nImplementing this method as stated in the specification using `min(amount, misbehaver.stake)` will cover the fact that slashing/seizing was only partially successful. If `misbehaver.stake` is zero no error might be emitted even though no stake was slashed/seized.\\n```\\n/\\*\\*\\n \\* @dev Slash provided token amount from every member in the misbehaved\\n \\* operators array and burn 100% of all the tokens.\\n \\* @param amount Token amount to slash from every misbehaved operator.\\n \\* @param misbehavedOperators Array of addresses to seize the tokens from.\\n \\*/\\nfunction slash(uint256 amount, address[] memory misbehavedOperators)\\n public\\n onlyApprovedOperatorContract(msg.sender) {\\n for (uint i = 0; i < misbehavedOperators.length; i++) {\\n address operator = misbehavedOperators[i];\\n require(authorizations[msg.sender][operator], "Not authorized");\\n operators[operator].amount = operators[operator].amount.sub(amount);\\n }\\n\\n token.burn(misbehavedOperators.length.mul(amount));\\n}\\n\\n/\\*\\*\\n \\* @dev Seize provided token amount from every member in the misbehaved\\n \\* operators array. The tattletale is rewarded with 5% of the total seized\\n \\* amount scaled by the reward adjustment parameter and the rest 95% is burned.\\n \\* @param amount Token amount to seize from every misbehaved operator.\\n \\* @param rewardMultiplier Reward adjustment in percentage. Min 1% and 100% max.\\n \\* @param tattletale Address to receive the 5% reward.\\n \\* @param misbehavedOperators Array of addresses to seize the tokens from.\\n \\*/\\nfunction seize(\\n uint256 amount,\\n uint256 rewardMultiplier,\\n address tattletale,\\n address[] memory misbehavedOperators\\n) public onlyApprovedOperatorContract(msg.sender) {\\n for (uint i = 0; i < misbehavedOperators.length; i++) {\\n address operator = misbehavedOperators[i];\\n require(authorizations[msg.sender][operator], "Not authorized");\\n operators[operator].amount = operators[operator].amount.sub(amount);\\n }\\n\\n uint256 total = misbehavedOperators.length.mul(amount);\\n uint256 tattletaleReward = (total.mul(5).div(100)).mul(rewardMultiplier).div(100);\\n\\n token.transfer(tattletale, tattletaleReward);\\n token.burn(total.sub(tattletaleReward));\\n}\\n```\\n
Require that `minimumStake` has been provided and can be seized/slashed. Update the documentation to reflect the fact that the solution always seizes/slashes `minimumStake`. Ensure that stakers cannot cancel their stake while they are actively participating in the network.
null
```\\n/\\*\\*\\n \\* @dev Slash provided token amount from every member in the misbehaved\\n \\* operators array and burn 100% of all the tokens.\\n \\* @param amount Token amount to slash from every misbehaved operator.\\n \\* @param misbehavedOperators Array of addresses to seize the tokens from.\\n \\*/\\nfunction slash(uint256 amount, address[] memory misbehavedOperators)\\n public\\n onlyApprovedOperatorContract(msg.sender) {\\n for (uint i = 0; i < misbehavedOperators.length; i++) {\\n address operator = misbehavedOperators[i];\\n require(authorizations[msg.sender][operator], "Not authorized");\\n operators[operator].amount = operators[operator].amount.sub(amount);\\n }\\n\\n token.burn(misbehavedOperators.length.mul(amount));\\n}\\n\\n/\\*\\*\\n \\* @dev Seize provided token amount from every member in the misbehaved\\n \\* operators array. The tattletale is rewarded with 5% of the total seized\\n \\* amount scaled by the reward adjustment parameter and the rest 95% is burned.\\n \\* @param amount Token amount to seize from every misbehaved operator.\\n \\* @param rewardMultiplier Reward adjustment in percentage. Min 1% and 100% max.\\n \\* @param tattletale Address to receive the 5% reward.\\n \\* @param misbehavedOperators Array of addresses to seize the tokens from.\\n \\*/\\nfunction seize(\\n uint256 amount,\\n uint256 rewardMultiplier,\\n address tattletale,\\n address[] memory misbehavedOperators\\n) public onlyApprovedOperatorContract(msg.sender) {\\n for (uint i = 0; i < misbehavedOperators.length; i++) {\\n address operator = misbehavedOperators[i];\\n require(authorizations[msg.sender][operator], "Not authorized");\\n operators[operator].amount = operators[operator].amount.sub(amount);\\n }\\n\\n uint256 total = misbehavedOperators.length.mul(amount);\\n uint256 tattletaleReward = (total.mul(5).div(100)).mul(rewardMultiplier).div(100);\\n\\n token.transfer(tattletale, tattletaleReward);\\n token.burn(total.sub(tattletaleReward));\\n}\\n```\\n
keep-tecdsa - Change state-mutability of checkSignatureFraud to view
low
```\\nfunction submitSignatureFraud(\\n uint8 \\_v,\\n bytes32 \\_r,\\n bytes32 \\_s,\\n bytes32 \\_signedDigest,\\n bytes calldata \\_preimage\\n) external returns (bool \\_isFraud) {\\n require(publicKey.length != 0, "Public key was not set yet");\\n\\n bytes32 calculatedDigest = sha256(\\_preimage);\\n require(\\n \\_signedDigest == calculatedDigest,\\n "Signed digest does not match double sha256 hash of the preimage"\\n );\\n\\n bool isSignatureValid = publicKeyToAddress(publicKey) ==\\n ecrecover(\\_signedDigest, \\_v, \\_r, \\_s);\\n\\n // Check if the signature is valid but was not requested.\\n require(\\n isSignatureValid && !digests[\\_signedDigest],\\n "Signature is not fraudulent"\\n );\\n\\n return true;\\n}\\n```\\n
Declare method as `view`. Consider renaming `submitSignatureFraud` to e.g. `checkSignatureFraud` to emphasize that it is only checking the signature and not actually changing state.
null
```\\nfunction submitSignatureFraud(\\n uint8 \\_v,\\n bytes32 \\_r,\\n bytes32 \\_s,\\n bytes32 \\_signedDigest,\\n bytes calldata \\_preimage\\n) external returns (bool \\_isFraud) {\\n require(publicKey.length != 0, "Public key was not set yet");\\n\\n bytes32 calculatedDigest = sha256(\\_preimage);\\n require(\\n \\_signedDigest == calculatedDigest,\\n "Signed digest does not match double sha256 hash of the preimage"\\n );\\n\\n bool isSignatureValid = publicKeyToAddress(publicKey) ==\\n ecrecover(\\_signedDigest, \\_v, \\_r, \\_s);\\n\\n // Check if the signature is valid but was not requested.\\n require(\\n isSignatureValid && !digests[\\_signedDigest],\\n "Signature is not fraudulent"\\n );\\n\\n return true;\\n}\\n```\\n
keep-core - Specification inconsistency: TokenStaking.slash() is never called
low
According to the keep specification stake should be slashed if a staker violates the protocol:\\nSlashing If a staker violates the protocol of an operation in a way which can be proven on-chain, they will be penalized by having their stakes slashed.\\nWhile this functionality can only be called by the approved operator contract, it is not being used throughout the system. In contrast `seize()` is being called when reporting unauthorized signing or relay entry timeout.\\n```\\n/\\*\\*\\n \\* @dev Slash provided token amount from every member in the misbehaved\\n \\* operators array and burn 100% of all the tokens.\\n \\* @param amount Token amount to slash from every misbehaved operator.\\n \\* @param misbehavedOperators Array of addresses to seize the tokens from.\\n \\*/\\nfunction slash(uint256 amount, address[] memory misbehavedOperators)\\n public\\n onlyApprovedOperatorContract(msg.sender) {\\n for (uint i = 0; i < misbehavedOperators.length; i++) {\\n address operator = misbehavedOperators[i];\\n require(authorizations[msg.sender][operator], "Not authorized");\\n operators[operator].amount = operators[operator].amount.sub(amount);\\n }\\n\\n token.burn(misbehavedOperators.length.mul(amount));\\n}\\n```\\n
Implement slashing according to the specification.
null
```\\n/\\*\\*\\n \\* @dev Slash provided token amount from every member in the misbehaved\\n \\* operators array and burn 100% of all the tokens.\\n \\* @param amount Token amount to slash from every misbehaved operator.\\n \\* @param misbehavedOperators Array of addresses to seize the tokens from.\\n \\*/\\nfunction slash(uint256 amount, address[] memory misbehavedOperators)\\n public\\n onlyApprovedOperatorContract(msg.sender) {\\n for (uint i = 0; i < misbehavedOperators.length; i++) {\\n address operator = misbehavedOperators[i];\\n require(authorizations[msg.sender][operator], "Not authorized");\\n operators[operator].amount = operators[operator].amount.sub(amount);\\n }\\n\\n token.burn(misbehavedOperators.length.mul(amount));\\n}\\n```\\n
tbtc - Remove notifyDepositExpiryCourtesyCall and allow exitCourtesyCall exiting the courtesy call at term
low
Following a deep dive into state transitions with the client it was agreed that `notifyDepositExpiryCourtesyCall` should be removed from the system as it is a left-over of a previous version of the deposit contract.\\nAdditionally, `exitCourtesyCall` should be callable at any time.\\n```\\n/// @notice Goes from courtesy call to active\\n/// @dev Only callable if collateral is sufficient and the deposit is not expiring\\n/// @param \\_d deposit storage pointer\\nfunction exitCourtesyCall(DepositUtils.Deposit storage \\_d) public {\\n require(\\_d.inCourtesyCall(), "Not currently in courtesy call");\\n require(block.timestamp <= \\_d.fundedAt + TBTCConstants.getDepositTerm(), "Deposit is expiring");\\n require(getCollateralizationPercentage(\\_d) >= \\_d.undercollateralizedThresholdPercent, "Deposit is still undercollateralized");\\n \\_d.setActive();\\n \\_d.logExitedCourtesyCall();\\n}\\n```\\n
Remove the `notifyDepositExpiryCourtesyCall` state transition and remove the requirement on `exitCourtesyCall` being callable only before the deposit expires.
null
```\\n/// @notice Goes from courtesy call to active\\n/// @dev Only callable if collateral is sufficient and the deposit is not expiring\\n/// @param \\_d deposit storage pointer\\nfunction exitCourtesyCall(DepositUtils.Deposit storage \\_d) public {\\n require(\\_d.inCourtesyCall(), "Not currently in courtesy call");\\n require(block.timestamp <= \\_d.fundedAt + TBTCConstants.getDepositTerm(), "Deposit is expiring");\\n require(getCollateralizationPercentage(\\_d) >= \\_d.undercollateralizedThresholdPercent, "Deposit is still undercollateralized");\\n \\_d.setActive();\\n \\_d.logExitedCourtesyCall();\\n}\\n```\\n
keep-tecdsa - withdraw should check for zero value transfer
low
Requesting the withdrawal of zero `ETH` in `KeepBonding.withdraw` should fail as this would allow the method to succeed, calling the user-provided destination even though the sender has no unbonded value.\\n```\\nfunction withdraw(uint256 amount, address payable destination) public {\\n require(\\n unbondedValue[msg.sender] >= amount,\\n "Insufficient unbonded value"\\n );\\n\\n unbondedValue[msg.sender] -= amount;\\n\\n (bool success, ) = destination.call.value(amount)("");\\n require(success, "Transfer failed");\\n}\\n```\\n\\nAnd a similar instance in BondedECDSAKeep:\\n```\\n/// @notice Withdraws amount of ether hold in the keep for the member.\\n/// The value is sent to the beneficiary of the specific member.\\n/// @param \\_member Keep member address.\\nfunction withdraw(address \\_member) external {\\n uint256 value = memberETHBalances[\\_member];\\n memberETHBalances[\\_member] = 0;\\n\\n /\\* solium-disable-next-line security/no-call-value \\*/\\n (bool success, ) = tokenStaking.magpieOf(\\_member).call.value(value)("");\\n\\n require(success, "Transfer failed");\\n}\\n```\\n
Require that the amount to be withdrawn is greater than zero.
null
```\\nfunction withdraw(uint256 amount, address payable destination) public {\\n require(\\n unbondedValue[msg.sender] >= amount,\\n "Insufficient unbonded value"\\n );\\n\\n unbondedValue[msg.sender] -= amount;\\n\\n (bool success, ) = destination.call.value(amount)("");\\n require(success, "Transfer failed");\\n}\\n```\\n
tbtc - Signer collusion may bypass increaseRedemptionFee flow
low
DepositRedemption.increaseRedemptionFee is used by signers to approve a signable bitcoin transaction with a higher fee, in case the network is congested and miners are not approving the lower-fee transaction.\\nFee increases can be performed every 4 hours:\\n```\\nrequire(block.timestamp >= \\_d.withdrawalRequestTime + TBTCConstants.getIncreaseFeeTimer(), "Fee increase not yet permitted");\\n```\\n\\nIn addition, each increase must increment the fee by exactly the initial proposed fee:\\n```\\n// Check that we're incrementing the fee by exactly the redeemer's initial fee\\nuint256 \\_previousOutputValue = DepositUtils.bytes8LEToUint(\\_previousOutputValueBytes);\\n\\_newOutputValue = DepositUtils.bytes8LEToUint(\\_newOutputValueBytes);\\nrequire(\\_previousOutputValue.sub(\\_newOutputValue) == \\_d.initialRedemptionFee, "Not an allowed fee step");\\n```\\n\\nOutside of these two restrictions, there is no limit to the number of times `increaseRedemptionFee` can be called. Over a 20-hour period, for example, `increaseRedemptionFee` could be called 5 times, increasing the fee to `initialRedemptionFee * 5`.\\nRather than calling `increaseRedemptionFee` 5 times over 20 hours, colluding signers may immediately create and sign a transaction with a fee of `initialRedemptionFee * 5`, wait for it to be mined, then submit it to `provideRedemptionProof`. Because `provideRedemptionProof` does not check that a transaction signature signs an approved digest, interested parties would need to monitor the bitcoin blockchain, notice the spend, and provide an ECDSA fraud proof before `provideRedemptionProof` is called.
Resolution\\nIssue addressed in keep-network/tbtc#522\\nTrack the latest approved fee, and ensure the transaction in `provideRedemptionProof` does not include a higher fee.
null
```\\nrequire(block.timestamp >= \\_d.withdrawalRequestTime + TBTCConstants.getIncreaseFeeTimer(), "Fee increase not yet permitted");\\n```\\n
tbtc - liquidating a deposit does not send the complete remainder of the contract balance to recipients
low
`purchaseSignerBondsAtAuction` might leave a wei in the contract if:\\nthere is only one wei remaining in the contract\\nthere is more than one wei remaining but the contract balance is odd.\\ncontract balances must be > 1 wei otherwise no transfer is attempted\\nthe division at line 271 floors the result if dividing an odd balance. The contract is sending `floor(contract.balance / 2)` to the keep group and liquidationInitiator leaving one 1 in the contract.\\n```\\nif (contractEthBalance > 1) {\\n if (\\_wasFraud) {\\n initiator.transfer(contractEthBalance);\\n } else {\\n // There will always be a liquidation initiator.\\n uint256 split = contractEthBalance.div(2);\\n \\_d.pushFundsToKeepGroup(split);\\n initiator.transfer(split);\\n }\\n}\\n```\\n
Define a reasonable minimum amount when awarding the fraud reporter or liquidation initiator. Alternatively, always transfer the contract balance. When splitting the amount use the contract balance after the first transfer as the value being sent to the second recipient. Use the presence of locked funds in a contract as an error indicator unless funds were sent forcefully to the contract.
null
```\\nif (contractEthBalance > 1) {\\n if (\\_wasFraud) {\\n initiator.transfer(contractEthBalance);\\n } else {\\n // There will always be a liquidation initiator.\\n uint256 split = contractEthBalance.div(2);\\n \\_d.pushFundsToKeepGroup(split);\\n initiator.transfer(split);\\n }\\n}\\n```\\n
tbtc - approveAndCall unused return parameter
low
`approveAndCall` always returns false because the return value `bool success` is never set.\\n```\\n/// @notice Set allowance for other address and notify.\\n/// Allows `\\_spender` to transfer the specified TDT\\n/// on your behalf and then ping the contract about it.\\n/// @dev The `\\_spender` should implement the `tokenRecipient` interface below\\n/// to receive approval notifications.\\n/// @param \\_spender Address of contract authorized to spend.\\n/// @param \\_tdtId The TDT they can spend.\\n/// @param \\_extraData Extra information to send to the approved contract.\\nfunction approveAndCall(address \\_spender, uint256 \\_tdtId, bytes memory \\_extraData) public returns (bool success) {\\n tokenRecipient spender = tokenRecipient(\\_spender);\\n approve(\\_spender, \\_tdtId);\\n spender.receiveApproval(msg.sender, \\_tdtId, address(this), \\_extraData);\\n}\\n```\\n
Return the correct success state.
null
```\\n/// @notice Set allowance for other address and notify.\\n/// Allows `\\_spender` to transfer the specified TDT\\n/// on your behalf and then ping the contract about it.\\n/// @dev The `\\_spender` should implement the `tokenRecipient` interface below\\n/// to receive approval notifications.\\n/// @param \\_spender Address of contract authorized to spend.\\n/// @param \\_tdtId The TDT they can spend.\\n/// @param \\_extraData Extra information to send to the approved contract.\\nfunction approveAndCall(address \\_spender, uint256 \\_tdtId, bytes memory \\_extraData) public returns (bool success) {\\n tokenRecipient spender = tokenRecipient(\\_spender);\\n approve(\\_spender, \\_tdtId);\\n spender.receiveApproval(msg.sender, \\_tdtId, address(this), \\_extraData);\\n}\\n```\\n
bitcoin-spv - Unnecessary memory allocation in BTCUtils Pending
low
`BTCUtils` makes liberal use of `BytesLib.slice`, which returns a freshly-allocated slice of an existing bytes array. In many cases, the desired behavior is simply to read a 32-byte slice of a byte array. As a result, the typical pattern used is: `bytesVar.slice(start, start + 32).toBytes32()`.\\nThis pattern introduces unnecessary complexity and memory allocation in a critically important library: cloning a portion of the array, storing that clone in memory, and then reading it from memory. A simpler alternative would be to implement `BytesLib.readBytes32(bytes _b, uint _idx)` and other β€œmemory-read” functions.\\nRather than moving the free memory pointer and redundantly reading, storing, then re-reading memory, `readBytes32` and similar functions would perform a simple length check and `mload` directly from the desired index in the array.\\nextractInputTxIdLE:\\n```\\n/// @notice Extracts the outpoint tx id from an input\\n/// @dev 32 byte tx id\\n/// @param \\_input The input\\n/// @return The tx id (little-endian bytes)\\nfunction extractInputTxIdLE(bytes memory \\_input) internal pure returns (bytes32) {\\n return \\_input.slice(0, 32).toBytes32();\\n}\\n```\\n\\nverifyHash256Merkle:\\n```\\nuint \\_idx = \\_index;\\nbytes32 \\_root = \\_proof.slice(\\_proof.length - 32, 32).toBytes32();\\nbytes32 \\_current = \\_proof.slice(0, 32).toBytes32();\\n\\nfor (uint i = 1; i < (\\_proof.length.div(32)) - 1; i++) {\\n if (\\_idx % 2 == 1) {\\n \\_current = \\_hash256MerkleStep(\\_proof.slice(i \\* 32, 32), abi.encodePacked(\\_current));\\n } else {\\n \\_current = \\_hash256MerkleStep(abi.encodePacked(\\_current), \\_proof.slice(i \\* 32, 32));\\n }\\n \\_idx = \\_idx 1;\\n}\\nreturn \\_current == \\_root;\\n```\\n
Implement `BytesLib.readBytes32` and favor its use over the `bytesVar.slice(start, start + 32).toBytes32()` pattern. Implement other memory-read functions where possible, and avoid the use of `slice`.\\nNote, too, that implementing this change in `verifyHash256Merkle` would allow `_hash256MerkleStep` to accept 2 `bytes32` inputs (rather than bytes), removing additional unnecessary casting and memory allocation.
null
```\\n/// @notice Extracts the outpoint tx id from an input\\n/// @dev 32 byte tx id\\n/// @param \\_input The input\\n/// @return The tx id (little-endian bytes)\\nfunction extractInputTxIdLE(bytes memory \\_input) internal pure returns (bytes32) {\\n return \\_input.slice(0, 32).toBytes32();\\n}\\n```\\n
bitcoin-spv - ValidateSPV.validateHeaderChain does not completely validate input Won't Fix
low
`ValidateSPV.validateHeaderChain` takes as input a sequence of Bitcoin headers and calculates the total accumulated difficulty across the entire sequence. The input headers are checked to ensure they are relatively well-formed:\\n```\\n// Check header chain length\\nif (\\_headers.length % 80 != 0) {return ERR\\_BAD\\_LENGTH;}\\n```\\n\\nHowever, the function lacks a check for nonzero length of `_headers`. Although the total difficulty returned would be zero, an explicit check would make this more clear.
If `headers.length` is zero, return `ERR_BAD_LENGTH`
null
```\\n// Check header chain length\\nif (\\_headers.length % 80 != 0) {return ERR\\_BAD\\_LENGTH;}\\n```\\n
bitcoin-spv - unnecessary intermediate cast
low
`CheckBitcoinSigs.accountFromPubkey()` casts the `bytes32` keccack256 hash of the `pubkey` to `uint256`, then `uint160` and then finally to `address` while the intermediate cast is not required.\\n```\\n/// @notice Derives an Ethereum Account address from a pubkey\\n/// @dev The address is the last 20 bytes of the keccak256 of the address\\n/// @param \\_pubkey The public key X & Y. Unprefixed, as a 64-byte array\\n/// @return The account address\\nfunction accountFromPubkey(bytes memory \\_pubkey) internal pure returns (address) {\\n require(\\_pubkey.length == 64, "Pubkey must be 64-byte raw, uncompressed key.");\\n\\n // keccak hash of uncompressed unprefixed pubkey\\n bytes32 \\_digest = keccak256(\\_pubkey);\\n return address(uint160(uint256(\\_digest)));\\n}\\n```\\n
The intermediate cast from `uint256` to `uint160` can be omitted. Refactor to `return address(uint256(_digest))` instead.
null
```\\n/// @notice Derives an Ethereum Account address from a pubkey\\n/// @dev The address is the last 20 bytes of the keccak256 of the address\\n/// @param \\_pubkey The public key X & Y. Unprefixed, as a 64-byte array\\n/// @return The account address\\nfunction accountFromPubkey(bytes memory \\_pubkey) internal pure returns (address) {\\n require(\\_pubkey.length == 64, "Pubkey must be 64-byte raw, uncompressed key.");\\n\\n // keccak hash of uncompressed unprefixed pubkey\\n bytes32 \\_digest = keccak256(\\_pubkey);\\n return address(uint160(uint256(\\_digest)));\\n}\\n```\\n
bitcoin-spv - unnecessary logic in BytesLib.toBytes32()
low
The heavily used library function `BytesLib.toBytes32()` unnecessarily casts `_source` to `bytes` (same type) and creates a copy of the dynamic byte array to check it's length, while this can be done directly on the user-provided `bytes` `_source`.\\n```\\nfunction toBytes32(bytes memory \\_source) pure internal returns (bytes32 result) {\\n bytes memory tempEmptyStringTest = bytes(\\_source);\\n if (tempEmptyStringTest.length == 0) {\\n return 0x0;\\n }\\n\\n assembly {\\n result := mload(add(\\_source, 32))\\n }\\n}\\n```\\n
```\\nfunction toBytes32(bytes memory \\_source) pure internal returns (bytes32 result) {\\n if (\\_source.length == 0) {\\n return 0x0;\\n }\\n\\n assembly {\\n result := mload(add(\\_source, 32))\\n }\\n }\\n```\\n
null
```\\nfunction toBytes32(bytes memory \\_source) pure internal returns (bytes32 result) {\\n bytes memory tempEmptyStringTest = bytes(\\_source);\\n if (tempEmptyStringTest.length == 0) {\\n return 0x0;\\n }\\n\\n assembly {\\n result := mload(add(\\_source, 32))\\n }\\n}\\n```\\n
bitcoin-spv - redundant functionality Won't Fix
low
The library exposes redundant implementations of bitcoins double `sha256`.\\nsolidity native implementation with an overzealous type correction issue 5.45\\n```\\n/// @notice Implements bitcoin's hash256 (double sha2)\\n/// @dev abi.encodePacked changes the return to bytes instead of bytes32\\n/// @param \\_b The pre-image\\n/// @return The digest\\nfunction hash256(bytes memory \\_b) internal pure returns (bytes32) {\\n return abi.encodePacked(sha256(abi.encodePacked(sha256(\\_b)))).toBytes32();\\n}\\n```\\n\\nassembly implementation\\nNote this implementation does not handle errors when staticcall'ing the precompiled `sha256` contract (private chains).\\n```\\n/// @notice Implements bitcoin's hash256 (double sha2)\\n/// @dev sha2 is precompiled smart contract located at address(2)\\n/// @param \\_b The pre-image\\n/// @return The digest\\nfunction hash256View(bytes memory \\_b) internal view returns (bytes32 res) {\\n assembly {\\n let ptr := mload(0x40)\\n pop(staticcall(gas, 2, add(\\_b, 32), mload(\\_b), ptr, 32))\\n pop(staticcall(gas, 2, ptr, 32, ptr, 32))\\n res := mload(ptr)\\n }\\n}\\n```\\n
We recommend providing only one implementation for calculating the double `sha256` as maintaining two interfaces for the same functionality is not desirable. Furthermore, even though the assembly implementation is saving gas, we recommend keeping the language provided implementation.
null
```\\n/// @notice Implements bitcoin's hash256 (double sha2)\\n/// @dev abi.encodePacked changes the return to bytes instead of bytes32\\n/// @param \\_b The pre-image\\n/// @return The digest\\nfunction hash256(bytes memory \\_b) internal pure returns (bytes32) {\\n return abi.encodePacked(sha256(abi.encodePacked(sha256(\\_b)))).toBytes32();\\n}\\n```\\n
bitcoin-spv - unnecessary type correction
low
The type correction `encodePacked().toBytes32()` is not needed as `sha256` already returns `bytes32`.\\n```\\nfunction hash256(bytes memory \\_b) internal pure returns (bytes32) {\\n return abi.encodePacked(sha256(abi.encodePacked(sha256(\\_b)))).toBytes32();\\n}\\n```\\n
Refactor to `return sha256(abi.encodePacked(sha256(_b)));` to save gas.
null
```\\nfunction hash256(bytes memory \\_b) internal pure returns (bytes32) {\\n return abi.encodePacked(sha256(abi.encodePacked(sha256(\\_b)))).toBytes32();\\n}\\n```\\n
tbtc - Where possible, a specific contract type should be used rather than address
low
Rather than storing addresses and then casting to the known contract type, it's better to use the best type available so the compiler can check for type safety.\\n`TBTCSystem.priceFeed` is of type `address`, but it could be type `IBTCETHPriceFeed` instead. Not only would this give a little more type safety when deploying new modules, but it would avoid repeated casts throughout the codebase of the form `IBTCETHPriceFeed(priceFeed)`, `IRelay(relay)`, `TBTCSystem()`, and others.\\n```\\nstruct Deposit {\\n\\n // SET DURING CONSTRUCTION\\n address TBTCSystem;\\n address TBTCToken;\\n address TBTCDepositToken;\\n address FeeRebateToken;\\n address VendingMachine;\\n uint256 lotSizeSatoshis;\\n uint8 currentState;\\n uint256 signerFeeDivisor;\\n uint128 undercollateralizedThresholdPercent;\\n uint128 severelyUndercollateralizedThresholdPercent;\\n```\\n\\n```\\ncontract DepositFactory is CloneFactory, TBTCSystemAuthority{\\n\\n // Holds the address of the deposit contract\\n // which will be used as a master contract for cloning.\\n address public masterDepositAddress;\\n address public tbtcSystem;\\n address public tbtcToken;\\n address public tbtcDepositToken;\\n address public feeRebateToken;\\n address public vendingMachine;\\n uint256 public keepThreshold;\\n uint256 public keepSize;\\n```\\n\\nRemediation\\nWhere possible, use more specific types instead of `address`. This goes for parameter types as well as state variable types.
Resolution\\nThis issue has been addressed with https://github.com/keep-network/tbtc/issues/507 and keep-network/tbtc#542.
null
```\\nstruct Deposit {\\n\\n // SET DURING CONSTRUCTION\\n address TBTCSystem;\\n address TBTCToken;\\n address TBTCDepositToken;\\n address FeeRebateToken;\\n address VendingMachine;\\n uint256 lotSizeSatoshis;\\n uint8 currentState;\\n uint256 signerFeeDivisor;\\n uint128 undercollateralizedThresholdPercent;\\n uint128 severelyUndercollateralizedThresholdPercent;\\n```\\n
tbtc - Variable shadowing in DepositFactory
low
`DepositFactory` inherits from `TBTCSystemAuthority`. Both contracts declare a state variable with the same name, `tbtcSystem`.\\n```\\naddress public tbtcSystem;\\n```\\n
Remove the shadowed variable.
null
```\\naddress public tbtcSystem;\\n```\\n
tbtc - Values may contain dirty lower-order bits Pending
low
`FundingScript` and `RedemptionScript` use `mload` to cast the first bytes of a byte array to `bytes4`. Because `mload` deals with 32-byte chunks, the resulting `bytes4` value may contain dirty lower-order bits.\\nFundingScript.receiveApproval:\\n```\\n// Verify \\_extraData is a call to unqualifiedDepositToTbtc.\\nbytes4 functionSignature;\\nassembly { functionSignature := mload(add(\\_extraData, 0x20)) }\\nrequire(\\n functionSignature == vendingMachine.unqualifiedDepositToTbtc.selector,\\n "Bad \\_extraData signature. Call must be to unqualifiedDepositToTbtc."\\n);\\n```\\n\\nRedemptionScript.receiveApproval:\\n```\\n// Verify \\_extraData is a call to tbtcToBtc.\\nbytes4 functionSignature;\\nassembly { functionSignature := mload(add(\\_extraData, 0x20)) }\\nrequire(\\n functionSignature == vendingMachine.tbtcToBtc.selector,\\n "Bad \\_extraData signature. Call must be to tbtcToBtc."\\n);\\n```\\n
Solidity truncates these unneeded bytes in the subsequent comparison operations, so there is no action required. However, this is good to keep in mind if these values are ever used for anything outside of strict comparison.
null
```\\n// Verify \\_extraData is a call to unqualifiedDepositToTbtc.\\nbytes4 functionSignature;\\nassembly { functionSignature := mload(add(\\_extraData, 0x20)) }\\nrequire(\\n functionSignature == vendingMachine.unqualifiedDepositToTbtc.selector,\\n "Bad \\_extraData signature. Call must be to unqualifiedDepositToTbtc."\\n);\\n```\\n
tbtc - Revert error string may be malformed Pending
low
`FundingScript` handles an error from a call to `VendingMachine` like so.\\n```\\n// Call the VendingMachine.\\n// We could explictly encode the call to vending machine, but this would\\n// involve manually parsing \\_extraData and allocating variables.\\n(bool success, bytes memory returnData) = address(vendingMachine).call(\\n \\_extraData\\n);\\nrequire(success, string(returnData));\\n```\\n\\nOn a high-level revert, `returnData` will already include the typical β€œerror selector”. As `FundingScript` propagates this error message, it will add another error selector, which may make it difficult to read the error message.\\nThe same issue is present in RedemptionScript:\\n```\\n(bool success, bytes memory returnData) = address(vendingMachine).call(\\_extraData);\\n// By default, `address.call` will catch any revert messages.\\n// Converting the `returnData` to a string will effectively forward any revert messages.\\n// https://ethereum.stackexchange.com/questions/69133/forward-revert-message-from-low-level-solidity-call\\n// TODO: there's some noisy couple bytes at the beginning of the converted string, maybe the ABI-coded length?\\nrequire(success, string(returnData));\\n```\\n
Rather than adding an assembly-level revert to the affected contracts, ensure nested error selectors are handled in external libraries.
null
```\\n// Call the VendingMachine.\\n// We could explictly encode the call to vending machine, but this would\\n// involve manually parsing \\_extraData and allocating variables.\\n(bool success, bytes memory returnData) = address(vendingMachine).call(\\n \\_extraData\\n);\\nrequire(success, string(returnData));\\n```\\n
tbtc - Where possible, use constant rather than state variables
low
`TBTCSystem` uses a state variable for `pausedDuration`, but this value is never changed.\\n```\\nuint256 pausedDuration = 10 days;\\n```\\n
Consider using the `constant` keyword.
null
```\\nuint256 pausedDuration = 10 days;\\n```\\n
tbtc - Variable shadowing in TBTCDepositToken constructor
low
`TBTCDepositToken` inherits from `DepositFactoryAuthority`, which has a single state variable, `_depositFactory`. This variable is shadowed in the `TBTCDepositToken` constructor.\\n```\\nconstructor(address \\_depositFactory)\\n ERC721Metadata("tBTC Deopsit Token", "TDT")\\n DepositFactoryAuthority(\\_depositFactory)\\npublic {\\n // solium-disable-previous-line no-empty-blocks\\n}\\n```\\n
Rename the parameter or state variable.
null
```\\nconstructor(address \\_depositFactory)\\n ERC721Metadata("tBTC Deopsit Token", "TDT")\\n DepositFactoryAuthority(\\_depositFactory)\\npublic {\\n // solium-disable-previous-line no-empty-blocks\\n}\\n```\\n
Incorrect response from price feed if called during an onERC1155Received callback Acknowledged
medium
The ERC 1155 standard requires that smart contracts must implement `onERC1155Received` and `onERC1155BatchReceived` to accept transfers.\\nThis means that on any token received, code run on the receiving smart contract.\\nIn `NiftyswapExchange` when adding / removing liquidity or buying tokens, the methods mentioned above are called when the tokens are sent. When this happens, the state of the contract is changed but not completed, the tokens are sent to the receiving smart contract but the state is not completely updated.\\nThis happens in these cases\\n`_baseToToken` (when buying tokens)\\n```\\n// // Refund Base Token if any\\nif (totalRefundBaseTokens > 0) {\\n baseToken.safeTransferFrom(address(this), \\_recipient, baseTokenID, totalRefundBaseTokens, "");\\n}\\n\\n// Send Tokens all tokens purchased\\ntoken.safeBatchTransferFrom(address(this), \\_recipient, \\_tokenIds, \\_tokensBoughtAmounts, "");\\n```\\n\\n`_removeLiquidity`\\n```\\n// Transfer total Base Tokens and all Tokens ids\\nbaseToken.safeTransferFrom(address(this), \\_provider, baseTokenID, totalBaseTokens, "");\\ntoken.safeBatchTransferFrom(address(this), \\_provider, \\_tokenIds, tokenAmounts, "");\\n```\\n\\n`_addLiquidity`\\n```\\n// Mint liquidity pool tokens\\n\\_batchMint(\\_provider, \\_tokenIds, liquiditiesToMint, "");\\n\\n// Transfer all Base Tokens to this contract\\nbaseToken.safeTransferFrom(\\_provider, address(this), baseTokenID, totalBaseTokens, abi.encode(DEPOSIT\\_SIG));\\n```\\n\\nEach of these examples send some tokens to the smart contract, which triggers calling some code on the receiving smart contract.\\nWhile these methods have the `nonReentrant` modifier which protects them from re-netrancy, the result of the methods `getPrice_baseToToken` and `getPrice_tokenToBase` is affected. These 2 methods do not have the `nonReentrant` modifier.\\nThe price reported by the `getPrice_baseToToken` and `getPrice_tokenToBase` methods is incorrect (until after the end of the transaction) because they rely on the number of tokens owned by the NiftyswapExchange; which between the calls is not finalized. Hence the price reported will be incorrect.\\nThis gives the smart contract which receives the tokens, the opportunity to use other systems (if they exist) that rely on the result of `getPrice_baseToToken` and `getPrice_tokenToBase` to use the returned price to its advantage.\\nIt's important to note that this is a bug only if other systems rely on the price reported by this `NiftyswapExchange`. Also the current contract is not affected, nor its balances or internal ledger, only other systems relying on its reported price will be fooled.
Resolution\\nThe design will not be modified. Horizon Games should clearly document this risk for 3rd parties seeking to use Niftyswap as a price feed.\\nBecause there is no way to enforce how other systems work, a restriction can be added on `NiftyswapExchange` to protect other systems (if any) that rely on `NiftyswapExchange` for price discovery.\\nAdding a `nonReentrant` modifier on the view methods `getPrice_baseToToken` and `getPrice_tokenToBase` will add a bit of protection for the ecosystem.
null
```\\n// // Refund Base Token if any\\nif (totalRefundBaseTokens > 0) {\\n baseToken.safeTransferFrom(address(this), \\_recipient, baseTokenID, totalRefundBaseTokens, "");\\n}\\n\\n// Send Tokens all tokens purchased\\ntoken.safeBatchTransferFrom(address(this), \\_recipient, \\_tokenIds, \\_tokensBoughtAmounts, "");\\n```\\n
Ether send function remainder handling
low
The Ether send function depicted below implements logic to reimburse the sender if an extraneous amount is left in the contract after the disbursement.\\n```\\nfunction sendEth(address payable [] memory \\_to, uint256[] memory \\_value) public restrictedToOwner payable returns (bool \\_success) {\\n // input validation\\n require(\\_to.length == \\_value.length);\\n require(\\_to.length <= 255);\\n\\n // count values for refunding sender\\n uint256 beforeValue = msg.value;\\n uint256 afterValue = 0;\\n\\n // loop through to addresses and send value\\n for (uint8 i = 0; i < \\_to.length; i++) {\\n afterValue = afterValue.add(\\_value[i]);\\n assert(\\_to[i].send(\\_value[i]));\\n }\\n\\n // send back remaining value to sender\\n uint256 remainingValue = beforeValue.sub(afterValue);\\n if (remainingValue > 0) {\\n assert(msg.sender.send(remainingValue));\\n }\\n return true;\\n}\\n```\\n\\nIt is also the only place where the `SafeMath` dependency is being used. More specifically to check there was no underflow in the arithmetic adding up the disbursed amounts.\\nHowever, since the individual sends would revert themselves should more Ether than what was available in the balance be specified these protection measures seem unnecessary.\\nNot only the above is true but the current codebase does not allow to take funds locked within the contract out in the off chance someone forced funds into this smart contract (e.g., by self-destructing some other smart contract containing funds into this one).
The easiest way to handle both retiring `SafeMath` and returning locked funds would be to phase out all the intra-function arithmetic and just transferring `address(this).balance` to `msg.sender` at the end of the disbursement. Since all the funds in there are meant to be from the caller of the function this serves the purpose of returning extraneous funds to him well and, adding to that, it allows for some front-running fun if someone β€œself-destructed” funds to this smart contract by mistake.
null
```\\nfunction sendEth(address payable [] memory \\_to, uint256[] memory \\_value) public restrictedToOwner payable returns (bool \\_success) {\\n // input validation\\n require(\\_to.length == \\_value.length);\\n require(\\_to.length <= 255);\\n\\n // count values for refunding sender\\n uint256 beforeValue = msg.value;\\n uint256 afterValue = 0;\\n\\n // loop through to addresses and send value\\n for (uint8 i = 0; i < \\_to.length; i++) {\\n afterValue = afterValue.add(\\_value[i]);\\n assert(\\_to[i].send(\\_value[i]));\\n }\\n\\n // send back remaining value to sender\\n uint256 remainingValue = beforeValue.sub(afterValue);\\n if (remainingValue > 0) {\\n assert(msg.sender.send(remainingValue));\\n }\\n return true;\\n}\\n```\\n
Unneeded type cast of contract type
low
The typecast being done on the `address` parameter in the lien below is unneeded.\\n```\\nERC20 token = ERC20(\\_tokenAddress);\\n```\\n
Assign the right type at the function parameter definition like so:\\n```\\n function sendErc20(ERC20 _tokenAddress, address[] memory _to, uint256[] memory _value) public restrictedToOwner returns (bool _success) {\\n```\\n
null
```\\nERC20 token = ERC20(\\_tokenAddress);\\n```\\n
Inadequate use of assert
low
The usage of `require` vs `assert` has always been a matter of discussion because of the fine lines distinguishing these transaction-terminating expressions.\\nHowever, the usage of the `assert` syntax in this case is not the most appropriate.\\nBorrowing the explanation from the latest solidity docs (v. https://solidity.readthedocs.io/en/latest/control-structures.html#id4) :\\n```\\nThe assert function should only be used to test for internal errors, and to check invariants. \\n```\\n\\nSince assert-style exceptions (using the `0xfe` opcode) consume all gas available to the call and require-style ones (using the `0xfd` opcode) do not since the Metropolis release when the `REVERT` instruction was added, the usage of `require` in the lines depicted in the examples section would only result in gas savings and the same security assumptions.\\nIn this case, even though the calls are being made to external contracts the supposedly abide to a predefined specification, this is by no means an invariant of the presented system since the component is external to the built system and its integrity cannot be formally verified.\\n```\\nassert(\\_to[i].send(\\_value[i]));\\n```\\n\\n```\\nassert(msg.sender.send(remainingValue));\\n```\\n\\n```\\nassert(token.transferFrom(msg.sender, \\_to[i], \\_value[i]) == true);\\n```\\n
Exchange the `assert` statements for `require` ones.
null
```\\nThe assert function should only be used to test for internal errors, and to check invariants. \\n```\\n
uint overflow may lead to stealing funds
high
It's possible to create a delegation with a very huge amount which may result in a lot of critically bad malicious usages:\\n```\\nuint holderBalance = SkaleToken(contractManager.getContract("SkaleToken")).balanceOf(holder);\\nuint lockedToDelegate = tokenState.getLockedCount(holder) - tokenState.getPurchasedAmount(holder);\\nrequire(holderBalance >= amount + lockedToDelegate, "Delegator hasn't enough tokens to delegate");\\n```\\n\\n`amount` is passed by a user as a parameter, so if it's close to `uint` max value, `amount` + lockedToDelegate would overflow and this requirement would pass.\\nHaving delegation with an almost infinite amount of tokens can lead to many various attacks on the system up to stealing funds and breaking everything.
Using `SafeMath` everywhere should prevent this and other similar issues. There should be more critical attacks caused by overflows/underflows, so `SafeMath` should be used everywhere in the codebase.
null
```\\nuint holderBalance = SkaleToken(contractManager.getContract("SkaleToken")).balanceOf(holder);\\nuint lockedToDelegate = tokenState.getLockedCount(holder) - tokenState.getPurchasedAmount(holder);\\nrequire(holderBalance >= amount + lockedToDelegate, "Delegator hasn't enough tokens to delegate");\\n```\\n
Holders can burn locked funds
high
Skale token is a modified ERC-777 that allows locking some part of the balance. Locking is checked during every transfer:\\n```\\n// Property of the company SKALE Labs inc.---------------------------------\\n uint locked = \\_getLockedOf(from);\\n if (locked > 0) {\\n require(\\_balances[from] >= locked + amount, "Token should be unlocked for transferring");\\n }\\n//-------------------------------------------------------------------------\\n \\_balances[from] = \\_balances[from].sub(amount);\\n \\_balances[to] = \\_balances[to].add(amount);\\n```\\n\\nBut it's not checked during `burn` function and it's possible to β€œburn” `locked` tokens. Tokens will be burned, but `locked` amount will remain the same. That will result in having more `locked` tokens than the balance which may have very unpredictable behaviour.
Allow burning only unlocked tokens.
null
```\\n// Property of the company SKALE Labs inc.---------------------------------\\n uint locked = \\_getLockedOf(from);\\n if (locked > 0) {\\n require(\\_balances[from] >= locked + amount, "Token should be unlocked for transferring");\\n }\\n//-------------------------------------------------------------------------\\n \\_balances[from] = \\_balances[from].sub(amount);\\n \\_balances[to] = \\_balances[to].add(amount);\\n```\\n
Node can unlink validator
high
Validators can link a node address to them by calling `linkNodeAddress` function:\\n```\\nfunction linkNodeAddress(address validatorAddress, address nodeAddress) external allow("DelegationService") {\\n uint validatorId = getValidatorId(validatorAddress);\\n require(\\_validatorAddressToId[nodeAddress] == 0, "Validator cannot override node address");\\n \\_validatorAddressToId[nodeAddress] = validatorId;\\n}\\n\\nfunction unlinkNodeAddress(address validatorAddress, address nodeAddress) external allow("DelegationService") {\\n uint validatorId = getValidatorId(validatorAddress);\\n require(\\_validatorAddressToId[nodeAddress] == validatorId, "Validator hasn't permissions to unlink node");\\n \\_validatorAddressToId[nodeAddress] = 0;\\n}\\n```\\n\\nAfter that, the node has the same rights and is almost indistinguishable from the validator. So the node can even remove validator's address from `_validatorAddressToId` list and take over full control over validator. Additionally, the node can even remove itself by calling `unlinkNodeAddress`, leaving validator with no control at all forever.\\nAlso, even without nodes, a validator can initially call `unlinkNodeAddress` to remove itself.
Linked nodes (and validator) should not be able to unlink validator's address from the `_validatorAddressToId` mapping.
null
```\\nfunction linkNodeAddress(address validatorAddress, address nodeAddress) external allow("DelegationService") {\\n uint validatorId = getValidatorId(validatorAddress);\\n require(\\_validatorAddressToId[nodeAddress] == 0, "Validator cannot override node address");\\n \\_validatorAddressToId[nodeAddress] = validatorId;\\n}\\n\\nfunction unlinkNodeAddress(address validatorAddress, address nodeAddress) external allow("DelegationService") {\\n uint validatorId = getValidatorId(validatorAddress);\\n require(\\_validatorAddressToId[nodeAddress] == validatorId, "Validator hasn't permissions to unlink node");\\n \\_validatorAddressToId[nodeAddress] = 0;\\n}\\n```\\n
Unlocking funds after slashing
high
The initial funds can be unlocked if 51+% of them are delegated. However if any portion of the funds are slashed, the rest of the funds will not be unlocked at the end of the delegation period.\\n```\\nif (\\_isPurchased[delegationId]) {\\n address holder = delegation.holder;\\n \\_totalDelegated[holder] += delegation.amount;\\n if (\\_totalDelegated[holder] >= \\_purchased[holder]) {\\n purchasedToUnlocked(holder);\\n }\\n```\\n
Consider slashed tokens as delegated, or include them in the calculation for process to unlock in `endingDelegatedToUnlocked`
null
```\\nif (\\_isPurchased[delegationId]) {\\n address holder = delegation.holder;\\n \\_totalDelegated[holder] += delegation.amount;\\n if (\\_totalDelegated[holder] >= \\_purchased[holder]) {\\n purchasedToUnlocked(holder);\\n }\\n```\\n
Bounties and fees should only be locked for the first 3 months
high
Bounties are currently locked for the first 3 months after delegation:\\n```\\nskaleBalances.lockBounty(shares[i].holder, timeHelpers.addMonths(delegationStarted, 3));\\n```\\n\\nInstead, they should be locked for the first 3 months after the token launch.
It's better just to forbid any withdrawals for the first 3 months, no need to track it separately for every delegation. This recommendation is mainly to simplify the process.
null
```\\nskaleBalances.lockBounty(shares[i].holder, timeHelpers.addMonths(delegationStarted, 3));\\n```\\n
getLockedCount is iterating over all history of delegations
high
`getLockedCount` is iterating over all delegations of a specific holder and may even change the state of these delegations by calling `getState`.\\n```\\nfunction getLockedCount(address holder) external returns (uint amount) {\\n amount = 0;\\n DelegationController delegationController = DelegationController(contractManager.getContract("DelegationController"));\\n uint[] memory delegationIds = delegationController.getDelegationsByHolder(holder);\\n for (uint i = 0; i < delegationIds.length; ++i) {\\n uint id = delegationIds[i];\\n if (isLocked(getState(id))) {\\n amount += delegationController.getDelegation(id).amount;\\n }\\n }\\n return amount + getPurchasedAmount(holder) + this.getSlashedAmount(holder);\\n}\\n```\\n\\nThis problem is major because delegations number is growing over time and may even potentially grow more than the gas limit and lock all tokens forever. `getLockedCount` is called during every transfer which makes any token transfer much more expensive than it should be.
Remove iterations over a potentially unlimited amount of tokens. All the necessary data can be precalculated before and `getLockedCount` function can have O(1) complexity.
null
```\\nfunction getLockedCount(address holder) external returns (uint amount) {\\n amount = 0;\\n DelegationController delegationController = DelegationController(contractManager.getContract("DelegationController"));\\n uint[] memory delegationIds = delegationController.getDelegationsByHolder(holder);\\n for (uint i = 0; i < delegationIds.length; ++i) {\\n uint id = delegationIds[i];\\n if (isLocked(getState(id))) {\\n amount += delegationController.getDelegation(id).amount;\\n }\\n }\\n return amount + getPurchasedAmount(holder) + this.getSlashedAmount(holder);\\n}\\n```\\n
Tokens are unlocked only when delegation ends
high
After the first 3 months since at least 50% of tokens are delegated, all tokens should be unlocked. In practice, they are only unlocked if at least 50% of tokens, that were bought on the initial launch, are undelegated.\\n```\\nif (\\_isPurchased[delegationId]) {\\n address holder = delegation.holder;\\n \\_totalDelegated[holder] += delegation.amount;\\n if (\\_totalDelegated[holder] >= \\_purchased[holder]) {\\n purchasedToUnlocked(holder);\\n }\\n}\\n```\\n
Implement lock mechanism according to the legal requirement.
null
```\\nif (\\_isPurchased[delegationId]) {\\n address holder = delegation.holder;\\n \\_totalDelegated[holder] += delegation.amount;\\n if (\\_totalDelegated[holder] >= \\_purchased[holder]) {\\n purchasedToUnlocked(holder);\\n }\\n}\\n```\\n
Tokens after delegation should not be unlocked automatically
high
When some amount of tokens are delegated to a validator when the delegation period ends, these tokens are unlocked. However these tokens should be added to `_purchased` as they were in that state before their delegation.\\n```\\nif (\\_isPurchased[delegationId]) {\\n address holder = delegation.holder;\\n \\_totalDelegated[holder] += delegation.amount;\\n if (\\_totalDelegated[holder] >= \\_purchased[holder]) {\\n purchasedToUnlocked(holder);\\n }\\n}\\n```\\n
Tokens should only be unlocked if the main legal requirement `(_totalDelegated[holder] >= _purchased[holder])` is satisfied, which in the above case this has not happened.
null
```\\nif (\\_isPurchased[delegationId]) {\\n address holder = delegation.holder;\\n \\_totalDelegated[holder] += delegation.amount;\\n if (\\_totalDelegated[holder] >= \\_purchased[holder]) {\\n purchasedToUnlocked(holder);\\n }\\n}\\n```\\n
Some unlocked tokens can become locked after delegation is rejected
high
When some amount of tokens are requested to be delegated to a validator, the validator can reject the request. The previous status of these tokens should be intact and not changed (locked or unlocked).\\nHere the initial status of tokens gets stored and it's either completely `locked` or unlocked:\\n```\\nif (\\_purchased[delegation.holder] > 0) {\\n \\_isPurchased[delegationId] = true;\\n if (\\_purchased[delegation.holder] > delegation.amount) {\\n \\_purchased[delegation.holder] -= delegation.amount;\\n } else {\\n \\_purchased[delegation.holder] = 0;\\n }\\n} else {\\n \\_isPurchased[delegationId] = false;\\n}\\n```\\n\\nThe problem is that if some amount of these tokens are locked at the time of the request and the rest tokens are unlocked, they will all be considered as locked after the delegation was rejected.\\n```\\nfunction \\_cancel(uint delegationId, DelegationController.Delegation memory delegation) internal returns (State state) {\\n if (\\_isPurchased[delegationId]) {\\n state = purchasedProposedToPurchased(delegationId, delegation);\\n } else {\\n state = proposedToUnlocked(delegationId);\\n }\\n}\\n```\\n
Don't change the status of the rejected tokens.
null
```\\nif (\\_purchased[delegation.holder] > 0) {\\n \\_isPurchased[delegationId] = true;\\n if (\\_purchased[delegation.holder] > delegation.amount) {\\n \\_purchased[delegation.holder] -= delegation.amount;\\n } else {\\n \\_purchased[delegation.holder] = 0;\\n }\\n} else {\\n \\_isPurchased[delegationId] = false;\\n}\\n```\\n
Gas limit for bounty and slashing distribution
high
After every bounty payment (should be once per month) to a validator, the bounty is distributed to all delegators. In order to do that, there is a `for` loop that iterates over all active delegators and sends their bounty to `SkaleBalances` contract:\\n```\\nfor (uint i = 0; i < shares.length; ++i) {\\n skaleToken.send(address(skaleBalances), shares[i].amount, abi.encode(shares[i].holder));\\n\\n uint created = delegationController.getDelegation(shares[i].delegationId).created;\\n uint delegationStarted = timeHelpers.getNextMonthStartFromDate(created);\\n skaleBalances.lockBounty(shares[i].holder, timeHelpers.addMonths(delegationStarted, 3));\\n}\\n```\\n\\nThere are also few more loops over all the active delegators. This leads to a huge gas cost of distribution mechanism. A number of active delegators that can be processed before hitting the gas limit is limited and not big enough.\\nThe same issue is with slashing:\\n```\\nfunction slash(uint validatorId, uint amount) external allow("SkaleDKG") {\\n ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));\\n require(validatorService.validatorExists(validatorId), "Validator does not exist");\\n\\n Distributor distributor = Distributor(contractManager.getContract("Distributor"));\\n TokenState tokenState = TokenState(contractManager.getContract("TokenState"));\\n\\n Distributor.Share[] memory shares = distributor.distributePenalties(validatorId, amount);\\n for (uint i = 0; i < shares.length; ++i) {\\n tokenState.slash(shares[i].delegationId, shares[i].amount);\\n }\\n}\\n```\\n
The best solution would require major changes to the codebase, but would eventually make it simpler and safer. Instead of distributing and centrally calculating bounty for each delegator during one call it's better to just store all the necessary values, so delegator would be able to calculate the bounty on withdrawal. Amongst the necessary values, there should be history of total delegated amounts per validator during each bounty payment and history of all delegations with durations of their active state.
null
```\\nfor (uint i = 0; i < shares.length; ++i) {\\n skaleToken.send(address(skaleBalances), shares[i].amount, abi.encode(shares[i].holder));\\n\\n uint created = delegationController.getDelegation(shares[i].delegationId).created;\\n uint delegationStarted = timeHelpers.getNextMonthStartFromDate(created);\\n skaleBalances.lockBounty(shares[i].holder, timeHelpers.addMonths(delegationStarted, 3));\\n}\\n```\\n
Delegations might stuck in non-active validator Pending
medium
If a validator does not get enough funds to run a node (MSR - Minimum staking requirement), all token holders that delegated tokens to the validator cannot switch to a different validator, and might result in funds getting stuck with the nonfunctioning validator for up to 12 months.\\nExample\\n```\\nrequire((validatorNodes.length + 1) \\* msr <= delegationsTotal, "Validator has to meet Minimum Staking Requirement");\\n```\\n
Resolution\\nSkale team acknowledged this issue and will address this in future versions.\\nAllow token holders to withdraw delegation earlier if the validator didn't get enough funds for running nodes.
null
```\\nrequire((validatorNodes.length + 1) \\* msr <= delegationsTotal, "Validator has to meet Minimum Staking Requirement");\\n```\\n
Disabled Validators still have delegated funds Pending
medium
The owner of `ValidatorService` contract can enable and disable validators. The issue is that when a validator is disabled, it still has its delegations, and delegated funds will be locked until the end of their delegation period (up to 12 months).\\n```\\nfunction enableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyOwner {\\n trustedValidators[validatorId] = true;\\n}\\n\\nfunction disableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyOwner {\\n trustedValidators[validatorId] = false;\\n}\\n```\\n
It might make sense to release all delegations and stop validator's nodes if it's not trusted anymore. However, the rationale behind disabling the validators might be different that what we think, in any case there should be a way to handle this scenario, where the validator is disabled but there are funds delegated to it.
null
```\\nfunction enableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyOwner {\\n trustedValidators[validatorId] = true;\\n}\\n\\nfunction disableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyOwner {\\n trustedValidators[validatorId] = false;\\n}\\n```\\n
_endingDelegations list is redundant
medium
`_endingDelegations` is a list of delegations that is created for optimisation purposes. But the only place it's used is in `getPurchasedAmount` function, so only a subset of all delegations is going to be updated.\\n```\\nfunction getPurchasedAmount(address holder) public returns (uint amount) {\\n // check if any delegation was ended\\n for (uint i = 0; i < \\_endingDelegations[holder].length; ++i) {\\n getState(\\_endingDelegations[holder][i]);\\n }\\n return \\_purchased[holder];\\n```\\n\\nBut `getPurchasedAmount` function is mostly used after iterating over all delegations of the holder.
Resolution\\nIssue is fixed as a part of the major code changes in skalenetwork/skale-manager#92\\nRemove `_endingDelegations` and switch to a mechanism that does not require looping through delegations list of potentially unlimited size.
null
```\\nfunction getPurchasedAmount(address holder) public returns (uint amount) {\\n // check if any delegation was ended\\n for (uint i = 0; i < \\_endingDelegations[holder].length; ++i) {\\n getState(\\_endingDelegations[holder][i]);\\n }\\n return \\_purchased[holder];\\n```\\n
Some functions are defined but not implemented
medium
There are many functions that are defined but not implemented. They have a revert with a message as not implemented.\\nThis results in complex code and reduces readability. Here is a some of these functions within the scope of this audit:\\n```\\nfunction getAllDelegationRequests() external returns(uint[] memory) {\\n revert("Not implemented");\\n}\\n\\nfunction getDelegationRequestsForValidator(uint validatorId) external returns (uint[] memory) {\\n revert("Not implemented");\\n}\\n```\\n
If these functions are needed for this release, they must be implemented. If they are for future plan, it's better to remove the extra code in the smart contracts.
null
```\\nfunction getAllDelegationRequests() external returns(uint[] memory) {\\n revert("Not implemented");\\n}\\n\\nfunction getDelegationRequestsForValidator(uint validatorId) external returns (uint[] memory) {\\n revert("Not implemented");\\n}\\n```\\n
tokenState.setState redundant checks
medium
`tokenState.setState` is used to change the state of the token from:\\nPROPOSED to ACCEPTED (in accept())\\nDELEGATED to ENDING_DELEGATED (in `requestUndelegation()`\\nThe if/else statement in `setState` is too complicated and can be simplified, both to optimize gas usage and to increase readability.\\n```\\nfunction setState(uint delegationId, State newState) internal {\\n TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));\\n DelegationController delegationController = DelegationController(contractManager.getContract("DelegationController"));\\n\\n require(newState != State.PROPOSED, "Can't set state to proposed");\\n\\n if (newState == State.ACCEPTED) {\\n State currentState = getState(delegationId);\\n require(currentState == State.PROPOSED, "Can't set state to accepted");\\n\\n \\_state[delegationId] = State.ACCEPTED;\\n \\_timelimit[delegationId] = timeHelpers.getNextMonthStart();\\n } else if (newState == State.DELEGATED) {\\n revert("Can't set state to delegated");\\n } else if (newState == State.ENDING\\_DELEGATED) {\\n require(getState(delegationId) == State.DELEGATED, "Can't set state to ending delegated");\\n DelegationController.Delegation memory delegation = delegationController.getDelegation(delegationId);\\n\\n \\_state[delegationId] = State.ENDING\\_DELEGATED;\\n \\_timelimit[delegationId] = timeHelpers.calculateDelegationEndTime(delegation.created, delegation.delegationPeriod, 3);\\n \\_endingDelegations[delegation.holder].push(delegationId);\\n } else {\\n revert("Unknown state");\\n }\\n}\\n```\\n
Some of the changes that do not change the functionality of the `setState` function:\\nRemove `reverts()` and add the valid states to the `require()` at the beginning of the function\\nRemove multiple calls to `getState()`\\nRemove final else/revert as this is an internal function and States passed should be valid More optimization can be done which requires further understanding of the system and the state machine.\\n```\\nfunction setState(uint delegationId, State newState) internal {\\n TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));\\n DelegationController delegationController = DelegationController(contractManager.getContract("DelegationController"));\\n\\n require(newState != State.PROPOSED || newState != State.DELEGATED, "Invalid state change");\\n State currentState = getState(delegationId);\\n\\n if (newState == State.ACCEPTED) {\\n require(currentState == State.PROPOSED, "Can't set state to accepted");\\n\\n \\_state[delegationId] = State.ACCEPTED;\\n \\_timelimit[delegationId] = timeHelpers.getNextMonthStart();\\n } else if (newState == State.ENDING\\_DELEGATED) {\\n require(currentState == State.DELEGATED, "Can't set state to ending delegated");\\n DelegationController.Delegation memory delegation = delegationController.getDelegation(delegationId);\\n\\n \\_state[delegationId] = State.ENDING\\_DELEGATED;\\n \\_timelimit[delegationId] = timeHelpers.calculateDelegationEndTime(delegation.created, delegation.delegationPeriod, 3);\\n \\_endingDelegations[delegation.holder].push(delegationId);\\n }\\n }\\n```\\n
null
```\\nfunction setState(uint delegationId, State newState) internal {\\n TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));\\n DelegationController delegationController = DelegationController(contractManager.getContract("DelegationController"));\\n\\n require(newState != State.PROPOSED, "Can't set state to proposed");\\n\\n if (newState == State.ACCEPTED) {\\n State currentState = getState(delegationId);\\n require(currentState == State.PROPOSED, "Can't set state to accepted");\\n\\n \\_state[delegationId] = State.ACCEPTED;\\n \\_timelimit[delegationId] = timeHelpers.getNextMonthStart();\\n } else if (newState == State.DELEGATED) {\\n revert("Can't set state to delegated");\\n } else if (newState == State.ENDING\\_DELEGATED) {\\n require(getState(delegationId) == State.DELEGATED, "Can't set state to ending delegated");\\n DelegationController.Delegation memory delegation = delegationController.getDelegation(delegationId);\\n\\n \\_state[delegationId] = State.ENDING\\_DELEGATED;\\n \\_timelimit[delegationId] = timeHelpers.calculateDelegationEndTime(delegation.created, delegation.delegationPeriod, 3);\\n \\_endingDelegations[delegation.holder].push(delegationId);\\n } else {\\n revert("Unknown state");\\n }\\n}\\n```\\n
Users can burn delegated tokens using re-entrancy attack
high
When a user burns tokens, the following code is called:\\n```\\n uint locked = \\_getAndUpdateLockedAmount(from);\\n if (locked > 0) {\\n require(\\_balances[from] >= locked.add(amount), "Token should be unlocked for burning");\\n }\\n//-------------------------------------------------------------------------\\n\\n \\_callTokensToSend(\\n operator, from, address(0), amount, data, operatorData\\n );\\n\\n // Update state variables\\n \\_totalSupply = \\_totalSupply.sub(amount);\\n \\_balances[from] = \\_balances[from].sub(amount);\\n```\\n\\nThere is a callback function right after the check that there are enough unlocked tokens to burn. In this callback, the user can delegate all the tokens right before burning them without breaking the code flow.
Resolution\\nMitigated in skalenetwork/skale-manager#128\\n`_callTokensToSend` should be called before checking for the unlocked amount of tokens, which is better defined as Checks-Effects-Interactions Pattern.
null
```\\n uint locked = \\_getAndUpdateLockedAmount(from);\\n if (locked > 0) {\\n require(\\_balances[from] >= locked.add(amount), "Token should be unlocked for burning");\\n }\\n//-------------------------------------------------------------------------\\n\\n \\_callTokensToSend(\\n operator, from, address(0), amount, data, operatorData\\n );\\n\\n // Update state variables\\n \\_totalSupply = \\_totalSupply.sub(amount);\\n \\_balances[from] = \\_balances[from].sub(amount);\\n```\\n
Rounding errors after slashing
high
When slashing happens `_delegatedToValidator` and `_effectiveDelegatedToValidator` values are reduced.\\n```\\nfunction confiscate(uint validatorId, uint amount) external {\\n uint currentMonth = getCurrentMonth();\\n Fraction memory coefficient = reduce(\\_delegatedToValidator[validatorId], amount, currentMonth);\\n reduce(\\_effectiveDelegatedToValidator[validatorId], coefficient, currentMonth);\\n putToSlashingLog(\\_slashesOfValidator[validatorId], coefficient, currentMonth);\\n \\_slashes.push(SlashingEvent({reducingCoefficient: coefficient, validatorId: validatorId, month: currentMonth}));\\n}\\n```\\n\\nWhen holders process slashings, they reduce `_delegatedByHolderToValidator`, `_delegatedByHolder`, `_effectiveDelegatedByHolderToValidator` values.\\n```\\nif (oldValue > 0) {\\n reduce(\\n \\_delegatedByHolderToValidator[holder][validatorId],\\n \\_delegatedByHolder[holder],\\n \\_slashes[index].reducingCoefficient,\\n month);\\n reduce(\\n \\_effectiveDelegatedByHolderToValidator[holder][validatorId],\\n \\_slashes[index].reducingCoefficient,\\n month);\\n slashingSignals[index.sub(begin)].holder = holder;\\n slashingSignals[index.sub(begin)].penalty = oldValue.sub(getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month));\\n}\\n```\\n\\nAlso when holders are undelegating, they are calculating how many tokens from `delegations[delegationId].amount` were slashed.\\n```\\nuint amountAfterSlashing = calculateDelegationAmountAfterSlashing(delegationId);\\n```\\n\\nAll these values should be calculated one from another, but they all will have different rounding errors after slashing. For example, the assumptions that the total sum of all delegations from holder `X` to validator `Y` should still be equal to `_delegatedByHolderToValidator[X][Y]` is not true anymore. The problem is that these assumptions are still used. For example, when undelegating some delegation with delegated `amount` equals amount(after slashing), the holder will reduce `_delegatedByHolderToValidator[X][Y]`, `_delegatedByHolder[X]` and `_delegatedToValidator[Y]` by `amount`. Since rounding errors of all these values are different that will lead to 2 possible scenarios:\\nIf rounding error reduces `amount` not that much as other values, we can have `uint` underflow. This is especially dangerous because all calculations are delayed and we will know about underflow and `SafeMath` revert in the next month or later.\\nDevelopers already made sure that rounding errors are aligned in a correct way, and that the reduced value should always be larger than the subtracted, so there should not be underflow. This solution is very unstable because it's hard to verify it and keep in mind even during a small code change. 2. If rounding errors make `amount` smaller then it should be, when other values should be zero (for example, when all the delegations are undelegated), these values will become some very small values. The problem here is that it would be impossible to compare values to zero.
Consider not calling `revert` on these subtractions and make result value be equals to zero if underflow happens.\\nConsider comparing to some small `epsilon` value instead of zero. Or similar to the previous point, on every subtraction check if the value is smaller then `epsilon`, and make it zero if it is.
null
```\\nfunction confiscate(uint validatorId, uint amount) external {\\n uint currentMonth = getCurrentMonth();\\n Fraction memory coefficient = reduce(\\_delegatedToValidator[validatorId], amount, currentMonth);\\n reduce(\\_effectiveDelegatedToValidator[validatorId], coefficient, currentMonth);\\n putToSlashingLog(\\_slashesOfValidator[validatorId], coefficient, currentMonth);\\n \\_slashes.push(SlashingEvent({reducingCoefficient: coefficient, validatorId: validatorId, month: currentMonth}));\\n}\\n```\\n
Slashes do not affect bounty distribution
high
When slashes are processed by a holder, only `_delegatedByHolderToValidator` and `_delegatedByHolder` values are reduced. But `_effectiveDelegatedByHolderToValidator` value remains the same. This value is used to distribute bounties amongst delegators. So slashing will not affect that distribution.\\n```\\nuint oldValue = getAndUpdateDelegatedByHolderToValidator(holder, validatorId);\\nif (oldValue > 0) {\\n uint month = \\_slashes[index].month;\\n reduce(\\n \\_delegatedByHolderToValidator[holder][validatorId],\\n \\_delegatedByHolder[holder],\\n \\_slashes[index].reducingCoefficient,\\n month);\\n slashingSignals[index.sub(begin)].holder = holder;\\n slashingSignals[index.sub(begin)].penalty = oldValue.sub(getAndUpdateDelegatedByHolderToValidator(holder, validatorId));\\n}\\n```\\n
Reduce `_effectiveDelegatedByHolderToValidator` and `_effectiveDelegatedToValidator` when slashes are processed.
null
```\\nuint oldValue = getAndUpdateDelegatedByHolderToValidator(holder, validatorId);\\nif (oldValue > 0) {\\n uint month = \\_slashes[index].month;\\n reduce(\\n \\_delegatedByHolderToValidator[holder][validatorId],\\n \\_delegatedByHolder[holder],\\n \\_slashes[index].reducingCoefficient,\\n month);\\n slashingSignals[index.sub(begin)].holder = holder;\\n slashingSignals[index.sub(begin)].penalty = oldValue.sub(getAndUpdateDelegatedByHolderToValidator(holder, validatorId));\\n}\\n```\\n