@keep-network/tbtc-v2 0.1.1-dev.76 → 0.1.1-dev.79

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/artifacts/Bank.json +32 -27
  2. package/artifacts/Bridge.json +34 -34
  3. package/artifacts/Deposit.json +10 -10
  4. package/artifacts/DepositSweep.json +10 -10
  5. package/artifacts/EcdsaDkgValidator.json +16 -17
  6. package/artifacts/EcdsaInactivity.json +6 -6
  7. package/artifacts/EcdsaSortitionPool.json +1004 -0
  8. package/artifacts/Fraud.json +10 -10
  9. package/artifacts/KeepRegistry.json +1 -1
  10. package/artifacts/KeepStake.json +2 -2
  11. package/artifacts/KeepToken.json +2 -2
  12. package/artifacts/KeepTokenStaking.json +1 -1
  13. package/artifacts/MovingFunds.json +10 -10
  14. package/artifacts/NuCypherStakingEscrow.json +1 -1
  15. package/artifacts/NuCypherToken.json +2 -2
  16. package/artifacts/RandomBeaconStub.json +6 -6
  17. package/artifacts/Redemption.json +10 -10
  18. package/artifacts/ReimbursementPool.json +24 -24
  19. package/artifacts/Relay.json +12 -12
  20. package/artifacts/T.json +2 -2
  21. package/artifacts/TBTC.json +19 -19
  22. package/artifacts/TBTCToken.json +19 -19
  23. package/artifacts/TokenStaking.json +1 -1
  24. package/artifacts/TokenholderGovernor.json +9 -9
  25. package/artifacts/TokenholderTimelock.json +8 -8
  26. package/artifacts/VendingMachine.json +24 -24
  27. package/artifacts/VendingMachineKeep.json +1 -1
  28. package/artifacts/VendingMachineNuCypher.json +1 -1
  29. package/artifacts/WalletRegistry.json +893 -1167
  30. package/artifacts/WalletRegistryGovernance.json +2754 -0
  31. package/artifacts/Wallets.json +10 -10
  32. package/artifacts/solcInputs/{49c80d59bf0ae61f27a8bb5db19af68a.json → 4f6d4f5cd1e3d835e20ed55926a445cd.json} +113 -74
  33. package/build/contracts/GovernanceUtils.sol/GovernanceUtils.dbg.json +1 -1
  34. package/build/contracts/bank/Bank.sol/Bank.dbg.json +1 -1
  35. package/build/contracts/bank/Bank.sol/Bank.json +8 -3
  36. package/build/contracts/bank/IReceiveBalanceApproval.sol/IReceiveBalanceApproval.dbg.json +4 -0
  37. package/build/contracts/bank/IReceiveBalanceApproval.sol/IReceiveBalanceApproval.json +34 -0
  38. package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.dbg.json +1 -1
  39. package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.json +2 -2
  40. package/build/contracts/bridge/Bridge.sol/Bridge.dbg.json +1 -1
  41. package/build/contracts/bridge/Bridge.sol/Bridge.json +2 -2
  42. package/build/contracts/bridge/BridgeState.sol/BridgeState.dbg.json +1 -1
  43. package/build/contracts/bridge/BridgeState.sol/BridgeState.json +2 -2
  44. package/build/contracts/bridge/Deposit.sol/Deposit.dbg.json +1 -1
  45. package/build/contracts/bridge/Deposit.sol/Deposit.json +2 -2
  46. package/build/contracts/bridge/DepositSweep.sol/DepositSweep.dbg.json +1 -1
  47. package/build/contracts/bridge/DepositSweep.sol/DepositSweep.json +2 -2
  48. package/build/contracts/bridge/EcdsaLib.sol/EcdsaLib.dbg.json +1 -1
  49. package/build/contracts/bridge/Fraud.sol/Fraud.dbg.json +1 -1
  50. package/build/contracts/bridge/Fraud.sol/Fraud.json +2 -2
  51. package/build/contracts/bridge/Heartbeat.sol/Heartbeat.dbg.json +1 -1
  52. package/build/contracts/bridge/IRelay.sol/IRelay.dbg.json +1 -1
  53. package/build/contracts/bridge/MovingFunds.sol/MovingFunds.dbg.json +1 -1
  54. package/build/contracts/bridge/MovingFunds.sol/MovingFunds.json +2 -2
  55. package/build/contracts/bridge/Redemption.sol/OutboundTx.dbg.json +1 -1
  56. package/build/contracts/bridge/Redemption.sol/OutboundTx.json +2 -2
  57. package/build/contracts/bridge/Redemption.sol/Redemption.dbg.json +1 -1
  58. package/build/contracts/bridge/Redemption.sol/Redemption.json +2 -2
  59. package/build/contracts/bridge/VendingMachine.sol/VendingMachine.dbg.json +1 -1
  60. package/build/contracts/bridge/Wallets.sol/Wallets.dbg.json +1 -1
  61. package/build/contracts/bridge/Wallets.sol/Wallets.json +2 -2
  62. package/build/contracts/token/TBTC.sol/TBTC.dbg.json +1 -1
  63. package/build/contracts/vault/DonationVault.sol/DonationVault.dbg.json +1 -1
  64. package/build/contracts/vault/DonationVault.sol/DonationVault.json +7 -2
  65. package/build/contracts/vault/IVault.sol/IVault.dbg.json +1 -1
  66. package/build/contracts/vault/IVault.sol/IVault.json +5 -0
  67. package/build/contracts/vault/TBTCVault.sol/TBTCVault.dbg.json +1 -1
  68. package/build/contracts/vault/TBTCVault.sol/TBTCVault.json +7 -2
  69. package/contracts/bank/Bank.sol +18 -9
  70. package/contracts/bank/IReceiveBalanceApproval.sol +45 -0
  71. package/contracts/hardhat-dependency-compiler/@keep-network/ecdsa/contracts/WalletRegistry.sol +3 -0
  72. package/contracts/vault/DonationVault.sol +5 -5
  73. package/contracts/vault/IVault.sol +3 -19
  74. package/contracts/vault/TBTCVault.sol +5 -5
  75. package/deploy/05_deploy_bridge.ts +5 -1
  76. package/deploy/09_transfer_proxy_admin_ownership.ts +15 -8
  77. package/export.json +2527 -3066
  78. package/package.json +1 -1
  79. package/artifacts/DefaultProxyAdmin.json +0 -259
  80. package/artifacts/SortitionPool.json +0 -1005
  81. package/artifacts/WalletRegistry_Implementation.json +0 -2824
  82. package/artifacts/WalletRegistry_Proxy.json +0 -259
  83. package/artifacts/solcInputs/1635d55d57a0a2552952c0d22586ed23.json +0 -56
  84. package/deploy/00_resolve_wallet_registry.ts +0 -83
@@ -2,19 +2,22 @@
2
2
  "language": "Solidity",
3
3
  "sources": {
4
4
  "contracts/bank/Bank.sol": {
5
- "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\n\nimport \"../vault/IVault.sol\";\n\n/// @title Bitcoin Bank\n/// @notice Bank is a central component tracking Bitcoin balances. Balances can\n/// be transferred between holders and holders can approve their\n/// balances to be spent by others. Balances in the Bank are updated for\n/// depositors who deposit their Bitcoin into the Bridge and only the\n/// Bridge can increase balances.\n/// @dev Bank is a governable contract and the Governance can upgrade the Bridge\n/// address.\ncontract Bank is Ownable {\n address public bridge;\n\n /// @notice The balance of a given account in the Bank. Zero by default.\n mapping(address => uint256) public balanceOf;\n\n /// @notice The remaining amount of balance a spender will be\n /// allowed to transfer on behalf of an owner using\n /// `transferBalanceFrom`. Zero by default.\n mapping(address => mapping(address => uint256)) public allowance;\n\n /// @notice Returns the current nonce for EIP2612 permission for the\n /// provided balance owner for a replay protection. Used to\n /// construct EIP2612 signature provided to `permit` function.\n mapping(address => uint256) public nonce;\n\n uint256 public immutable cachedChainId;\n bytes32 public immutable cachedDomainSeparator;\n\n /// @notice Returns EIP2612 Permit message hash. Used to construct EIP2612\n /// signature provided to `permit` function.\n bytes32 public constant PERMIT_TYPEHASH =\n keccak256(\n \"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\"\n );\n\n event BalanceTransferred(\n address indexed from,\n address indexed to,\n uint256 amount\n );\n\n event BalanceApproved(\n address indexed owner,\n address indexed spender,\n uint256 amount\n );\n\n event BalanceIncreased(address indexed owner, uint256 amount);\n\n event BalanceDecreased(address indexed owner, uint256 amount);\n\n event BridgeUpdated(address newBridge);\n\n modifier onlyBridge() {\n require(msg.sender == address(bridge), \"Caller is not the bridge\");\n _;\n }\n\n constructor() {\n cachedChainId = block.chainid;\n cachedDomainSeparator = buildDomainSeparator();\n }\n\n /// @notice Allows the Governance to upgrade the Bridge address.\n /// @dev The function does not implement any governance delay and does not\n /// check the status of the Bridge. The Governance implementation needs\n /// to ensure all requirements for the upgrade are satisfied before\n /// executing this function.\n function updateBridge(address _bridge) external onlyOwner {\n require(_bridge != address(0), \"Bridge address must not be 0x0\");\n bridge = _bridge;\n emit BridgeUpdated(_bridge);\n }\n\n /// @notice Moves the given `amount` of balance from the caller to\n /// `recipient`.\n /// @dev Requirements:\n /// - `recipient` cannot be the zero address,\n /// - the caller must have a balance of at least `amount`.\n function transferBalance(address recipient, uint256 amount) external {\n _transferBalance(msg.sender, recipient, amount);\n }\n\n /// @notice Sets `amount` as the allowance of `spender` over the caller's\n /// balance.\n /// @dev If the `amount` is set to `type(uint256).max` then\n /// `transferBalanceFrom` will not reduce an allowance.\n /// Beware that changing an allowance with this function brings the\n /// risk that someone may use both the old and the new allowance by\n /// unfortunate transaction ordering. Please use\n /// `increaseBalanceAllowance` and `decreaseBalanceAllowance` to\n /// eliminate the risk.\n function approveBalance(address spender, uint256 amount) external {\n _approveBalance(msg.sender, spender, amount);\n }\n\n /// @notice Sets `amount` as the allowance of a smart contract `vault` over\n /// the caller's balance and calls the vault via\n /// `receiveBalanceApproval`.\n /// @dev If the `amount` is set to `type(uint256).max` then the logic in\n /// `receiveBalanceApproval` or later call to `transferBalanceFrom` by\n /// the vault will not reduce an allowance. Beware that changing an\n /// allowance with this function brings the risk that vault may use\n /// both the old and the new allowance by unfortunate transaction\n /// ordering. Please use `increaseBalanceAllowance` and\n /// `decreaseBalanceAllowance` to eliminate the risk.\n function approveBalanceAndCall(address vault, uint256 amount) external {\n _approveBalance(msg.sender, vault, amount);\n IVault(vault).receiveBalanceApproval(msg.sender, amount);\n }\n\n /// @notice Atomically increases the balance allowance granted to `spender`\n /// by the caller by the given `addedValue`.\n function increaseBalanceAllowance(address spender, uint256 addedValue)\n external\n {\n _approveBalance(\n msg.sender,\n spender,\n allowance[msg.sender][spender] + addedValue\n );\n }\n\n /// @notice Atomically decreases the balance allowance granted to `spender`\n /// by the caller by the given `subtractedValue`.\n function decreaseBalanceAllowance(address spender, uint256 subtractedValue)\n external\n {\n uint256 currentAllowance = allowance[msg.sender][spender];\n require(\n currentAllowance >= subtractedValue,\n \"Can not decrease balance allowance below zero\"\n );\n unchecked {\n _approveBalance(\n msg.sender,\n spender,\n currentAllowance - subtractedValue\n );\n }\n }\n\n /// @notice Moves `amount` of balance from `spender` to `recipient` using the\n /// allowance mechanism. `amount` is then deducted from the caller's\n /// allowance unless the allowance was made for `type(uint256).max`.\n /// @dev Requirements:\n /// - `recipient` cannot be the zero address,\n /// - `spender` must have a balance of at least `amount`,\n /// - the caller must have allowance for `spender`'s balance of at\n /// least `amount`.\n function transferBalanceFrom(\n address spender,\n address recipient,\n uint256 amount\n ) external {\n uint256 currentAllowance = allowance[spender][msg.sender];\n if (currentAllowance != type(uint256).max) {\n require(\n currentAllowance >= amount,\n \"Transfer amount exceeds allowance\"\n );\n unchecked {\n _approveBalance(spender, msg.sender, currentAllowance - amount);\n }\n }\n _transferBalance(spender, recipient, amount);\n }\n\n /// @notice EIP2612 approval made with secp256k1 signature.\n /// Users can authorize a transfer of their balance with a signature\n /// conforming EIP712 standard, rather than an on-chain transaction\n /// from their address. Anyone can submit this signature on the\n /// user's behalf by calling the permit function, paying gas fees,\n /// and possibly performing other actions in the same transaction.\n /// @dev The deadline argument can be set to `type(uint256).max to create\n /// permits that effectively never expire. If the `amount` is set\n /// to `type(uint256).max` then `transferBalanceFrom` will not\n /// reduce an allowance. Beware that changing an allowance with this\n /// function brings the risk that someone may use both the old and the\n /// new allowance by unfortunate transaction ordering. Please use\n /// `increaseBalanceAllowance` and `decreaseBalanceAllowance` to\n /// eliminate the risk.\n function permit(\n address owner,\n address spender,\n uint256 amount,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external {\n /* solhint-disable-next-line not-rely-on-time */\n require(deadline >= block.timestamp, \"Permission expired\");\n\n // Validate `s` and `v` values for a malleability concern described in EIP2.\n // Only signatures with `s` value in the lower half of the secp256k1\n // curve's order and `v` value of 27 or 28 are considered valid.\n require(\n uint256(s) <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,\n \"Invalid signature 's' value\"\n );\n require(v == 27 || v == 28, \"Invalid signature 'v' value\");\n\n bytes32 digest = keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR(),\n keccak256(\n abi.encode(\n PERMIT_TYPEHASH,\n owner,\n spender,\n amount,\n nonce[owner]++,\n deadline\n )\n )\n )\n );\n address recoveredAddress = ecrecover(digest, v, r, s);\n require(\n recoveredAddress != address(0) && recoveredAddress == owner,\n \"Invalid signature\"\n );\n _approveBalance(owner, spender, amount);\n }\n\n /// @notice Increases balances of the provided `recipients` by the provided\n /// `amounts`. Can only be called by the Bridge.\n /// @dev Requirements:\n /// - length of `recipients` and `amounts` must be the same.\n function increaseBalances(\n address[] calldata recipients,\n uint256[] calldata amounts\n ) external onlyBridge {\n require(\n recipients.length == amounts.length,\n \"Arrays must have the same length\"\n );\n for (uint256 i = 0; i < recipients.length; i++) {\n _increaseBalance(recipients[i], amounts[i]);\n }\n }\n\n /// @notice Increases balance of the provided `recipient` by the provided\n /// `amount`. Can only be called by the Bridge.\n function increaseBalance(address recipient, uint256 amount)\n external\n onlyBridge\n {\n _increaseBalance(recipient, amount);\n }\n\n /// @notice Increases the given smart contract `vault`'s balance and\n /// notifies the `vault` contract. Called by the Bridge after\n /// the deposits routed by depositors to that `vault` have been\n /// swept by the Bridge. This way, the depositor does not have to\n /// issue a separate transaction to the `vault` contract.\n /// Can be called only by the Bridge.\n /// @dev Requirements:\n /// - `vault` must implement `IVault` interface,\n /// - length of `depositors` and `depositedAmounts` must be the same.\n /// @param vault Address of `IVault` recipient contract.\n /// @param depositors Addresses of depositors whose deposits have been swept.\n /// @param depositedAmounts Amounts deposited by individual depositors and\n /// swept. The `vault`'s balance in the Bank will be increased by the\n /// sum of all elements in this array.\n function increaseBalanceAndCall(\n address vault,\n address[] calldata depositors,\n uint256[] calldata depositedAmounts\n ) external onlyBridge {\n require(\n depositors.length == depositedAmounts.length,\n \"Arrays must have the same length\"\n );\n uint256 totalAmount = 0;\n for (uint256 i = 0; i < depositedAmounts.length; i++) {\n totalAmount += depositedAmounts[i];\n }\n _increaseBalance(vault, totalAmount);\n IVault(vault).receiveBalanceIncrease(depositors, depositedAmounts);\n }\n\n /// @notice Decreases caller's balance by the provided `amount`. There is no\n /// way to restore the balance so do not call this function unless\n /// you really know what you are doing!\n function decreaseBalance(uint256 amount) external {\n balanceOf[msg.sender] -= amount;\n emit BalanceDecreased(msg.sender, amount);\n }\n\n /// @notice Returns hash of EIP712 Domain struct with `TBTC Bank` as\n /// a signing domain and Bank contract as a verifying contract.\n /// Used to construct EIP2612 signature provided to `permit`\n /// function.\n /* solhint-disable-next-line func-name-mixedcase */\n function DOMAIN_SEPARATOR() public view returns (bytes32) {\n // As explained in EIP-2612, if the DOMAIN_SEPARATOR contains the\n // chainId and is defined at contract deployment instead of\n // reconstructed for every signature, there is a risk of possible replay\n // attacks between chains in the event of a future chain split.\n // To address this issue, we check the cached chain ID against the\n // current one and in case they are different, we build domain separator\n // from scratch.\n if (block.chainid == cachedChainId) {\n return cachedDomainSeparator;\n } else {\n return buildDomainSeparator();\n }\n }\n\n function _increaseBalance(address recipient, uint256 amount) internal {\n require(\n recipient != address(this),\n \"Can not increase balance for Bank\"\n );\n balanceOf[recipient] += amount;\n emit BalanceIncreased(recipient, amount);\n }\n\n function _transferBalance(\n address spender,\n address recipient,\n uint256 amount\n ) private {\n require(\n recipient != address(0),\n \"Can not transfer to the zero address\"\n );\n require(\n recipient != address(this),\n \"Can not transfer to the Bank address\"\n );\n\n uint256 spenderBalance = balanceOf[spender];\n require(spenderBalance >= amount, \"Transfer amount exceeds balance\");\n unchecked {\n balanceOf[spender] = spenderBalance - amount;\n }\n balanceOf[recipient] += amount;\n emit BalanceTransferred(spender, recipient, amount);\n }\n\n function _approveBalance(\n address owner,\n address spender,\n uint256 amount\n ) private {\n require(spender != address(0), \"Can not approve to the zero address\");\n allowance[owner][spender] = amount;\n emit BalanceApproved(owner, spender, amount);\n }\n\n function buildDomainSeparator() private view returns (bytes32) {\n return\n keccak256(\n abi.encode(\n keccak256(\n \"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"\n ),\n keccak256(bytes(\"TBTC Bank\")),\n keccak256(bytes(\"1\")),\n block.chainid,\n address(this)\n )\n );\n }\n}\n"
5
+ "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\n\nimport \"./IReceiveBalanceApproval.sol\";\nimport \"../vault/IVault.sol\";\n\n/// @title Bitcoin Bank\n/// @notice Bank is a central component tracking Bitcoin balances. Balances can\n/// be transferred between holders and holders can approve their\n/// balances to be spent by others. Balances in the Bank are updated for\n/// depositors who deposit their Bitcoin into the Bridge and only the\n/// Bridge can increase balances.\n/// @dev Bank is a governable contract and the Governance can upgrade the Bridge\n/// address.\ncontract Bank is Ownable {\n address public bridge;\n\n /// @notice The balance of a given account in the Bank. Zero by default.\n mapping(address => uint256) public balanceOf;\n\n /// @notice The remaining amount of balance a spender will be\n /// allowed to transfer on behalf of an owner using\n /// `transferBalanceFrom`. Zero by default.\n mapping(address => mapping(address => uint256)) public allowance;\n\n /// @notice Returns the current nonce for EIP2612 permission for the\n /// provided balance owner for a replay protection. Used to\n /// construct EIP2612 signature provided to `permit` function.\n mapping(address => uint256) public nonce;\n\n uint256 public immutable cachedChainId;\n bytes32 public immutable cachedDomainSeparator;\n\n /// @notice Returns EIP2612 Permit message hash. Used to construct EIP2612\n /// signature provided to `permit` function.\n bytes32 public constant PERMIT_TYPEHASH =\n keccak256(\n \"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\"\n );\n\n event BalanceTransferred(\n address indexed from,\n address indexed to,\n uint256 amount\n );\n\n event BalanceApproved(\n address indexed owner,\n address indexed spender,\n uint256 amount\n );\n\n event BalanceIncreased(address indexed owner, uint256 amount);\n\n event BalanceDecreased(address indexed owner, uint256 amount);\n\n event BridgeUpdated(address newBridge);\n\n modifier onlyBridge() {\n require(msg.sender == address(bridge), \"Caller is not the bridge\");\n _;\n }\n\n constructor() {\n cachedChainId = block.chainid;\n cachedDomainSeparator = buildDomainSeparator();\n }\n\n /// @notice Allows the Governance to upgrade the Bridge address.\n /// @dev The function does not implement any governance delay and does not\n /// check the status of the Bridge. The Governance implementation needs\n /// to ensure all requirements for the upgrade are satisfied before\n /// executing this function.\n function updateBridge(address _bridge) external onlyOwner {\n require(_bridge != address(0), \"Bridge address must not be 0x0\");\n bridge = _bridge;\n emit BridgeUpdated(_bridge);\n }\n\n /// @notice Moves the given `amount` of balance from the caller to\n /// `recipient`.\n /// @dev Requirements:\n /// - `recipient` cannot be the zero address,\n /// - the caller must have a balance of at least `amount`.\n function transferBalance(address recipient, uint256 amount) external {\n _transferBalance(msg.sender, recipient, amount);\n }\n\n /// @notice Sets `amount` as the allowance of `spender` over the caller's\n /// balance.\n /// @dev If the `amount` is set to `type(uint256).max` then\n /// `transferBalanceFrom` will not reduce an allowance.\n /// Beware that changing an allowance with this function brings the\n /// risk that someone may use both the old and the new allowance by\n /// unfortunate transaction ordering. Please use\n /// `increaseBalanceAllowance` and `decreaseBalanceAllowance` to\n /// eliminate the risk.\n function approveBalance(address spender, uint256 amount) external {\n _approveBalance(msg.sender, spender, amount);\n }\n\n /// @notice Sets the `amount` as an allowance of a smart contract `spender`\n /// over the caller's balance and calls the `spender` via\n /// `receiveBalanceApproval`.\n /// @dev If the `amount` is set to `type(uint256).max`, the potential\n /// `transferBalanceFrom` executed in `receiveBalanceApproval` of\n /// `spender` will not reduce an allowance. Beware that changing an\n /// allowance with this function brings the risk that `spender` may use\n /// both the old and the new allowance by unfortunate transaction\n /// ordering. Please use `increaseBalanceAllowance` and\n /// `decreaseBalanceAllowance` to eliminate the risk.\n function approveBalanceAndCall(\n address spender,\n uint256 amount,\n bytes memory extraData\n ) external {\n _approveBalance(msg.sender, spender, amount);\n IReceiveBalanceApproval(spender).receiveBalanceApproval(\n msg.sender,\n amount,\n extraData\n );\n }\n\n /// @notice Atomically increases the balance allowance granted to `spender`\n /// by the caller by the given `addedValue`.\n function increaseBalanceAllowance(address spender, uint256 addedValue)\n external\n {\n _approveBalance(\n msg.sender,\n spender,\n allowance[msg.sender][spender] + addedValue\n );\n }\n\n /// @notice Atomically decreases the balance allowance granted to `spender`\n /// by the caller by the given `subtractedValue`.\n function decreaseBalanceAllowance(address spender, uint256 subtractedValue)\n external\n {\n uint256 currentAllowance = allowance[msg.sender][spender];\n require(\n currentAllowance >= subtractedValue,\n \"Can not decrease balance allowance below zero\"\n );\n unchecked {\n _approveBalance(\n msg.sender,\n spender,\n currentAllowance - subtractedValue\n );\n }\n }\n\n /// @notice Moves `amount` of balance from `spender` to `recipient` using the\n /// allowance mechanism. `amount` is then deducted from the caller's\n /// allowance unless the allowance was made for `type(uint256).max`.\n /// @dev Requirements:\n /// - `recipient` cannot be the zero address,\n /// - `spender` must have a balance of at least `amount`,\n /// - the caller must have allowance for `spender`'s balance of at\n /// least `amount`.\n function transferBalanceFrom(\n address spender,\n address recipient,\n uint256 amount\n ) external {\n uint256 currentAllowance = allowance[spender][msg.sender];\n if (currentAllowance != type(uint256).max) {\n require(\n currentAllowance >= amount,\n \"Transfer amount exceeds allowance\"\n );\n unchecked {\n _approveBalance(spender, msg.sender, currentAllowance - amount);\n }\n }\n _transferBalance(spender, recipient, amount);\n }\n\n /// @notice EIP2612 approval made with secp256k1 signature.\n /// Users can authorize a transfer of their balance with a signature\n /// conforming EIP712 standard, rather than an on-chain transaction\n /// from their address. Anyone can submit this signature on the\n /// user's behalf by calling the permit function, paying gas fees,\n /// and possibly performing other actions in the same transaction.\n /// @dev The deadline argument can be set to `type(uint256).max to create\n /// permits that effectively never expire. If the `amount` is set\n /// to `type(uint256).max` then `transferBalanceFrom` will not\n /// reduce an allowance. Beware that changing an allowance with this\n /// function brings the risk that someone may use both the old and the\n /// new allowance by unfortunate transaction ordering. Please use\n /// `increaseBalanceAllowance` and `decreaseBalanceAllowance` to\n /// eliminate the risk.\n function permit(\n address owner,\n address spender,\n uint256 amount,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external {\n /* solhint-disable-next-line not-rely-on-time */\n require(deadline >= block.timestamp, \"Permission expired\");\n\n // Validate `s` and `v` values for a malleability concern described in EIP2.\n // Only signatures with `s` value in the lower half of the secp256k1\n // curve's order and `v` value of 27 or 28 are considered valid.\n require(\n uint256(s) <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,\n \"Invalid signature 's' value\"\n );\n require(v == 27 || v == 28, \"Invalid signature 'v' value\");\n\n bytes32 digest = keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR(),\n keccak256(\n abi.encode(\n PERMIT_TYPEHASH,\n owner,\n spender,\n amount,\n nonce[owner]++,\n deadline\n )\n )\n )\n );\n address recoveredAddress = ecrecover(digest, v, r, s);\n require(\n recoveredAddress != address(0) && recoveredAddress == owner,\n \"Invalid signature\"\n );\n _approveBalance(owner, spender, amount);\n }\n\n /// @notice Increases balances of the provided `recipients` by the provided\n /// `amounts`. Can only be called by the Bridge.\n /// @dev Requirements:\n /// - length of `recipients` and `amounts` must be the same.\n function increaseBalances(\n address[] calldata recipients,\n uint256[] calldata amounts\n ) external onlyBridge {\n require(\n recipients.length == amounts.length,\n \"Arrays must have the same length\"\n );\n for (uint256 i = 0; i < recipients.length; i++) {\n _increaseBalance(recipients[i], amounts[i]);\n }\n }\n\n /// @notice Increases balance of the provided `recipient` by the provided\n /// `amount`. Can only be called by the Bridge.\n function increaseBalance(address recipient, uint256 amount)\n external\n onlyBridge\n {\n _increaseBalance(recipient, amount);\n }\n\n /// @notice Increases the given smart contract `vault`'s balance and\n /// notifies the `vault` contract. Called by the Bridge after\n /// the deposits routed by depositors to that `vault` have been\n /// swept by the Bridge. This way, the depositor does not have to\n /// issue a separate transaction to the `vault` contract.\n /// Can be called only by the Bridge.\n /// @dev Requirements:\n /// - `vault` must implement `IVault` interface,\n /// - length of `depositors` and `depositedAmounts` must be the same.\n /// @param vault Address of `IVault` recipient contract.\n /// @param depositors Addresses of depositors whose deposits have been swept.\n /// @param depositedAmounts Amounts deposited by individual depositors and\n /// swept. The `vault`'s balance in the Bank will be increased by the\n /// sum of all elements in this array.\n function increaseBalanceAndCall(\n address vault,\n address[] calldata depositors,\n uint256[] calldata depositedAmounts\n ) external onlyBridge {\n require(\n depositors.length == depositedAmounts.length,\n \"Arrays must have the same length\"\n );\n uint256 totalAmount = 0;\n for (uint256 i = 0; i < depositedAmounts.length; i++) {\n totalAmount += depositedAmounts[i];\n }\n _increaseBalance(vault, totalAmount);\n IVault(vault).receiveBalanceIncrease(depositors, depositedAmounts);\n }\n\n /// @notice Decreases caller's balance by the provided `amount`. There is no\n /// way to restore the balance so do not call this function unless\n /// you really know what you are doing!\n function decreaseBalance(uint256 amount) external {\n balanceOf[msg.sender] -= amount;\n emit BalanceDecreased(msg.sender, amount);\n }\n\n /// @notice Returns hash of EIP712 Domain struct with `TBTC Bank` as\n /// a signing domain and Bank contract as a verifying contract.\n /// Used to construct EIP2612 signature provided to `permit`\n /// function.\n /* solhint-disable-next-line func-name-mixedcase */\n function DOMAIN_SEPARATOR() public view returns (bytes32) {\n // As explained in EIP-2612, if the DOMAIN_SEPARATOR contains the\n // chainId and is defined at contract deployment instead of\n // reconstructed for every signature, there is a risk of possible replay\n // attacks between chains in the event of a future chain split.\n // To address this issue, we check the cached chain ID against the\n // current one and in case they are different, we build domain separator\n // from scratch.\n if (block.chainid == cachedChainId) {\n return cachedDomainSeparator;\n } else {\n return buildDomainSeparator();\n }\n }\n\n function _increaseBalance(address recipient, uint256 amount) internal {\n require(\n recipient != address(this),\n \"Can not increase balance for Bank\"\n );\n balanceOf[recipient] += amount;\n emit BalanceIncreased(recipient, amount);\n }\n\n function _transferBalance(\n address spender,\n address recipient,\n uint256 amount\n ) private {\n require(\n recipient != address(0),\n \"Can not transfer to the zero address\"\n );\n require(\n recipient != address(this),\n \"Can not transfer to the Bank address\"\n );\n\n uint256 spenderBalance = balanceOf[spender];\n require(spenderBalance >= amount, \"Transfer amount exceeds balance\");\n unchecked {\n balanceOf[spender] = spenderBalance - amount;\n }\n balanceOf[recipient] += amount;\n emit BalanceTransferred(spender, recipient, amount);\n }\n\n function _approveBalance(\n address owner,\n address spender,\n uint256 amount\n ) private {\n require(spender != address(0), \"Can not approve to the zero address\");\n allowance[owner][spender] = amount;\n emit BalanceApproved(owner, spender, amount);\n }\n\n function buildDomainSeparator() private view returns (bytes32) {\n return\n keccak256(\n abi.encode(\n keccak256(\n \"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"\n ),\n keccak256(bytes(\"TBTC Bank\")),\n keccak256(bytes(\"1\")),\n block.chainid,\n address(this)\n )\n );\n }\n}\n"
6
6
  },
7
7
  "@openzeppelin/contracts/access/Ownable.sol": {
8
8
  "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n address private _owner;\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the deployer as the initial owner.\n */\n constructor() {\n _transferOwnership(_msgSender());\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n _;\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions anymore. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby removing any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n _transferOwnership(address(0));\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n _transferOwnership(newOwner);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Internal function without access restriction.\n */\n function _transferOwnership(address newOwner) internal virtual {\n address oldOwner = _owner;\n _owner = newOwner;\n emit OwnershipTransferred(oldOwner, newOwner);\n }\n}\n"
9
9
  },
10
+ "contracts/bank/IReceiveBalanceApproval.sol": {
11
+ "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\n/// @title IReceiveBalanceApproval\n/// @notice `IReceiveBalanceApproval` is an interface for a smart contract\n/// consuming Bank balances approved to them in the same transaction by\n/// other contracts or externally owned accounts (EOA).\ninterface IReceiveBalanceApproval {\n /// @notice Called by the Bank in `approveBalanceAndCall` function after\n /// the balance `owner` approved `amount` of their balance in the\n /// Bank for the contract. This way, the depositor can approve\n /// balance and call the contract to use the approved balance in\n /// a single transaction.\n /// @param owner Address of the Bank balance owner who approved their\n /// balance to be used by the contract.\n /// @param amount The amount of the Bank balance approved by the owner\n /// to be used by the contract.\n /// @param extraData The `extraData` passed to `Bank.approveBalanceAndCall`.\n // @dev The implementation must ensure this function can only be called\n /// by the Bank. The Bank does _not_ guarantee that the `amount`\n /// approved by the `owner` currently exists on their balance. That is,\n /// the `owner` could approve more balance than they currently have.\n /// This works the same as `Bank.approve` function. The contract must\n /// ensure the actual balance is checked before performing any action\n /// based on it.\n function receiveBalanceApproval(\n address owner,\n uint256 amount,\n bytes memory extraData\n ) external;\n}\n"
12
+ },
10
13
  "contracts/vault/IVault.sol": {
11
- "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\n/// @title Bank Vault interface\n/// @notice `IVault` is an interface for a smart contract consuming Bank\n/// balances of other contracts or externally owned accounts (EOA).\ninterface IVault {\n /// @notice Called by the Bank in `approveBalanceAndCall` function after\n /// the balance `owner` approved `amount` of their balance in the\n /// Bank for the vault. This way, the depositor can approve balance\n /// and call the vault to use the approved balance in a single\n /// transaction.\n /// @param owner Address of the Bank balance owner who approved their\n /// balance to be used by the vault.\n /// @param amount The amount of the Bank balance approved by the owner\n /// to be used by the vault.\n // @dev The implementation must ensure this function can only be called\n /// by the Bank. The Bank does _not_ guarantee that the `amount`\n /// approved by the `owner` currently exists on their balance. That is,\n /// the `owner` could approve more balance than they currently have.\n /// This works the same as `Bank.approve` function. The vault must\n /// ensure the actual balance is checked before performing any action\n /// based on it.\n function receiveBalanceApproval(address owner, uint256 amount) external;\n\n /// @notice Called by the Bank in `increaseBalanceAndCall` function after\n /// increasing the balance in the Bank for the vault. It happens in\n /// the same transaction in which deposits were swept by the Bridge.\n /// This allows the depositor to route their deposit revealed to the\n /// Bridge to the particular smart contract (vault) in the same\n /// transaction in which the deposit is revealed. This way, the\n /// depositor does not have to execute additional transaction after\n /// the deposit gets swept by the Bridge to approve and transfer\n /// their balance to the vault.\n /// @param depositors Addresses of depositors whose deposits have been swept.\n /// @param depositedAmounts Amounts deposited by individual depositors and\n /// swept.\n /// @dev The implementation must ensure this function can only be called\n /// by the Bank. The Bank guarantees that the vault's balance was\n /// increased by the sum of all deposited amounts before this function\n /// is called, in the same transaction.\n function receiveBalanceIncrease(\n address[] calldata depositors,\n uint256[] calldata depositedAmounts\n ) external;\n}\n"
14
+ "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport \"../bank/IReceiveBalanceApproval.sol\";\n\n/// @title Bank Vault interface\n/// @notice `IVault` is an interface for a smart contract consuming Bank\n/// balances of other contracts or externally owned accounts (EOA).\ninterface IVault is IReceiveBalanceApproval {\n /// @notice Called by the Bank in `increaseBalanceAndCall` function after\n /// increasing the balance in the Bank for the vault. It happens in\n /// the same transaction in which deposits were swept by the Bridge.\n /// This allows the depositor to route their deposit revealed to the\n /// Bridge to the particular smart contract (vault) in the same\n /// transaction in which the deposit is revealed. This way, the\n /// depositor does not have to execute additional transaction after\n /// the deposit gets swept by the Bridge to approve and transfer\n /// their balance to the vault.\n /// @param depositors Addresses of depositors whose deposits have been swept.\n /// @param depositedAmounts Amounts deposited by individual depositors and\n /// swept.\n /// @dev The implementation must ensure this function can only be called\n /// by the Bank. The Bank guarantees that the vault's balance was\n /// increased by the sum of all deposited amounts before this function\n /// is called, in the same transaction.\n function receiveBalanceIncrease(\n address[] calldata depositors,\n uint256[] calldata depositedAmounts\n ) external;\n}\n"
12
15
  },
13
16
  "@openzeppelin/contracts/utils/Context.sol": {
14
17
  "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
15
18
  },
16
19
  "contracts/vault/TBTCVault.sol": {
17
- "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport \"@keep-network/random-beacon/contracts/Governable.sol\";\n\nimport \"./IVault.sol\";\nimport \"../bank/Bank.sol\";\nimport \"../token/TBTC.sol\";\n\n/// @title TBTC application vault\n/// @notice TBTC is a fully Bitcoin-backed ERC-20 token pegged to the price of\n/// Bitcoin. It facilitates Bitcoin holders to act on the Ethereum\n/// blockchain and access the decentralized finance (DeFi) ecosystem.\n/// TBTC Vault mints and redeems TBTC based on Bitcoin balances in the\n/// Bank.\n/// @dev TBTC Vault is the owner of TBTC token contract and is the only contract\n/// minting the token.\ncontract TBTCVault is IVault, Governable {\n Bank public bank;\n TBTC public tbtcToken;\n\n event Minted(address indexed to, uint256 amount);\n\n event Redeemed(address indexed from, uint256 amount);\n\n modifier onlyBank() {\n require(msg.sender == address(bank), \"Caller is not the Bank\");\n _;\n }\n\n constructor(Bank _bank, TBTC _tbtcToken) {\n require(\n address(_bank) != address(0),\n \"Bank can not be the zero address\"\n );\n\n require(\n address(_tbtcToken) != address(0),\n \"TBTC token can not be the zero address\"\n );\n\n bank = _bank;\n tbtcToken = _tbtcToken;\n\n _transferGovernance(msg.sender);\n }\n\n /// @notice Allows the governance of the TBTCVault to recover any ERC20\n /// token sent mistakenly to the TBTC token contract address.\n /// @param token Address of the recovered ERC20 token contract.\n /// @param recipient Address the recovered token should be sent to.\n /// @param amount Recovered amount.\n function recoverERC20(\n IERC20 token,\n address recipient,\n uint256 amount\n ) external onlyGovernance {\n tbtcToken.recoverERC20(token, recipient, amount);\n }\n\n /// @notice Allows the governance of the TBTCVault to recover any ERC721\n /// token sent mistakenly to the TBTC token contract address.\n /// @param token Address of the recovered ERC721 token contract.\n /// @param recipient Address the recovered token should be sent to.\n /// @param tokenId Identifier of the recovered token.\n /// @param data Additional data.\n function recoverERC721(\n IERC721 token,\n address recipient,\n uint256 tokenId,\n bytes calldata data\n ) external onlyGovernance {\n tbtcToken.recoverERC721(token, recipient, tokenId, data);\n }\n\n /// @notice Transfers the given `amount` of the Bank balance from caller\n /// to TBTC Vault, and mints `amount` of TBTC to the caller.\n /// @dev TBTC Vault must have an allowance for caller's balance in the Bank\n /// for at least `amount`.\n /// @param amount Amount of TBTC to mint.\n function mint(uint256 amount) external {\n address minter = msg.sender;\n require(\n bank.balanceOf(minter) >= amount,\n \"Amount exceeds balance in the bank\"\n );\n _mint(minter, amount);\n bank.transferBalanceFrom(minter, address(this), amount);\n }\n\n /// @notice Transfers the given `amount` of the Bank balance from the caller\n /// to TBTC Vault and mints `amount` of TBTC to the caller.\n /// @dev Can only be called by the Bank via `approveBalanceAndCall`.\n /// @param owner The owner who approved their Bank balance.\n /// @param amount Amount of TBTC to mint.\n function receiveBalanceApproval(address owner, uint256 amount)\n external\n override\n onlyBank\n {\n require(\n bank.balanceOf(owner) >= amount,\n \"Amount exceeds balance in the bank\"\n );\n _mint(owner, amount);\n bank.transferBalanceFrom(owner, address(this), amount);\n }\n\n /// @notice Mints the same amount of TBTC as the deposited amount for each\n /// depositor in the array. Can only be called by the Bank after the\n /// Bridge swept deposits and Bank increased balance for the\n /// vault.\n /// @dev Fails if `depositors` array is empty. Expects the length of\n /// `depositors` and `depositedAmounts` is the same.\n function receiveBalanceIncrease(\n address[] calldata depositors,\n uint256[] calldata depositedAmounts\n ) external override onlyBank {\n require(depositors.length != 0, \"No depositors specified\");\n for (uint256 i = 0; i < depositors.length; i++) {\n _mint(depositors[i], depositedAmounts[i]);\n }\n }\n\n /// @notice Burns `amount` of TBTC from the caller's account and transfers\n /// `amount` back to the caller's balance in the Bank.\n /// @dev Caller must have at least `amount` of TBTC approved to\n /// TBTC Vault.\n /// @param amount Amount of TBTC to redeem.\n function redeem(uint256 amount) external {\n _redeem(msg.sender, amount);\n }\n\n /// @notice Burns `amount` of TBTC from the caller's account and transfers\n /// `amount` back to the caller's balance in the Bank.\n /// @dev This function is doing the same as `redeem` but it allows to\n /// execute redemption without an additional approval transaction.\n /// The function can be called only via `approveAndCall` of TBTC token.\n /// @param from TBTC token holder executing redemption.\n /// @param amount Amount of TBTC to redeem.\n /// @param token TBTC token address.\n function receiveApproval(\n address from,\n uint256 amount,\n address token,\n bytes calldata\n ) external {\n require(token == address(tbtcToken), \"Token is not TBTC\");\n require(msg.sender == token, \"Only TBTC caller allowed\");\n _redeem(from, amount);\n }\n\n // slither-disable-next-line calls-loop\n function _mint(address minter, uint256 amount) internal {\n emit Minted(minter, amount);\n tbtcToken.mint(minter, amount);\n }\n\n function _redeem(address redeemer, uint256 amount) internal {\n emit Redeemed(redeemer, amount);\n tbtcToken.burnFrom(redeemer, amount);\n bank.transferBalance(redeemer, amount);\n }\n}\n"
20
+ "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport \"@keep-network/random-beacon/contracts/Governable.sol\";\n\nimport \"./IVault.sol\";\nimport \"../bank/Bank.sol\";\nimport \"../token/TBTC.sol\";\n\n/// @title TBTC application vault\n/// @notice TBTC is a fully Bitcoin-backed ERC-20 token pegged to the price of\n/// Bitcoin. It facilitates Bitcoin holders to act on the Ethereum\n/// blockchain and access the decentralized finance (DeFi) ecosystem.\n/// TBTC Vault mints and redeems TBTC based on Bitcoin balances in the\n/// Bank.\n/// @dev TBTC Vault is the owner of TBTC token contract and is the only contract\n/// minting the token.\ncontract TBTCVault is IVault, Governable {\n Bank public bank;\n TBTC public tbtcToken;\n\n event Minted(address indexed to, uint256 amount);\n\n event Redeemed(address indexed from, uint256 amount);\n\n modifier onlyBank() {\n require(msg.sender == address(bank), \"Caller is not the Bank\");\n _;\n }\n\n constructor(Bank _bank, TBTC _tbtcToken) {\n require(\n address(_bank) != address(0),\n \"Bank can not be the zero address\"\n );\n\n require(\n address(_tbtcToken) != address(0),\n \"TBTC token can not be the zero address\"\n );\n\n bank = _bank;\n tbtcToken = _tbtcToken;\n\n _transferGovernance(msg.sender);\n }\n\n /// @notice Allows the governance of the TBTCVault to recover any ERC20\n /// token sent mistakenly to the TBTC token contract address.\n /// @param token Address of the recovered ERC20 token contract.\n /// @param recipient Address the recovered token should be sent to.\n /// @param amount Recovered amount.\n function recoverERC20(\n IERC20 token,\n address recipient,\n uint256 amount\n ) external onlyGovernance {\n tbtcToken.recoverERC20(token, recipient, amount);\n }\n\n /// @notice Allows the governance of the TBTCVault to recover any ERC721\n /// token sent mistakenly to the TBTC token contract address.\n /// @param token Address of the recovered ERC721 token contract.\n /// @param recipient Address the recovered token should be sent to.\n /// @param tokenId Identifier of the recovered token.\n /// @param data Additional data.\n function recoverERC721(\n IERC721 token,\n address recipient,\n uint256 tokenId,\n bytes calldata data\n ) external onlyGovernance {\n tbtcToken.recoverERC721(token, recipient, tokenId, data);\n }\n\n /// @notice Transfers the given `amount` of the Bank balance from caller\n /// to TBTC Vault, and mints `amount` of TBTC to the caller.\n /// @dev TBTC Vault must have an allowance for caller's balance in the Bank\n /// for at least `amount`.\n /// @param amount Amount of TBTC to mint.\n function mint(uint256 amount) external {\n address minter = msg.sender;\n require(\n bank.balanceOf(minter) >= amount,\n \"Amount exceeds balance in the bank\"\n );\n _mint(minter, amount);\n bank.transferBalanceFrom(minter, address(this), amount);\n }\n\n /// @notice Transfers the given `amount` of the Bank balance from the caller\n /// to TBTC Vault and mints `amount` of TBTC to the caller.\n /// @dev Can only be called by the Bank via `approveBalanceAndCall`.\n /// @param owner The owner who approved their Bank balance.\n /// @param amount Amount of TBTC to mint.\n function receiveBalanceApproval(\n address owner,\n uint256 amount,\n bytes memory\n ) external override onlyBank {\n require(\n bank.balanceOf(owner) >= amount,\n \"Amount exceeds balance in the bank\"\n );\n _mint(owner, amount);\n bank.transferBalanceFrom(owner, address(this), amount);\n }\n\n /// @notice Mints the same amount of TBTC as the deposited amount for each\n /// depositor in the array. Can only be called by the Bank after the\n /// Bridge swept deposits and Bank increased balance for the\n /// vault.\n /// @dev Fails if `depositors` array is empty. Expects the length of\n /// `depositors` and `depositedAmounts` is the same.\n function receiveBalanceIncrease(\n address[] calldata depositors,\n uint256[] calldata depositedAmounts\n ) external override onlyBank {\n require(depositors.length != 0, \"No depositors specified\");\n for (uint256 i = 0; i < depositors.length; i++) {\n _mint(depositors[i], depositedAmounts[i]);\n }\n }\n\n /// @notice Burns `amount` of TBTC from the caller's account and transfers\n /// `amount` back to the caller's balance in the Bank.\n /// @dev Caller must have at least `amount` of TBTC approved to\n /// TBTC Vault.\n /// @param amount Amount of TBTC to redeem.\n function redeem(uint256 amount) external {\n _redeem(msg.sender, amount);\n }\n\n /// @notice Burns `amount` of TBTC from the caller's account and transfers\n /// `amount` back to the caller's balance in the Bank.\n /// @dev This function is doing the same as `redeem` but it allows to\n /// execute redemption without an additional approval transaction.\n /// The function can be called only via `approveAndCall` of TBTC token.\n /// @param from TBTC token holder executing redemption.\n /// @param amount Amount of TBTC to redeem.\n /// @param token TBTC token address.\n function receiveApproval(\n address from,\n uint256 amount,\n address token,\n bytes calldata\n ) external {\n require(token == address(tbtcToken), \"Token is not TBTC\");\n require(msg.sender == token, \"Only TBTC caller allowed\");\n _redeem(from, amount);\n }\n\n // slither-disable-next-line calls-loop\n function _mint(address minter, uint256 amount) internal {\n emit Minted(minter, amount);\n tbtcToken.mint(minter, amount);\n }\n\n function _redeem(address redeemer, uint256 amount) internal {\n emit Redeemed(redeemer, amount);\n tbtcToken.burnFrom(redeemer, amount);\n bank.transferBalance(redeemer, amount);\n }\n}\n"
18
21
  },
19
22
  "@keep-network/random-beacon/contracts/Governable.sol": {
20
23
  "content": "// SPDX-License-Identifier: MIT\n//\n// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄\n// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓\n// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓\n// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀\n// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌\n// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓\n//\n// Trust math, not hardware.\n\npragma solidity ^0.8.9;\n\n/// @notice Governable contract.\n/// @dev A constructor is not defined, which makes the contract compatible with\n/// upgradable proxies. This requires calling explicitly `_transferGovernance`\n/// function in a child contract.\nabstract contract Governable {\n // Governance of the contract\n // The variable should be initialized by the implementing contract.\n // slither-disable-next-line uninitialized-state\n address public governance;\n\n // Reserved storage space in case we need to add more variables,\n // since there are upgradeable contracts that inherit from this one.\n // See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n // slither-disable-next-line unused-state\n uint256[49] private __gap;\n\n event GovernanceTransferred(address oldGovernance, address newGovernance);\n\n modifier onlyGovernance() virtual {\n require(governance == msg.sender, \"Caller is not the governance\");\n _;\n }\n\n /// @notice Transfers governance of the contract to `newGovernance`.\n function transferGovernance(address newGovernance)\n external\n virtual\n onlyGovernance\n {\n require(\n newGovernance != address(0),\n \"New governance is the zero address\"\n );\n _transferGovernance(newGovernance);\n }\n\n function _transferGovernance(address newGovernance) internal virtual {\n address oldGovernance = governance;\n governance = newGovernance;\n emit GovernanceTransferred(oldGovernance, newGovernance);\n }\n}\n"
@@ -115,6 +118,96 @@
115
118
  "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol": {
116
119
  "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary StringsUpgradeable {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n}\n"
117
120
  },
121
+ "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol": {
122
+ "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../../utils/AddressUpgradeable.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n /**\n * @dev Indicates that the contract has been initialized.\n * @custom:oz-retyped-from bool\n */\n uint8 private _initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private _initializing;\n\n /**\n * @dev Triggered when the contract has been initialized or reinitialized.\n */\n event Initialized(uint8 version);\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`.\n */\n modifier initializer() {\n bool isTopLevelCall = _setInitializedVersion(1);\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original\n * initialization step. This is essential to configure modules that are added through upgrades and that require\n * initialization.\n *\n * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n * a contract, executing them in the right order is up to the developer or operator.\n */\n modifier reinitializer(uint8 version) {\n bool isTopLevelCall = _setInitializedVersion(version);\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(version);\n }\n }\n\n /**\n * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n * {initializer} and {reinitializer} modifiers, directly or indirectly.\n */\n modifier onlyInitializing() {\n require(_initializing, \"Initializable: contract is not initializing\");\n _;\n }\n\n /**\n * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n * through proxies.\n */\n function _disableInitializers() internal virtual {\n _setInitializedVersion(type(uint8).max);\n }\n\n function _setInitializedVersion(uint8 version) private returns (bool) {\n // If the contract is initializing we ignore whether _initialized is set in order to support multiple\n // inheritance patterns, but we only do this in the context of a constructor, and for the lowest level\n // of initializers, because in other contexts the contract may have been reentered.\n if (_initializing) {\n require(\n version == 1 && !AddressUpgradeable.isContract(address(this)),\n \"Initializable: contract is already initialized\"\n );\n return false;\n } else {\n require(_initialized < version, \"Initializable: contract is already initialized\");\n _initialized = version;\n return true;\n }\n }\n}\n"
123
+ },
124
+ "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol": {
125
+ "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary AddressUpgradeable {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
126
+ },
127
+ "contracts/bridge/Bridge.sol": {
128
+ "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport \"@keep-network/random-beacon/contracts/Governable.sol\";\nimport {IWalletOwner as EcdsaWalletOwner} from \"@keep-network/ecdsa/contracts/api/IWalletOwner.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\nimport \"./IRelay.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Deposit.sol\";\nimport \"./DepositSweep.sol\";\nimport \"./Redemption.sol\";\nimport \"./BitcoinTx.sol\";\nimport \"./EcdsaLib.sol\";\nimport \"./Wallets.sol\";\nimport \"./Fraud.sol\";\nimport \"./MovingFunds.sol\";\n\nimport \"../bank/Bank.sol\";\n\n/// @title Bitcoin Bridge\n/// @notice Bridge manages BTC deposit and redemption flow and is increasing and\n/// decreasing balances in the Bank as a result of BTC deposit and\n/// redemption operations performed by depositors and redeemers.\n///\n/// Depositors send BTC funds to the most recently created off-chain\n/// ECDSA wallet of the bridge using pay-to-script-hash (P2SH) or\n/// pay-to-witness-script-hash (P2WSH) containing hashed information\n/// about the depositor’s Ethereum address. Then, the depositor reveals\n/// their Ethereum address along with their deposit blinding factor,\n/// refund public key hash and refund locktime to the Bridge on Ethereum\n/// chain. The off-chain ECDSA wallet listens for these sorts of\n/// messages and when it gets one, it checks the Bitcoin network to make\n/// sure the deposit lines up. If it does, the off-chain ECDSA wallet\n/// may decide to pick the deposit transaction for sweeping, and when\n/// the sweep operation is confirmed on the Bitcoin network, the ECDSA\n/// wallet informs the Bridge about the sweep increasing appropriate\n/// balances in the Bank.\n/// @dev Bridge is an upgradeable component of the Bank. The order of\n/// functionalities in this contract is: deposit, sweep, redemption,\n/// moving funds, wallet lifecycle, frauds, parameters.\ncontract Bridge is Governable, EcdsaWalletOwner, Initializable {\n using BridgeState for BridgeState.Storage;\n using Deposit for BridgeState.Storage;\n using DepositSweep for BridgeState.Storage;\n using Redemption for BridgeState.Storage;\n using MovingFunds for BridgeState.Storage;\n using Wallets for BridgeState.Storage;\n using Fraud for BridgeState.Storage;\n\n BridgeState.Storage internal self;\n\n event DepositRevealed(\n bytes32 fundingTxHash,\n uint32 fundingOutputIndex,\n address indexed depositor,\n uint64 amount,\n bytes8 blindingFactor,\n bytes20 indexed walletPubKeyHash,\n bytes20 refundPubKeyHash,\n bytes4 refundLocktime,\n address vault\n );\n\n event DepositsSwept(bytes20 walletPubKeyHash, bytes32 sweepTxHash);\n\n event RedemptionRequested(\n bytes20 indexed walletPubKeyHash,\n bytes redeemerOutputScript,\n address indexed redeemer,\n uint64 requestedAmount,\n uint64 treasuryFee,\n uint64 txMaxFee\n );\n\n event RedemptionsCompleted(\n bytes20 indexed walletPubKeyHash,\n bytes32 redemptionTxHash\n );\n\n event RedemptionTimedOut(\n bytes20 indexed walletPubKeyHash,\n bytes redeemerOutputScript\n );\n\n event WalletMovingFunds(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event MovingFundsCommitmentSubmitted(\n bytes20 indexed walletPubKeyHash,\n bytes20[] targetWallets,\n address submitter\n );\n\n event MovingFundsTimeoutReset(bytes20 indexed walletPubKeyHash);\n\n event MovingFundsCompleted(\n bytes20 indexed walletPubKeyHash,\n bytes32 movingFundsTxHash\n );\n\n event MovingFundsTimedOut(bytes20 indexed walletPubKeyHash);\n\n event MovingFundsBelowDustReported(bytes20 indexed walletPubKeyHash);\n\n event MovedFundsSwept(\n bytes20 indexed walletPubKeyHash,\n bytes32 sweepTxHash\n );\n\n event MovedFundsSweepTimedOut(\n bytes20 indexed walletPubKeyHash,\n bytes32 movingFundsTxHash,\n uint32 movingFundsTxOutputIndex\n );\n\n event NewWalletRequested();\n\n event NewWalletRegistered(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletClosing(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletClosed(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletTerminated(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event FraudChallengeSubmitted(\n bytes20 indexed walletPubKeyHash,\n bytes32 sighash,\n uint8 v,\n bytes32 r,\n bytes32 s\n );\n\n event FraudChallengeDefeated(\n bytes20 indexed walletPubKeyHash,\n bytes32 sighash\n );\n\n event FraudChallengeDefeatTimedOut(\n bytes20 indexed walletPubKeyHash,\n bytes32 sighash\n );\n\n event VaultStatusUpdated(address indexed vault, bool isTrusted);\n\n event DepositParametersUpdated(\n uint64 depositDustThreshold,\n uint64 depositTreasuryFeeDivisor,\n uint64 depositTxMaxFee\n );\n\n event RedemptionParametersUpdated(\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint256 redemptionTimeout,\n uint96 redemptionTimeoutSlashingAmount,\n uint256 redemptionTimeoutNotifierRewardMultiplier\n );\n\n event MovingFundsParametersUpdated(\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeoutResetDelay,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint256 movingFundsTimeoutNotifierRewardMultiplier,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint256 movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n\n event WalletParametersUpdated(\n uint32 walletCreationPeriod,\n uint64 walletCreationMinBtcBalance,\n uint64 walletCreationMaxBtcBalance,\n uint64 walletClosureMinBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n );\n\n event FraudParametersUpdated(\n uint256 fraudChallengeDepositAmount,\n uint256 fraudChallengeDefeatTimeout,\n uint96 fraudSlashingAmount,\n uint256 fraudNotifierRewardMultiplier\n );\n\n /// @dev Initializes upgradable contract on deployment.\n /// @param _bank Address of the Bank the Bridge belongs to.\n /// @param _relay Address of the Bitcoin relay providing the current Bitcoin\n /// network difficulty.\n /// @param _treasury Address where the deposit and redemption treasury fees\n /// will be sent to.\n /// @param _ecdsaWalletRegistry Address of the ECDSA Wallet Registry contract.\n /// @param _txProofDifficultyFactor The number of confirmations on the Bitcoin\n /// chain required to successfully evaluate an SPV proof.\n function initialize(\n address _bank,\n address _relay,\n address _treasury,\n address _ecdsaWalletRegistry,\n uint256 _txProofDifficultyFactor\n ) external initializer {\n require(_bank != address(0), \"Bank address cannot be zero\");\n self.bank = Bank(_bank);\n\n require(_relay != address(0), \"Relay address cannot be zero\");\n self.relay = IRelay(_relay);\n\n require(\n _ecdsaWalletRegistry != address(0),\n \"ECDSA Wallet Registry address cannot be zero\"\n );\n self.ecdsaWalletRegistry = EcdsaWalletRegistry(_ecdsaWalletRegistry);\n\n require(_treasury != address(0), \"Treasury address cannot be zero\");\n self.treasury = _treasury;\n\n self.txProofDifficultyFactor = _txProofDifficultyFactor;\n\n // TODO: Revisit initial values.\n // https://github.com/keep-network/tbtc-v2/issues/258\n self.depositDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC\n self.depositTxMaxFee = 10000; // 10000 satoshi\n self.depositTreasuryFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005\n self.redemptionDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC\n self.redemptionTreasuryFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005\n self.redemptionTxMaxFee = 10000; // 10000 satoshi\n self.redemptionTimeout = 172800; // 48 hours\n self.redemptionTimeoutSlashingAmount = 10000 * 1e18; // 10000 T\n self.redemptionTimeoutNotifierRewardMultiplier = 100; // 100%\n self.movingFundsTxMaxTotalFee = 10000; // 10000 satoshi\n self.movingFundsDustThreshold = 20000; // 20000 satoshi\n self.movingFundsTimeoutResetDelay = 6 days;\n self.movingFundsTimeout = 7 days;\n self.movingFundsTimeoutSlashingAmount = 10000 * 1e18; // 10000 T\n self.movingFundsTimeoutNotifierRewardMultiplier = 100; //100%\n self.movedFundsSweepTxMaxTotalFee = 10000; // 10000 satoshi\n self.movedFundsSweepTimeout = 7 days;\n self.movedFundsSweepTimeoutSlashingAmount = 10000 * 1e18; // 10000 T\n self.movedFundsSweepTimeoutNotifierRewardMultiplier = 100; //100%\n self.fraudChallengeDepositAmount = 2 ether;\n self.fraudChallengeDefeatTimeout = 7 days;\n self.fraudSlashingAmount = 10000 * 1e18; // 10000 T\n self.fraudNotifierRewardMultiplier = 100; // 100%\n self.walletCreationPeriod = 1 weeks;\n self.walletCreationMinBtcBalance = 1e8; // 1 BTC\n self.walletCreationMaxBtcBalance = 100e8; // 100 BTC\n self.walletClosureMinBtcBalance = 5 * 1e7; // 0.5 BTC\n self.walletMaxAge = 26 weeks; // ~6 months\n self.walletMaxBtcTransfer = 10e8; // 10 BTC\n self.walletClosingPeriod = 40 days;\n\n _transferGovernance(msg.sender);\n }\n\n /// @notice Used by the depositor to reveal information about their P2(W)SH\n /// Bitcoin deposit to the Bridge on Ethereum chain. The off-chain\n /// wallet listens for revealed deposit events and may decide to\n /// include the revealed deposit in the next executed sweep.\n /// Information about the Bitcoin deposit can be revealed before or\n /// after the Bitcoin transaction with P2(W)SH deposit is mined on\n /// the Bitcoin chain. Worth noting, the gas cost of this function\n /// scales with the number of P2(W)SH transaction inputs and\n /// outputs. The deposit may be routed to one of the trusted vaults.\n /// When a deposit is routed to a vault, vault gets notified when\n /// the deposit gets swept and it may execute the appropriate action.\n /// @param fundingTx Bitcoin funding transaction data, see `BitcoinTx.Info`.\n /// @param reveal Deposit reveal data, see `RevealInfo struct.\n /// @dev Requirements:\n /// - `reveal.walletPubKeyHash` must identify a `Live` wallet,\n /// - `reveal.vault` must be 0x0 or point to a trusted vault,\n /// - `reveal.fundingOutputIndex` must point to the actual P2(W)SH\n /// output of the BTC deposit transaction,\n /// - `reveal.depositor` must be the Ethereum address used in the\n /// P2(W)SH BTC deposit transaction,\n /// - `reveal.blindingFactor` must be the blinding factor used in the\n /// P2(W)SH BTC deposit transaction,\n /// - `reveal.walletPubKeyHash` must be the wallet pub key hash used in\n /// the P2(W)SH BTC deposit transaction,\n /// - `reveal.refundPubKeyHash` must be the refund pub key hash used in\n /// the P2(W)SH BTC deposit transaction,\n /// - `reveal.refundLocktime` must be the refund locktime used in the\n /// P2(W)SH BTC deposit transaction,\n /// - BTC deposit for the given `fundingTxHash`, `fundingOutputIndex`\n /// can be revealed only one time.\n ///\n /// If any of these requirements is not met, the wallet _must_ refuse\n /// to sweep the deposit and the depositor has to wait until the\n /// deposit script unlocks to receive their BTC back.\n function revealDeposit(\n BitcoinTx.Info calldata fundingTx,\n Deposit.DepositRevealInfo calldata reveal\n ) external {\n self.revealDeposit(fundingTx, reveal);\n }\n\n /// @notice Used by the wallet to prove the BTC deposit sweep transaction\n /// and to update Bank balances accordingly. Sweep is only accepted\n /// if it satisfies SPV proof.\n ///\n /// The function is performing Bank balance updates by first\n /// computing the Bitcoin fee for the sweep transaction. The fee is\n /// divided evenly between all swept deposits. Each depositor\n /// receives a balance in the bank equal to the amount inferred\n /// during the reveal transaction, minus their fee share.\n ///\n /// It is possible to prove the given sweep only one time.\n /// @param sweepTx Bitcoin sweep transaction data.\n /// @param sweepProof Bitcoin sweep proof data.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain. If no main UTXO exists for the given wallet,\n /// this parameter is ignored.\n /// @param vault Optional address of the vault where all swept deposits\n /// should be routed to. All deposits swept as part of the transaction\n /// must have their `vault` parameters set to the same address.\n /// If this parameter is set to an address of a trusted vault, swept\n /// deposits are routed to that vault.\n /// If this parameter is set to the zero address or to an address\n /// of a non-trusted vault, swept deposits are not routed to a\n /// vault but depositors' balances are increased in the Bank\n /// individually.\n /// @dev Requirements:\n /// - `sweepTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash,\n /// - The `sweepTx` should represent a Bitcoin transaction with 1..n\n /// inputs. If the wallet has no main UTXO, all n inputs should\n /// correspond to P2(W)SH revealed deposits UTXOs. If the wallet has\n /// an existing main UTXO, one of the n inputs must point to that\n /// main UTXO and remaining n-1 inputs should correspond to P2(W)SH\n /// revealed deposits UTXOs. That transaction must have only\n /// one P2(W)PKH output locking funds on the 20-byte wallet public\n /// key hash,\n /// - All revealed deposits that are swept by `sweepTx` must have\n /// their `vault` parameters set to the same address as the address\n /// passed in the `vault` function parameter,\n /// - `sweepProof` components must match the expected structure. See\n /// `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// If there is no main UTXO, this parameter is ignored.\n function submitDepositSweepProof(\n BitcoinTx.Info calldata sweepTx,\n BitcoinTx.Proof calldata sweepProof,\n BitcoinTx.UTXO calldata mainUtxo,\n address vault\n ) external {\n self.submitDepositSweepProof(sweepTx, sweepProof, mainUtxo, vault);\n }\n\n /// @notice Requests redemption of the given amount from the specified\n /// wallet to the redeemer Bitcoin output script.\n /// @param walletPubKeyHash The 20-byte wallet public key hash (computed\n /// using Bitcoin HASH160 over the compressed ECDSA public key).\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain.\n /// @param redeemerOutputScript The redeemer's length-prefixed output\n /// script (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock\n /// redeemed BTC.\n /// @param amount Requested amount in satoshi. This is also the TBTC amount\n /// that is taken from redeemer's balance in the Bank upon request.\n /// Once the request is handled, the actual amount of BTC locked\n /// on the redeemer output script will be always lower than this value\n /// since the treasury and Bitcoin transaction fees must be incurred.\n /// The minimal amount satisfying the request can be computed as:\n /// `amount - (amount / redemptionTreasuryFeeDivisor) - redemptionTxMaxFee`.\n /// Fees values are taken at the moment of request creation.\n /// @dev Requirements:\n /// - Wallet behind `walletPubKeyHash` must be live,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain,\n /// - `redeemerOutputScript` must be a proper Bitcoin script,\n /// - `redeemerOutputScript` cannot have wallet PKH as payload,\n /// - `amount` must be above or equal the `redemptionDustThreshold`,\n /// - Given `walletPubKeyHash` and `redeemerOutputScript` pair can be\n /// used for only one pending request at the same time,\n /// - Wallet must have enough Bitcoin balance to proceed the request,\n /// - Redeemer must make an allowance in the Bank that the Bridge\n /// contract can spend the given `amount`.\n function requestRedemption(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes calldata redeemerOutputScript,\n uint64 amount\n ) external {\n self.requestRedemption(\n walletPubKeyHash,\n mainUtxo,\n redeemerOutputScript,\n amount\n );\n }\n\n /// @notice Used by the wallet to prove the BTC redemption transaction\n /// and to make the necessary bookkeeping. Redemption is only\n /// accepted if it satisfies SPV proof.\n ///\n /// The function is performing Bank balance updates by burning\n /// the total redeemed Bitcoin amount from Bridge balance and\n /// transferring the treasury fee sum to the treasury address.\n ///\n /// It is possible to prove the given redemption only one time.\n /// @param redemptionTx Bitcoin redemption transaction data.\n /// @param redemptionProof Bitcoin redemption proof data.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n /// HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the redemption transaction.\n /// @dev Requirements:\n /// - `redemptionTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash,\n /// - The `redemptionTx` should represent a Bitcoin transaction with\n /// exactly 1 input that refers to the wallet's main UTXO. That\n /// transaction should have 1..n outputs handling existing pending\n /// redemption requests or pointing to reported timed out requests.\n /// There can be also 1 optional output representing the\n /// change and pointing back to the 20-byte wallet public key hash.\n /// The change should be always present if the redeemed value sum\n /// is lower than the total wallet's BTC balance,\n /// - `redemptionProof` components must match the expected structure.\n /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// Additionally, the recent main UTXO on Ethereum must be set,\n /// - `walletPubKeyHash` must be connected with the main UTXO used\n /// as transaction single input.\n /// Other remarks:\n /// - Putting the change output as the first transaction output can\n /// save some gas because the output processing loop begins each\n /// iteration by checking whether the given output is the change\n /// thus uses some gas for making the comparison. Once the change\n /// is identified, that check is omitted in further iterations.\n function submitRedemptionProof(\n BitcoinTx.Info calldata redemptionTx,\n BitcoinTx.Proof calldata redemptionProof,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes20 walletPubKeyHash\n ) external {\n self.submitRedemptionProof(\n redemptionTx,\n redemptionProof,\n mainUtxo,\n walletPubKeyHash\n );\n }\n\n /// @notice Notifies that there is a pending redemption request associated\n /// with the given wallet, that has timed out. The redemption\n /// request is identified by the key built as\n /// `keccak256(walletPubKeyHash | redeemerOutputScript)`.\n /// The results of calling this function:\n /// - The pending redemptions value for the wallet will be decreased\n /// by the requested amount (minus treasury fee),\n /// - The tokens taken from the redeemer on redemption request will\n /// be returned to the redeemer,\n /// - The request will be moved from pending redemptions to\n /// timed-out redemptions,\n /// - If the state of the wallet is `Live` or `MovingFunds`, the\n /// wallet operators will be slashed and the notifier will be\n /// rewarded,\n /// - If the state of wallet is `Live`, the wallet will be closed or\n /// marked as `MovingFunds` (depending on the presence or absence\n /// of the wallet's main UTXO) and the wallet will no longer be\n /// marked as the active wallet (if it was marked as such).\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @param redeemerOutputScript The redeemer's length-prefixed output\n /// script (P2PKH, P2WPKH, P2SH or P2WSH).\n /// @dev Requirements:\n /// - The wallet must be in the Live or MovingFunds or Terminated state,\n /// - The redemption request identified by `walletPubKeyHash` and\n /// `redeemerOutputScript` must exist,\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events of the `WalletRegistry` contract,\n /// - The amount of time defined by `redemptionTimeout` must have\n /// passed since the redemption was requested (the request must be\n /// timed-out).\n function notifyRedemptionTimeout(\n bytes20 walletPubKeyHash,\n uint32[] calldata walletMembersIDs,\n bytes calldata redeemerOutputScript\n ) external {\n self.notifyRedemptionTimeout(\n walletPubKeyHash,\n walletMembersIDs,\n redeemerOutputScript\n );\n }\n\n /// @notice Submits the moving funds target wallets commitment.\n /// Once all requirements are met, that function registers the\n /// target wallets commitment and opens the way for moving funds\n /// proof submission.\n /// @param walletPubKeyHash 20-byte public key hash of the source wallet.\n /// @param walletMainUtxo Data of the source wallet's main UTXO, as\n /// currently known on the Ethereum chain.\n /// @param walletMembersIDs Identifiers of the source wallet signing group\n /// members.\n /// @param walletMemberIndex Position of the caller in the source wallet\n /// signing group members list.\n /// @param targetWallets List of 20-byte public key hashes of the target\n /// wallets that the source wallet commits to move the funds to.\n /// @dev Requirements:\n /// - The source wallet must be in the MovingFunds state,\n /// - The source wallet must not have pending redemption requests,\n /// - The source wallet must not have pending moved funds sweep requests,\n /// - The source wallet must not have submitted its commitment already,\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given source wallet in the ECDSA registry. Those IDs are\n /// not directly stored in the contract for gas efficiency purposes\n /// but they can be read from appropriate `DkgResultSubmitted`\n /// and `DkgResultApproved` events,\n /// - The `walletMemberIndex` must be in range [1, walletMembersIDs.length],\n /// - The caller must be the member of the source wallet signing group\n /// at the position indicated by `walletMemberIndex` parameter,\n /// - The `walletMainUtxo` components must point to the recent main\n /// UTXO of the source wallet, as currently known on the Ethereum\n /// chain,\n /// - Source wallet BTC balance must be greater than zero,\n /// - At least one Live wallet must exist in the system,\n /// - Submitted target wallets count must match the expected count\n /// `N = min(liveWalletsCount, ceil(walletBtcBalance / walletMaxBtcTransfer))`\n /// where `N > 0`,\n /// - Each target wallet must be not equal to the source wallet,\n /// - Each target wallet must follow the expected order i.e. all\n /// target wallets 20-byte public key hashes represented as numbers\n /// must form a strictly increasing sequence without duplicates,\n /// - Each target wallet must be in Live state.\n function submitMovingFundsCommitment(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata walletMainUtxo,\n uint32[] calldata walletMembersIDs,\n uint256 walletMemberIndex,\n bytes20[] calldata targetWallets\n ) external {\n self.submitMovingFundsCommitment(\n walletPubKeyHash,\n walletMainUtxo,\n walletMembersIDs,\n walletMemberIndex,\n targetWallets\n );\n }\n\n /// @notice Resets the moving funds timeout for the given wallet if the\n /// target wallet commitment cannot be submitted due to a lack\n /// of live wallets in the system.\n /// @param walletPubKeyHash 20-byte public key hash of the moving funds wallet.\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state,\n /// - The target wallets commitment must not be already submitted for\n /// the given moving funds wallet,\n /// - Live wallets count must be zero,\n /// - The moving funds timeout reset delay must be elapsed.\n function resetMovingFundsTimeout(bytes20 walletPubKeyHash) external {\n self.resetMovingFundsTimeout(walletPubKeyHash);\n }\n\n /// @notice Used by the wallet to prove the BTC moving funds transaction\n /// and to make the necessary state changes. Moving funds is only\n /// accepted if it satisfies SPV proof.\n ///\n /// The function validates the moving funds transaction structure\n /// by checking if it actually spends the main UTXO of the declared\n /// wallet and locks the value on the pre-committed target wallets\n /// using a reasonable transaction fee. If all preconditions are\n /// met, this functions closes the source wallet.\n ///\n /// It is possible to prove the given moving funds transaction only\n /// one time.\n /// @param movingFundsTx Bitcoin moving funds transaction data.\n /// @param movingFundsProof Bitcoin moving funds proof data.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n /// HASH160 over the compressed ECDSA public key) of the wallet\n /// which performed the moving funds transaction.\n /// @dev Requirements:\n /// - `movingFundsTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash,\n /// - The `movingFundsTx` should represent a Bitcoin transaction with\n /// exactly 1 input that refers to the wallet's main UTXO. That\n /// transaction should have 1..n outputs corresponding to the\n /// pre-committed target wallets. Outputs must be ordered in the\n /// same way as their corresponding target wallets are ordered\n /// within the target wallets commitment,\n /// - `movingFundsProof` components must match the expected structure.\n /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// Additionally, the recent main UTXO on Ethereum must be set,\n /// - `walletPubKeyHash` must be connected with the main UTXO used\n /// as transaction single input,\n /// - The wallet that `walletPubKeyHash` points to must be in the\n /// MovingFunds state,\n /// - The target wallets commitment must be submitted by the wallet\n /// that `walletPubKeyHash` points to,\n /// - The total Bitcoin transaction fee must be lesser or equal\n /// to `movingFundsTxMaxTotalFee` governable parameter.\n function submitMovingFundsProof(\n BitcoinTx.Info calldata movingFundsTx,\n BitcoinTx.Proof calldata movingFundsProof,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes20 walletPubKeyHash\n ) external {\n self.submitMovingFundsProof(\n movingFundsTx,\n movingFundsProof,\n mainUtxo,\n walletPubKeyHash\n );\n }\n\n /// @notice Notifies about a timed out moving funds process. Terminates\n /// the wallet and slashes signing group members as a result.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state,\n /// - The moving funds timeout must be actually exceeded,\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events of the `WalletRegistry` contract.\n function notifyMovingFundsTimeout(\n bytes20 walletPubKeyHash,\n uint32[] calldata walletMembersIDs\n ) external {\n self.notifyMovingFundsTimeout(walletPubKeyHash, walletMembersIDs);\n }\n\n /// @notice Notifies about a moving funds wallet whose BTC balance is\n /// below the moving funds dust threshold. Ends the moving funds\n /// process and begins wallet closing immediately.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known\n /// on the Ethereum chain.\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state,\n /// - The `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// If the wallet has no main UTXO, this parameter can be empty as it\n /// is ignored,\n /// - The wallet BTC balance must be below the moving funds threshold.\n function notifyMovingFundsBelowDust(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata mainUtxo\n ) external {\n self.notifyMovingFundsBelowDust(walletPubKeyHash, mainUtxo);\n }\n\n /// @notice Used by the wallet to prove the BTC moved funds sweep\n /// transaction and to make the necessary state changes. Moved\n /// funds sweep is only accepted if it satisfies SPV proof.\n ///\n /// The function validates the sweep transaction structure by\n /// checking if it actually spends the moved funds UTXO and the\n /// sweeping wallet's main UTXO (optionally), and if it locks the\n /// value on the sweeping wallet's 20-byte public key hash using a\n /// reasonable transaction fee. If all preconditions are\n /// met, this function updates the sweeping wallet main UTXO, thus\n /// their BTC balance.\n ///\n /// It is possible to prove the given sweep transaction only\n /// one time.\n /// @param sweepTx Bitcoin sweep funds transaction data.\n /// @param sweepProof Bitcoin sweep funds proof data.\n /// @param mainUtxo Data of the sweeping wallet's main UTXO, as currently\n /// known on the Ethereum chain.\n /// @dev Requirements:\n /// - `sweepTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash,\n /// - The `sweepTx` should represent a Bitcoin transaction with\n /// the first input pointing to a moved funds sweep request targeted\n /// to the wallet, and optionally, the second input pointing to the\n /// wallet's main UTXO, if the sweeping wallet has a main UTXO set.\n /// There should be only one output locking funds on the sweeping\n /// wallet 20-byte public key hash,\n /// - `sweepProof` components must match the expected structure.\n /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the sweeping wallet, as currently known on the Ethereum chain.\n /// If there is no main UTXO, this parameter is ignored,\n /// - The sweeping wallet must be in the Live or MovingFunds state,\n /// - The total Bitcoin transaction fee must be lesser or equal\n /// to `movedFundsSweepTxMaxTotalFee` governable parameter.\n function submitMovedFundsSweepProof(\n BitcoinTx.Info calldata sweepTx,\n BitcoinTx.Proof calldata sweepProof,\n BitcoinTx.UTXO calldata mainUtxo\n ) external {\n self.submitMovedFundsSweepProof(sweepTx, sweepProof, mainUtxo);\n }\n\n /// @notice Notifies about a timed out moved funds sweep process. If the\n /// wallet is not terminated yet, that function terminates\n /// the wallet and slashes signing group members as a result.\n /// Marks the given sweep request as TimedOut.\n /// @param movingFundsTxHash 32-byte hash of the moving funds transaction\n /// that caused the sweep request to be created.\n /// @param movingFundsTxOutputIndex Index of the moving funds transaction\n /// output that is subject of the sweep request.\n /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @dev Requirements:\n /// - The moved funds sweep request must be in the Pending state,\n /// - The moved funds sweep timeout must be actually exceeded,\n /// - The wallet must be either in the Live or MovingFunds or\n /// Terminated state,\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events of the `WalletRegistry` contract.\n function notifyMovedFundsSweepTimeout(\n bytes32 movingFundsTxHash,\n uint32 movingFundsTxOutputIndex,\n uint32[] calldata walletMembersIDs\n ) external {\n self.notifyMovedFundsSweepTimeout(\n movingFundsTxHash,\n movingFundsTxOutputIndex,\n walletMembersIDs\n );\n }\n\n /// @notice Requests creation of a new wallet. This function just\n /// forms a request and the creation process is performed\n /// asynchronously. Once a wallet is created, the ECDSA Wallet\n /// Registry will notify this contract by calling the\n /// `__ecdsaWalletCreatedCallback` function.\n /// @param activeWalletMainUtxo Data of the active wallet's main UTXO, as\n /// currently known on the Ethereum chain.\n /// @dev Requirements:\n /// - `activeWalletMainUtxo` components must point to the recent main\n /// UTXO of the given active wallet, as currently known on the\n /// Ethereum chain. If there is no active wallet at the moment, or\n /// the active wallet has no main UTXO, this parameter can be\n /// empty as it is ignored,\n /// - Wallet creation must not be in progress,\n /// - If the active wallet is set, one of the following\n /// conditions must be true:\n /// - The active wallet BTC balance is above the minimum threshold\n /// and the active wallet is old enough, i.e. the creation period\n /// was elapsed since its creation time,\n /// - The active wallet BTC balance is above the maximum threshold.\n function requestNewWallet(BitcoinTx.UTXO calldata activeWalletMainUtxo)\n external\n {\n self.requestNewWallet(activeWalletMainUtxo);\n }\n\n /// @notice A callback function that is called by the ECDSA Wallet Registry\n /// once a new ECDSA wallet is created.\n /// @param ecdsaWalletID Wallet's unique identifier.\n /// @param publicKeyX Wallet's public key's X coordinate.\n /// @param publicKeyY Wallet's public key's Y coordinate.\n /// @dev Requirements:\n /// - The only caller authorized to call this function is `registry`,\n /// - Given wallet data must not belong to an already registered wallet.\n function __ecdsaWalletCreatedCallback(\n bytes32 ecdsaWalletID,\n bytes32 publicKeyX,\n bytes32 publicKeyY\n ) external override {\n self.registerNewWallet(ecdsaWalletID, publicKeyX, publicKeyY);\n }\n\n /// @notice A callback function that is called by the ECDSA Wallet Registry\n /// once a wallet heartbeat failure is detected.\n /// @param publicKeyX Wallet's public key's X coordinate.\n /// @param publicKeyY Wallet's public key's Y coordinate.\n /// @dev Requirements:\n /// - The only caller authorized to call this function is `registry`,\n /// - Wallet must be in Live state.\n function __ecdsaWalletHeartbeatFailedCallback(\n bytes32,\n bytes32 publicKeyX,\n bytes32 publicKeyY\n ) external override {\n self.notifyWalletHeartbeatFailed(publicKeyX, publicKeyY);\n }\n\n /// @notice Notifies that the wallet is either old enough or has too few\n /// satoshi left and qualifies to be closed.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @param walletMainUtxo Data of the wallet's main UTXO, as currently\n /// known on the Ethereum chain.\n /// @dev Requirements:\n /// - Wallet must not be set as the current active wallet,\n /// - Wallet must exceed the wallet maximum age OR the wallet BTC\n /// balance must be lesser than the minimum threshold. If the latter\n /// case is true, the `walletMainUtxo` components must point to the\n /// recent main UTXO of the given wallet, as currently known on the\n /// Ethereum chain. If the wallet has no main UTXO, this parameter\n /// can be empty as it is ignored since the wallet balance is\n /// assumed to be zero,\n /// - Wallet must be in Live state.\n function notifyCloseableWallet(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata walletMainUtxo\n ) external {\n self.notifyCloseableWallet(walletPubKeyHash, walletMainUtxo);\n }\n\n /// @notice Notifies about the end of the closing period for the given wallet.\n /// Closes the wallet ultimately and notifies the ECDSA registry\n /// about this fact.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @dev Requirements:\n /// - The wallet must be in the Closing state,\n /// - The wallet closing period must have elapsed.\n function notifyWalletClosingPeriodElapsed(bytes20 walletPubKeyHash)\n external\n {\n self.notifyWalletClosingPeriodElapsed(walletPubKeyHash);\n }\n\n /// @notice Submits a fraud challenge indicating that a UTXO being under\n /// wallet control was unlocked by the wallet but was not used\n /// according to the protocol rules. That means the wallet signed\n /// a transaction input pointing to that UTXO and there is a unique\n /// sighash and signature pair associated with that input. This\n /// function uses those parameters to create a fraud accusation that\n /// proves a given transaction input unlocking the given UTXO was\n /// actually signed by the wallet. This function cannot determine\n /// whether the transaction was actually broadcast and the input was\n /// consumed in a fraudulent way so it just opens a challenge period\n /// during which the wallet can defeat the challenge by submitting\n /// proof of a transaction that consumes the given input according\n /// to protocol rules. To prevent spurious allegations, the caller\n /// must deposit ETH that is returned back upon justified fraud\n /// challenge or confiscated otherwise.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes).\n /// @param preimageSha256 The hash that was generated by applying SHA-256\n /// one time over the preimage used during input signing. The preimage\n /// is a serialized subset of the transaction and its structure\n /// depends on the transaction input (see BIP-143 for reference).\n /// Notice that applying SHA-256 over the `preimageSha256` results\n /// in `sighash`. The path from `preimage` to `sighash` looks like\n /// this:\n /// preimage -> (SHA-256) -> preimageSha256 -> (SHA-256) -> sighash.\n /// @param signature Bitcoin signature in the R/S/V format.\n /// @dev Requirements:\n /// - Wallet behind `walletPublicKey` must be in Live or MovingFunds\n /// or Closing state,\n /// - The challenger must send appropriate amount of ETH used as\n /// fraud challenge deposit,\n /// - The signature (represented by r, s and v) must be generated by\n /// the wallet behind `walletPubKey` during signing of `sighash`\n /// which was calculated from `preimageSha256`,\n /// - Wallet can be challenged for the given signature only once.\n function submitFraudChallenge(\n bytes calldata walletPublicKey,\n bytes memory preimageSha256,\n BitcoinTx.RSVSignature calldata signature\n ) external payable {\n self.submitFraudChallenge(walletPublicKey, preimageSha256, signature);\n }\n\n /// @notice Allows to defeat a pending fraud challenge against a wallet if\n /// the transaction that spends the UTXO follows the protocol rules.\n /// In order to defeat the challenge the same `walletPublicKey` and\n /// signature (represented by `r`, `s` and `v`) must be provided as\n /// were used to calculate the sighash during input signing.\n /// The fraud challenge defeat attempt will only succeed if the\n /// inputs in the preimage are considered honestly spent by the\n /// wallet. Therefore the transaction spending the UTXO must be\n /// proven in the Bridge before a challenge defeat is called.\n /// If successfully defeated, the fraud challenge is marked as\n /// resolved and the amount of ether deposited by the challenger is\n /// sent to the treasury.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes).\n /// @param preimage The preimage which produces sighash used to generate the\n /// ECDSA signature that is the subject of the fraud claim. It is a\n /// serialized subset of the transaction. The exact subset used as\n /// the preimage depends on the transaction input the signature is\n /// produced for. See BIP-143 for reference.\n /// @param witness Flag indicating whether the preimage was produced for a\n /// witness input. True for witness, false for non-witness input.\n /// @dev Requirements:\n /// - `walletPublicKey` and `sighash` calculated as `hash256(preimage)`\n /// must identify an open fraud challenge,\n /// - the preimage must be a valid preimage of a transaction generated\n /// according to the protocol rules and already proved in the Bridge,\n /// - before a defeat attempt is made the transaction that spends the\n /// given UTXO must be proven in the Bridge.\n function defeatFraudChallenge(\n bytes calldata walletPublicKey,\n bytes calldata preimage,\n bool witness\n ) external {\n self.defeatFraudChallenge(walletPublicKey, preimage, witness);\n }\n\n /// @notice Allows to defeat a pending fraud challenge against a wallet by\n /// proving the sighash and signature were produced for an off-chain\n /// wallet heartbeat message following a strict format.\n /// In order to defeat the challenge the same `walletPublicKey` and\n /// signature (represented by `r`, `s` and `v`) must be provided as\n /// were used to calculate the sighash during heartbeat message\n /// signing. The fraud challenge defeat attempt will only succeed if\n /// the signed message follows a strict format required for\n /// heartbeat messages. If successfully defeated, the fraud\n /// challenge is marked as resolved and the amount of ether\n /// deposited by the challenger is sent to the treasury.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes).\n /// @param heartbeatMessage Off-chain heartbeat message meeting the heartbeat\n /// message format requirements which produces sighash used to\n /// generate the ECDSA signature that is the subject of the fraud\n /// claim.\n /// @dev Requirements:\n /// - `walletPublicKey` and `sighash` calculated as\n /// `hash256(heartbeatMessage)` must identify an open fraud challenge,\n /// - `heartbeatMessage` must follow a strict format of heartbeat\n /// messages.\n function defeatFraudChallengeWithHeartbeat(\n bytes calldata walletPublicKey,\n bytes calldata heartbeatMessage\n ) external {\n self.defeatFraudChallengeWithHeartbeat(\n walletPublicKey,\n heartbeatMessage\n );\n }\n\n /// @notice Notifies about defeat timeout for the given fraud challenge.\n /// Can be called only if there was a fraud challenge identified by\n /// the provided `walletPublicKey` and `sighash` and it was not\n /// defeated on time. The amount of time that needs to pass after\n /// a fraud challenge is reported is indicated by the\n /// `challengeDefeatTimeout`. After a successful fraud challenge\n /// defeat timeout notification the fraud challenge is marked as\n /// resolved, the stake of each operator is slashed, the ether\n /// deposited is returned to the challenger and the challenger is\n /// rewarded.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes).\n /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @param preimageSha256 The hash that was generated by applying SHA-256\n /// one time over the preimage used during input signing. The preimage\n /// is a serialized subset of the transaction and its structure\n /// depends on the transaction input (see BIP-143 for reference).\n /// Notice that applying SHA-256 over the `preimageSha256` results\n /// in `sighash`. The path from `preimage` to `sighash` looks like\n /// this:\n /// preimage -> (SHA-256) -> preimageSha256 -> (SHA-256) -> sighash.\n /// @dev Requirements:\n /// - The wallet must be in the Live or MovingFunds or Closing or\n /// Terminated state,\n /// - The `walletPublicKey` and `sighash` calculated from\n /// `preimageSha256` must identify an open fraud challenge,\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events of the `WalletRegistry` contract,\n /// - The amount of time indicated by `challengeDefeatTimeout` must pass\n /// after the challenge was reported.\n function notifyFraudChallengeDefeatTimeout(\n bytes calldata walletPublicKey,\n uint32[] calldata walletMembersIDs,\n bytes memory preimageSha256\n ) external {\n self.notifyFraudChallengeDefeatTimeout(\n walletPublicKey,\n walletMembersIDs,\n preimageSha256\n );\n }\n\n /// @notice Allows the Governance to mark the given vault address as trusted\n /// or no longer trusted. Vaults are not trusted by default.\n /// Trusted vault must meet the following criteria:\n /// - `IVault.receiveBalanceIncrease` must have a known, low gas\n /// cost,\n /// - `IVault.receiveBalanceIncrease` must never revert.\n /// @dev Without restricting reveal only to trusted vaults, malicious\n /// vaults not meeting the criteria would be able to nuke sweep proof\n /// transactions executed by ECDSA wallet with deposits routed to\n /// them.\n /// @param vault The address of the vault.\n /// @param isTrusted flag indicating whether the vault is trusted or not.\n /// @dev Can only be called by the Governance.\n function setVaultStatus(address vault, bool isTrusted)\n external\n onlyGovernance\n {\n self.isVaultTrusted[vault] = isTrusted;\n emit VaultStatusUpdated(vault, isTrusted);\n }\n\n /// @notice Updates parameters of deposits.\n /// @param depositDustThreshold New value of the deposit dust threshold in\n /// satoshis. It is the minimal amount that can be requested to\n //// deposit. Value of this parameter must take into account the value\n /// of `depositTreasuryFeeDivisor` and `depositTxMaxFee` parameters\n /// in order to make requests that can incur the treasury and\n /// transaction fee and still satisfy the depositor.\n /// @param depositTreasuryFeeDivisor New value of the treasury fee divisor.\n /// It is the divisor used to compute the treasury fee taken from\n /// each deposit and transferred to the treasury upon sweep proof\n /// submission. That fee is computed as follows:\n /// `treasuryFee = depositedAmount / depositTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each deposit,\n /// the `depositTreasuryFeeDivisor` should be set to `50`\n /// because `1/50 = 0.02 = 2%`.\n /// @param depositTxMaxFee New value of the deposit tx max fee in satoshis.\n /// It is the maximum amount of BTC transaction fee that can\n /// be incurred by each swept deposit being part of the given sweep\n /// transaction. If the maximum BTC transaction fee is exceeded,\n /// such transaction is considered a fraud.\n /// @dev Requirements:\n /// - Deposit dust threshold must be greater than zero,\n /// - Deposit treasury fee divisor must be greater than zero,\n /// - Deposit transaction max fee must be greater than zero.\n function updateDepositParameters(\n uint64 depositDustThreshold,\n uint64 depositTreasuryFeeDivisor,\n uint64 depositTxMaxFee\n ) external onlyGovernance {\n self.updateDepositParameters(\n depositDustThreshold,\n depositTreasuryFeeDivisor,\n depositTxMaxFee\n );\n }\n\n /// @notice Updates parameters of redemptions.\n /// @param redemptionDustThreshold New value of the redemption dust\n /// threshold in satoshis. It is the minimal amount that can be\n /// requested for redemption. Value of this parameter must take into\n /// account the value of `redemptionTreasuryFeeDivisor` and\n /// `redemptionTxMaxFee` parameters in order to make requests that\n /// can incur the treasury and transaction fee and still satisfy the\n /// redeemer.\n /// @param redemptionTreasuryFeeDivisor New value of the redemption\n /// treasury fee divisor. It is the divisor used to compute the\n /// treasury fee taken from each redemption request and transferred\n /// to the treasury upon successful request finalization. That fee is\n /// computed as follows:\n /// `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each\n /// redemption request, the `redemptionTreasuryFeeDivisor` should\n /// be set to `50` because `1/50 = 0.02 = 2%`.\n /// @param redemptionTxMaxFee New value of the redemption transaction max\n /// fee in satoshis. It is the maximum amount of BTC transaction fee\n /// that can be incurred by each redemption request being part of the\n /// given redemption transaction. If the maximum BTC transaction fee\n /// is exceeded, such transaction is considered a fraud.\n /// This is a per-redemption output max fee for the redemption\n /// transaction.\n /// @param redemptionTimeout New value of the redemption timeout in seconds.\n /// It is the time after which the redemption request can be reported\n /// as timed out. It is counted from the moment when the redemption\n /// request was created via `requestRedemption` call. Reported timed\n /// out requests are cancelled and locked TBTC is returned to the\n /// redeemer in full amount.\n /// @param redemptionTimeoutSlashingAmount New value of the redemption\n /// timeout slashing amount in T, it is the amount slashed from each\n /// wallet member for redemption timeout.\n /// @param redemptionTimeoutNotifierRewardMultiplier New value of the\n /// redemption timeout notifier reward multiplier as percentage,\n /// it determines the percentage of the notifier reward from the\n /// staking contact the notifier of a redemption timeout receives.\n /// The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Redemption dust threshold must be greater than moving funds dust\n /// threshold,\n /// - Redemption treasury fee divisor must be greater than zero,\n /// - Redemption transaction max fee must be greater than zero,\n /// - Redemption timeout must be greater than zero,\n /// - Redemption timeout notifier reward multiplier must be in the\n /// range [0, 100].\n function updateRedemptionParameters(\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint256 redemptionTimeout,\n uint96 redemptionTimeoutSlashingAmount,\n uint256 redemptionTimeoutNotifierRewardMultiplier\n ) external onlyGovernance {\n self.updateRedemptionParameters(\n redemptionDustThreshold,\n redemptionTreasuryFeeDivisor,\n redemptionTxMaxFee,\n redemptionTimeout,\n redemptionTimeoutSlashingAmount,\n redemptionTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Updates parameters of moving funds.\n /// @param movingFundsTxMaxTotalFee New value of the moving funds transaction\n /// max total fee in satoshis. It is the maximum amount of the total\n /// BTC transaction fee that is acceptable in a single moving funds\n /// transaction. This is a _total_ max fee for the entire moving\n /// funds transaction.\n /// @param movingFundsDustThreshold New value of the moving funds dust\n /// threshold. It is the minimal satoshi amount that makes sense to\n /// be transferred during the moving funds process. Moving funds\n /// wallets having their BTC balance below that value can begin\n /// closing immediately as transferring such a low value may not be\n /// possible due to BTC network fees.\n /// @param movingFundsTimeoutResetDelay New value of the moving funds\n /// timeout reset delay in seconds. It is the time after which the\n /// moving funds timeout can be reset in case the target wallet\n /// commitment cannot be submitted due to a lack of live wallets\n /// in the system. It is counted from the moment when the wallet\n /// was requested to move their funds and switched to the MovingFunds\n /// state or from the moment the timeout was reset the last time.\n /// @param movingFundsTimeout New value of the moving funds timeout in\n /// seconds. It is the time after which the moving funds process can\n /// be reported as timed out. It is counted from the moment when the\n /// wallet was requested to move their funds and switched to the\n /// MovingFunds state.\n /// @param movingFundsTimeoutSlashingAmount New value of the moving funds\n /// timeout slashing amount in T, it is the amount slashed from each\n /// wallet member for moving funds timeout.\n /// @param movingFundsTimeoutNotifierRewardMultiplier New value of the\n /// moving funds timeout notifier reward multiplier as percentage,\n /// it determines the percentage of the notifier reward from the\n /// staking contact the notifier of a moving funds timeout receives.\n /// The value must be in the range [0, 100].\n /// @param movedFundsSweepTxMaxTotalFee New value of the moved funds sweep\n /// transaction max total fee in satoshis. It is the maximum amount\n /// of the total BTC transaction fee that is acceptable in a single\n /// moved funds sweep transaction. This is a _total_ max fee for the\n /// entire moved funds sweep transaction.\n /// @param movedFundsSweepTimeout New value of the moved funds sweep\n /// timeout in seconds. It is the time after which the moved funds\n /// sweep process can be reported as timed out. It is counted from\n /// the moment when the wallet was requested to sweep the received\n /// funds.\n /// @param movedFundsSweepTimeoutSlashingAmount New value of the moved\n /// funds sweep timeout slashing amount in T, it is the amount\n /// slashed from each wallet member for moved funds sweep timeout.\n /// @param movedFundsSweepTimeoutNotifierRewardMultiplier New value of\n /// the moved funds sweep timeout notifier reward multiplier as\n /// percentage, it determines the percentage of the notifier reward\n /// from the staking contact the notifier of a moved funds sweep\n /// timeout receives. The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Moving funds transaction max total fee must be greater than zero,\n /// - Moving funds dust threshold must be greater than zero and lower\n /// than the redemption dust threshold,\n /// - Moving funds timeout reset delay must be greater than zero,\n /// - Moving funds timeout must be greater than the moving funds\n /// timeout reset delay,\n /// - Moving funds timeout notifier reward multiplier must be in the\n /// range [0, 100],\n /// - Moved funds sweep transaction max total fee must be greater than zero,\n /// - Moved funds sweep timeout must be greater than zero,\n /// - Moved funds sweep timeout notifier reward multiplier must be in the\n /// range [0, 100].\n function updateMovingFundsParameters(\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeoutResetDelay,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint256 movingFundsTimeoutNotifierRewardMultiplier,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint256 movedFundsSweepTimeoutNotifierRewardMultiplier\n ) external onlyGovernance {\n self.updateMovingFundsParameters(\n movingFundsTxMaxTotalFee,\n movingFundsDustThreshold,\n movingFundsTimeoutResetDelay,\n movingFundsTimeout,\n movingFundsTimeoutSlashingAmount,\n movingFundsTimeoutNotifierRewardMultiplier,\n movedFundsSweepTxMaxTotalFee,\n movedFundsSweepTimeout,\n movedFundsSweepTimeoutSlashingAmount,\n movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Updates parameters of wallets.\n /// @param walletCreationPeriod New value of the wallet creation period in\n /// seconds, determines how frequently a new wallet creation can be\n /// requested.\n /// @param walletCreationMinBtcBalance New value of the wallet minimum BTC\n /// balance in satoshi, used to decide about wallet creation.\n /// @param walletCreationMaxBtcBalance New value of the wallet maximum BTC\n /// balance in satoshi, used to decide about wallet creation.\n /// @param walletClosureMinBtcBalance New value of the wallet minimum BTC\n /// balance in satoshi, used to decide about wallet closure.\n /// @param walletMaxAge New value of the wallet maximum age in seconds,\n /// indicates the maximum age of a wallet in seconds, after which\n /// the wallet moving funds process can be requested.\n /// @param walletMaxBtcTransfer New value of the wallet maximum BTC transfer\n /// in satoshi, determines the maximum amount that can be transferred\n // to a single target wallet during the moving funds process.\n /// @param walletClosingPeriod New value of the wallet closing period in\n /// seconds, determines the length of the wallet closing period,\n // i.e. the period when the wallet remains in the Closing state\n // and can be subject of deposit fraud challenges.\n /// @dev Requirements:\n /// - Wallet minimum BTC balance must be greater than zero,\n /// - Wallet maximum BTC balance must be greater than the wallet\n /// minimum BTC balance,\n /// - Wallet maximum BTC transfer must be greater than zero,\n /// - Wallet closing period must be greater than zero.\n function updateWalletParameters(\n uint32 walletCreationPeriod,\n uint64 walletCreationMinBtcBalance,\n uint64 walletCreationMaxBtcBalance,\n uint64 walletClosureMinBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n ) external onlyGovernance {\n self.updateWalletParameters(\n walletCreationPeriod,\n walletCreationMinBtcBalance,\n walletCreationMaxBtcBalance,\n walletClosureMinBtcBalance,\n walletMaxAge,\n walletMaxBtcTransfer,\n walletClosingPeriod\n );\n }\n\n /// @notice Updates parameters related to frauds.\n /// @param fraudChallengeDepositAmount New value of the fraud challenge\n /// deposit amount in wei, it is the amount of ETH the party\n /// challenging the wallet for fraud needs to deposit.\n /// @param fraudChallengeDefeatTimeout New value of the challenge defeat\n /// timeout in seconds, it is the amount of time the wallet has to\n /// defeat a fraud challenge. The value must be greater than zero.\n /// @param fraudSlashingAmount New value of the fraud slashing amount in T,\n /// it is the amount slashed from each wallet member for committing\n /// a fraud.\n /// @param fraudNotifierRewardMultiplier New value of the fraud notifier\n /// reward multiplier as percentage, it determines the percentage of\n /// the notifier reward from the staking contact the notifier of\n /// a fraud receives. The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Fraud challenge defeat timeout must be greater than 0,\n /// - Fraud notifier reward multiplier must be in the range [0, 100].\n function updateFraudParameters(\n uint256 fraudChallengeDepositAmount,\n uint256 fraudChallengeDefeatTimeout,\n uint96 fraudSlashingAmount,\n uint256 fraudNotifierRewardMultiplier\n ) external onlyGovernance {\n self.updateFraudParameters(\n fraudChallengeDepositAmount,\n fraudChallengeDefeatTimeout,\n fraudSlashingAmount,\n fraudNotifierRewardMultiplier\n );\n }\n\n /// @notice Collection of all revealed deposits indexed by\n /// keccak256(fundingTxHash | fundingOutputIndex).\n /// The fundingTxHash is bytes32 (ordered as in Bitcoin internally)\n /// and fundingOutputIndex an uint32. This mapping may contain valid\n /// and invalid deposits and the wallet is responsible for\n /// validating them before attempting to execute a sweep.\n function deposits(uint256 depositKey)\n external\n view\n returns (Deposit.DepositRequest memory)\n {\n return self.deposits[depositKey];\n }\n\n /// @notice Collection of all pending redemption requests indexed by\n /// redemption key built as\n /// keccak256(walletPubKeyHash | redeemerOutputScript). The\n /// walletPubKeyHash is the 20-byte wallet's public key hash\n /// (computed using Bitcoin HASH160 over the compressed ECDSA\n /// public key) and redeemerOutputScript is a Bitcoin script\n /// (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock\n /// redeemed BTC as requested by the redeemer. Requests are added\n /// to this mapping by the `requestRedemption` method (duplicates\n /// not allowed) and are removed by one of the following methods:\n /// - `submitRedemptionProof` in case the request was handled\n /// successfully,\n /// - `notifyRedemptionTimeout` in case the request was reported\n /// to be timed out.\n function pendingRedemptions(uint256 redemptionKey)\n external\n view\n returns (Redemption.RedemptionRequest memory)\n {\n return self.pendingRedemptions[redemptionKey];\n }\n\n /// @notice Collection of all timed out redemptions requests indexed by\n /// redemption key built as\n /// keccak256(walletPubKeyHash | redeemerOutputScript). The\n /// walletPubKeyHash is the 20-byte wallet's public key hash\n /// (computed using Bitcoin HASH160 over the compressed ECDSA\n /// public key) and redeemerOutputScript is the Bitcoin script\n /// (P2PKH, P2WPKH, P2SH or P2WSH) that is involved in the timed\n /// out request. Timed out requests are stored in this mapping to\n /// avoid slashing the wallets multiple times for the same timeout.\n /// Only one method can add to this mapping:\n /// - `notifyRedemptionTimeout` which puts the redemption key\n /// to this mapping basing on a timed out request stored\n /// previously in `pendingRedemptions` mapping.\n function timedOutRedemptions(uint256 redemptionKey)\n external\n view\n returns (Redemption.RedemptionRequest memory)\n {\n return self.timedOutRedemptions[redemptionKey];\n }\n\n /// @notice Collection of main UTXOs that are honestly spent indexed by\n /// keccak256(fundingTxHash | fundingOutputIndex). The fundingTxHash\n /// is bytes32 (ordered as in Bitcoin internally) and\n /// fundingOutputIndex an uint32. A main UTXO is considered honestly\n /// spent if it was used as an input of a transaction that have been\n /// proven in the Bridge.\n function spentMainUTXOs(uint256 utxoKey) external view returns (bool) {\n return self.spentMainUTXOs[utxoKey];\n }\n\n /// @notice Gets details about a registered wallet.\n /// @param walletPubKeyHash The 20-byte wallet public key hash (computed\n /// using Bitcoin HASH160 over the compressed ECDSA public key).\n /// @return Wallet details.\n function wallets(bytes20 walletPubKeyHash)\n external\n view\n returns (Wallets.Wallet memory)\n {\n return self.registeredWallets[walletPubKeyHash];\n }\n\n /// @notice Gets the public key hash of the active wallet.\n /// @return The 20-byte public key hash (computed using Bitcoin HASH160\n /// over the compressed ECDSA public key) of the active wallet.\n /// Returns bytes20(0) if there is no active wallet at the moment.\n function activeWalletPubKeyHash() external view returns (bytes20) {\n return self.activeWalletPubKeyHash;\n }\n\n /// @notice Gets the live wallets count.\n /// @return The current count of wallets being in the Live state.\n function liveWalletsCount() external view returns (uint32) {\n return self.liveWalletsCount;\n }\n\n /// @notice Returns the fraud challenge identified by the given key built\n /// as keccak256(walletPublicKey|sighash).\n function fraudChallenges(uint256 challengeKey)\n external\n view\n returns (Fraud.FraudChallenge memory)\n {\n return self.fraudChallenges[challengeKey];\n }\n\n /// @notice Collection of all moved funds sweep requests indexed by\n /// `keccak256(movingFundsTxHash | movingFundsOutputIndex)`.\n /// The `movingFundsTxHash` is `bytes32` (ordered as in Bitcoin\n /// internally) and `movingFundsOutputIndex` an `uint32`. Each entry\n /// is actually an UTXO representing the moved funds and is supposed\n /// to be swept with the current main UTXO of the recipient wallet.\n /// @param requestKey Request key built as\n /// `keccak256(movingFundsTxHash | movingFundsOutputIndex)`.\n /// @return Details of the moved funds sweep request.\n function movedFundsSweepRequests(uint256 requestKey)\n external\n view\n returns (MovingFunds.MovedFundsSweepRequest memory)\n {\n return self.movedFundsSweepRequests[requestKey];\n }\n\n /// @notice Indicates if the vault with the given address is trusted or not.\n /// Depositors can route their revealed deposits only to trusted\n /// vaults and have trusted vaults notified about new deposits as\n /// soon as these deposits get swept. Vaults not trusted by the\n /// Bridge can still be used by Bank balance owners on their own\n /// responsibility - anyone can approve their Bank balance to any\n /// address.\n function isVaultTrusted(address vault) external view returns (bool) {\n return self.isVaultTrusted[vault];\n }\n\n /// @notice Returns the current values of Bridge deposit parameters.\n /// @return depositDustThreshold The minimal amount that can be requested\n /// to deposit. Value of this parameter must take into account the\n /// value of `depositTreasuryFeeDivisor` and `depositTxMaxFee`\n /// parameters in order to make requests that can incur the\n /// treasury and transaction fee and still satisfy the depositor.\n /// @return depositTreasuryFeeDivisor Divisor used to compute the treasury\n /// fee taken from each deposit and transferred to the treasury upon\n /// sweep proof submission. That fee is computed as follows:\n /// `treasuryFee = depositedAmount / depositTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each deposit,\n /// the `depositTreasuryFeeDivisor` should be set to `50`\n /// because `1/50 = 0.02 = 2%`.\n /// @return depositTxMaxFee Maximum amount of BTC transaction fee that can\n /// be incurred by each swept deposit being part of the given sweep\n /// transaction. If the maximum BTC transaction fee is exceeded,\n /// such transaction is considered a fraud.\n function depositParameters()\n external\n view\n returns (\n uint64 depositDustThreshold,\n uint64 depositTreasuryFeeDivisor,\n uint64 depositTxMaxFee\n )\n {\n depositDustThreshold = self.depositDustThreshold;\n depositTreasuryFeeDivisor = self.depositTreasuryFeeDivisor;\n depositTxMaxFee = self.depositTxMaxFee;\n }\n\n /// @notice Returns the current values of Bridge redemption parameters.\n /// @return redemptionDustThreshold The minimal amount that can be requested\n /// for redemption. Value of this parameter must take into account\n /// the value of `redemptionTreasuryFeeDivisor` and `redemptionTxMaxFee`\n /// parameters in order to make requests that can incur the\n /// treasury and transaction fee and still satisfy the redeemer.\n /// @return redemptionTreasuryFeeDivisor Divisor used to compute the treasury\n /// fee taken from each redemption request and transferred to the\n /// treasury upon successful request finalization. That fee is\n /// computed as follows:\n /// `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each\n /// redemption request, the `redemptionTreasuryFeeDivisor` should\n /// be set to `50` because `1/50 = 0.02 = 2%`.\n /// @return redemptionTxMaxFee Maximum amount of BTC transaction fee that\n /// can be incurred by each redemption request being part of the\n /// given redemption transaction. If the maximum BTC transaction\n /// fee is exceeded, such transaction is considered a fraud.\n /// This is a per-redemption output max fee for the redemption\n /// transaction.\n /// @return redemptionTimeout Time after which the redemption request can be\n /// reported as timed out. It is counted from the moment when the\n /// redemption request was created via `requestRedemption` call.\n /// Reported timed out requests are cancelled and locked TBTC is\n /// returned to the redeemer in full amount.\n /// @return redemptionTimeoutSlashingAmount The amount of stake slashed\n /// from each member of a wallet for a redemption timeout.\n /// @return redemptionTimeoutNotifierRewardMultiplier The percentage of the\n /// notifier reward from the staking contract the notifier of a\n /// redemption timeout receives. The value is in the range [0, 100].\n function redemptionParameters()\n external\n view\n returns (\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint256 redemptionTimeout,\n uint96 redemptionTimeoutSlashingAmount,\n uint256 redemptionTimeoutNotifierRewardMultiplier\n )\n {\n redemptionDustThreshold = self.redemptionDustThreshold;\n redemptionTreasuryFeeDivisor = self.redemptionTreasuryFeeDivisor;\n redemptionTxMaxFee = self.redemptionTxMaxFee;\n redemptionTimeout = self.redemptionTimeout;\n redemptionTimeoutSlashingAmount = self.redemptionTimeoutSlashingAmount;\n redemptionTimeoutNotifierRewardMultiplier = self\n .redemptionTimeoutNotifierRewardMultiplier;\n }\n\n /// @notice Returns the current values of Bridge moving funds between\n /// wallets parameters.\n /// @return movingFundsTxMaxTotalFee Maximum amount of the total BTC\n /// transaction fee that is acceptable in a single moving funds\n /// transaction. This is a _total_ max fee for the entire moving\n /// funds transaction.\n /// @return movingFundsDustThreshold The minimal satoshi amount that makes\n /// sense to be transferred during the moving funds process. Moving\n /// funds wallets having their BTC balance below that value can\n /// begin closing immediately as transferring such a low value may\n /// not be possible due to BTC network fees.\n /// @return movingFundsTimeoutResetDelay Time after which the moving funds\n /// timeout can be reset in case the target wallet commitment\n /// cannot be submitted due to a lack of live wallets in the system.\n /// It is counted from the moment when the wallet was requested to\n /// move their funds and switched to the MovingFunds state or from\n /// the moment the timeout was reset the last time. Value in seconds\n /// This value should be lower than the value of the\n /// `movingFundsTimeout`.\n /// @return movingFundsTimeout Time after which the moving funds process\n /// can be reported as timed out. It is counted from the moment\n /// when the wallet was requested to move their funds and switched\n /// to the MovingFunds state. Value in seconds.\n /// @return movingFundsTimeoutSlashingAmount The amount of stake slashed\n /// from each member of a wallet for a moving funds timeout.\n /// @return movingFundsTimeoutNotifierRewardMultiplier The percentage of the\n /// notifier reward from the staking contract the notifier of a\n /// moving funds timeout receives. The value is in the range [0, 100].\n /// @return movedFundsSweepTxMaxTotalFee Maximum amount of the total BTC\n /// transaction fee that is acceptable in a single moved funds\n /// sweep transaction. This is a _total_ max fee for the entire\n /// moved funds sweep transaction.\n /// @return movedFundsSweepTimeout Time after which the moved funds sweep\n /// process can be reported as timed out. It is counted from the\n /// moment when the wallet was requested to sweep the received funds.\n /// Value in seconds.\n /// @return movedFundsSweepTimeoutSlashingAmount The amount of stake slashed\n /// from each member of a wallet for a moved funds sweep timeout.\n /// @return movedFundsSweepTimeoutNotifierRewardMultiplier The percentage\n /// of the notifier reward from the staking contract the notifier\n /// of a moved funds sweep timeout receives. The value is in the\n /// range [0, 100].\n function movingFundsParameters()\n external\n view\n returns (\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeoutResetDelay,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint256 movingFundsTimeoutNotifierRewardMultiplier,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint256 movedFundsSweepTimeoutNotifierRewardMultiplier\n )\n {\n movingFundsTxMaxTotalFee = self.movingFundsTxMaxTotalFee;\n movingFundsDustThreshold = self.movingFundsDustThreshold;\n movingFundsTimeoutResetDelay = self.movingFundsTimeoutResetDelay;\n movingFundsTimeout = self.movingFundsTimeout;\n movingFundsTimeoutSlashingAmount = self\n .movingFundsTimeoutSlashingAmount;\n movingFundsTimeoutNotifierRewardMultiplier = self\n .movingFundsTimeoutNotifierRewardMultiplier;\n movedFundsSweepTxMaxTotalFee = self.movedFundsSweepTxMaxTotalFee;\n movedFundsSweepTimeout = self.movedFundsSweepTimeout;\n movedFundsSweepTimeoutSlashingAmount = self\n .movedFundsSweepTimeoutSlashingAmount;\n movedFundsSweepTimeoutNotifierRewardMultiplier = self\n .movedFundsSweepTimeoutNotifierRewardMultiplier;\n }\n\n /// @return walletCreationPeriod Determines how frequently a new wallet\n /// creation can be requested. Value in seconds.\n /// @return walletCreationMinBtcBalance The minimum BTC threshold in satoshi\n /// that is used to decide about wallet creation.\n /// @return walletCreationMaxBtcBalance The maximum BTC threshold in satoshi\n /// that is used to decide about wallet creation.\n /// @return walletClosureMinBtcBalance The minimum BTC threshold in satoshi\n /// that is used to decide about wallet closure.\n /// @return walletMaxAge The maximum age of a wallet in seconds, after which\n /// the wallet moving funds process can be requested.\n /// @return walletMaxBtcTransfer The maximum BTC amount in satoshi than\n /// can be transferred to a single target wallet during the moving\n /// funds process.\n /// @return walletClosingPeriod Determines the length of the wallet closing\n /// period, i.e. the period when the wallet remains in the Closing\n /// state and can be subject of deposit fraud challenges. Value\n /// in seconds.\n function walletParameters()\n external\n view\n returns (\n uint32 walletCreationPeriod,\n uint64 walletCreationMinBtcBalance,\n uint64 walletCreationMaxBtcBalance,\n uint64 walletClosureMinBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n )\n {\n walletCreationPeriod = self.walletCreationPeriod;\n walletCreationMinBtcBalance = self.walletCreationMinBtcBalance;\n walletCreationMaxBtcBalance = self.walletCreationMaxBtcBalance;\n walletClosureMinBtcBalance = self.walletClosureMinBtcBalance;\n walletMaxAge = self.walletMaxAge;\n walletMaxBtcTransfer = self.walletMaxBtcTransfer;\n walletClosingPeriod = self.walletClosingPeriod;\n }\n\n /// @notice Returns the current values of Bridge fraud parameters.\n /// @return fraudChallengeDepositAmount The amount of ETH in wei the party\n /// challenging the wallet for fraud needs to deposit.\n /// @return fraudChallengeDefeatTimeout The amount of time the wallet has to\n /// defeat a fraud challenge.\n /// @return fraudSlashingAmount The amount slashed from each wallet member\n /// for committing a fraud.\n /// @return fraudNotifierRewardMultiplier The percentage of the notifier\n /// reward from the staking contract the notifier of a fraud\n /// receives. The value is in the range [0, 100].\n function fraudParameters()\n external\n view\n returns (\n uint256 fraudChallengeDepositAmount,\n uint256 fraudChallengeDefeatTimeout,\n uint96 fraudSlashingAmount,\n uint256 fraudNotifierRewardMultiplier\n )\n {\n fraudChallengeDepositAmount = self.fraudChallengeDepositAmount;\n fraudChallengeDefeatTimeout = self.fraudChallengeDefeatTimeout;\n fraudSlashingAmount = self.fraudSlashingAmount;\n fraudNotifierRewardMultiplier = self.fraudNotifierRewardMultiplier;\n }\n\n /// @notice Returns the addresses of contracts Bridge is interacting with.\n /// @return bank Address of the Bank the Bridge belongs to.\n /// @return relay Address of the Bitcoin relay providing the current Bitcoin\n /// network difficulty.\n /// @return ecdsaWalletRegistry Address of the ECDSA Wallet Registry.\n function contractReferences()\n external\n view\n returns (\n Bank bank,\n IRelay relay,\n EcdsaWalletRegistry ecdsaWalletRegistry\n )\n {\n bank = self.bank;\n relay = self.relay;\n ecdsaWalletRegistry = self.ecdsaWalletRegistry;\n }\n\n /// @notice Address where the deposit treasury fees will be sent to.\n /// Treasury takes part in the operators rewarding process.\n function treasury() external view returns (address) {\n return self.treasury;\n }\n\n /// @notice The number of confirmations on the Bitcoin chain required to\n /// successfully evaluate an SPV proof.\n function txProofDifficultyFactor() external view returns (uint256) {\n return self.txProofDifficultyFactor;\n }\n}\n"
129
+ },
130
+ "@keep-network/ecdsa/contracts/api/IWalletOwner.sol": {
131
+ "content": "// SPDX-License-Identifier: MIT\n//\n// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄\n// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓\n// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓\n// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀\n// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌\n// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓\n//\n// Trust math, not hardware.\n\npragma solidity ^0.8.9;\n\ninterface IWalletOwner {\n /// @notice Callback function executed once a new wallet is created.\n /// @dev Should be callable only by the Wallet Registry.\n /// @param walletID Wallet's unique identifier.\n /// @param publicKeyY Wallet's public key's X coordinate.\n /// @param publicKeyY Wallet's public key's Y coordinate.\n function __ecdsaWalletCreatedCallback(\n bytes32 walletID,\n bytes32 publicKeyX,\n bytes32 publicKeyY\n ) external;\n\n /// @notice Callback function executed once a wallet heartbeat failure\n /// is detected.\n /// @dev Should be callable only by the Wallet Registry.\n /// @param walletID Wallet's unique identifier.\n /// @param publicKeyY Wallet's public key's X coordinate.\n /// @param publicKeyY Wallet's public key's Y coordinate.\n function __ecdsaWalletHeartbeatFailedCallback(\n bytes32 walletID,\n bytes32 publicKeyX,\n bytes32 publicKeyY\n ) external;\n}\n"
132
+ },
133
+ "contracts/bridge/IRelay.sol": {
134
+ "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\n/// @title Interface for the Bitcoin relay\n/// @notice Contains only the methods needed by tBTC v2. The Bitcoin relay\n/// provides the difficulty of the previous and current epoch. One\n/// difficulty epoch spans 2016 blocks.\ninterface IRelay {\n /// @notice Returns the difficulty of the current epoch.\n function getCurrentEpochDifficulty() external view returns (uint256);\n\n /// @notice Returns the difficulty of the previous epoch.\n function getPrevEpochDifficulty() external view returns (uint256);\n}\n"
135
+ },
136
+ "contracts/bridge/BridgeState.sol": {
137
+ "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {IWalletRegistry as EcdsaWalletRegistry} from \"@keep-network/ecdsa/contracts/api/IWalletRegistry.sol\";\n\nimport \"./IRelay.sol\";\nimport \"./Deposit.sol\";\nimport \"./Redemption.sol\";\nimport \"./Fraud.sol\";\nimport \"./Wallets.sol\";\nimport \"./MovingFunds.sol\";\n\nimport \"../bank/Bank.sol\";\n\nlibrary BridgeState {\n struct Storage {\n // Address of the Bank the Bridge belongs to.\n Bank bank;\n // Bitcoin relay providing the current Bitcoin network difficulty.\n IRelay relay;\n // ECDSA Wallet Registry contract handle.\n EcdsaWalletRegistry ecdsaWalletRegistry;\n // The number of confirmations on the Bitcoin chain required to\n // successfully evaluate an SPV proof.\n uint256 txProofDifficultyFactor;\n // Address where the deposit and redemption treasury fees will be sent\n // to. Treasury takes part in the operators rewarding process.\n address treasury;\n // The minimal amount that can be requested to deposit.\n // Value of this parameter must take into account the value of\n // `depositTreasuryFeeDivisor` and `depositTxMaxFee` parameters in order\n // to make requests that can incur the treasury and transaction fee and\n // still satisfy the depositor.\n uint64 depositDustThreshold;\n // Divisor used to compute the treasury fee taken from each deposit and\n // transferred to the treasury upon sweep proof submission. That fee is\n // computed as follows:\n // `treasuryFee = depositedAmount / depositTreasuryFeeDivisor`\n // For example, if the treasury fee needs to be 2% of each deposit,\n // the `depositTreasuryFeeDivisor` should be set to `50` because\n // `1/50 = 0.02 = 2%`.\n uint64 depositTreasuryFeeDivisor;\n // Maximum amount of BTC transaction fee that can be incurred by each\n // swept deposit being part of the given sweep transaction. If the\n // maximum BTC transaction fee is exceeded, such transaction is\n // considered a fraud.\n //\n // This is a per-deposit input max fee for the sweep transaction.\n uint64 depositTxMaxFee;\n // Collection of all revealed deposits indexed by\n // `keccak256(fundingTxHash | fundingOutputIndex)`.\n // The `fundingTxHash` is `bytes32` (ordered as in Bitcoin internally)\n // and `fundingOutputIndex` an `uint32`. This mapping may contain valid\n // and invalid deposits and the wallet is responsible for validating\n // them before attempting to execute a sweep.\n mapping(uint256 => Deposit.DepositRequest) deposits;\n // Indicates if the vault with the given address is trusted or not.\n // Depositors can route their revealed deposits only to trusted vaults\n // and have trusted vaults notified about new deposits as soon as these\n // deposits get swept. Vaults not trusted by the Bridge can still be\n // used by Bank balance owners on their own responsibility - anyone can\n // approve their Bank balance to any address.\n mapping(address => bool) isVaultTrusted;\n // Maximum amount of the total BTC transaction fee that is acceptable in\n // a single moving funds transaction.\n //\n // This is a TOTAL max fee for the moving funds transaction. Note\n // that `depositTxMaxFee` is per single deposit and `redemptionTxMaxFee`\n // if per single redemption. `movingFundsTxMaxTotalFee` is a total\n // fee for the entire transaction.\n uint64 movingFundsTxMaxTotalFee;\n // The minimal satoshi amount that makes sense to be transferred during\n // the moving funds process. Moving funds wallets having their BTC\n // balance below that value can begin closing immediately as\n // transferring such a low value may not be possible due to\n // BTC network fees. The value of this parameter must always be lower\n // than `redemptionDustThreshold` in order to prevent redemption requests\n // with values lower or equal to `movingFundsDustThreshold`.\n uint64 movingFundsDustThreshold;\n // Time after which the moving funds timeout can be reset in case the\n // target wallet commitment cannot be submitted due to a lack of live\n // wallets in the system. It is counted from the moment when the wallet\n // was requested to move their funds and switched to the MovingFunds\n // state or from the moment the timeout was reset the last time.\n // Value in seconds. This value should be lower than the value\n // of the `movingFundsTimeout`.\n uint32 movingFundsTimeoutResetDelay;\n // Time after which the moving funds process can be reported as\n // timed out. It is counted from the moment when the wallet\n // was requested to move their funds and switched to the MovingFunds\n // state. Value in seconds.\n uint32 movingFundsTimeout;\n // The amount of stake slashed from each member of a wallet for a moving\n // funds timeout.\n uint96 movingFundsTimeoutSlashingAmount;\n // The percentage of the notifier reward from the staking contract\n // the notifier of a moving funds timeout receives. The value is in the\n // range [0, 100].\n uint256 movingFundsTimeoutNotifierRewardMultiplier;\n // Maximum amount of the total BTC transaction fee that is acceptable in\n // a single moved funds sweep transaction.\n //\n // This is a TOTAL max fee for the moved funds sweep transaction. Note\n // that `depositTxMaxFee` is per single deposit and `redemptionTxMaxFee`\n // if per single redemption. `movedFundsSweepTxMaxTotalFee` is a total\n // fee for the entire transaction.\n uint64 movedFundsSweepTxMaxTotalFee;\n // Time after which the moved funds sweep process can be reported as\n // timed out. It is counted from the moment when the recipient wallet\n // was requested to sweep the received funds. Value in seconds.\n uint32 movedFundsSweepTimeout;\n // The amount of stake slashed from each member of a wallet for a moved\n // funds sweep timeout.\n uint96 movedFundsSweepTimeoutSlashingAmount;\n // The percentage of the notifier reward from the staking contract\n // the notifier of a moved funds sweep timeout receives. The value is\n // in the range [0, 100].\n uint256 movedFundsSweepTimeoutNotifierRewardMultiplier;\n // Collection of all moved funds sweep requests indexed by\n // `keccak256(movingFundsTxHash | movingFundsOutputIndex)`.\n // The `movingFundsTxHash` is `bytes32` (ordered as in Bitcoin\n // internally) and `movingFundsOutputIndex` an `uint32`. Each entry\n // is actually an UTXO representing the moved funds and is supposed\n // to be swept with the current main UTXO of the recipient wallet.\n mapping(uint256 => MovingFunds.MovedFundsSweepRequest) movedFundsSweepRequests;\n // The minimal amount that can be requested for redemption.\n // Value of this parameter must take into account the value of\n // `redemptionTreasuryFeeDivisor` and `redemptionTxMaxFee`\n // parameters in order to make requests that can incur the\n // treasury and transaction fee and still satisfy the redeemer.\n // Additionally, the value of this parameter must always be greater\n // than `movingFundsDustThreshold` in order to prevent redemption\n // requests with values lower or equal to `movingFundsDustThreshold`.\n uint64 redemptionDustThreshold;\n // Divisor used to compute the treasury fee taken from each\n // redemption request and transferred to the treasury upon\n // successful request finalization. That fee is computed as follows:\n // `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`\n // For example, if the treasury fee needs to be 2% of each\n // redemption request, the `redemptionTreasuryFeeDivisor` should\n // be set to `50` because `1/50 = 0.02 = 2%`.\n uint64 redemptionTreasuryFeeDivisor;\n // Maximum amount of BTC transaction fee that can be incurred by\n // each redemption request being part of the given redemption\n // transaction. If the maximum BTC transaction fee is exceeded, such\n // transaction is considered a fraud.\n //\n // This is a per-redemption output max fee for the redemption\n // transaction.\n uint64 redemptionTxMaxFee;\n // Time after which the redemption request can be reported as\n // timed out. It is counted from the moment when the redemption\n // request was created via `requestRedemption` call. Reported\n // timed out requests are cancelled and locked TBTC is returned\n // to the redeemer in full amount.\n uint256 redemptionTimeout;\n // The amount of stake slashed from each member of a wallet for a\n // redemption timeout.\n uint96 redemptionTimeoutSlashingAmount;\n // The percentage of the notifier reward from the staking contract\n // the notifier of a redemption timeout receives. The value is in the\n // range [0, 100].\n uint256 redemptionTimeoutNotifierRewardMultiplier;\n // Collection of all pending redemption requests indexed by\n // redemption key built as\n // `keccak256(walletPubKeyHash | redeemerOutputScript)`.\n // The `walletPubKeyHash` is the 20-byte wallet's public key hash\n // (computed using Bitcoin HASH160 over the compressed ECDSA\n // public key) and `redeemerOutputScript` is a Bitcoin script\n // (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock\n // redeemed BTC as requested by the redeemer. Requests are added\n // to this mapping by the `requestRedemption` method (duplicates\n // not allowed) and are removed by one of the following methods:\n // - `submitRedemptionProof` in case the request was handled\n // successfully,\n // - `notifyRedemptionTimeout` in case the request was reported\n // to be timed out.\n mapping(uint256 => Redemption.RedemptionRequest) pendingRedemptions;\n // Collection of all timed out redemptions requests indexed by\n // redemption key built as\n // `keccak256(walletPubKeyHash | redeemerOutputScript)`. The\n // `walletPubKeyHash` is the 20-byte wallet's public key hash\n // (computed using Bitcoin HASH160 over the compressed ECDSA\n // public key) and `redeemerOutputScript` is the Bitcoin script\n // (P2PKH, P2WPKH, P2SH or P2WSH) that is involved in the timed\n // out request. Timed out requests are stored in this mapping to\n // avoid slashing the wallets multiple times for the same timeout.\n // Only one method can add to this mapping:\n // - `notifyRedemptionTimeout` which puts the redemption key to this\n // mapping basing on a timed out request stored previously in\n // `pendingRedemptions` mapping.\n mapping(uint256 => Redemption.RedemptionRequest) timedOutRedemptions;\n // The amount of ETH in wei the party challenging the wallet for fraud\n // needs to deposit.\n uint256 fraudChallengeDepositAmount;\n // The amount of time the wallet has to defeat a fraud challenge.\n uint256 fraudChallengeDefeatTimeout;\n // The amount of stake slashed from each member of a wallet for a fraud.\n uint96 fraudSlashingAmount;\n // The percentage of the notifier reward from the staking contract\n // the notifier of a fraud receives. The value is in the range [0, 100].\n uint256 fraudNotifierRewardMultiplier;\n // Collection of all submitted fraud challenges indexed by challenge\n // key built as `keccak256(walletPublicKey|sighash)`.\n mapping(uint256 => Fraud.FraudChallenge) fraudChallenges;\n // Collection of main UTXOs that are honestly spent indexed by\n // `keccak256(fundingTxHash | fundingOutputIndex)`. The `fundingTxHash`\n // is `bytes32` (ordered as in Bitcoin internally) and\n // `fundingOutputIndex` an `uint32`. A main UTXO is considered honestly\n // spent if it was used as an input of a transaction that have been\n // proven in the Bridge.\n mapping(uint256 => bool) spentMainUTXOs;\n // Determines how frequently a new wallet creation can be requested.\n // Value in seconds.\n uint32 walletCreationPeriod;\n // The minimum BTC threshold in satoshi that is used to decide about\n // wallet creation. Specifically, we allow for the creation of a new\n // wallet if the active wallet is old enough and their amount of BTC\n // is greater than or equal this threshold.\n uint64 walletCreationMinBtcBalance;\n // The maximum BTC threshold in satoshi that is used to decide about\n // wallet creation. Specifically, we allow for the creation of a new\n // wallet if the active wallet's amount of BTC is greater than or equal\n // this threshold, regardless of the active wallet's age.\n uint64 walletCreationMaxBtcBalance;\n // The minimum BTC threshold in satoshi that is used to decide about\n // wallet closing. Specifically, we allow for the closure of the given\n // wallet if their amount of BTC is lesser than this threshold,\n // regardless of the wallet's age.\n uint64 walletClosureMinBtcBalance;\n // The maximum age of a wallet in seconds, after which the wallet\n // moving funds process can be requested.\n uint32 walletMaxAge;\n // 20-byte wallet public key hash being reference to the currently\n // active wallet. Can be unset to the zero value under certain\n // circumstances.\n bytes20 activeWalletPubKeyHash;\n // The current number of wallets in the Live state.\n uint32 liveWalletsCount;\n // The maximum BTC amount in satoshi than can be transferred to a single\n // target wallet during the moving funds process.\n uint64 walletMaxBtcTransfer;\n // Determines the length of the wallet closing period, i.e. the period\n // when the wallet remains in the Closing state and can be subject\n // of deposit fraud challenges. This value is in seconds and should be\n // greater than the deposit refund time plus some time margin.\n uint32 walletClosingPeriod;\n // Maps the 20-byte wallet public key hash (computed using Bitcoin\n // HASH160 over the compressed ECDSA public key) to the basic wallet\n // information like state and pending redemptions value.\n mapping(bytes20 => Wallets.Wallet) registeredWallets;\n // Reserved storage space in case we need to add more variables.\n // The convention from OpenZeppelin suggests the storage space should\n // add up to 50 slots. Here we want to have more slots as there are\n // planned upgrades of the Bridge contract. If more entires are added to\n // the struct in the upcoming versions we need to reduce the array size.\n // See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n // slither-disable-next-line unused-state\n uint256[50] __gap;\n }\n\n event DepositParametersUpdated(\n uint64 depositDustThreshold,\n uint64 depositTreasuryFeeDivisor,\n uint64 depositTxMaxFee\n );\n\n event RedemptionParametersUpdated(\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint256 redemptionTimeout,\n uint96 redemptionTimeoutSlashingAmount,\n uint256 redemptionTimeoutNotifierRewardMultiplier\n );\n\n event MovingFundsParametersUpdated(\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeoutResetDelay,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint256 movingFundsTimeoutNotifierRewardMultiplier,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint256 movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n\n event WalletParametersUpdated(\n uint32 walletCreationPeriod,\n uint64 walletCreationMinBtcBalance,\n uint64 walletCreationMaxBtcBalance,\n uint64 walletClosureMinBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n );\n\n event FraudParametersUpdated(\n uint256 fraudChallengeDepositAmount,\n uint256 fraudChallengeDefeatTimeout,\n uint96 fraudSlashingAmount,\n uint256 fraudNotifierRewardMultiplier\n );\n\n /// @notice Updates parameters of deposits.\n /// @param _depositDustThreshold New value of the deposit dust threshold in\n /// satoshis. It is the minimal amount that can be requested to\n //// deposit. Value of this parameter must take into account the value\n /// of `depositTreasuryFeeDivisor` and `depositTxMaxFee` parameters\n /// in order to make requests that can incur the treasury and\n /// transaction fee and still satisfy the depositor.\n /// @param _depositTreasuryFeeDivisor New value of the treasury fee divisor.\n /// It is the divisor used to compute the treasury fee taken from\n /// each deposit and transferred to the treasury upon sweep proof\n /// submission. That fee is computed as follows:\n /// `treasuryFee = depositedAmount / depositTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each deposit,\n /// the `depositTreasuryFeeDivisor` should be set to `50`\n /// because `1/50 = 0.02 = 2%`.\n /// @param _depositTxMaxFee New value of the deposit tx max fee in satoshis.\n /// It is the maximum amount of BTC transaction fee that can\n /// be incurred by each swept deposit being part of the given sweep\n /// transaction. If the maximum BTC transaction fee is exceeded,\n /// such transaction is considered a fraud.\n /// @dev Requirements:\n /// - Deposit dust threshold must be greater than zero,\n /// - Deposit treasury fee divisor must be greater than zero,\n /// - Deposit transaction max fee must be greater than zero.\n function updateDepositParameters(\n Storage storage self,\n uint64 _depositDustThreshold,\n uint64 _depositTreasuryFeeDivisor,\n uint64 _depositTxMaxFee\n ) internal {\n require(\n _depositDustThreshold > 0,\n \"Deposit dust threshold must be greater than zero\"\n );\n\n require(\n _depositTreasuryFeeDivisor > 0,\n \"Deposit treasury fee divisor must be greater than zero\"\n );\n\n require(\n _depositTxMaxFee > 0,\n \"Deposit transaction max fee must be greater than zero\"\n );\n\n self.depositDustThreshold = _depositDustThreshold;\n self.depositTreasuryFeeDivisor = _depositTreasuryFeeDivisor;\n self.depositTxMaxFee = _depositTxMaxFee;\n\n emit DepositParametersUpdated(\n _depositDustThreshold,\n _depositTreasuryFeeDivisor,\n _depositTxMaxFee\n );\n }\n\n /// @notice Updates parameters of redemptions.\n /// @param _redemptionDustThreshold New value of the redemption dust\n /// threshold in satoshis. It is the minimal amount that can be\n /// requested for redemption. Value of this parameter must take into\n /// account the value of `redemptionTreasuryFeeDivisor` and\n /// `redemptionTxMaxFee` parameters in order to make requests that\n /// can incur the treasury and transaction fee and still satisfy the\n /// redeemer.\n /// @param _redemptionTreasuryFeeDivisor New value of the redemption\n /// treasury fee divisor. It is the divisor used to compute the\n /// treasury fee taken from each redemption request and transferred\n /// to the treasury upon successful request finalization. That fee is\n /// computed as follows:\n /// `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each\n /// redemption request, the `redemptionTreasuryFeeDivisor` should\n /// be set to `50` because `1/50 = 0.02 = 2%`.\n /// @param _redemptionTxMaxFee New value of the redemption transaction max\n /// fee in satoshis. It is the maximum amount of BTC transaction fee\n /// that can be incurred by each redemption request being part of the\n /// given redemption transaction. If the maximum BTC transaction fee\n /// is exceeded, such transaction is considered a fraud.\n /// This is a per-redemption output max fee for the redemption\n /// transaction.\n /// @param _redemptionTimeout New value of the redemption timeout in seconds.\n /// It is the time after which the redemption request can be reported\n /// as timed out. It is counted from the moment when the redemption\n /// request was created via `requestRedemption` call. Reported timed\n /// out requests are cancelled and locked TBTC is returned to the\n /// redeemer in full amount.\n /// @param _redemptionTimeoutSlashingAmount New value of the redemption\n /// timeout slashing amount in T, it is the amount slashed from each\n /// wallet member for redemption timeout.\n /// @param _redemptionTimeoutNotifierRewardMultiplier New value of the\n /// redemption timeout notifier reward multiplier as percentage,\n /// it determines the percentage of the notifier reward from the\n /// staking contact the notifier of a redemption timeout receives.\n /// The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Redemption dust threshold must be greater than moving funds dust\n /// threshold,\n /// - Redemption treasury fee divisor must be greater than zero,\n /// - Redemption transaction max fee must be greater than zero,\n /// - Redemption timeout must be greater than zero,\n /// - Redemption timeout notifier reward multiplier must be in the\n /// range [0, 100].\n function updateRedemptionParameters(\n Storage storage self,\n uint64 _redemptionDustThreshold,\n uint64 _redemptionTreasuryFeeDivisor,\n uint64 _redemptionTxMaxFee,\n uint256 _redemptionTimeout,\n uint96 _redemptionTimeoutSlashingAmount,\n uint256 _redemptionTimeoutNotifierRewardMultiplier\n ) internal {\n require(\n _redemptionDustThreshold > self.movingFundsDustThreshold,\n \"Redemption dust threshold must be greater than moving funds dust threshold\"\n );\n\n require(\n _redemptionTreasuryFeeDivisor > 0,\n \"Redemption treasury fee divisor must be greater than zero\"\n );\n\n require(\n _redemptionTxMaxFee > 0,\n \"Redemption transaction max fee must be greater than zero\"\n );\n\n require(\n _redemptionTimeout > 0,\n \"Redemption timeout must be greater than zero\"\n );\n\n require(\n _redemptionTimeoutNotifierRewardMultiplier <= 100,\n \"Redemption timeout notifier reward multiplier must be in the range [0, 100]\"\n );\n\n self.redemptionDustThreshold = _redemptionDustThreshold;\n self.redemptionTreasuryFeeDivisor = _redemptionTreasuryFeeDivisor;\n self.redemptionTxMaxFee = _redemptionTxMaxFee;\n self.redemptionTimeout = _redemptionTimeout;\n self.redemptionTimeoutSlashingAmount = _redemptionTimeoutSlashingAmount;\n self\n .redemptionTimeoutNotifierRewardMultiplier = _redemptionTimeoutNotifierRewardMultiplier;\n\n emit RedemptionParametersUpdated(\n _redemptionDustThreshold,\n _redemptionTreasuryFeeDivisor,\n _redemptionTxMaxFee,\n _redemptionTimeout,\n _redemptionTimeoutSlashingAmount,\n _redemptionTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Updates parameters of moving funds.\n /// @param _movingFundsTxMaxTotalFee New value of the moving funds transaction\n /// max total fee in satoshis. It is the maximum amount of the total\n /// BTC transaction fee that is acceptable in a single moving funds\n /// transaction. This is a _total_ max fee for the entire moving\n /// funds transaction.\n /// @param _movingFundsDustThreshold New value of the moving funds dust\n /// threshold. It is the minimal satoshi amount that makes sense to\n /// be transferred during the moving funds process. Moving funds\n /// wallets having their BTC balance below that value can begin\n /// closing immediately as transferring such a low value may not be\n /// possible due to BTC network fees.\n /// @param _movingFundsTimeoutResetDelay New value of the moving funds\n /// timeout reset delay in seconds. It is the time after which the\n /// moving funds timeout can be reset in case the target wallet\n /// commitment cannot be submitted due to a lack of live wallets\n /// in the system. It is counted from the moment when the wallet\n /// was requested to move their funds and switched to the MovingFunds\n /// state or from the moment the timeout was reset the last time.\n /// @param _movingFundsTimeout New value of the moving funds timeout in\n /// seconds. It is the time after which the moving funds process can\n /// be reported as timed out. It is counted from the moment when the\n /// wallet was requested to move their funds and switched to the\n /// MovingFunds state.\n /// @param _movingFundsTimeoutSlashingAmount New value of the moving funds\n /// timeout slashing amount in T, it is the amount slashed from each\n /// wallet member for moving funds timeout.\n /// @param _movingFundsTimeoutNotifierRewardMultiplier New value of the\n /// moving funds timeout notifier reward multiplier as percentage,\n /// it determines the percentage of the notifier reward from the\n /// staking contact the notifier of a moving funds timeout receives.\n /// The value must be in the range [0, 100].\n /// @param _movedFundsSweepTxMaxTotalFee New value of the moved funds sweep\n /// transaction max total fee in satoshis. It is the maximum amount\n /// of the total BTC transaction fee that is acceptable in a single\n /// moved funds sweep transaction. This is a _total_ max fee for the\n /// entire moved funds sweep transaction.\n /// @param _movedFundsSweepTimeout New value of the moved funds sweep\n /// timeout in seconds. It is the time after which the moved funds\n /// sweep process can be reported as timed out. It is counted from\n /// the moment when the wallet was requested to sweep the received\n /// funds.\n /// @param _movedFundsSweepTimeoutSlashingAmount New value of the moved\n /// funds sweep timeout slashing amount in T, it is the amount\n /// slashed from each wallet member for moved funds sweep timeout.\n /// @param _movedFundsSweepTimeoutNotifierRewardMultiplier New value of\n /// the moved funds sweep timeout notifier reward multiplier as\n /// percentage, it determines the percentage of the notifier reward\n /// from the staking contact the notifier of a moved funds sweep\n /// timeout receives. The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Moving funds transaction max total fee must be greater than zero,\n /// - Moving funds dust threshold must be greater than zero and lower\n /// than the redemption dust threshold,\n /// - Moving funds timeout reset delay must be greater than zero,\n /// - Moving funds timeout must be greater than the moving funds\n /// timeout reset delay,\n /// - Moving funds timeout notifier reward multiplier must be in the\n /// range [0, 100],\n /// - Moved funds sweep transaction max total fee must be greater than zero,\n /// - Moved funds sweep timeout must be greater than zero,\n /// - Moved funds sweep timeout notifier reward multiplier must be in the\n /// range [0, 100].\n function updateMovingFundsParameters(\n Storage storage self,\n uint64 _movingFundsTxMaxTotalFee,\n uint64 _movingFundsDustThreshold,\n uint32 _movingFundsTimeoutResetDelay,\n uint32 _movingFundsTimeout,\n uint96 _movingFundsTimeoutSlashingAmount,\n uint256 _movingFundsTimeoutNotifierRewardMultiplier,\n uint64 _movedFundsSweepTxMaxTotalFee,\n uint32 _movedFundsSweepTimeout,\n uint96 _movedFundsSweepTimeoutSlashingAmount,\n uint256 _movedFundsSweepTimeoutNotifierRewardMultiplier\n ) internal {\n require(\n _movingFundsTxMaxTotalFee > 0,\n \"Moving funds transaction max total fee must be greater than zero\"\n );\n\n require(\n _movingFundsDustThreshold > 0 &&\n _movingFundsDustThreshold < self.redemptionDustThreshold,\n \"Moving funds dust threshold must be greater than zero and lower than redemption dust threshold\"\n );\n\n require(\n _movingFundsTimeoutResetDelay > 0,\n \"Moving funds timeout reset delay must be greater than zero\"\n );\n\n require(\n _movingFundsTimeout > _movingFundsTimeoutResetDelay,\n \"Moving funds timeout must be greater than its reset delay\"\n );\n\n require(\n _movingFundsTimeoutNotifierRewardMultiplier <= 100,\n \"Moving funds timeout notifier reward multiplier must be in the range [0, 100]\"\n );\n\n require(\n _movedFundsSweepTxMaxTotalFee > 0,\n \"Moved funds sweep transaction max total fee must be greater than zero\"\n );\n\n require(\n _movedFundsSweepTimeout > 0,\n \"Moved funds sweep timeout must be greater than zero\"\n );\n\n require(\n _movedFundsSweepTimeoutNotifierRewardMultiplier <= 100,\n \"Moved funds sweep timeout notifier reward multiplier must be in the range [0, 100]\"\n );\n\n self.movingFundsTxMaxTotalFee = _movingFundsTxMaxTotalFee;\n self.movingFundsDustThreshold = _movingFundsDustThreshold;\n self.movingFundsTimeoutResetDelay = _movingFundsTimeoutResetDelay;\n self.movingFundsTimeout = _movingFundsTimeout;\n self\n .movingFundsTimeoutSlashingAmount = _movingFundsTimeoutSlashingAmount;\n self\n .movingFundsTimeoutNotifierRewardMultiplier = _movingFundsTimeoutNotifierRewardMultiplier;\n self.movedFundsSweepTxMaxTotalFee = _movedFundsSweepTxMaxTotalFee;\n self.movedFundsSweepTimeout = _movedFundsSweepTimeout;\n self\n .movedFundsSweepTimeoutSlashingAmount = _movedFundsSweepTimeoutSlashingAmount;\n self\n .movedFundsSweepTimeoutNotifierRewardMultiplier = _movedFundsSweepTimeoutNotifierRewardMultiplier;\n\n emit MovingFundsParametersUpdated(\n _movingFundsTxMaxTotalFee,\n _movingFundsDustThreshold,\n _movingFundsTimeoutResetDelay,\n _movingFundsTimeout,\n _movingFundsTimeoutSlashingAmount,\n _movingFundsTimeoutNotifierRewardMultiplier,\n _movedFundsSweepTxMaxTotalFee,\n _movedFundsSweepTimeout,\n _movedFundsSweepTimeoutSlashingAmount,\n _movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Updates parameters of wallets.\n /// @param _walletCreationPeriod New value of the wallet creation period in\n /// seconds, determines how frequently a new wallet creation can be\n /// requested.\n /// @param _walletCreationMinBtcBalance New value of the wallet minimum BTC\n /// balance in satoshi, used to decide about wallet creation.\n /// @param _walletCreationMaxBtcBalance New value of the wallet maximum BTC\n /// balance in satoshi, used to decide about wallet creation.\n /// @param _walletClosureMinBtcBalance New value of the wallet minimum BTC\n /// balance in satoshi, used to decide about wallet closure.\n /// @param _walletMaxAge New value of the wallet maximum age in seconds,\n /// indicates the maximum age of a wallet in seconds, after which\n /// the wallet moving funds process can be requested.\n /// @param _walletMaxBtcTransfer New value of the wallet maximum BTC transfer\n /// in satoshi, determines the maximum amount that can be transferred\n /// to a single target wallet during the moving funds process.\n /// @param _walletClosingPeriod New value of the wallet closing period in\n /// seconds, determines the length of the wallet closing period,\n // i.e. the period when the wallet remains in the Closing state\n // and can be subject of deposit fraud challenges.\n /// @dev Requirements:\n /// - Wallet minimum BTC balance must be greater than zero,\n /// - Wallet maximum BTC balance must be greater than the wallet\n /// minimum BTC balance,\n /// - Wallet maximum BTC transfer must be greater than zero,\n /// - Wallet closing period must be greater than zero.\n function updateWalletParameters(\n Storage storage self,\n uint32 _walletCreationPeriod,\n uint64 _walletCreationMinBtcBalance,\n uint64 _walletCreationMaxBtcBalance,\n uint64 _walletClosureMinBtcBalance,\n uint32 _walletMaxAge,\n uint64 _walletMaxBtcTransfer,\n uint32 _walletClosingPeriod\n ) internal {\n require(\n _walletCreationMaxBtcBalance > _walletCreationMinBtcBalance,\n \"Wallet creation maximum BTC balance must be greater than the creation minimum BTC balance\"\n );\n require(\n _walletClosureMinBtcBalance > 0,\n \"Wallet closure minimum BTC balance must be greater than zero\"\n );\n require(\n _walletMaxBtcTransfer > 0,\n \"Wallet maximum BTC transfer must be greater than zero\"\n );\n require(\n _walletClosingPeriod > 0,\n \"Wallet closing period must be greater than zero\"\n );\n\n self.walletCreationPeriod = _walletCreationPeriod;\n self.walletCreationMinBtcBalance = _walletCreationMinBtcBalance;\n self.walletCreationMaxBtcBalance = _walletCreationMaxBtcBalance;\n self.walletClosureMinBtcBalance = _walletClosureMinBtcBalance;\n self.walletMaxAge = _walletMaxAge;\n self.walletMaxBtcTransfer = _walletMaxBtcTransfer;\n self.walletClosingPeriod = _walletClosingPeriod;\n\n emit WalletParametersUpdated(\n _walletCreationPeriod,\n _walletCreationMinBtcBalance,\n _walletCreationMaxBtcBalance,\n _walletClosureMinBtcBalance,\n _walletMaxAge,\n _walletMaxBtcTransfer,\n _walletClosingPeriod\n );\n }\n\n /// @notice Updates parameters related to frauds.\n /// @param _fraudChallengeDepositAmount New value of the fraud challenge\n /// deposit amount in wei, it is the amount of ETH the party\n /// challenging the wallet for fraud needs to deposit.\n /// @param _fraudChallengeDefeatTimeout New value of the challenge defeat\n /// timeout in seconds, it is the amount of time the wallet has to\n /// defeat a fraud challenge. The value must be greater than zero.\n /// @param _fraudSlashingAmount New value of the fraud slashing amount in T,\n /// it is the amount slashed from each wallet member for committing\n /// a fraud.\n /// @param _fraudNotifierRewardMultiplier New value of the fraud notifier\n /// reward multiplier as percentage, it determines the percentage of\n /// the notifier reward from the staking contact the notifier of\n /// a fraud receives. The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Fraud challenge defeat timeout must be greater than 0,\n /// - Fraud notifier reward multiplier must be in the range [0, 100].\n function updateFraudParameters(\n Storage storage self,\n uint256 _fraudChallengeDepositAmount,\n uint256 _fraudChallengeDefeatTimeout,\n uint96 _fraudSlashingAmount,\n uint256 _fraudNotifierRewardMultiplier\n ) internal {\n require(\n _fraudChallengeDefeatTimeout > 0,\n \"Fraud challenge defeat timeout must be greater than zero\"\n );\n\n require(\n _fraudNotifierRewardMultiplier <= 100,\n \"Fraud notifier reward multiplier must be in the range [0, 100]\"\n );\n\n self.fraudChallengeDepositAmount = _fraudChallengeDepositAmount;\n self.fraudChallengeDefeatTimeout = _fraudChallengeDefeatTimeout;\n self.fraudSlashingAmount = _fraudSlashingAmount;\n self.fraudNotifierRewardMultiplier = _fraudNotifierRewardMultiplier;\n\n emit FraudParametersUpdated(\n _fraudChallengeDepositAmount,\n _fraudChallengeDefeatTimeout,\n _fraudSlashingAmount,\n _fraudNotifierRewardMultiplier\n );\n }\n}\n"
138
+ },
139
+ "contracts/bridge/Deposit.sol": {
140
+ "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\nimport {BytesLib} from \"@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol\";\n\nimport \"./BitcoinTx.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Wallets.sol\";\n\n/// @title Bridge deposit\n/// @notice The library handles the logic for revealing Bitcoin deposits to\n/// the Bridge.\n/// @dev The depositor puts together a P2SH or P2WSH address to deposit the\n/// funds. This script is unique to each depositor and looks like this:\n///\n/// ```\n/// <depositorAddress> DROP\n/// <blindingFactor> DROP\n/// DUP HASH160 <walletPubKeyHash> EQUAL\n/// IF\n/// CHECKSIG\n/// ELSE\n/// DUP HASH160 <refundPubkeyHash> EQUALVERIFY\n/// <refundLocktime> CHECKLOCKTIMEVERIFY DROP\n/// CHECKSIG\n/// ENDIF\n/// ```\n///\n/// Since each depositor has their own Ethereum address and their own\n/// secret blinding factor, each depositor’s script is unique, and the hash\n/// of each depositor’s script is unique.\nlibrary Deposit {\n using BTCUtils for bytes;\n using BytesLib for bytes;\n\n /// @notice Represents data which must be revealed by the depositor during\n /// deposit reveal.\n struct DepositRevealInfo {\n // Index of the funding output belonging to the funding transaction.\n uint32 fundingOutputIndex;\n // Ethereum depositor address.\n address depositor;\n // The blinding factor as 8 bytes. Byte endianness doesn't matter\n // as this factor is not interpreted as uint.\n bytes8 blindingFactor;\n // The compressed Bitcoin public key (33 bytes and 02 or 03 prefix)\n // of the deposit's wallet hashed in the HASH160 Bitcoin opcode style.\n bytes20 walletPubKeyHash;\n // The compressed Bitcoin public key (33 bytes and 02 or 03 prefix)\n // that can be used to make the deposit refund after the refund\n // locktime passes. Hashed in the HASH160 Bitcoin opcode style.\n bytes20 refundPubKeyHash;\n // The refund locktime (4-byte LE). Interpreted according to locktime\n // parsing rules described in:\n // https://developer.bitcoin.org/devguide/transactions.html#locktime-and-sequence-number\n // and used with OP_CHECKLOCKTIMEVERIFY opcode as described in:\n // https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki\n bytes4 refundLocktime;\n // Address of the Bank vault to which the deposit is routed to.\n // Optional, can be 0x0. The vault must be trusted by the Bridge.\n address vault;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's calldata argument.\n }\n\n /// @notice Represents tBTC deposit request data.\n struct DepositRequest {\n // Ethereum depositor address.\n address depositor;\n // Deposit amount in satoshi.\n uint64 amount;\n // UNIX timestamp the deposit was revealed at.\n uint32 revealedAt;\n // Address of the Bank vault the deposit is routed to.\n // Optional, can be 0x0.\n address vault;\n // Treasury TBTC fee in satoshi at the moment of deposit reveal.\n uint64 treasuryFee;\n // UNIX timestamp the deposit was swept at. Note this is not the\n // time when the deposit was swept on the Bitcoin chain but actually\n // the time when the sweep proof was delivered to the Ethereum chain.\n uint32 sweptAt;\n // This struct doesn't contain `__gap` property as the structure is stored\n // in a mapping, mappings store values in different slots and they are\n // not contiguous with other values.\n }\n\n event DepositRevealed(\n bytes32 fundingTxHash,\n uint32 fundingOutputIndex,\n address indexed depositor,\n uint64 amount,\n bytes8 blindingFactor,\n bytes20 indexed walletPubKeyHash,\n bytes20 refundPubKeyHash,\n bytes4 refundLocktime,\n address vault\n );\n\n /// @notice Used by the depositor to reveal information about their P2(W)SH\n /// Bitcoin deposit to the Bridge on Ethereum chain. The off-chain\n /// wallet listens for revealed deposit events and may decide to\n /// include the revealed deposit in the next executed sweep.\n /// Information about the Bitcoin deposit can be revealed before or\n /// after the Bitcoin transaction with P2(W)SH deposit is mined on\n /// the Bitcoin chain. Worth noting, the gas cost of this function\n /// scales with the number of P2(W)SH transaction inputs and\n /// outputs. The deposit may be routed to one of the trusted vaults.\n /// When a deposit is routed to a vault, vault gets notified when\n /// the deposit gets swept and it may execute the appropriate action.\n /// @param fundingTx Bitcoin funding transaction data, see `BitcoinTx.Info`.\n /// @param reveal Deposit reveal data, see `RevealInfo struct.\n /// @dev Requirements:\n /// - `reveal.walletPubKeyHash` must identify a `Live` wallet,\n /// - `reveal.vault` must be 0x0 or point to a trusted vault,\n /// - `reveal.fundingOutputIndex` must point to the actual P2(W)SH\n /// output of the BTC deposit transaction,\n /// - `reveal.depositor` must be the Ethereum address used in the\n /// P2(W)SH BTC deposit transaction,\n /// - `reveal.blindingFactor` must be the blinding factor used in the\n /// P2(W)SH BTC deposit transaction,\n /// - `reveal.walletPubKeyHash` must be the wallet pub key hash used in\n /// the P2(W)SH BTC deposit transaction,\n /// - `reveal.refundPubKeyHash` must be the refund pub key hash used in\n /// the P2(W)SH BTC deposit transaction,\n /// - `reveal.refundLocktime` must be the refund locktime used in the\n /// P2(W)SH BTC deposit transaction,\n /// - BTC deposit for the given `fundingTxHash`, `fundingOutputIndex`\n /// can be revealed only one time.\n ///\n /// If any of these requirements is not met, the wallet _must_ refuse\n /// to sweep the deposit and the depositor has to wait until the\n /// deposit script unlocks to receive their BTC back.\n function revealDeposit(\n BridgeState.Storage storage self,\n BitcoinTx.Info calldata fundingTx,\n DepositRevealInfo calldata reveal\n ) external {\n require(\n self.registeredWallets[reveal.walletPubKeyHash].state ==\n Wallets.WalletState.Live,\n \"Wallet must be in Live state\"\n );\n\n require(\n reveal.vault == address(0) || self.isVaultTrusted[reveal.vault],\n \"Vault is not trusted\"\n );\n\n bytes memory expectedScript = abi.encodePacked(\n hex\"14\", // Byte length of depositor Ethereum address.\n reveal.depositor,\n hex\"75\", // OP_DROP\n hex\"08\", // Byte length of blinding factor value.\n reveal.blindingFactor,\n hex\"75\", // OP_DROP\n hex\"76\", // OP_DUP\n hex\"a9\", // OP_HASH160\n hex\"14\", // Byte length of a compressed Bitcoin public key hash.\n reveal.walletPubKeyHash,\n hex\"87\", // OP_EQUAL\n hex\"63\", // OP_IF\n hex\"ac\", // OP_CHECKSIG\n hex\"67\", // OP_ELSE\n hex\"76\", // OP_DUP\n hex\"a9\", // OP_HASH160\n hex\"14\", // Byte length of a compressed Bitcoin public key hash.\n reveal.refundPubKeyHash,\n hex\"88\", // OP_EQUALVERIFY\n hex\"04\", // Byte length of refund locktime value.\n reveal.refundLocktime,\n hex\"b1\", // OP_CHECKLOCKTIMEVERIFY\n hex\"75\", // OP_DROP\n hex\"ac\", // OP_CHECKSIG\n hex\"68\" // OP_ENDIF\n );\n\n bytes memory fundingOutput = fundingTx\n .outputVector\n .extractOutputAtIndex(reveal.fundingOutputIndex);\n bytes memory fundingOutputHash = fundingOutput.extractHash();\n\n if (fundingOutputHash.length == 20) {\n // A 20-byte output hash is used by P2SH. That hash is constructed\n // by applying OP_HASH160 on the locking script. A 20-byte output\n // hash is used as well by P2PKH and P2WPKH (OP_HASH160 on the\n // public key). However, since we compare the actual output hash\n // with an expected locking script hash, this check will succeed only\n // for P2SH transaction type with expected script hash value. For\n // P2PKH and P2WPKH, it will fail on the output hash comparison with\n // the expected locking script hash.\n require(\n fundingOutputHash.slice20(0) == expectedScript.hash160View(),\n \"Wrong 20-byte script hash\"\n );\n } else if (fundingOutputHash.length == 32) {\n // A 32-byte output hash is used by P2WSH. That hash is constructed\n // by applying OP_SHA256 on the locking script.\n require(\n fundingOutputHash.toBytes32() == sha256(expectedScript),\n \"Wrong 32-byte script hash\"\n );\n } else {\n revert(\"Wrong script hash length\");\n }\n\n // Resulting TX hash is in native Bitcoin little-endian format.\n bytes32 fundingTxHash = abi\n .encodePacked(\n fundingTx.version,\n fundingTx.inputVector,\n fundingTx.outputVector,\n fundingTx.locktime\n )\n .hash256View();\n\n DepositRequest storage deposit = self.deposits[\n uint256(\n keccak256(\n abi.encodePacked(fundingTxHash, reveal.fundingOutputIndex)\n )\n )\n ];\n require(deposit.revealedAt == 0, \"Deposit already revealed\");\n\n uint64 fundingOutputAmount = fundingOutput.extractValue();\n\n require(\n fundingOutputAmount >= self.depositDustThreshold,\n \"Deposit amount too small\"\n );\n\n deposit.amount = fundingOutputAmount;\n deposit.depositor = reveal.depositor;\n /* solhint-disable-next-line not-rely-on-time */\n deposit.revealedAt = uint32(block.timestamp);\n deposit.vault = reveal.vault;\n deposit.treasuryFee = self.depositTreasuryFeeDivisor > 0\n ? fundingOutputAmount / self.depositTreasuryFeeDivisor\n : 0;\n // slither-disable-next-line reentrancy-events\n emit DepositRevealed(\n fundingTxHash,\n reveal.fundingOutputIndex,\n reveal.depositor,\n fundingOutputAmount,\n reveal.blindingFactor,\n reveal.walletPubKeyHash,\n reveal.refundPubKeyHash,\n reveal.refundLocktime,\n reveal.vault\n );\n }\n}\n"
141
+ },
142
+ "contracts/bridge/DepositSweep.sol": {
143
+ "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\n\nimport \"./BitcoinTx.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Wallets.sol\";\n\nimport \"../bank/Bank.sol\";\n\n/// @title Bridge deposit sweep\n/// @notice The library handles the logic for sweeping transactions revealed to\n/// the Bridge\n/// @dev Bridge active wallet periodically signs a transaction that unlocks all\n/// of the valid, revealed deposits above the dust threshold, combines them\n/// into a single UTXO with the existing main wallet UTXO, and relocks\n/// those transactions without a 30-day refund clause to the same wallet.\n/// This has two main effects: it consolidates the UTXO set and it disables\n/// the refund. Balances of depositors in the Bank are increased when the\n/// SPV sweep proof is submitted to the Bridge.\nlibrary DepositSweep {\n using BridgeState for BridgeState.Storage;\n using BitcoinTx for BridgeState.Storage;\n\n using BTCUtils for bytes;\n\n /// @notice Represents temporary information needed during the processing\n /// of the deposit sweep Bitcoin transaction inputs. This structure\n /// is an internal one and should not be exported outside of the\n /// deposit sweep transaction processing code.\n /// @dev Allows to mitigate \"stack too deep\" errors on EVM.\n struct DepositSweepTxInputsProcessingInfo {\n // Input vector of the deposit sweep Bitcoin transaction. It is\n // assumed the vector's structure is valid so it must be validated\n // using e.g. `BTCUtils.validateVin` function before being used\n // during the processing. The validation is usually done as part\n // of the `BitcoinTx.validateProof` call that checks the SPV proof.\n bytes sweepTxInputVector;\n // Data of the wallet's main UTXO. If no main UTXO exists for the given\n // sweeping wallet, this parameter's fields should be zeroed to bypass\n // the main UTXO validation\n BitcoinTx.UTXO mainUtxo;\n // Address of the vault where all swept deposits should be routed to.\n // It is used to validate whether all swept deposits have been revealed\n // with the same `vault` parameter. It is an optional parameter.\n // Set to zero address if deposits are not routed to a vault.\n address vault;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's memory argument.\n }\n\n /// @notice Represents an outcome of the sweep Bitcoin transaction\n /// inputs processing.\n struct DepositSweepTxInputsInfo {\n // Sum of all inputs values i.e. all deposits and main UTXO value,\n // if present.\n uint256 inputsTotalValue;\n // Addresses of depositors who performed processed deposits. Ordered in\n // the same order as deposits inputs in the input vector. Size of this\n // array is either equal to the number of inputs (main UTXO doesn't\n // exist) or less by one (main UTXO exists and is pointed by one of\n // the inputs).\n address[] depositors;\n // Amounts of deposits corresponding to processed deposits. Ordered in\n // the same order as deposits inputs in the input vector. Size of this\n // array is either equal to the number of inputs (main UTXO doesn't\n // exist) or less by one (main UTXO exists and is pointed by one of\n // the inputs).\n uint256[] depositedAmounts;\n // Values of the treasury fee corresponding to processed deposits.\n // Ordered in the same order as deposits inputs in the input vector.\n // Size of this array is either equal to the number of inputs (main\n // UTXO doesn't exist) or less by one (main UTXO exists and is pointed\n // by one of the inputs).\n uint256[] treasuryFees;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's memory argument.\n }\n\n event DepositsSwept(bytes20 walletPubKeyHash, bytes32 sweepTxHash);\n\n /// @notice Used by the wallet to prove the BTC deposit sweep transaction\n /// and to update Bank balances accordingly. Sweep is only accepted\n /// if it satisfies SPV proof.\n ///\n /// The function is performing Bank balance updates by first\n /// computing the Bitcoin fee for the sweep transaction. The fee is\n /// divided evenly between all swept deposits. Each depositor\n /// receives a balance in the bank equal to the amount inferred\n /// during the reveal transaction, minus their fee share.\n ///\n /// It is possible to prove the given sweep only one time.\n /// @param sweepTx Bitcoin sweep transaction data.\n /// @param sweepProof Bitcoin sweep proof data.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain. If no main UTXO exists for the given wallet,\n /// this parameter is ignored.\n /// @param vault Optional address of the vault where all swept deposits\n /// should be routed to. All deposits swept as part of the transaction\n /// must have their `vault` parameters set to the same address.\n /// If this parameter is set to an address of a trusted vault, swept\n /// deposits are routed to that vault.\n /// If this parameter is set to the zero address or to an address\n /// of a non-trusted vault, swept deposits are not routed to a\n /// vault but depositors' balances are increased in the Bank\n /// individually.\n /// @dev Requirements:\n /// - `sweepTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash,\n /// - The `sweepTx` should represent a Bitcoin transaction with 1..n\n /// inputs. If the wallet has no main UTXO, all n inputs should\n /// correspond to P2(W)SH revealed deposits UTXOs. If the wallet has\n /// an existing main UTXO, one of the n inputs must point to that\n /// main UTXO and remaining n-1 inputs should correspond to P2(W)SH\n /// revealed deposits UTXOs. That transaction must have only\n /// one P2(W)PKH output locking funds on the 20-byte wallet public\n /// key hash,\n /// - All revealed deposits that are swept by `sweepTx` must have\n /// their `vault` parameters set to the same address as the address\n /// passed in the `vault` function parameter,\n /// - `sweepProof` components must match the expected structure. See\n /// `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// If there is no main UTXO, this parameter is ignored.\n function submitDepositSweepProof(\n BridgeState.Storage storage self,\n BitcoinTx.Info calldata sweepTx,\n BitcoinTx.Proof calldata sweepProof,\n BitcoinTx.UTXO calldata mainUtxo,\n address vault\n ) external {\n // The actual transaction proof is performed here. After that point, we\n // can assume the transaction happened on Bitcoin chain and has\n // a sufficient number of confirmations as determined by\n // `txProofDifficultyFactor` constant.\n bytes32 sweepTxHash = self.validateProof(sweepTx, sweepProof);\n\n // Process sweep transaction output and extract its target wallet\n // public key hash and value.\n (\n bytes20 walletPubKeyHash,\n uint64 sweepTxOutputValue\n ) = processDepositSweepTxOutput(self, sweepTx.outputVector);\n\n (\n Wallets.Wallet storage wallet,\n BitcoinTx.UTXO memory resolvedMainUtxo\n ) = resolveDepositSweepingWallet(self, walletPubKeyHash, mainUtxo);\n\n // Process sweep transaction inputs and extract all information needed\n // to perform deposit bookkeeping.\n DepositSweepTxInputsInfo\n memory inputsInfo = processDepositSweepTxInputs(\n self,\n DepositSweepTxInputsProcessingInfo(\n sweepTx.inputVector,\n resolvedMainUtxo,\n vault\n )\n );\n\n // Helper variable that will hold the sum of treasury fees paid by\n // all deposits.\n uint256 totalTreasuryFee = 0;\n\n // Determine the transaction fee that should be incurred by each deposit\n // and the indivisible remainder that should be additionally incurred\n // by the last deposit.\n (\n uint256 depositTxFee,\n uint256 depositTxFeeRemainder\n ) = depositSweepTxFeeDistribution(\n inputsInfo.inputsTotalValue,\n sweepTxOutputValue,\n inputsInfo.depositedAmounts.length\n );\n\n // Make sure the highest value of the deposit transaction fee does not\n // exceed the maximum value limited by the governable parameter.\n require(\n depositTxFee + depositTxFeeRemainder <= self.depositTxMaxFee,\n \"Transaction fee is too high\"\n );\n\n // Reduce each deposit amount by treasury fee and transaction fee.\n for (uint256 i = 0; i < inputsInfo.depositedAmounts.length; i++) {\n // The last deposit should incur the deposit transaction fee\n // remainder.\n uint256 depositTxFeeIncurred = i ==\n inputsInfo.depositedAmounts.length - 1\n ? depositTxFee + depositTxFeeRemainder\n : depositTxFee;\n\n // There is no need to check whether\n // `inputsInfo.depositedAmounts[i] - inputsInfo.treasuryFees[i] - txFee > 0`\n // since the `depositDustThreshold` should force that condition\n // to be always true.\n inputsInfo.depositedAmounts[i] =\n inputsInfo.depositedAmounts[i] -\n inputsInfo.treasuryFees[i] -\n depositTxFeeIncurred;\n totalTreasuryFee += inputsInfo.treasuryFees[i];\n }\n\n // Record this sweep data and assign them to the wallet public key hash\n // as new main UTXO. Transaction output index is always 0 as sweep\n // transaction always contains only one output.\n wallet.mainUtxoHash = keccak256(\n abi.encodePacked(sweepTxHash, uint32(0), sweepTxOutputValue)\n );\n\n // slither-disable-next-line reentrancy-events\n emit DepositsSwept(walletPubKeyHash, sweepTxHash);\n\n if (vault != address(0) && self.isVaultTrusted[vault]) {\n // If the `vault` address is not zero and belongs to a trusted\n // vault, route the deposits to that vault.\n self.bank.increaseBalanceAndCall(\n vault,\n inputsInfo.depositors,\n inputsInfo.depositedAmounts\n );\n } else {\n // If the `vault` address is zero or belongs to a non-trusted\n // vault, increase balances in the Bank individually for each\n // depositor.\n self.bank.increaseBalances(\n inputsInfo.depositors,\n inputsInfo.depositedAmounts\n );\n }\n\n // Pass the treasury fee to the treasury address.\n self.bank.increaseBalance(self.treasury, totalTreasuryFee);\n }\n\n /// @notice Resolves sweeping wallet based on the provided wallet public key\n /// hash. Validates the wallet state and current main UTXO, as\n /// currently known on the Ethereum chain.\n /// @param walletPubKeyHash public key hash of the wallet proving the sweep\n /// Bitcoin transaction.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain. If no main UTXO exists for the given wallet,\n /// this parameter is ignored.\n /// @return wallet Data of the sweeping wallet.\n /// @return resolvedMainUtxo The actual main UTXO of the sweeping wallet\n /// resolved by cross-checking the `mainUtxo` parameter with\n /// the chain state. If the validation went well, this is the\n /// plain-text main UTXO corresponding to the `wallet.mainUtxoHash`.\n /// @dev Requirements:\n /// - Sweeping wallet must be either in Live or MovingFunds state,\n /// - If the main UTXO of the sweeping wallet exists in the storage,\n /// the passed `mainUTXO` parameter must be equal to the stored one.\n function resolveDepositSweepingWallet(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata mainUtxo\n )\n internal\n view\n returns (\n Wallets.Wallet storage wallet,\n BitcoinTx.UTXO memory resolvedMainUtxo\n )\n {\n wallet = self.registeredWallets[walletPubKeyHash];\n\n Wallets.WalletState walletState = wallet.state;\n require(\n walletState == Wallets.WalletState.Live ||\n walletState == Wallets.WalletState.MovingFunds,\n \"Wallet must be in Live or MovingFunds state\"\n );\n\n // Check if the main UTXO for given wallet exists. If so, validate\n // passed main UTXO data against the stored hash and use them for\n // further processing. If no main UTXO exists, use empty data.\n resolvedMainUtxo = BitcoinTx.UTXO(bytes32(0), 0, 0);\n bytes32 mainUtxoHash = wallet.mainUtxoHash;\n if (mainUtxoHash != bytes32(0)) {\n require(\n keccak256(\n abi.encodePacked(\n mainUtxo.txHash,\n mainUtxo.txOutputIndex,\n mainUtxo.txOutputValue\n )\n ) == mainUtxoHash,\n \"Invalid main UTXO data\"\n );\n resolvedMainUtxo = mainUtxo;\n }\n }\n\n /// @notice Processes the Bitcoin sweep transaction output vector by\n /// extracting the single output and using it to gain additional\n /// information required for further processing (e.g. value and\n /// wallet public key hash).\n /// @param sweepTxOutputVector Bitcoin sweep transaction output vector.\n /// This function assumes vector's structure is valid so it must be\n /// validated using e.g. `BTCUtils.validateVout` function before\n /// it is passed here.\n /// @return walletPubKeyHash 20-byte wallet public key hash.\n /// @return value 8-byte sweep transaction output value.\n function processDepositSweepTxOutput(\n BridgeState.Storage storage self,\n bytes memory sweepTxOutputVector\n ) internal view returns (bytes20 walletPubKeyHash, uint64 value) {\n // To determine the total number of sweep transaction outputs, we need to\n // parse the compactSize uint (VarInt) the output vector is prepended by.\n // That compactSize uint encodes the number of vector elements using the\n // format presented in:\n // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers\n // We don't need asserting the compactSize uint is parseable since it\n // was already checked during `validateVout` validation.\n // See `BitcoinTx.outputVector` docs for more details.\n (, uint256 outputsCount) = sweepTxOutputVector.parseVarInt();\n require(\n outputsCount == 1,\n \"Sweep transaction must have a single output\"\n );\n\n bytes memory output = sweepTxOutputVector.extractOutputAtIndex(0);\n walletPubKeyHash = self.extractPubKeyHash(output);\n value = output.extractValue();\n\n return (walletPubKeyHash, value);\n }\n\n /// @notice Processes the Bitcoin sweep transaction input vector. It\n /// extracts each input and tries to obtain associated deposit or\n /// main UTXO data, depending on the input type. Reverts\n /// if one of the inputs cannot be recognized as a pointer to a\n /// revealed deposit or expected main UTXO.\n /// This function also marks each processed deposit as swept.\n /// @return resultInfo Outcomes of the processing.\n function processDepositSweepTxInputs(\n BridgeState.Storage storage self,\n DepositSweepTxInputsProcessingInfo memory processInfo\n ) internal returns (DepositSweepTxInputsInfo memory resultInfo) {\n // If the passed `mainUtxo` parameter's values are zeroed, the main UTXO\n // for the given wallet doesn't exist and it is not expected to be\n // included in the sweep transaction input vector.\n bool mainUtxoExpected = processInfo.mainUtxo.txHash != bytes32(0);\n bool mainUtxoFound = false;\n\n // Determining the total number of sweep transaction inputs in the same\n // way as for number of outputs. See `BitcoinTx.inputVector` docs for\n // more details.\n (uint256 inputsCompactSizeUintLength, uint256 inputsCount) = processInfo\n .sweepTxInputVector\n .parseVarInt();\n\n // To determine the first input starting index, we must jump over\n // the compactSize uint which prepends the input vector. One byte\n // must be added because `BtcUtils.parseVarInt` does not include\n // compactSize uint tag in the returned length.\n //\n // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`\n // returns `0`, so we jump over one byte of compactSize uint.\n //\n // For >= 253 && <= 0xffff there is `0xfd` tag,\n // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no\n // tag byte included) so we need to jump over 1+2 bytes of\n // compactSize uint.\n //\n // Please refer `BTCUtils` library and compactSize uint\n // docs in `BitcoinTx` library for more details.\n uint256 inputStartingIndex = 1 + inputsCompactSizeUintLength;\n\n // Determine the swept deposits count. If main UTXO is NOT expected,\n // all inputs should be deposits. If main UTXO is expected, one input\n // should point to that main UTXO.\n resultInfo.depositors = new address[](\n !mainUtxoExpected ? inputsCount : inputsCount - 1\n );\n resultInfo.depositedAmounts = new uint256[](\n resultInfo.depositors.length\n );\n resultInfo.treasuryFees = new uint256[](resultInfo.depositors.length);\n\n // Initialize helper variables.\n uint256 processedDepositsCount = 0;\n\n // Inputs processing loop.\n for (uint256 i = 0; i < inputsCount; i++) {\n (\n bytes32 outpointTxHash,\n uint32 outpointIndex,\n uint256 inputLength\n ) = parseDepositSweepTxInputAt(\n processInfo.sweepTxInputVector,\n inputStartingIndex\n );\n\n Deposit.DepositRequest storage deposit = self.deposits[\n uint256(\n keccak256(abi.encodePacked(outpointTxHash, outpointIndex))\n )\n ];\n\n if (deposit.revealedAt != 0) {\n // If we entered here, that means the input was identified as\n // a revealed deposit.\n require(deposit.sweptAt == 0, \"Deposit already swept\");\n\n require(\n deposit.vault == processInfo.vault,\n \"Deposit should be routed to another vault\"\n );\n\n if (processedDepositsCount == resultInfo.depositors.length) {\n // If this condition is true, that means a deposit input\n // took place of an expected main UTXO input.\n // In other words, there is no expected main UTXO\n // input and all inputs come from valid, revealed deposits.\n revert(\n \"Expected main UTXO not present in sweep transaction inputs\"\n );\n }\n\n /* solhint-disable-next-line not-rely-on-time */\n deposit.sweptAt = uint32(block.timestamp);\n\n resultInfo.depositors[processedDepositsCount] = deposit\n .depositor;\n resultInfo.depositedAmounts[processedDepositsCount] = deposit\n .amount;\n resultInfo.inputsTotalValue += resultInfo.depositedAmounts[\n processedDepositsCount\n ];\n resultInfo.treasuryFees[processedDepositsCount] = deposit\n .treasuryFee;\n\n processedDepositsCount++;\n } else if (\n mainUtxoExpected != mainUtxoFound &&\n processInfo.mainUtxo.txHash == outpointTxHash &&\n processInfo.mainUtxo.txOutputIndex == outpointIndex\n ) {\n // If we entered here, that means the input was identified as\n // the expected main UTXO.\n resultInfo.inputsTotalValue += processInfo\n .mainUtxo\n .txOutputValue;\n mainUtxoFound = true;\n\n // Main UTXO used as an input, mark it as spent.\n self.spentMainUTXOs[\n uint256(\n keccak256(\n abi.encodePacked(outpointTxHash, outpointIndex)\n )\n )\n ] = true;\n } else {\n revert(\"Unknown input type\");\n }\n\n // Make the `inputStartingIndex` pointing to the next input by\n // increasing it by current input's length.\n inputStartingIndex += inputLength;\n }\n\n // Construction of the input processing loop guarantees that:\n // `processedDepositsCount == resultInfo.depositors.length == resultInfo.depositedAmounts.length`\n // is always true at this point. We just use the first variable\n // to assert the total count of swept deposit is bigger than zero.\n require(\n processedDepositsCount > 0,\n \"Sweep transaction must process at least one deposit\"\n );\n\n // Assert the main UTXO was used as one of current sweep's inputs if\n // it was actually expected.\n require(\n mainUtxoExpected == mainUtxoFound,\n \"Expected main UTXO not present in sweep transaction inputs\"\n );\n\n return resultInfo;\n }\n\n /// @notice Parses a Bitcoin transaction input starting at the given index.\n /// @param inputVector Bitcoin transaction input vector.\n /// @param inputStartingIndex Index the given input starts at.\n /// @return outpointTxHash 32-byte hash of the Bitcoin transaction which is\n /// pointed in the given input's outpoint.\n /// @return outpointIndex 4-byte index of the Bitcoin transaction output\n /// which is pointed in the given input's outpoint.\n /// @return inputLength Byte length of the given input.\n /// @dev This function assumes vector's structure is valid so it must be\n /// validated using e.g. `BTCUtils.validateVin` function before it\n /// is passed here.\n function parseDepositSweepTxInputAt(\n bytes memory inputVector,\n uint256 inputStartingIndex\n )\n internal\n pure\n returns (\n bytes32 outpointTxHash,\n uint32 outpointIndex,\n uint256 inputLength\n )\n {\n outpointTxHash = inputVector.extractInputTxIdLeAt(inputStartingIndex);\n\n outpointIndex = BTCUtils.reverseUint32(\n uint32(inputVector.extractTxIndexLeAt(inputStartingIndex))\n );\n\n inputLength = inputVector.determineInputLengthAt(inputStartingIndex);\n\n return (outpointTxHash, outpointIndex, inputLength);\n }\n\n /// @notice Determines the distribution of the sweep transaction fee\n /// over swept deposits.\n /// @param sweepTxInputsTotalValue Total value of all sweep transaction inputs.\n /// @param sweepTxOutputValue Value of the sweep transaction output.\n /// @param depositsCount Count of the deposits swept by the sweep transaction.\n /// @return depositTxFee Transaction fee per deposit determined by evenly\n /// spreading the divisible part of the sweep transaction fee\n /// over all deposits.\n /// @return depositTxFeeRemainder The indivisible part of the sweep\n /// transaction fee than cannot be distributed over all deposits.\n /// @dev It is up to the caller to decide how the remainder should be\n /// counted in. This function only computes its value.\n function depositSweepTxFeeDistribution(\n uint256 sweepTxInputsTotalValue,\n uint256 sweepTxOutputValue,\n uint256 depositsCount\n )\n internal\n pure\n returns (uint256 depositTxFee, uint256 depositTxFeeRemainder)\n {\n // The sweep transaction fee is just the difference between inputs\n // amounts sum and the output amount.\n uint256 sweepTxFee = sweepTxInputsTotalValue - sweepTxOutputValue;\n // Compute the indivisible remainder that remains after dividing the\n // sweep transaction fee over all deposits evenly.\n depositTxFeeRemainder = sweepTxFee % depositsCount;\n // Compute the transaction fee per deposit by dividing the sweep\n // transaction fee (reduced by the remainder) by the number of deposits.\n depositTxFee = (sweepTxFee - depositTxFeeRemainder) / depositsCount;\n\n return (depositTxFee, depositTxFeeRemainder);\n }\n}\n"
144
+ },
145
+ "contracts/bridge/Redemption.sol": {
146
+ "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\nimport {BytesLib} from \"@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol\";\n\nimport \"./BitcoinTx.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Wallets.sol\";\n\nimport \"../bank/Bank.sol\";\n\n/// @notice Aggregates functions common to the redemption transaction proof\n/// validation and to the moving funds transaction proof validation.\nlibrary OutboundTx {\n using BTCUtils for bytes;\n\n /// @notice Checks whether an outbound Bitcoin transaction performed from\n /// the given wallet has an input vector that contains a single\n /// input referring to the wallet's main UTXO. Marks that main UTXO\n /// as correctly spent if the validation succeeds. Reverts otherwise.\n /// There are two outbound transactions from a wallet possible: a\n /// redemption transaction or a moving funds to another wallet\n /// transaction.\n /// @param walletOutboundTxInputVector Bitcoin outbound transaction's input\n /// vector. This function assumes vector's structure is valid so it\n /// must be validated using e.g. `BTCUtils.validateVin` function\n /// before it is passed here.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n // HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the outbound transaction.\n function processWalletOutboundTxInput(\n BridgeState.Storage storage self,\n bytes memory walletOutboundTxInputVector,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes20 walletPubKeyHash\n ) internal {\n // Assert that main UTXO for passed wallet exists in storage.\n bytes32 mainUtxoHash = self\n .registeredWallets[walletPubKeyHash]\n .mainUtxoHash;\n require(mainUtxoHash != bytes32(0), \"No main UTXO for given wallet\");\n\n // Assert that passed main UTXO parameter is the same as in storage and\n // can be used for further processing.\n require(\n keccak256(\n abi.encodePacked(\n mainUtxo.txHash,\n mainUtxo.txOutputIndex,\n mainUtxo.txOutputValue\n )\n ) == mainUtxoHash,\n \"Invalid main UTXO data\"\n );\n\n // Assert that the single outbound transaction input actually\n // refers to the wallet's main UTXO.\n (\n bytes32 outpointTxHash,\n uint32 outpointIndex\n ) = parseWalletOutboundTxInput(walletOutboundTxInputVector);\n require(\n mainUtxo.txHash == outpointTxHash &&\n mainUtxo.txOutputIndex == outpointIndex,\n \"Outbound transaction input must point to the wallet's main UTXO\"\n );\n\n // Main UTXO used as an input, mark it as spent.\n self.spentMainUTXOs[\n uint256(\n keccak256(\n abi.encodePacked(mainUtxo.txHash, mainUtxo.txOutputIndex)\n )\n )\n ] = true;\n }\n\n /// @notice Parses the input vector of an outbound Bitcoin transaction\n /// performed from the given wallet. It extracts the single input\n /// then the transaction hash and output index from its outpoint.\n /// There are two outbound transactions from a wallet possible: a\n /// redemption transaction or a moving funds to another wallet\n /// transaction.\n /// @param walletOutboundTxInputVector Bitcoin outbound transaction input\n /// vector. This function assumes vector's structure is valid so it\n /// must be validated using e.g. `BTCUtils.validateVin` function\n /// before it is passed here.\n /// @return outpointTxHash 32-byte hash of the Bitcoin transaction which is\n /// pointed in the input's outpoint.\n /// @return outpointIndex 4-byte index of the Bitcoin transaction output\n /// which is pointed in the input's outpoint.\n function parseWalletOutboundTxInput(\n bytes memory walletOutboundTxInputVector\n ) internal pure returns (bytes32 outpointTxHash, uint32 outpointIndex) {\n // To determine the total number of Bitcoin transaction inputs,\n // we need to parse the compactSize uint (VarInt) the input vector is\n // prepended by. That compactSize uint encodes the number of vector\n // elements using the format presented in:\n // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers\n // We don't need asserting the compactSize uint is parseable since it\n // was already checked during `validateVin` validation.\n // See `BitcoinTx.inputVector` docs for more details.\n (, uint256 inputsCount) = walletOutboundTxInputVector.parseVarInt();\n require(\n inputsCount == 1,\n \"Outbound transaction must have a single input\"\n );\n\n bytes memory input = walletOutboundTxInputVector.extractInputAtIndex(0);\n\n outpointTxHash = input.extractInputTxIdLE();\n\n outpointIndex = BTCUtils.reverseUint32(\n uint32(input.extractTxIndexLE())\n );\n\n // There is only one input in the transaction. Input has an outpoint\n // field that is a reference to the transaction being spent (see\n // `BitcoinTx` docs). The outpoint contains the hash of the transaction\n // to spend (`outpointTxHash`) and the index of the specific output\n // from that transaction (`outpointIndex`).\n return (outpointTxHash, outpointIndex);\n }\n}\n\n/// @title Bridge redemption\n/// @notice The library handles the logic for redeeming Bitcoin balances from\n/// the Bridge.\n/// @dev To initiate a redemption, a user with a Bank balance supplies\n/// a Bitcoin address. Then, the system calculates the redemption fee, and\n/// releases balance to the provided Bitcoin address. Just like in case of\n/// sweeps of revealed deposits, redemption requests are processed in\n/// batches and require SPV proof to be submitted to the Bridge.\nlibrary Redemption {\n using BridgeState for BridgeState.Storage;\n using Wallets for BridgeState.Storage;\n using BitcoinTx for BridgeState.Storage;\n\n using BTCUtils for bytes;\n using BytesLib for bytes;\n\n /// @notice Represents a redemption request.\n struct RedemptionRequest {\n // ETH address of the redeemer who created the request.\n address redeemer;\n // Requested TBTC amount in satoshi.\n uint64 requestedAmount;\n // Treasury TBTC fee in satoshi at the moment of request creation.\n uint64 treasuryFee;\n // Transaction maximum BTC fee in satoshi at the moment of request\n // creation.\n uint64 txMaxFee;\n // UNIX timestamp the request was created at.\n uint32 requestedAt;\n // This struct doesn't contain `__gap` property as the structure is stored\n // in a mapping, mappings store values in different slots and they are\n // not contiguous with other values.\n }\n\n /// @notice Represents an outcome of the redemption Bitcoin transaction\n /// outputs processing.\n struct RedemptionTxOutputsInfo {\n // Total TBTC value in satoshi that should be burned by the Bridge.\n // It includes the total amount of all BTC redeemed in the transaction\n // and the fee paid to BTC miners for the redemption transaction.\n uint64 totalBurnableValue;\n // Total TBTC value in satoshi that should be transferred to\n // the treasury. It is a sum of all treasury fees paid by all\n // redeemers included in the redemption transaction.\n uint64 totalTreasuryFee;\n // Index of the change output. The change output becomes\n // the new main wallet's UTXO.\n uint32 changeIndex;\n // Value in satoshi of the change output.\n uint64 changeValue;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's memory argument.\n }\n\n /// @notice Represents temporary information needed during the processing of\n /// the redemption Bitcoin transaction outputs. This structure is an\n /// internal one and should not be exported outside of the redemption\n /// transaction processing code.\n /// @dev Allows to mitigate \"stack too deep\" errors on EVM.\n struct RedemptionTxOutputsProcessingInfo {\n // The first output starting index in the transaction.\n uint256 outputStartingIndex;\n // The number of outputs in the transaction.\n uint256 outputsCount;\n // P2PKH script for the wallet. Needed to determine the change output.\n bytes32 walletP2PKHScriptKeccak;\n // P2WPKH script for the wallet. Needed to determine the change output.\n bytes32 walletP2WPKHScriptKeccak;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's memory argument.\n }\n\n event RedemptionRequested(\n bytes20 indexed walletPubKeyHash,\n bytes redeemerOutputScript,\n address indexed redeemer,\n uint64 requestedAmount,\n uint64 treasuryFee,\n uint64 txMaxFee\n );\n\n event RedemptionsCompleted(\n bytes20 indexed walletPubKeyHash,\n bytes32 redemptionTxHash\n );\n\n event RedemptionTimedOut(\n bytes20 indexed walletPubKeyHash,\n bytes redeemerOutputScript\n );\n\n /// @notice Requests redemption of the given amount from the specified\n /// wallet to the redeemer Bitcoin output script.\n /// @param walletPubKeyHash The 20-byte wallet public key hash (computed\n /// using Bitcoin HASH160 over the compressed ECDSA public key).\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain.\n /// @param redeemerOutputScript The redeemer's length-prefixed output\n /// script (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock\n /// redeemed BTC.\n /// @param amount Requested amount in satoshi. This is also the TBTC amount\n /// that is taken from redeemer's balance in the Bank upon request.\n /// Once the request is handled, the actual amount of BTC locked\n /// on the redeemer output script will be always lower than this value\n /// since the treasury and Bitcoin transaction fees must be incurred.\n /// The minimal amount satisfying the request can be computed as:\n /// `amount - (amount / redemptionTreasuryFeeDivisor) - redemptionTxMaxFee`.\n /// Fees values are taken at the moment of request creation.\n /// @dev Requirements:\n /// - Wallet behind `walletPubKeyHash` must be live,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain,\n /// - `redeemerOutputScript` must be a proper Bitcoin script,\n /// - `redeemerOutputScript` cannot have wallet PKH as payload,\n /// - `amount` must be above or equal the `redemptionDustThreshold`,\n /// - Given `walletPubKeyHash` and `redeemerOutputScript` pair can be\n /// used for only one pending request at the same time,\n /// - Wallet must have enough Bitcoin balance to proceed the request,\n /// - Redeemer must make an allowance in the Bank that the Bridge\n /// contract can spend the given `amount`.\n function requestRedemption(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes calldata redeemerOutputScript,\n uint64 amount\n ) external {\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n\n require(\n wallet.state == Wallets.WalletState.Live,\n \"Wallet must be in Live state\"\n );\n\n bytes32 mainUtxoHash = wallet.mainUtxoHash;\n require(\n mainUtxoHash != bytes32(0),\n \"No main UTXO for the given wallet\"\n );\n require(\n keccak256(\n abi.encodePacked(\n mainUtxo.txHash,\n mainUtxo.txOutputIndex,\n mainUtxo.txOutputValue\n )\n ) == mainUtxoHash,\n \"Invalid main UTXO data\"\n );\n\n // Validate if redeemer output script is a correct standard type\n // (P2PKH, P2WPKH, P2SH or P2WSH). This is done by building a stub\n // output with 0 as value and using `BTCUtils.extractHash` on it. Such\n // a function extracts the payload properly only from standard outputs\n // so if it succeeds, we have a guarantee the redeemer output script\n // is proper. Worth to note `extractHash` ignores the value at all\n // so this is why we can use 0 safely. This way of validation is the\n // same as in tBTC v1.\n bytes memory redeemerOutputScriptPayload = abi\n .encodePacked(bytes8(0), redeemerOutputScript)\n .extractHash();\n require(\n redeemerOutputScriptPayload.length > 0,\n \"Redeemer output script must be a standard type\"\n );\n // Check if the redeemer output script payload does not point to the\n // wallet public key hash.\n require(\n keccak256(abi.encodePacked(walletPubKeyHash)) !=\n keccak256(redeemerOutputScriptPayload),\n \"Redeemer output script must not point to the wallet PKH\"\n );\n\n require(\n amount >= self.redemptionDustThreshold,\n \"Redemption amount too small\"\n );\n\n // The redemption key is built on top of the wallet public key hash\n // and redeemer output script pair. That means there can be only one\n // request asking for redemption from the given wallet to the given\n // BTC script at the same time.\n uint256 redemptionKey = uint256(\n keccak256(abi.encodePacked(walletPubKeyHash, redeemerOutputScript))\n );\n\n // Check if given redemption key is not used by a pending redemption.\n // There is no need to check for existence in `timedOutRedemptions`\n // since the wallet's state is changed to other than Live after\n // first time out is reported so making new requests is not possible.\n // slither-disable-next-line incorrect-equality\n require(\n self.pendingRedemptions[redemptionKey].requestedAt == 0,\n \"There is a pending redemption request from this wallet to the same address\"\n );\n\n // No need to check whether `amount - treasuryFee - txMaxFee > 0`\n // since the `redemptionDustThreshold` should force that condition\n // to be always true.\n uint64 treasuryFee = self.redemptionTreasuryFeeDivisor > 0\n ? amount / self.redemptionTreasuryFeeDivisor\n : 0;\n uint64 txMaxFee = self.redemptionTxMaxFee;\n\n // The main wallet UTXO's value doesn't include all pending redemptions.\n // To determine if the requested redemption can be performed by the\n // wallet we need to subtract the total value of all pending redemptions\n // from that wallet's main UTXO value. Given that the treasury fee is\n // not redeemed from the wallet, we are subtracting it.\n wallet.pendingRedemptionsValue += amount - treasuryFee;\n require(\n mainUtxo.txOutputValue >= wallet.pendingRedemptionsValue,\n \"Insufficient wallet funds\"\n );\n\n self.pendingRedemptions[redemptionKey] = RedemptionRequest(\n msg.sender,\n amount,\n treasuryFee,\n txMaxFee,\n /* solhint-disable-next-line not-rely-on-time */\n uint32(block.timestamp)\n );\n\n emit RedemptionRequested(\n walletPubKeyHash,\n redeemerOutputScript,\n msg.sender,\n amount,\n treasuryFee,\n txMaxFee\n );\n\n self.bank.transferBalanceFrom(msg.sender, address(this), amount);\n }\n\n /// @notice Used by the wallet to prove the BTC redemption transaction\n /// and to make the necessary bookkeeping. Redemption is only\n /// accepted if it satisfies SPV proof.\n ///\n /// The function is performing Bank balance updates by burning\n /// the total redeemed Bitcoin amount from Bridge balance and\n /// transferring the treasury fee sum to the treasury address.\n ///\n /// It is possible to prove the given redemption only one time.\n /// @param redemptionTx Bitcoin redemption transaction data.\n /// @param redemptionProof Bitcoin redemption proof data.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n /// HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the redemption transaction.\n /// @dev Requirements:\n /// - `redemptionTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash,\n /// - The `redemptionTx` should represent a Bitcoin transaction with\n /// exactly 1 input that refers to the wallet's main UTXO. That\n /// transaction should have 1..n outputs handling existing pending\n /// redemption requests or pointing to reported timed out requests.\n /// There can be also 1 optional output representing the\n /// change and pointing back to the 20-byte wallet public key hash.\n /// The change should be always present if the redeemed value sum\n /// is lower than the total wallet's BTC balance,\n /// - `redemptionProof` components must match the expected structure.\n /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// Additionally, the recent main UTXO on Ethereum must be set,\n /// - `walletPubKeyHash` must be connected with the main UTXO used\n /// as transaction single input.\n /// Other remarks:\n /// - Putting the change output as the first transaction output can\n /// save some gas because the output processing loop begins each\n /// iteration by checking whether the given output is the change\n /// thus uses some gas for making the comparison. Once the change\n /// is identified, that check is omitted in further iterations.\n function submitRedemptionProof(\n BridgeState.Storage storage self,\n BitcoinTx.Info calldata redemptionTx,\n BitcoinTx.Proof calldata redemptionProof,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes20 walletPubKeyHash\n ) external {\n // The actual transaction proof is performed here. After that point, we\n // can assume the transaction happened on Bitcoin chain and has\n // a sufficient number of confirmations as determined by\n // `txProofDifficultyFactor` constant.\n bytes32 redemptionTxHash = self.validateProof(\n redemptionTx,\n redemptionProof\n );\n\n // Process the redemption transaction input. Specifically, check if it\n // refers to the expected wallet's main UTXO.\n OutboundTx.processWalletOutboundTxInput(\n self,\n redemptionTx.inputVector,\n mainUtxo,\n walletPubKeyHash\n );\n\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n\n Wallets.WalletState walletState = wallet.state;\n require(\n walletState == Wallets.WalletState.Live ||\n walletState == Wallets.WalletState.MovingFunds,\n \"Wallet must be in Live or MovingFunds state\"\n );\n\n // Process redemption transaction outputs to extract some info required\n // for further processing.\n RedemptionTxOutputsInfo memory outputsInfo = processRedemptionTxOutputs(\n self,\n redemptionTx.outputVector,\n walletPubKeyHash\n );\n\n if (outputsInfo.changeValue > 0) {\n // If the change value is grater than zero, it means the change\n // output exists and can be used as new wallet's main UTXO.\n wallet.mainUtxoHash = keccak256(\n abi.encodePacked(\n redemptionTxHash,\n outputsInfo.changeIndex,\n outputsInfo.changeValue\n )\n );\n } else {\n // If the change value is zero, it means the change output doesn't\n // exists and no funds left on the wallet. Delete the main UTXO\n // for that wallet to represent that state in a proper way.\n delete wallet.mainUtxoHash;\n }\n\n wallet.pendingRedemptionsValue -= outputsInfo.totalBurnableValue;\n\n emit RedemptionsCompleted(walletPubKeyHash, redemptionTxHash);\n\n self.bank.decreaseBalance(outputsInfo.totalBurnableValue);\n self.bank.transferBalance(self.treasury, outputsInfo.totalTreasuryFee);\n }\n\n /// @notice Processes the Bitcoin redemption transaction output vector.\n /// It extracts each output and tries to identify it as a pending\n /// redemption request, reported timed out request, or change.\n /// Reverts if one of the outputs cannot be recognized properly.\n /// This function also marks each request as processed by removing\n /// them from `pendingRedemptions` mapping.\n /// @param redemptionTxOutputVector Bitcoin redemption transaction output\n /// vector. This function assumes vector's structure is valid so it\n /// must be validated using e.g. `BTCUtils.validateVout` function\n /// before it is passed here.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n // HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the redemption transaction.\n /// @return info Outcomes of the processing.\n function processRedemptionTxOutputs(\n BridgeState.Storage storage self,\n bytes memory redemptionTxOutputVector,\n bytes20 walletPubKeyHash\n ) internal returns (RedemptionTxOutputsInfo memory info) {\n // Determining the total number of redemption transaction outputs in\n // the same way as for number of inputs. See `BitcoinTx.outputVector`\n // docs for more details.\n (\n uint256 outputsCompactSizeUintLength,\n uint256 outputsCount\n ) = redemptionTxOutputVector.parseVarInt();\n\n // To determine the first output starting index, we must jump over\n // the compactSize uint which prepends the output vector. One byte\n // must be added because `BtcUtils.parseVarInt` does not include\n // compactSize uint tag in the returned length.\n //\n // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`\n // returns `0`, so we jump over one byte of compactSize uint.\n //\n // For >= 253 && <= 0xffff there is `0xfd` tag,\n // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no\n // tag byte included) so we need to jump over 1+2 bytes of\n // compactSize uint.\n //\n // Please refer `BTCUtils` library and compactSize uint\n // docs in `BitcoinTx` library for more details.\n uint256 outputStartingIndex = 1 + outputsCompactSizeUintLength;\n\n // Calculate the keccak256 for two possible wallet's P2PKH or P2WPKH\n // scripts that can be used to lock the change. This is done upfront to\n // save on gas. Both scripts have a strict format defined by Bitcoin.\n //\n // The P2PKH script has the byte format: <0x1976a914> <20-byte PKH> <0x88ac>.\n // According to https://en.bitcoin.it/wiki/Script#Opcodes this translates to:\n // - 0x19: Byte length of the entire script\n // - 0x76: OP_DUP\n // - 0xa9: OP_HASH160\n // - 0x14: Byte length of the public key hash\n // - 0x88: OP_EQUALVERIFY\n // - 0xac: OP_CHECKSIG\n // which matches the P2PKH structure as per:\n // https://en.bitcoin.it/wiki/Transaction#Pay-to-PubkeyHash\n bytes32 walletP2PKHScriptKeccak = keccak256(\n abi.encodePacked(hex\"1976a914\", walletPubKeyHash, hex\"88ac\")\n );\n // The P2WPKH script has the byte format: <0x160014> <20-byte PKH>.\n // According to https://en.bitcoin.it/wiki/Script#Opcodes this translates to:\n // - 0x16: Byte length of the entire script\n // - 0x00: OP_0\n // - 0x14: Byte length of the public key hash\n // which matches the P2WPKH structure as per:\n // https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#P2WPKH\n bytes32 walletP2WPKHScriptKeccak = keccak256(\n abi.encodePacked(hex\"160014\", walletPubKeyHash)\n );\n\n return\n processRedemptionTxOutputs(\n self,\n redemptionTxOutputVector,\n walletPubKeyHash,\n RedemptionTxOutputsProcessingInfo(\n outputStartingIndex,\n outputsCount,\n walletP2PKHScriptKeccak,\n walletP2WPKHScriptKeccak\n )\n );\n }\n\n /// @notice Processes all outputs from the redemption transaction. Tries to\n /// identify output as a change output, pending redemption request\n // or reported redemption. Reverts if one of the outputs cannot be\n /// recognized properly. Marks each request as processed by removing\n /// them from `pendingRedemptions` mapping.\n /// @param redemptionTxOutputVector Bitcoin redemption transaction output\n /// vector. This function assumes vector's structure is valid so it\n /// must be validated using e.g. `BTCUtils.validateVout` function\n /// before it is passed here.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n // HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the redemption transaction.\n /// @param processInfo RedemptionTxOutputsProcessingInfo identifying output\n /// starting index, the number of outputs and possible wallet change\n /// P2PKH and P2WPKH scripts.\n function processRedemptionTxOutputs(\n BridgeState.Storage storage self,\n bytes memory redemptionTxOutputVector,\n bytes20 walletPubKeyHash,\n RedemptionTxOutputsProcessingInfo memory processInfo\n ) internal returns (RedemptionTxOutputsInfo memory resultInfo) {\n // Helper flag indicating whether there was at least one redemption\n // output present (redemption must be either pending or reported as\n // timed out).\n bool redemptionPresent = false;\n\n // Outputs processing loop.\n for (uint256 i = 0; i < processInfo.outputsCount; i++) {\n // TODO: Check if we can optimize gas costs by adding\n // `extractValueAt` and `extractHashAt` in `bitcoin-spv-sol`\n // in order to avoid allocating bytes in memory.\n // https://github.com/keep-network/tbtc-v2/issues/257\n uint256 outputLength = redemptionTxOutputVector\n .determineOutputLengthAt(processInfo.outputStartingIndex);\n bytes memory output = redemptionTxOutputVector.slice(\n processInfo.outputStartingIndex,\n outputLength\n );\n\n // Extract the value from given output.\n uint64 outputValue = output.extractValue();\n // The output consists of an 8-byte value and a variable length\n // script. To extract that script we slice the output starting from\n // 9th byte until the end.\n bytes memory outputScript = output.slice(8, output.length - 8);\n\n if (\n resultInfo.changeValue == 0 &&\n (keccak256(outputScript) ==\n processInfo.walletP2PKHScriptKeccak ||\n keccak256(outputScript) ==\n processInfo.walletP2WPKHScriptKeccak) &&\n outputValue > 0\n ) {\n // If we entered here, that means the change output with a\n // proper non-zero value was found.\n resultInfo.changeIndex = uint32(i);\n resultInfo.changeValue = outputValue;\n } else {\n // If we entered here, that the means the given output is\n // supposed to represent a redemption.\n (\n uint64 burnableValue,\n uint64 treasuryFee\n ) = processNonChangeRedemptionTxOutput(\n self,\n walletPubKeyHash,\n outputScript,\n outputValue\n );\n resultInfo.totalBurnableValue += burnableValue;\n resultInfo.totalTreasuryFee += treasuryFee;\n redemptionPresent = true;\n }\n\n // Make the `outputStartingIndex` pointing to the next output by\n // increasing it by current output's length.\n processInfo.outputStartingIndex += outputLength;\n }\n\n // Protect against the cases when there is only a single change output\n // referring back to the wallet PKH and just burning main UTXO value\n // for transaction fees.\n require(\n redemptionPresent,\n \"Redemption transaction must process at least one redemption\"\n );\n }\n\n /// @notice Processes a single redemption transaction output. Tries to\n /// identify output as a pending redemption request or reported\n /// redemption timeout. Output script passed to this function must\n /// not be the change output. Such output needs to be identified\n /// separately before calling this function.\n /// Reverts if output is neither requested pending redemption nor\n /// requested and reported timed-out redemption.\n /// This function also marks each pending request as processed by\n /// removing them from `pendingRedemptions` mapping.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n // HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the redemption transaction.\n /// @param outputScript Non-change output script to be processed.\n /// @param outputValue Value of the output being processed.\n /// @return burnableValue The value burnable as a result of processing this\n /// single redemption output. This value needs to be summed up with\n /// burnable values of all other outputs to evaluate total burnable\n /// value for the entire redemption transaction. This value is 0\n /// for a timed-out redemption request.\n /// @return treasuryFee The treasury fee from this single redemption output.\n /// This value needs to be summed up with treasury fees of all other\n /// outputs to evaluate the total treasury fee for the entire\n /// redemption transaction. This value is 0 for a timed-out\n /// redemption request.\n function processNonChangeRedemptionTxOutput(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n bytes memory outputScript,\n uint64 outputValue\n ) internal returns (uint64 burnableValue, uint64 treasuryFee) {\n // This function should be called only if the given output is\n // supposed to represent a redemption. Build the redemption key\n // to perform that check.\n uint256 redemptionKey = uint256(\n keccak256(abi.encodePacked(walletPubKeyHash, outputScript))\n );\n\n if (self.pendingRedemptions[redemptionKey].requestedAt != 0) {\n // If we entered here, that means the output was identified\n // as a pending redemption request.\n RedemptionRequest storage request = self.pendingRedemptions[\n redemptionKey\n ];\n // Compute the request's redeemable amount as the requested\n // amount reduced by the treasury fee. The request's\n // minimal amount is then the redeemable amount reduced by\n // the maximum transaction fee.\n uint64 redeemableAmount = request.requestedAmount -\n request.treasuryFee;\n // Output value must fit between the request's redeemable\n // and minimal amounts to be deemed valid.\n require(\n redeemableAmount - request.txMaxFee <= outputValue &&\n outputValue <= redeemableAmount,\n \"Output value is not within the acceptable range of the pending request\"\n );\n // Add the redeemable amount to the total burnable value\n // the Bridge will use to decrease its balance in the Bank.\n burnableValue = redeemableAmount;\n // Add the request's treasury fee to the total treasury fee\n // value the Bridge will transfer to the treasury.\n treasuryFee = request.treasuryFee;\n // Request was properly handled so remove its redemption\n // key from the mapping to make it reusable for further\n // requests.\n delete self.pendingRedemptions[redemptionKey];\n } else {\n // If we entered here, the output is not a redemption\n // request but there is still a chance the given output is\n // related to a reported timed out redemption request.\n // If so, check if the output value matches the request\n // amount to confirm this is an overdue request fulfillment\n // then bypass this output and process the subsequent\n // ones. That also means the wallet was already punished\n // for the inactivity. Otherwise, just revert.\n RedemptionRequest storage request = self.timedOutRedemptions[\n redemptionKey\n ];\n\n require(\n request.requestedAt != 0,\n \"Output is a non-requested redemption\"\n );\n\n uint64 redeemableAmount = request.requestedAmount -\n request.treasuryFee;\n\n require(\n redeemableAmount - request.txMaxFee <= outputValue &&\n outputValue <= redeemableAmount,\n \"Output value is not within the acceptable range of the timed out request\"\n );\n }\n }\n\n /// @notice Notifies that there is a pending redemption request associated\n /// with the given wallet, that has timed out. The redemption\n /// request is identified by the key built as\n /// `keccak256(walletPubKeyHash | redeemerOutputScript)`.\n /// The results of calling this function:\n /// - the pending redemptions value for the wallet will be decreased\n /// by the requested amount (minus treasury fee),\n /// - the tokens taken from the redeemer on redemption request will\n /// be returned to the redeemer,\n /// - the request will be moved from pending redemptions to\n /// timed-out redemptions,\n /// - if the state of the wallet is `Live` or `MovingFunds`, the\n /// wallet operators will be slashed and the notifier will be\n /// rewarded,\n /// - if the state of wallet is `Live`, the wallet will be closed or\n /// marked as `MovingFunds` (depending on the presence or absence\n /// of the wallet's main UTXO) and the wallet will no longer be\n /// marked as the active wallet (if it was marked as such).\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @param redeemerOutputScript The redeemer's length-prefixed output\n /// script (P2PKH, P2WPKH, P2SH or P2WSH).\n /// @dev Requirements:\n /// - The wallet must be in the Live or MovingFunds or Terminated state,\n /// - The redemption request identified by `walletPubKeyHash` and\n /// `redeemerOutputScript` must exist,\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events of the `WalletRegistry` contract,\n /// - The amount of time defined by `redemptionTimeout` must have\n /// passed since the redemption was requested (the request must be\n /// timed-out).\n function notifyRedemptionTimeout(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n uint32[] calldata walletMembersIDs,\n bytes calldata redeemerOutputScript\n ) external {\n uint256 redemptionKey = uint256(\n keccak256(abi.encodePacked(walletPubKeyHash, redeemerOutputScript))\n );\n Redemption.RedemptionRequest memory request = self.pendingRedemptions[\n redemptionKey\n ];\n\n require(request.requestedAt > 0, \"Redemption request does not exist\");\n require(\n /* solhint-disable-next-line not-rely-on-time */\n request.requestedAt + self.redemptionTimeout < block.timestamp,\n \"Redemption request has not timed out\"\n );\n\n // Update the wallet's pending redemptions value\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n wallet.pendingRedemptionsValue -=\n request.requestedAmount -\n request.treasuryFee;\n\n require(\n wallet.state == Wallets.WalletState.Live ||\n wallet.state == Wallets.WalletState.MovingFunds ||\n wallet.state == Wallets.WalletState.Terminated,\n \"The wallet must be in Live, MovingFunds or Terminated state\"\n );\n\n // It is worth noting that there is no need to check if\n // `timedOutRedemption` mapping already contains the given redemption\n // key. There is no possibility to re-use a key of a reported timed-out\n // redemption because the wallet responsible for causing the timeout is\n // moved to a state that prevents it to receive new redemption requests.\n\n // Move the redemption from pending redemptions to timed-out redemptions\n self.timedOutRedemptions[redemptionKey] = request;\n delete self.pendingRedemptions[redemptionKey];\n\n if (\n wallet.state == Wallets.WalletState.Live ||\n wallet.state == Wallets.WalletState.MovingFunds\n ) {\n // Propagate timeout consequences to the wallet\n self.notifyWalletTimedOutRedemption(walletPubKeyHash);\n\n // Slash the wallet operators and reward the notifier\n self.ecdsaWalletRegistry.seize(\n self.redemptionTimeoutSlashingAmount,\n self.redemptionTimeoutNotifierRewardMultiplier,\n msg.sender,\n wallet.ecdsaWalletID,\n walletMembersIDs\n );\n }\n\n // slither-disable-next-line reentrancy-events\n emit RedemptionTimedOut(walletPubKeyHash, redeemerOutputScript);\n\n // Return the requested amount of tokens to the redeemer\n self.bank.transferBalance(request.redeemer, request.requestedAmount);\n }\n}\n"
147
+ },
148
+ "contracts/bridge/BitcoinTx.sol": {
149
+ "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\nimport {BytesLib} from \"@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol\";\nimport {ValidateSPV} from \"@keep-network/bitcoin-spv-sol/contracts/ValidateSPV.sol\";\n\nimport \"./BridgeState.sol\";\n\n/// @title Bitcoin transaction\n/// @notice Allows to reference Bitcoin raw transaction in Solidity.\n/// @dev See https://developer.bitcoin.org/reference/transactions.html#raw-transaction-format\n///\n/// Raw Bitcoin transaction data:\n///\n/// | Bytes | Name | BTC type | Description |\n/// |--------|--------------|------------------------|---------------------------|\n/// | 4 | version | int32_t (LE) | TX version number |\n/// | varies | tx_in_count | compactSize uint (LE) | Number of TX inputs |\n/// | varies | tx_in | txIn[] | TX inputs |\n/// | varies | tx_out_count | compactSize uint (LE) | Number of TX outputs |\n/// | varies | tx_out | txOut[] | TX outputs |\n/// | 4 | lock_time | uint32_t (LE) | Unix time or block number |\n///\n//\n/// Non-coinbase transaction input (txIn):\n///\n/// | Bytes | Name | BTC type | Description |\n/// |--------|------------------|------------------------|---------------------------------------------|\n/// | 36 | previous_output | outpoint | The previous outpoint being spent |\n/// | varies | script_bytes | compactSize uint (LE) | The number of bytes in the signature script |\n/// | varies | signature_script | char[] | The signature script, empty for P2WSH |\n/// | 4 | sequence | uint32_t (LE) | Sequence number |\n///\n///\n/// The reference to transaction being spent (outpoint):\n///\n/// | Bytes | Name | BTC type | Description |\n/// |-------|-------|---------------|------------------------------------------|\n/// | 32 | hash | char[32] | Hash of the transaction to spend |\n/// | 4 | index | uint32_t (LE) | Index of the specific output from the TX |\n///\n///\n/// Transaction output (txOut):\n///\n/// | Bytes | Name | BTC type | Description |\n/// |--------|-----------------|-----------------------|--------------------------------------|\n/// | 8 | value | int64_t (LE) | Number of satoshis to spend |\n/// | 1+ | pk_script_bytes | compactSize uint (LE) | Number of bytes in the pubkey script |\n/// | varies | pk_script | char[] | Pubkey script |\n///\n/// compactSize uint format:\n///\n/// | Value | Bytes | Format |\n/// |-----------------------------------------|-------|----------------------------------------------|\n/// | >= 0 && <= 252 | 1 | uint8_t |\n/// | >= 253 && <= 0xffff | 3 | 0xfd followed by the number as uint16_t (LE) |\n/// | >= 0x10000 && <= 0xffffffff | 5 | 0xfe followed by the number as uint32_t (LE) |\n/// | >= 0x100000000 && <= 0xffffffffffffffff | 9 | 0xff followed by the number as uint64_t (LE) |\n///\n/// (*) compactSize uint is often references as VarInt)\n///\n/// Coinbase transaction input (txIn):\n///\n/// | Bytes | Name | BTC type | Description |\n/// |--------|------------------|------------------------|---------------------------------------------|\n/// | 32 | hash | char[32] | A 32-byte 0x0 null (no previous_outpoint) |\n/// | 4 | index | uint32_t (LE) | 0xffffffff (no previous_outpoint) |\n/// | varies | script_bytes | compactSize uint (LE) | The number of bytes in the coinbase script |\n/// | varies | height | char[] | The block height of this block (BIP34) (*) |\n/// | varies | coinbase_script | none | Arbitrary data, max 100 bytes |\n/// | 4 | sequence | uint32_t (LE) | Sequence number\n///\n/// (*) Uses script language: starts with a data-pushing opcode that indicates how many bytes to push to\n/// the stack followed by the block height as a little-endian unsigned integer. This script must be as\n/// short as possible, otherwise it may be rejected. The data-pushing opcode will be 0x03 and the total\n/// size four bytes until block 16,777,216 about 300 years from now.\nlibrary BitcoinTx {\n using BTCUtils for bytes;\n using BTCUtils for uint256;\n using BytesLib for bytes;\n using ValidateSPV for bytes;\n using ValidateSPV for bytes32;\n\n /// @notice Represents Bitcoin transaction data.\n struct Info {\n /// @notice Bitcoin transaction version.\n /// @dev `version` from raw Bitcoin transaction data.\n /// Encoded as 4-bytes signed integer, little endian.\n bytes4 version;\n /// @notice All Bitcoin transaction inputs, prepended by the number of\n /// transaction inputs.\n /// @dev `tx_in_count | tx_in` from raw Bitcoin transaction data.\n ///\n /// The number of transaction inputs encoded as compactSize\n /// unsigned integer, little-endian.\n ///\n /// Note that some popular block explorers reverse the order of\n /// bytes from `outpoint`'s `hash` and display it as big-endian.\n /// Solidity code of Bridge expects hashes in little-endian, just\n /// like they are represented in a raw Bitcoin transaction.\n bytes inputVector;\n /// @notice All Bitcoin transaction outputs prepended by the number of\n /// transaction outputs.\n /// @dev `tx_out_count | tx_out` from raw Bitcoin transaction data.\n ///\n /// The number of transaction outputs encoded as a compactSize\n /// unsigned integer, little-endian.\n bytes outputVector;\n /// @notice Bitcoin transaction locktime.\n ///\n /// @dev `lock_time` from raw Bitcoin transaction data.\n /// Encoded as 4-bytes unsigned integer, little endian.\n bytes4 locktime;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's calldata argument.\n }\n\n /// @notice Represents data needed to perform a Bitcoin SPV proof.\n struct Proof {\n /// @notice The merkle proof of transaction inclusion in a block.\n bytes merkleProof;\n /// @notice Transaction index in the block (0-indexed).\n uint256 txIndexInBlock;\n /// @notice Single byte-string of 80-byte bitcoin headers,\n /// lowest height first.\n bytes bitcoinHeaders;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's calldata argument.\n }\n\n /// @notice Represents info about an unspent transaction output.\n struct UTXO {\n /// @notice Hash of the transaction the output belongs to.\n /// @dev Byte order corresponds to the Bitcoin internal byte order.\n bytes32 txHash;\n /// @notice Index of the transaction output (0-indexed).\n uint32 txOutputIndex;\n /// @notice Value of the transaction output.\n uint64 txOutputValue;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's calldata argument.\n }\n\n /// @notice Represents Bitcoin signature in the R/S/V format.\n struct RSVSignature {\n /// @notice Signature r value.\n bytes32 r;\n /// @notice Signature s value.\n bytes32 s;\n /// @notice Signature recovery value.\n uint8 v;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's calldata argument.\n }\n\n /// @notice Validates the SPV proof of the Bitcoin transaction.\n /// Reverts in case the validation or proof verification fail.\n /// @param txInfo Bitcoin transaction data.\n /// @param proof Bitcoin proof data.\n /// @return txHash Proven 32-byte transaction hash.\n function validateProof(\n BridgeState.Storage storage self,\n Info calldata txInfo,\n Proof calldata proof\n ) internal view returns (bytes32 txHash) {\n require(\n txInfo.inputVector.validateVin(),\n \"Invalid input vector provided\"\n );\n require(\n txInfo.outputVector.validateVout(),\n \"Invalid output vector provided\"\n );\n\n txHash = abi\n .encodePacked(\n txInfo.version,\n txInfo.inputVector,\n txInfo.outputVector,\n txInfo.locktime\n )\n .hash256View();\n\n require(\n txHash.prove(\n proof.bitcoinHeaders.extractMerkleRootLE(),\n proof.merkleProof,\n proof.txIndexInBlock\n ),\n \"Tx merkle proof is not valid for provided header and tx hash\"\n );\n\n evaluateProofDifficulty(self, proof.bitcoinHeaders);\n\n return txHash;\n }\n\n /// @notice Evaluates the given Bitcoin proof difficulty against the actual\n /// Bitcoin chain difficulty provided by the relay oracle.\n /// Reverts in case the evaluation fails.\n /// @param bitcoinHeaders Bitcoin headers chain being part of the SPV\n /// proof. Used to extract the observed proof difficulty.\n function evaluateProofDifficulty(\n BridgeState.Storage storage self,\n bytes memory bitcoinHeaders\n ) internal view {\n IRelay relay = self.relay;\n uint256 currentEpochDifficulty = relay.getCurrentEpochDifficulty();\n uint256 previousEpochDifficulty = relay.getPrevEpochDifficulty();\n\n uint256 requestedDiff = 0;\n uint256 firstHeaderDiff = bitcoinHeaders\n .extractTarget()\n .calculateDifficulty();\n\n if (firstHeaderDiff == currentEpochDifficulty) {\n requestedDiff = currentEpochDifficulty;\n } else if (firstHeaderDiff == previousEpochDifficulty) {\n requestedDiff = previousEpochDifficulty;\n } else {\n revert(\"Not at current or previous difficulty\");\n }\n\n uint256 observedDiff = bitcoinHeaders.validateHeaderChain();\n\n require(\n observedDiff != ValidateSPV.getErrBadLength(),\n \"Invalid length of the headers chain\"\n );\n require(\n observedDiff != ValidateSPV.getErrInvalidChain(),\n \"Invalid headers chain\"\n );\n require(\n observedDiff != ValidateSPV.getErrLowWork(),\n \"Insufficient work in a header\"\n );\n\n require(\n observedDiff >= requestedDiff * self.txProofDifficultyFactor,\n \"Insufficient accumulated difficulty in header chain\"\n );\n }\n\n /// @notice Extracts public key hash from the provided P2PKH or P2WPKH output.\n /// Reverts if the validation fails.\n /// @param output The transaction output.\n /// @return pubKeyHash 20-byte public key hash the output locks funds on.\n /// @dev Requirements:\n /// - The output must be of P2PKH or P2WPKH type and lock the funds\n /// on a 20-byte public key hash.\n function extractPubKeyHash(BridgeState.Storage storage, bytes memory output)\n internal\n view\n returns (bytes20 pubKeyHash)\n {\n bytes memory pubKeyHashBytes = output.extractHash();\n\n require(\n pubKeyHashBytes.length == 20,\n \"Output's public key hash must have 20 bytes\"\n );\n\n pubKeyHash = pubKeyHashBytes.slice20(0);\n\n // We need to make sure that the 20-byte public key hash\n // is actually used in the right context of a P2PKH or P2WPKH\n // output. To do so, we must extract the full script from the output\n // and compare with the expected P2PKH and P2WPKH scripts\n // referring to that 20-byte public key hash. The output consists\n // of an 8-byte value and a variable length script. To extract the\n // script we slice the output starting from 9th byte until the end.\n bytes32 outputScriptKeccak = keccak256(\n output.slice(8, output.length - 8)\n );\n // Build the expected P2PKH script which has the following byte\n // format: <0x1976a914> <20-byte PKH> <0x88ac>. According to\n // https://en.bitcoin.it/wiki/Script#Opcodes this translates to:\n // - 0x19: Byte length of the entire script\n // - 0x76: OP_DUP\n // - 0xa9: OP_HASH160\n // - 0x14: Byte length of the public key hash\n // - 0x88: OP_EQUALVERIFY\n // - 0xac: OP_CHECKSIG\n // which matches the P2PKH structure as per:\n // https://en.bitcoin.it/wiki/Transaction#Pay-to-PubkeyHash\n bytes32 P2PKHScriptKeccak = keccak256(\n abi.encodePacked(hex\"1976a914\", pubKeyHash, hex\"88ac\")\n );\n // Build the expected P2WPKH script which has the following format:\n // <0x160014> <20-byte PKH>. According to\n // https://en.bitcoin.it/wiki/Script#Opcodes this translates to:\n // - 0x16: Byte length of the entire script\n // - 0x00: OP_0\n // - 0x14: Byte length of the public key hash\n // which matches the P2WPKH structure as per:\n // https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#P2WPKH\n bytes32 P2WPKHScriptKeccak = keccak256(\n abi.encodePacked(hex\"160014\", pubKeyHash)\n );\n // Make sure the actual output script matches either the P2PKH\n // or P2WPKH format.\n require(\n outputScriptKeccak == P2PKHScriptKeccak ||\n outputScriptKeccak == P2WPKHScriptKeccak,\n \"Output must be P2PKH or P2WPKH\"\n );\n\n return pubKeyHash;\n }\n}\n"
150
+ },
151
+ "contracts/bridge/EcdsaLib.sol": {
152
+ "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport \"@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol\";\n\nlibrary EcdsaLib {\n using BytesLib for bytes;\n\n /// @notice Converts public key X and Y coordinates (32-byte each) to a\n /// compressed public key (33-byte). Compressed public key is X\n /// coordinate prefixed with `02` or `03` based on the Y coordinate parity.\n /// It is expected that the uncompressed public key is stripped\n /// (i.e. it is not prefixed with `04`).\n /// @param x Wallet's public key's X coordinate.\n /// @param y Wallet's public key's Y coordinate.\n /// @return Compressed public key (33-byte), prefixed with `02` or `03`.\n function compressPublicKey(bytes32 x, bytes32 y)\n internal\n pure\n returns (bytes memory)\n {\n bytes1 prefix;\n if (uint256(y) % 2 == 0) {\n prefix = hex\"02\";\n } else {\n prefix = hex\"03\";\n }\n\n return bytes.concat(prefix, x);\n }\n}\n"
153
+ },
154
+ "contracts/bridge/Wallets.sol": {
155
+ "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\nimport {EcdsaDkg} from \"@keep-network/ecdsa/contracts/libraries/EcdsaDkg.sol\";\nimport {Math} from \"@openzeppelin/contracts/utils/math/Math.sol\";\n\nimport \"./BitcoinTx.sol\";\nimport \"./EcdsaLib.sol\";\nimport \"./BridgeState.sol\";\n\n/// @title Wallet library\n/// @notice Library responsible for handling integration between Bridge\n/// contract and ECDSA wallets.\nlibrary Wallets {\n using BTCUtils for bytes;\n\n /// @notice Represents wallet state:\n enum WalletState {\n /// @dev The wallet is unknown to the Bridge.\n Unknown,\n /// @dev The wallet can sweep deposits and accept redemption requests.\n Live,\n /// @dev The wallet was deemed unhealthy and is expected to move their\n /// outstanding funds to another wallet. The wallet can still\n /// fulfill their pending redemption requests although new\n /// redemption requests and new deposit reveals are not accepted.\n MovingFunds,\n /// @dev The wallet moved or redeemed all their funds and is in the\n /// closing period where they can be subject of fraud challenges\n /// and must defend against them. This state is needed to protect\n /// against deposit frauds on deposits revealed but not swept.\n /// The closing period must be greater that the deposit refund\n /// time plus some time margin.\n Closing,\n /// @dev The wallet finalized the closing period successfully and\n /// cannot perform any action in the Bridge.\n Closed,\n /// @dev The wallet committed a fraud that was reported. The wallet is\n /// blocked and can not perform any actions in the Bridge.\n /// Off-chain coordination with the wallet operators is needed to\n /// recover funds.\n Terminated\n }\n\n /// @notice Holds information about a wallet.\n struct Wallet {\n // Identifier of a ECDSA Wallet registered in the ECDSA Wallet Registry.\n bytes32 ecdsaWalletID;\n // Latest wallet's main UTXO hash computed as\n // keccak256(txHash | txOutputIndex | txOutputValue). The `tx` prefix\n // refers to the transaction which created that main UTXO. The `txHash`\n // is `bytes32` (ordered as in Bitcoin internally), `txOutputIndex`\n // an `uint32`, and `txOutputValue` an `uint64` value.\n bytes32 mainUtxoHash;\n // The total redeemable value of pending redemption requests targeting\n // that wallet.\n uint64 pendingRedemptionsValue;\n // UNIX timestamp the wallet was created at.\n uint32 createdAt;\n // UNIX timestamp indicating the moment the wallet was requested to\n // move their funds.\n uint32 movingFundsRequestedAt;\n // UNIX timestamp indicating the moment the wallet's closing period\n // started.\n uint32 closingStartedAt;\n // Total count of pending moved funds sweep requests targeting this wallet.\n uint32 pendingMovedFundsSweepRequestsCount;\n // Current state of the wallet.\n WalletState state;\n // Moving funds target wallet commitment submitted by the wallet. It\n // is built by applying the keccak256 hash over the list of 20-byte\n // public key hashes of the target wallets.\n bytes32 movingFundsTargetWalletsCommitmentHash;\n // This struct doesn't contain `__gap` property as the structure is stored\n // in a mapping, mappings store values in different slots and they are\n // not contiguous with other values.\n }\n\n event NewWalletRequested();\n\n event NewWalletRegistered(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletMovingFunds(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletClosing(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletClosed(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletTerminated(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n /// @notice Requests creation of a new wallet. This function just\n /// forms a request and the creation process is performed\n /// asynchronously. Outcome of that process should be delivered\n /// using `registerNewWallet` function.\n /// @param activeWalletMainUtxo Data of the active wallet's main UTXO, as\n /// currently known on the Ethereum chain.\n /// @dev Requirements:\n /// - `activeWalletMainUtxo` components must point to the recent main\n /// UTXO of the given active wallet, as currently known on the\n /// Ethereum chain. If there is no active wallet at the moment, or\n /// the active wallet has no main UTXO, this parameter can be\n /// empty as it is ignored,\n /// - Wallet creation must not be in progress,\n /// - If the active wallet is set, one of the following\n /// conditions must be true:\n /// - The active wallet BTC balance is above the minimum threshold\n /// and the active wallet is old enough, i.e. the creation period\n /// was elapsed since its creation time,\n /// - The active wallet BTC balance is above the maximum threshold.\n function requestNewWallet(\n BridgeState.Storage storage self,\n BitcoinTx.UTXO calldata activeWalletMainUtxo\n ) external {\n require(\n self.ecdsaWalletRegistry.getWalletCreationState() ==\n EcdsaDkg.State.IDLE,\n \"Wallet creation already in progress\"\n );\n\n bytes20 activeWalletPubKeyHash = self.activeWalletPubKeyHash;\n\n // If the active wallet is set, fetch this wallet's details from\n // storage to perform conditions check. The `registerNewWallet`\n // function guarantees an active wallet is always one of the\n // registered ones.\n if (activeWalletPubKeyHash != bytes20(0)) {\n uint64 activeWalletBtcBalance = getWalletBtcBalance(\n self,\n activeWalletPubKeyHash,\n activeWalletMainUtxo\n );\n uint32 activeWalletCreatedAt = self\n .registeredWallets[activeWalletPubKeyHash]\n .createdAt;\n /* solhint-disable-next-line not-rely-on-time */\n bool activeWalletOldEnough = block.timestamp >=\n activeWalletCreatedAt + self.walletCreationPeriod;\n\n require(\n (activeWalletOldEnough &&\n activeWalletBtcBalance >=\n self.walletCreationMinBtcBalance) ||\n activeWalletBtcBalance >= self.walletCreationMaxBtcBalance,\n \"Wallet creation conditions are not met\"\n );\n }\n\n emit NewWalletRequested();\n\n self.ecdsaWalletRegistry.requestNewWallet();\n }\n\n /// @notice Gets BTC balance for given the wallet.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @param walletMainUtxo Data of the wallet's main UTXO, as currently\n /// known on the Ethereum chain.\n /// @return walletBtcBalance Current BTC balance for the given wallet.\n /// @dev Requirements:\n /// - `walletMainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// If the wallet has no main UTXO, this parameter can be empty as it\n /// is ignored.\n function getWalletBtcBalance(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata walletMainUtxo\n ) internal view returns (uint64 walletBtcBalance) {\n bytes32 walletMainUtxoHash = self\n .registeredWallets[walletPubKeyHash]\n .mainUtxoHash;\n\n // If the wallet has a main UTXO hash set, cross-check it with the\n // provided plain-text parameter and get the transaction output value\n // as BTC balance. Otherwise, the BTC balance is just zero.\n if (walletMainUtxoHash != bytes32(0)) {\n require(\n keccak256(\n abi.encodePacked(\n walletMainUtxo.txHash,\n walletMainUtxo.txOutputIndex,\n walletMainUtxo.txOutputValue\n )\n ) == walletMainUtxoHash,\n \"Invalid wallet main UTXO data\"\n );\n\n walletBtcBalance = walletMainUtxo.txOutputValue;\n }\n\n return walletBtcBalance;\n }\n\n /// @notice Registers a new wallet. This function should be called\n /// after the wallet creation process initiated using\n /// `requestNewWallet` completes and brings the outcomes.\n /// @param ecdsaWalletID Wallet's unique identifier.\n /// @param publicKeyX Wallet's public key's X coordinate.\n /// @param publicKeyY Wallet's public key's Y coordinate.\n /// @dev Requirements:\n /// - The only caller authorized to call this function is `registry`,\n /// - Given wallet data must not belong to an already registered wallet.\n function registerNewWallet(\n BridgeState.Storage storage self,\n bytes32 ecdsaWalletID,\n bytes32 publicKeyX,\n bytes32 publicKeyY\n ) external {\n require(\n msg.sender == address(self.ecdsaWalletRegistry),\n \"Caller is not the ECDSA Wallet Registry\"\n );\n\n // Compress wallet's public key and calculate Bitcoin's hash160 of it.\n bytes20 walletPubKeyHash = bytes20(\n EcdsaLib.compressPublicKey(publicKeyX, publicKeyY).hash160View()\n );\n\n Wallet storage wallet = self.registeredWallets[walletPubKeyHash];\n require(\n wallet.state == WalletState.Unknown,\n \"ECDSA wallet has been already registered\"\n );\n wallet.ecdsaWalletID = ecdsaWalletID;\n wallet.state = WalletState.Live;\n /* solhint-disable-next-line not-rely-on-time */\n wallet.createdAt = uint32(block.timestamp);\n\n // Set the freshly created wallet as the new active wallet.\n self.activeWalletPubKeyHash = walletPubKeyHash;\n\n self.liveWalletsCount++;\n\n emit NewWalletRegistered(ecdsaWalletID, walletPubKeyHash);\n }\n\n /// @notice Handles a notification about a wallet heartbeat failure and\n /// triggers the wallet moving funds process.\n /// @param publicKeyX Wallet's public key's X coordinate.\n /// @param publicKeyY Wallet's public key's Y coordinate.\n /// @dev Requirements:\n /// - The only caller authorized to call this function is `registry`,\n /// - Wallet must be in Live state.\n function notifyWalletHeartbeatFailed(\n BridgeState.Storage storage self,\n bytes32 publicKeyX,\n bytes32 publicKeyY\n ) external {\n require(\n msg.sender == address(self.ecdsaWalletRegistry),\n \"Caller is not the ECDSA Wallet Registry\"\n );\n\n // Compress wallet's public key and calculate Bitcoin's hash160 of it.\n bytes20 walletPubKeyHash = bytes20(\n EcdsaLib.compressPublicKey(publicKeyX, publicKeyY).hash160View()\n );\n\n require(\n self.registeredWallets[walletPubKeyHash].state == WalletState.Live,\n \"ECDSA wallet must be in Live state\"\n );\n\n moveFunds(self, walletPubKeyHash);\n }\n\n /// @notice Handles a notification about a wallet redemption timeout.\n /// Triggers the wallet moving funds process only if the wallet is\n /// still in the Live state. That means multiple action timeouts can\n /// be reported for the same wallet but only the first report\n /// requests the wallet to move their funds.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @dev Requirements:\n /// - The wallet must be in the `Live` or `MovingFunds` state.\n function notifyWalletTimedOutRedemption(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash\n ) internal {\n WalletState walletState = self\n .registeredWallets[walletPubKeyHash]\n .state;\n\n require(\n walletState == WalletState.Live ||\n walletState == WalletState.MovingFunds,\n \"ECDSA wallet must be in Live or MovingFunds state\"\n );\n\n if (walletState == WalletState.Live) {\n moveFunds(self, walletPubKeyHash);\n }\n }\n\n /// @notice Notifies that the wallet is either old enough or has too few\n /// satoshis left and qualifies to be closed.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @param walletMainUtxo Data of the wallet's main UTXO, as currently\n /// known on the Ethereum chain.\n /// @dev Requirements:\n /// - Wallet must not be set as the current active wallet,\n /// - Wallet must exceed the wallet maximum age OR the wallet BTC\n /// balance must be lesser than the minimum threshold. If the latter\n /// case is true, the `walletMainUtxo` components must point to the\n /// recent main UTXO of the given wallet, as currently known on the\n /// Ethereum chain. If the wallet has no main UTXO, this parameter\n /// can be empty as it is ignored since the wallet balance is\n /// assumed to be zero,\n /// - Wallet must be in Live state.\n function notifyCloseableWallet(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata walletMainUtxo\n ) external {\n require(\n self.activeWalletPubKeyHash != walletPubKeyHash,\n \"Active wallet cannot be considered closeable\"\n );\n\n Wallet storage wallet = self.registeredWallets[walletPubKeyHash];\n require(\n wallet.state == WalletState.Live,\n \"ECDSA wallet must be in Live state\"\n );\n\n /* solhint-disable-next-line not-rely-on-time */\n bool walletOldEnough = block.timestamp >=\n wallet.createdAt + self.walletMaxAge;\n\n require(\n walletOldEnough ||\n getWalletBtcBalance(self, walletPubKeyHash, walletMainUtxo) <\n self.walletClosureMinBtcBalance,\n \"Wallet needs to be old enough or have too few satoshis\"\n );\n\n moveFunds(self, walletPubKeyHash);\n }\n\n /// @notice Requests a wallet to move their funds. If the wallet balance\n /// is zero, the wallet closing begins immediately. If the move\n /// funds request refers to the current active wallet, such a wallet\n /// is no longer considered active and the active wallet slot\n /// is unset allowing to trigger a new wallet creation immediately.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @dev Requirements:\n /// - The caller must make sure that the wallet is in the Live state.\n function moveFunds(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash\n ) internal {\n Wallet storage wallet = self.registeredWallets[walletPubKeyHash];\n\n if (wallet.mainUtxoHash == bytes32(0)) {\n // If the wallet has no main UTXO, that means its BTC balance\n // is zero and the wallet closing should begin immediately.\n beginWalletClosing(self, walletPubKeyHash);\n } else {\n // Otherwise, initialize the moving funds process.\n wallet.state = WalletState.MovingFunds;\n /* solhint-disable-next-line not-rely-on-time */\n wallet.movingFundsRequestedAt = uint32(block.timestamp);\n\n emit WalletMovingFunds(wallet.ecdsaWalletID, walletPubKeyHash);\n }\n\n if (self.activeWalletPubKeyHash == walletPubKeyHash) {\n // If the move funds request refers to the current active wallet,\n // unset the active wallet and make the wallet creation process\n // possible in order to get a new healthy active wallet.\n delete self.activeWalletPubKeyHash;\n }\n\n self.liveWalletsCount--;\n }\n\n /// @notice Begins the closing period of the given wallet.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @dev Requirements:\n /// - The caller must make sure that the wallet is in the\n /// MovingFunds state.\n function beginWalletClosing(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash\n ) internal {\n Wallet storage wallet = self.registeredWallets[walletPubKeyHash];\n // Initialize the closing period.\n wallet.state = WalletState.Closing;\n /* solhint-disable-next-line not-rely-on-time */\n wallet.closingStartedAt = uint32(block.timestamp);\n\n emit WalletClosing(wallet.ecdsaWalletID, walletPubKeyHash);\n }\n\n /// @notice Notifies about the end of the closing period for the given wallet.\n /// Closes the wallet ultimately and notifies the ECDSA registry\n /// about this fact.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @dev Requirements:\n /// - The wallet must be in the Closing state,\n /// - The wallet closing period must have elapsed.\n function notifyWalletClosingPeriodElapsed(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash\n ) internal {\n Wallet storage wallet = self.registeredWallets[walletPubKeyHash];\n\n require(\n wallet.state == WalletState.Closing,\n \"ECDSA wallet must be in Closing state\"\n );\n\n require(\n /* solhint-disable-next-line not-rely-on-time */\n block.timestamp >\n wallet.closingStartedAt + self.walletClosingPeriod,\n \"Closing period has not elapsed yet\"\n );\n\n finalizeWalletClosing(self, walletPubKeyHash);\n }\n\n /// @notice Finalizes the closing period of the given wallet and notifies\n /// the ECDSA registry about this fact.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @dev Requirements:\n /// - The caller must make sure that the wallet is in the Closing state.\n function finalizeWalletClosing(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash\n ) internal {\n Wallet storage wallet = self.registeredWallets[walletPubKeyHash];\n\n wallet.state = WalletState.Closed;\n\n emit WalletClosed(wallet.ecdsaWalletID, walletPubKeyHash);\n\n self.ecdsaWalletRegistry.closeWallet(wallet.ecdsaWalletID);\n }\n\n /// @notice Terminates the given wallet and notifies the ECDSA registry\n /// about this fact. If the wallet termination refers to the current\n /// active wallet, such a wallet is no longer considered active and\n /// the active wallet slot is unset allowing to trigger a new wallet\n /// creation immediately.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @dev Requirements:\n /// - The caller must make sure that the wallet is in the\n /// Live or MovingFunds or Closing state.\n function terminateWallet(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash\n ) internal {\n Wallet storage wallet = self.registeredWallets[walletPubKeyHash];\n\n if (wallet.state == WalletState.Live) {\n self.liveWalletsCount--;\n }\n\n wallet.state = WalletState.Terminated;\n\n emit WalletTerminated(wallet.ecdsaWalletID, walletPubKeyHash);\n\n if (self.activeWalletPubKeyHash == walletPubKeyHash) {\n // If termination refers to the current active wallet,\n // unset the active wallet and make the wallet creation process\n // possible in order to get a new healthy active wallet.\n delete self.activeWalletPubKeyHash;\n }\n\n self.ecdsaWalletRegistry.closeWallet(wallet.ecdsaWalletID);\n }\n\n /// @notice Notifies that the wallet completed the moving funds process\n /// successfully. Checks if the funds were moved to the expected\n /// target wallets. Closes the source wallet if everything went\n /// good and reverts otherwise.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @param targetWalletsHash 32-byte keccak256 hash over the list of\n /// 20-byte public key hashes of the target wallets actually used\n /// within the moving funds transactions.\n /// @dev Requirements:\n /// - The caller must make sure the moving funds transaction actually\n /// happened on Bitcoin chain and fits the protocol requirements,\n /// - The source wallet must be in the MovingFunds state,\n /// - The target wallets commitment must be submitted by the source\n /// wallet,\n /// - The actual target wallets used in the moving funds transaction\n /// must be exactly the same as the target wallets commitment.\n function notifyWalletFundsMoved(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n bytes32 targetWalletsHash\n ) internal {\n Wallet storage wallet = self.registeredWallets[walletPubKeyHash];\n // Check that the wallet is in the MovingFunds state but don't check\n // if the moving funds timeout is exceeded. That should give a\n // possibility to move funds in case when timeout was hit but was\n // not reported yet.\n require(\n wallet.state == WalletState.MovingFunds,\n \"ECDSA wallet must be in MovingFunds state\"\n );\n\n bytes32 targetWalletsCommitmentHash = wallet\n .movingFundsTargetWalletsCommitmentHash;\n\n require(\n targetWalletsCommitmentHash != bytes32(0),\n \"Target wallets commitment not submitted yet\"\n );\n\n // Make sure that the target wallets where funds were moved to are\n // exactly the same as the ones the source wallet committed to.\n require(\n targetWalletsCommitmentHash == targetWalletsHash,\n \"Target wallets don't correspond to the commitment\"\n );\n\n // If funds were moved, the wallet has no longer a main UTXO.\n delete wallet.mainUtxoHash;\n\n beginWalletClosing(self, walletPubKeyHash);\n }\n}\n"
156
+ },
157
+ "contracts/bridge/Fraud.sol": {
158
+ "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {BytesLib} from \"@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol\";\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\nimport {CheckBitcoinSigs} from \"@keep-network/bitcoin-spv-sol/contracts/CheckBitcoinSigs.sol\";\n\nimport \"./BitcoinTx.sol\";\nimport \"./EcdsaLib.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Heartbeat.sol\";\nimport \"./MovingFunds.sol\";\nimport \"./Wallets.sol\";\n\n/// @title Bridge fraud\n/// @notice The library handles the logic for challenging Bridge wallets that\n/// committed fraud.\n/// @dev Anyone can submit a fraud challenge indicating that a UTXO being under\n/// the wallet control was unlocked by the wallet but was not used\n/// according to the protocol rules. That means the wallet signed\n/// a transaction input pointing to that UTXO and there is a unique\n/// sighash and signature pair associated with that input.\n///\n/// In order to defeat the challenge, the same wallet public key and\n/// signature must be provided as were used to calculate the sighash during\n/// the challenge. The wallet provides the preimage which produces sighash\n/// used to generate the ECDSA signature that is the subject of the fraud\n/// claim.\n///\n/// The fraud challenge defeat attempt will succeed if the inputs in the\n/// preimage are considered honestly spent by the wallet. Therefore the\n/// transaction spending the UTXO must be proven in the Bridge before\n/// a challenge defeat is called.\n///\n/// Another option is when a malicious wallet member used a signed heartbeat\n/// message periodically produced by the wallet off-chain to challenge the\n/// wallet for a fraud. Anyone from the wallet can defeat the challenge by\n/// proving the sighash and signature were produced for a heartbeat message\n/// following a strict format.\nlibrary Fraud {\n using Wallets for BridgeState.Storage;\n\n using BytesLib for bytes;\n using BTCUtils for bytes;\n using BTCUtils for uint32;\n using EcdsaLib for bytes;\n\n struct FraudChallenge {\n // The address of the party challenging the wallet.\n address challenger;\n // The amount of ETH the challenger deposited.\n uint256 depositAmount;\n // The timestamp the challenge was submitted at.\n uint32 reportedAt;\n // The flag indicating whether the challenge has been resolved.\n bool resolved;\n // This struct doesn't contain `__gap` property as the structure is stored\n // in a mapping, mappings store values in different slots and they are\n // not contiguous with other values.\n }\n\n event FraudChallengeSubmitted(\n bytes20 indexed walletPubKeyHash,\n bytes32 sighash,\n uint8 v,\n bytes32 r,\n bytes32 s\n );\n\n event FraudChallengeDefeated(\n bytes20 indexed walletPubKeyHash,\n bytes32 sighash\n );\n\n event FraudChallengeDefeatTimedOut(\n bytes20 indexed walletPubKeyHash,\n // Sighash calculated as a Bitcoin's hash256 (double sha2) of:\n // - a preimage of a transaction spending UTXO according to the protocol\n // rules OR\n // - a valid heartbeat message produced by the wallet off-chain.\n bytes32 sighash\n );\n\n /// @notice Submits a fraud challenge indicating that a UTXO being under\n /// wallet control was unlocked by the wallet but was not used\n /// according to the protocol rules. That means the wallet signed\n /// a transaction input pointing to that UTXO and there is a unique\n /// sighash and signature pair associated with that input. This\n /// function uses those parameters to create a fraud accusation that\n /// proves a given transaction input unlocking the given UTXO was\n /// actually signed by the wallet. This function cannot determine\n /// whether the transaction was actually broadcast and the input was\n /// consumed in a fraudulent way so it just opens a challenge period\n /// during which the wallet can defeat the challenge by submitting\n /// proof of a transaction that consumes the given input according\n /// to protocol rules. To prevent spurious allegations, the caller\n /// must deposit ETH that is returned back upon justified fraud\n /// challenge or confiscated otherwise.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes).\n /// @param preimageSha256 The hash that was generated by applying SHA-256\n /// one time over the preimage used during input signing. The preimage\n /// is a serialized subset of the transaction and its structure\n /// depends on the transaction input (see BIP-143 for reference).\n /// Notice that applying SHA-256 over the `preimageSha256` results\n /// in `sighash`. The path from `preimage` to `sighash` looks like\n /// this:\n /// preimage -> (SHA-256) -> preimageSha256 -> (SHA-256) -> sighash.\n /// @param signature Bitcoin signature in the R/S/V format\n /// @dev Requirements:\n /// - Wallet behind `walletPublicKey` must be in Live or MovingFunds\n /// or Closing state,\n /// - The challenger must send appropriate amount of ETH used as\n /// fraud challenge deposit,\n /// - The signature (represented by r, s and v) must be generated by\n /// the wallet behind `walletPubKey` during signing of `sighash`\n /// which was calculated from `preimageSha256`,\n /// - Wallet can be challenged for the given signature only once.\n function submitFraudChallenge(\n BridgeState.Storage storage self,\n bytes calldata walletPublicKey,\n bytes memory preimageSha256,\n BitcoinTx.RSVSignature calldata signature\n ) external {\n require(\n msg.value >= self.fraudChallengeDepositAmount,\n \"The amount of ETH deposited is too low\"\n );\n\n // To prevent ECDSA signature forgery `sighash` must be calculated\n // inside the function and not passed as a function parameter.\n // Signature forgery could result in a wrongful fraud accusation\n // against a wallet.\n bytes32 sighash = sha256(preimageSha256);\n\n require(\n CheckBitcoinSigs.checkSig(\n walletPublicKey,\n sighash,\n signature.v,\n signature.r,\n signature.s\n ),\n \"Signature verification failure\"\n );\n\n bytes memory compressedWalletPublicKey = EcdsaLib.compressPublicKey(\n walletPublicKey.slice32(0),\n walletPublicKey.slice32(32)\n );\n bytes20 walletPubKeyHash = compressedWalletPublicKey.hash160View();\n\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n\n require(\n wallet.state == Wallets.WalletState.Live ||\n wallet.state == Wallets.WalletState.MovingFunds ||\n wallet.state == Wallets.WalletState.Closing,\n \"Wallet must be in Live or MovingFunds or Closing state\"\n );\n\n uint256 challengeKey = uint256(\n keccak256(abi.encodePacked(walletPublicKey, sighash))\n );\n\n FraudChallenge storage challenge = self.fraudChallenges[challengeKey];\n require(challenge.reportedAt == 0, \"Fraud challenge already exists\");\n\n challenge.challenger = msg.sender;\n challenge.depositAmount = msg.value;\n /* solhint-disable-next-line not-rely-on-time */\n challenge.reportedAt = uint32(block.timestamp);\n challenge.resolved = false;\n // slither-disable-next-line reentrancy-events\n emit FraudChallengeSubmitted(\n walletPubKeyHash,\n sighash,\n signature.v,\n signature.r,\n signature.s\n );\n }\n\n /// @notice Allows to defeat a pending fraud challenge against a wallet if\n /// the transaction that spends the UTXO follows the protocol rules.\n /// In order to defeat the challenge the same `walletPublicKey` and\n /// signature (represented by `r`, `s` and `v`) must be provided as\n /// were used to calculate the sighash during input signing.\n /// The fraud challenge defeat attempt will only succeed if the\n /// inputs in the preimage are considered honestly spent by the\n /// wallet. Therefore the transaction spending the UTXO must be\n /// proven in the Bridge before a challenge defeat is called.\n /// If successfully defeated, the fraud challenge is marked as\n /// resolved and the amount of ether deposited by the challenger is\n /// sent to the treasury.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes).\n /// @param preimage The preimage which produces sighash used to generate the\n /// ECDSA signature that is the subject of the fraud claim. It is a\n /// serialized subset of the transaction. The exact subset used as\n /// the preimage depends on the transaction input the signature is\n /// produced for. See BIP-143 for reference.\n /// @param witness Flag indicating whether the preimage was produced for a\n /// witness input. True for witness, false for non-witness input.\n /// @dev Requirements:\n /// - `walletPublicKey` and `sighash` calculated as `hash256(preimage)`\n /// must identify an open fraud challenge,\n /// - the preimage must be a valid preimage of a transaction generated\n /// according to the protocol rules and already proved in the Bridge,\n /// - before a defeat attempt is made the transaction that spends the\n /// given UTXO must be proven in the Bridge.\n function defeatFraudChallenge(\n BridgeState.Storage storage self,\n bytes calldata walletPublicKey,\n bytes calldata preimage,\n bool witness\n ) external {\n bytes32 sighash = preimage.hash256();\n\n uint256 challengeKey = uint256(\n keccak256(abi.encodePacked(walletPublicKey, sighash))\n );\n\n FraudChallenge storage challenge = self.fraudChallenges[challengeKey];\n\n require(challenge.reportedAt > 0, \"Fraud challenge does not exist\");\n require(\n !challenge.resolved,\n \"Fraud challenge has already been resolved\"\n );\n\n // Ensure SIGHASH_ALL type was used during signing, which is represented\n // by type value `1`.\n require(extractSighashType(preimage) == 1, \"Wrong sighash type\");\n\n uint256 utxoKey = witness\n ? extractUtxoKeyFromWitnessPreimage(preimage)\n : extractUtxoKeyFromNonWitnessPreimage(preimage);\n\n // Check that the UTXO key identifies a correctly spent UTXO.\n require(\n self.deposits[utxoKey].sweptAt > 0 ||\n self.spentMainUTXOs[utxoKey] ||\n self.movedFundsSweepRequests[utxoKey].state ==\n MovingFunds.MovedFundsSweepRequestState.Processed,\n \"Spent UTXO not found among correctly spent UTXOs\"\n );\n\n resolveFraudChallenge(self, walletPublicKey, challenge, sighash);\n }\n\n /// @notice Allows to defeat a pending fraud challenge against a wallet by\n /// proving the sighash and signature were produced for an off-chain\n /// wallet heartbeat message following a strict format.\n /// In order to defeat the challenge the same `walletPublicKey` and\n /// signature (represented by `r`, `s` and `v`) must be provided as\n /// were used to calculate the sighash during heartbeat message\n /// signing. The fraud challenge defeat attempt will only succeed if\n /// the signed message follows a strict format required for\n /// heartbeat messages. If successfully defeated, the fraud\n /// challenge is marked as resolved and the amount of ether\n /// deposited by the challenger is sent to the treasury.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes),\n /// @param heartbeatMessage Off-chain heartbeat message meeting the heartbeat\n /// message format requirements which produces sighash used to\n /// generate the ECDSA signature that is the subject of the fraud\n /// claim.\n /// @dev Requirements:\n /// - `walletPublicKey` and `sighash` calculated as\n /// `hash256(heartbeatMessage)` must identify an open fraud challenge,\n /// - `heartbeatMessage` must follow a strict format of heartbeat\n /// messages.\n function defeatFraudChallengeWithHeartbeat(\n BridgeState.Storage storage self,\n bytes calldata walletPublicKey,\n bytes calldata heartbeatMessage\n ) external {\n bytes32 sighash = heartbeatMessage.hash256();\n\n uint256 challengeKey = uint256(\n keccak256(abi.encodePacked(walletPublicKey, sighash))\n );\n\n FraudChallenge storage challenge = self.fraudChallenges[challengeKey];\n\n require(challenge.reportedAt > 0, \"Fraud challenge does not exist\");\n require(\n !challenge.resolved,\n \"Fraud challenge has already been resolved\"\n );\n\n require(\n Heartbeat.isValidHeartbeatMessage(heartbeatMessage),\n \"Not a valid heartbeat message\"\n );\n\n resolveFraudChallenge(self, walletPublicKey, challenge, sighash);\n }\n\n /// @notice Called only for successfully defeated fraud challenges.\n /// The fraud challenge is marked as resolved and the amount of\n /// ether deposited by the challenger is sent to the treasury.\n /// @dev Requirements:\n /// - Must be called only for successfully defeated fraud challenges.\n function resolveFraudChallenge(\n BridgeState.Storage storage self,\n bytes calldata walletPublicKey,\n FraudChallenge storage challenge,\n bytes32 sighash\n ) internal {\n // Mark the challenge as resolved as it was successfully defeated\n challenge.resolved = true;\n\n // Send the ether deposited by the challenger to the treasury\n /* solhint-disable avoid-low-level-calls */\n // slither-disable-next-line low-level-calls,unchecked-lowlevel,arbitrary-send\n self.treasury.call{gas: 100000, value: challenge.depositAmount}(\"\");\n /* solhint-enable avoid-low-level-calls */\n\n bytes memory compressedWalletPublicKey = EcdsaLib.compressPublicKey(\n walletPublicKey.slice32(0),\n walletPublicKey.slice32(32)\n );\n bytes20 walletPubKeyHash = compressedWalletPublicKey.hash160View();\n\n // slither-disable-next-line reentrancy-events\n emit FraudChallengeDefeated(walletPubKeyHash, sighash);\n }\n\n /// @notice Notifies about defeat timeout for the given fraud challenge.\n /// Can be called only if there was a fraud challenge identified by\n /// the provided `walletPublicKey` and `sighash` and it was not\n /// defeated on time. The amount of time that needs to pass after\n /// a fraud challenge is reported is indicated by the\n /// `challengeDefeatTimeout`. After a successful fraud challenge\n /// defeat timeout notification the fraud challenge is marked as\n /// resolved, the stake of each operator is slashed, the ether\n /// deposited is returned to the challenger and the challenger is\n /// rewarded.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes).\n /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @param preimageSha256 The hash that was generated by applying SHA-256\n /// one time over the preimage used during input signing. The preimage\n /// is a serialized subset of the transaction and its structure\n /// depends on the transaction input (see BIP-143 for reference).\n /// Notice that applying SHA-256 over the `preimageSha256` results\n /// in `sighash`. The path from `preimage` to `sighash` looks like\n /// this:\n /// preimage -> (SHA-256) -> preimageSha256 -> (SHA-256) -> sighash.\n /// @dev Requirements:\n /// - The wallet must be in the Live or MovingFunds or Closing or\n /// Terminated state,\n /// - The `walletPublicKey` and `sighash` calculated from\n /// `preimageSha256` must identify an open fraud challenge,\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events of the `WalletRegistry` contract,\n /// - The amount of time indicated by `challengeDefeatTimeout` must pass\n /// after the challenge was reported.\n function notifyFraudChallengeDefeatTimeout(\n BridgeState.Storage storage self,\n bytes calldata walletPublicKey,\n uint32[] calldata walletMembersIDs,\n bytes memory preimageSha256\n ) external {\n bytes32 sighash = sha256(preimageSha256);\n\n uint256 challengeKey = uint256(\n keccak256(abi.encodePacked(walletPublicKey, sighash))\n );\n\n FraudChallenge storage challenge = self.fraudChallenges[challengeKey];\n\n require(challenge.reportedAt > 0, \"Fraud challenge does not exist\");\n\n require(\n !challenge.resolved,\n \"Fraud challenge has already been resolved\"\n );\n\n require(\n /* solhint-disable-next-line not-rely-on-time */\n block.timestamp >=\n challenge.reportedAt + self.fraudChallengeDefeatTimeout,\n \"Fraud challenge defeat period did not time out yet\"\n );\n\n challenge.resolved = true;\n // Return the ether deposited by the challenger\n /* solhint-disable avoid-low-level-calls */\n // slither-disable-next-line low-level-calls,unchecked-lowlevel\n challenge.challenger.call{gas: 100000, value: challenge.depositAmount}(\n \"\"\n );\n /* solhint-enable avoid-low-level-calls */\n\n bytes memory compressedWalletPublicKey = EcdsaLib.compressPublicKey(\n walletPublicKey.slice32(0),\n walletPublicKey.slice32(32)\n );\n bytes20 walletPubKeyHash = compressedWalletPublicKey.hash160View();\n\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n\n Wallets.WalletState walletState = wallet.state;\n\n if (\n walletState == Wallets.WalletState.Live ||\n walletState == Wallets.WalletState.MovingFunds ||\n walletState == Wallets.WalletState.Closing\n ) {\n self.terminateWallet(walletPubKeyHash);\n\n self.ecdsaWalletRegistry.seize(\n self.fraudSlashingAmount,\n self.fraudNotifierRewardMultiplier,\n challenge.challenger,\n wallet.ecdsaWalletID,\n walletMembersIDs\n );\n } else if (walletState == Wallets.WalletState.Terminated) {\n // This is a special case when the wallet was already terminated\n // due to a previous deliberate protocol violation. In that\n // case, this function should be still callable for other fraud\n // challenges timeouts in order to let the challenger unlock its\n // ETH deposit back. However, the wallet termination logic is\n // not called and the challenger is not rewarded.\n } else {\n revert(\n \"Wallet must be in Live or MovingFunds or Closing or Terminated state\"\n );\n }\n\n // slither-disable-next-line reentrancy-events\n emit FraudChallengeDefeatTimedOut(walletPubKeyHash, sighash);\n }\n\n /// @notice Extracts the UTXO keys from the given preimage used during\n /// signing of a witness input.\n /// @param preimage The preimage which produces sighash used to generate the\n /// ECDSA signature that is the subject of the fraud claim. It is a\n /// serialized subset of the transaction. The exact subset used as\n /// the preimage depends on the transaction input the signature is\n /// produced for. See BIP-143 for reference\n /// @return utxoKey UTXO key that identifies spent input.\n function extractUtxoKeyFromWitnessPreimage(bytes calldata preimage)\n internal\n pure\n returns (uint256 utxoKey)\n {\n // The expected structure of the preimage created during signing of a\n // witness input:\n // - transaction version (4 bytes)\n // - hash of previous outpoints of all inputs (32 bytes)\n // - hash of sequences of all inputs (32 bytes)\n // - outpoint (hash + index) of the input being signed (36 bytes)\n // - the unlocking script of the input (variable length)\n // - value of the outpoint (8 bytes)\n // - sequence of the input being signed (4 bytes)\n // - hash of all outputs (32 bytes)\n // - transaction locktime (4 bytes)\n // - sighash type (4 bytes)\n\n // See Bitcoin's BIP-143 for reference:\n // https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki.\n\n // The outpoint (hash and index) is located at the constant offset of\n // 68 (4 + 32 + 32).\n bytes32 outpointTxHash = preimage.extractInputTxIdLeAt(68);\n uint32 outpointIndex = BTCUtils.reverseUint32(\n uint32(preimage.extractTxIndexLeAt(68))\n );\n\n return\n uint256(keccak256(abi.encodePacked(outpointTxHash, outpointIndex)));\n }\n\n /// @notice Extracts the UTXO key from the given preimage used during\n /// signing of a non-witness input.\n /// @param preimage The preimage which produces sighash used to generate the\n /// ECDSA signature that is the subject of the fraud claim. It is a\n /// serialized subset of the transaction. The exact subset used as\n /// the preimage depends on the transaction input the signature is\n /// produced for. See BIP-143 for reference.\n /// @return utxoKey UTXO key that identifies spent input.\n function extractUtxoKeyFromNonWitnessPreimage(bytes calldata preimage)\n internal\n pure\n returns (uint256 utxoKey)\n {\n // The expected structure of the preimage created during signing of a\n // non-witness input:\n // - transaction version (4 bytes)\n // - number of inputs written as compactSize uint (1 byte, 3 bytes,\n // 5 bytes or 9 bytes)\n // - for each input\n // - outpoint (hash and index) (36 bytes)\n // - unlocking script for the input being signed (variable length)\n // or `00` for all other inputs (1 byte)\n // - input sequence (4 bytes)\n // - number of outputs written as compactSize uint (1 byte, 3 bytes,\n // 5 bytes or 9 bytes)\n // - outputs (variable length)\n // - transaction locktime (4 bytes)\n // - sighash type (4 bytes)\n\n // See example for reference:\n // https://en.bitcoin.it/wiki/OP_CHECKSIG#Code_samples_and_raw_dumps.\n\n // The input data begins at the constant offset of 4 (the first 4 bytes\n // are for the transaction version).\n (uint256 inputsCompactSizeUintLength, uint256 inputsCount) = preimage\n .parseVarIntAt(4);\n\n // To determine the first input starting index, we must jump 4 bytes\n // over the transaction version length and the compactSize uint which\n // prepends the input vector. One byte must be added because\n // `BtcUtils.parseVarInt` does not include compactSize uint tag in the\n // returned length.\n //\n // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`\n // returns `0`, so we jump over one byte of compactSize uint.\n //\n // For >= 253 && <= 0xffff there is `0xfd` tag,\n // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no\n // tag byte included) so we need to jump over 1+2 bytes of\n // compactSize uint.\n //\n // Please refer `BTCUtils` library and compactSize uint\n // docs in `BitcoinTx` library for more details.\n uint256 inputStartingIndex = 4 + 1 + inputsCompactSizeUintLength;\n\n for (uint256 i = 0; i < inputsCount; i++) {\n uint256 inputLength = preimage.determineInputLengthAt(\n inputStartingIndex\n );\n\n (, uint256 scriptSigLength) = preimage.extractScriptSigLenAt(\n inputStartingIndex\n );\n\n if (scriptSigLength > 0) {\n // The input this preimage was generated for was found.\n // All the other inputs in the preimage are marked with a null\n // scriptSig (\"00\") which has length of 1.\n bytes32 outpointTxHash = preimage.extractInputTxIdLeAt(\n inputStartingIndex\n );\n uint32 outpointIndex = BTCUtils.reverseUint32(\n uint32(preimage.extractTxIndexLeAt(inputStartingIndex))\n );\n\n utxoKey = uint256(\n keccak256(abi.encodePacked(outpointTxHash, outpointIndex))\n );\n\n break;\n }\n\n inputStartingIndex += inputLength;\n }\n\n return utxoKey;\n }\n\n /// @notice Extracts the sighash type from the given preimage.\n /// @param preimage Serialized subset of the transaction. See BIP-143 for\n /// reference.\n /// @dev Sighash type is stored as the last 4 bytes in the preimage (little\n /// endian).\n /// @return sighashType Sighash type as a 32-bit integer.\n function extractSighashType(bytes calldata preimage)\n internal\n pure\n returns (uint32 sighashType)\n {\n bytes4 sighashTypeBytes = preimage.slice4(preimage.length - 4);\n uint32 sighashTypeLE = uint32(sighashTypeBytes);\n return sighashTypeLE.reverseUint32();\n }\n}\n"
159
+ },
160
+ "contracts/bridge/MovingFunds.sol": {
161
+ "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\nimport {BytesLib} from \"@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol\";\n\nimport \"./BitcoinTx.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Redemption.sol\";\nimport \"./Wallets.sol\";\n\n/// @title Moving Bridge wallet funds\n/// @notice The library handles the logic for moving Bitcoin between Bridge\n/// wallets.\n/// @dev A wallet that failed a heartbeat, did not process requested redemption\n/// on time, or qualifies to be closed, begins the procedure of moving\n/// funds to other wallets in the Bridge. The wallet needs to commit to\n/// which other Live wallets it is moving the funds to and then, provide an\n/// SPV proof of moving funds to the previously committed wallets.\n/// Once the proof is submitted, all target wallets are supposed to\n/// sweep the received UTXOs with their own main UTXOs in order to\n/// update their BTC balances.\nlibrary MovingFunds {\n using BridgeState for BridgeState.Storage;\n using Wallets for BridgeState.Storage;\n using BitcoinTx for BridgeState.Storage;\n\n using BTCUtils for bytes;\n using BytesLib for bytes;\n\n /// @notice Represents temporary information needed during the processing\n /// of the moving funds Bitcoin transaction outputs. This structure\n /// is an internal one and should not be exported outside of the\n /// moving funds transaction processing code.\n /// @dev Allows to mitigate \"stack too deep\" errors on EVM.\n struct MovingFundsTxOutputsProcessingInfo {\n // 32-byte hash of the moving funds Bitcoin transaction.\n bytes32 movingFundsTxHash;\n // Output vector of the moving funds Bitcoin transaction. It is\n // assumed the vector's structure is valid so it must be validated\n // using e.g. `BTCUtils.validateVout` function before being used\n // during the processing. The validation is usually done as part\n // of the `BitcoinTx.validateProof` call that checks the SPV proof.\n bytes movingFundsTxOutputVector;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's memory argument.\n }\n\n /// @notice Represents moved funds sweep request state.\n enum MovedFundsSweepRequestState {\n /// @dev The request is unknown to the Bridge.\n Unknown,\n /// @dev Request is pending and can become either processed or timed out.\n Pending,\n /// @dev Request was processed by the target wallet.\n Processed,\n /// @dev Request was not processed in the given time window and\n /// the timeout was reported.\n TimedOut\n }\n\n /// @notice Represents a moved funds sweep request. The request is\n /// registered in `submitMovingFundsProof` where we know funds\n /// have been moved to the target wallet and the only step left is\n /// to have the target wallet sweep them.\n struct MovedFundsSweepRequest {\n // 20-byte public key hash of the wallet supposed to sweep the UTXO\n // representing the received funds with their own main UTXO\n bytes20 walletPubKeyHash;\n // Value of the received funds.\n uint64 value;\n // UNIX timestamp the request was created at.\n uint32 createdAt;\n // The current state of the request.\n MovedFundsSweepRequestState state;\n // This struct doesn't contain `__gap` property as the structure is stored\n // in a mapping, mappings store values in different slots and they are\n // not contiguous with other values.\n }\n\n event MovingFundsCommitmentSubmitted(\n bytes20 indexed walletPubKeyHash,\n bytes20[] targetWallets,\n address submitter\n );\n\n event MovingFundsTimeoutReset(bytes20 indexed walletPubKeyHash);\n\n event MovingFundsCompleted(\n bytes20 indexed walletPubKeyHash,\n bytes32 movingFundsTxHash\n );\n\n event MovingFundsTimedOut(bytes20 indexed walletPubKeyHash);\n\n event MovingFundsBelowDustReported(bytes20 indexed walletPubKeyHash);\n\n event MovedFundsSwept(\n bytes20 indexed walletPubKeyHash,\n bytes32 sweepTxHash\n );\n\n event MovedFundsSweepTimedOut(\n bytes20 indexed walletPubKeyHash,\n bytes32 movingFundsTxHash,\n uint32 movingFundsTxOutputIndex\n );\n\n /// @notice Submits the moving funds target wallets commitment.\n /// Once all requirements are met, that function registers the\n /// target wallets commitment and opens the way for moving funds\n /// proof submission.\n /// @param walletPubKeyHash 20-byte public key hash of the source wallet.\n /// @param walletMainUtxo Data of the source wallet's main UTXO, as\n /// currently known on the Ethereum chain.\n /// @param walletMembersIDs Identifiers of the source wallet signing group\n /// members.\n /// @param walletMemberIndex Position of the caller in the source wallet\n /// signing group members list.\n /// @param targetWallets List of 20-byte public key hashes of the target\n /// wallets that the source wallet commits to move the funds to.\n /// @dev Requirements:\n /// - The source wallet must be in the MovingFunds state,\n /// - The source wallet must not have pending redemption requests,\n /// - The source wallet must not have pending moved funds sweep requests,\n /// - The source wallet must not have submitted its commitment already,\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given source wallet in the ECDSA registry. Those IDs are\n /// not directly stored in the contract for gas efficiency purposes\n /// but they can be read from appropriate `DkgResultSubmitted`\n /// and `DkgResultApproved` events,\n /// - The `walletMemberIndex` must be in range [1, walletMembersIDs.length],\n /// - The caller must be the member of the source wallet signing group\n /// at the position indicated by `walletMemberIndex` parameter,\n /// - The `walletMainUtxo` components must point to the recent main\n /// UTXO of the source wallet, as currently known on the Ethereum\n /// chain,\n /// - Source wallet BTC balance must be greater than zero,\n /// - At least one Live wallet must exist in the system,\n /// - Submitted target wallets count must match the expected count\n /// `N = min(liveWalletsCount, ceil(walletBtcBalance / walletMaxBtcTransfer))`\n /// where `N > 0`,\n /// - Each target wallet must be not equal to the source wallet,\n /// - Each target wallet must follow the expected order i.e. all\n /// target wallets 20-byte public key hashes represented as numbers\n /// must form a strictly increasing sequence without duplicates,\n /// - Each target wallet must be in Live state.\n function submitMovingFundsCommitment(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata walletMainUtxo,\n uint32[] calldata walletMembersIDs,\n uint256 walletMemberIndex,\n bytes20[] calldata targetWallets\n ) external {\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n\n require(\n wallet.state == Wallets.WalletState.MovingFunds,\n \"Source wallet must be in MovingFunds state\"\n );\n\n require(\n wallet.pendingRedemptionsValue == 0,\n \"Source wallet must handle all pending redemptions first\"\n );\n\n require(\n wallet.pendingMovedFundsSweepRequestsCount == 0,\n \"Source wallet must handle all pending moved funds sweep requests first\"\n );\n\n require(\n wallet.movingFundsTargetWalletsCommitmentHash == bytes32(0),\n \"Target wallets commitment already submitted\"\n );\n\n require(\n self.ecdsaWalletRegistry.isWalletMember(\n wallet.ecdsaWalletID,\n walletMembersIDs,\n msg.sender,\n walletMemberIndex\n ),\n \"Caller is not a member of the source wallet\"\n );\n\n uint64 walletBtcBalance = self.getWalletBtcBalance(\n walletPubKeyHash,\n walletMainUtxo\n );\n\n require(walletBtcBalance > 0, \"Wallet BTC balance is zero\");\n\n uint256 expectedTargetWalletsCount = Math.min(\n self.liveWalletsCount,\n Math.ceilDiv(walletBtcBalance, self.walletMaxBtcTransfer)\n );\n\n // This requirement fails only when `liveWalletsCount` is zero. In\n // that case, the system cannot accept the commitment and must provide\n // new wallets first. However, the wallet supposed to submit the\n // commitment can keep resetting the moving funds timeout until then.\n require(expectedTargetWalletsCount > 0, \"No target wallets available\");\n\n require(\n targetWallets.length == expectedTargetWalletsCount,\n \"Submitted target wallets count is other than expected\"\n );\n\n uint160 lastProcessedTargetWallet = 0;\n\n for (uint256 i = 0; i < targetWallets.length; i++) {\n bytes20 targetWallet = targetWallets[i];\n\n require(\n targetWallet != walletPubKeyHash,\n \"Submitted target wallet cannot be equal to the source wallet\"\n );\n\n require(\n uint160(targetWallet) > lastProcessedTargetWallet,\n \"Submitted target wallet breaks the expected order\"\n );\n\n require(\n self.registeredWallets[targetWallet].state ==\n Wallets.WalletState.Live,\n \"Submitted target wallet must be in Live state\"\n );\n\n lastProcessedTargetWallet = uint160(targetWallet);\n }\n\n wallet.movingFundsTargetWalletsCommitmentHash = keccak256(\n abi.encodePacked(targetWallets)\n );\n\n emit MovingFundsCommitmentSubmitted(\n walletPubKeyHash,\n targetWallets,\n msg.sender\n );\n }\n\n /// @notice Resets the moving funds timeout for the given wallet if the\n /// target wallet commitment cannot be submitted due to a lack\n /// of live wallets in the system.\n /// @param walletPubKeyHash 20-byte public key hash of the moving funds wallet\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state,\n /// - The target wallets commitment must not be already submitted for\n /// the given moving funds wallet,\n /// - Live wallets count must be zero,\n /// - The moving funds timeout reset delay must be elapsed.\n function resetMovingFundsTimeout(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash\n ) external {\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n\n require(\n wallet.state == Wallets.WalletState.MovingFunds,\n \"ECDSA wallet must be in MovingFunds state\"\n );\n\n // If the moving funds wallet already submitted their target wallets\n // commitment, there is no point to reset the timeout since the\n // wallet can make the BTC transaction and submit the proof.\n require(\n wallet.movingFundsTargetWalletsCommitmentHash == bytes32(0),\n \"Target wallets commitment already submitted\"\n );\n\n require(self.liveWalletsCount == 0, \"Live wallets count must be zero\");\n\n require(\n /* solhint-disable-next-line not-rely-on-time */\n block.timestamp >\n wallet.movingFundsRequestedAt +\n self.movingFundsTimeoutResetDelay,\n \"Moving funds timeout cannot be reset yet\"\n );\n\n /* solhint-disable-next-line not-rely-on-time */\n wallet.movingFundsRequestedAt = uint32(block.timestamp);\n\n emit MovingFundsTimeoutReset(walletPubKeyHash);\n }\n\n /// @notice Used by the wallet to prove the BTC moving funds transaction\n /// and to make the necessary state changes. Moving funds is only\n /// accepted if it satisfies SPV proof.\n ///\n /// The function validates the moving funds transaction structure\n /// by checking if it actually spends the main UTXO of the declared\n /// wallet and locks the value on the pre-committed target wallets\n /// using a reasonable transaction fee. If all preconditions are\n /// met, this functions closes the source wallet.\n ///\n /// It is possible to prove the given moving funds transaction only\n /// one time.\n /// @param movingFundsTx Bitcoin moving funds transaction data.\n /// @param movingFundsProof Bitcoin moving funds proof data.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n /// HASH160 over the compressed ECDSA public key) of the wallet\n /// which performed the moving funds transaction.\n /// @dev Requirements:\n /// - `movingFundsTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash,\n /// - The `movingFundsTx` should represent a Bitcoin transaction with\n /// exactly 1 input that refers to the wallet's main UTXO. That\n /// transaction should have 1..n outputs corresponding to the\n /// pre-committed target wallets. Outputs must be ordered in the\n /// same way as their corresponding target wallets are ordered\n /// within the target wallets commitment,\n /// - `movingFundsProof` components must match the expected structure.\n /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// Additionally, the recent main UTXO on Ethereum must be set,\n /// - `walletPubKeyHash` must be connected with the main UTXO used\n /// as transaction single input,\n /// - The wallet that `walletPubKeyHash` points to must be in the\n /// MovingFunds state,\n /// - The target wallets commitment must be submitted by the wallet\n /// that `walletPubKeyHash` points to,\n /// - The total Bitcoin transaction fee must be lesser or equal\n /// to `movingFundsTxMaxTotalFee` governable parameter.\n function submitMovingFundsProof(\n BridgeState.Storage storage self,\n BitcoinTx.Info calldata movingFundsTx,\n BitcoinTx.Proof calldata movingFundsProof,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes20 walletPubKeyHash\n ) external {\n // The actual transaction proof is performed here. After that point, we\n // can assume the transaction happened on Bitcoin chain and has\n // a sufficient number of confirmations as determined by\n // `txProofDifficultyFactor` constant.\n bytes32 movingFundsTxHash = self.validateProof(\n movingFundsTx,\n movingFundsProof\n );\n\n // Process the moving funds transaction input. Specifically, check if\n // it refers to the expected wallet's main UTXO.\n OutboundTx.processWalletOutboundTxInput(\n self,\n movingFundsTx.inputVector,\n mainUtxo,\n walletPubKeyHash\n );\n\n (\n bytes32 targetWalletsHash,\n uint256 outputsTotalValue\n ) = processMovingFundsTxOutputs(\n self,\n MovingFundsTxOutputsProcessingInfo(\n movingFundsTxHash,\n movingFundsTx.outputVector\n )\n );\n\n require(\n mainUtxo.txOutputValue - outputsTotalValue <=\n self.movingFundsTxMaxTotalFee,\n \"Transaction fee is too high\"\n );\n\n self.notifyWalletFundsMoved(walletPubKeyHash, targetWalletsHash);\n // slither-disable-next-line reentrancy-events\n emit MovingFundsCompleted(walletPubKeyHash, movingFundsTxHash);\n }\n\n /// @notice Processes the moving funds Bitcoin transaction output vector\n /// and extracts information required for further processing.\n /// @param processInfo Processing info containing the moving funds tx\n /// hash and output vector.\n /// @return targetWalletsHash keccak256 hash over the list of actual\n /// target wallets used in the transaction.\n /// @return outputsTotalValue Sum of all outputs values.\n /// @dev Requirements:\n /// - The `movingFundsTxOutputVector` must be parseable, i.e. must\n /// be validated by the caller as stated in their parameter doc,\n /// - Each output must refer to a 20-byte public key hash,\n /// - The total outputs value must be evenly divided over all outputs.\n function processMovingFundsTxOutputs(\n BridgeState.Storage storage self,\n MovingFundsTxOutputsProcessingInfo memory processInfo\n ) internal returns (bytes32 targetWalletsHash, uint256 outputsTotalValue) {\n // Determining the total number of Bitcoin transaction outputs in\n // the same way as for number of inputs. See `BitcoinTx.outputVector`\n // docs for more details.\n (\n uint256 outputsCompactSizeUintLength,\n uint256 outputsCount\n ) = processInfo.movingFundsTxOutputVector.parseVarInt();\n\n // To determine the first output starting index, we must jump over\n // the compactSize uint which prepends the output vector. One byte\n // must be added because `BtcUtils.parseVarInt` does not include\n // compactSize uint tag in the returned length.\n //\n // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`\n // returns `0`, so we jump over one byte of compactSize uint.\n //\n // For >= 253 && <= 0xffff there is `0xfd` tag,\n // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no\n // tag byte included) so we need to jump over 1+2 bytes of\n // compactSize uint.\n //\n // Please refer `BTCUtils` library and compactSize uint\n // docs in `BitcoinTx` library for more details.\n uint256 outputStartingIndex = 1 + outputsCompactSizeUintLength;\n\n bytes20[] memory targetWallets = new bytes20[](outputsCount);\n uint64[] memory outputsValues = new uint64[](outputsCount);\n\n // Outputs processing loop. Note that the `outputIndex` must be\n // `uint32` to build proper `movedFundsSweepRequests` keys.\n for (\n uint32 outputIndex = 0;\n outputIndex < outputsCount;\n outputIndex++\n ) {\n uint256 outputLength = processInfo\n .movingFundsTxOutputVector\n .determineOutputLengthAt(outputStartingIndex);\n\n bytes memory output = processInfo.movingFundsTxOutputVector.slice(\n outputStartingIndex,\n outputLength\n );\n\n bytes20 targetWalletPubKeyHash = self.extractPubKeyHash(output);\n\n // Add the wallet public key hash to the list that will be used\n // to build the result list hash. There is no need to check if\n // given output is a change here because the actual target wallet\n // list must be exactly the same as the pre-committed target wallet\n // list which is guaranteed to be valid.\n targetWallets[outputIndex] = targetWalletPubKeyHash;\n\n // Extract the value from given output.\n outputsValues[outputIndex] = output.extractValue();\n outputsTotalValue += outputsValues[outputIndex];\n\n // Register a moved funds sweep request that must be handled\n // by the target wallet. The target wallet must sweep the\n // received funds with their own main UTXO in order to update\n // their BTC balance. Worth noting there is no need to check\n // if the sweep request already exists in the system because\n // the moving funds wallet is moved to the Closing state after\n // submitting the moving funds proof so there is no possibility\n // to submit the proof again and register the sweep request twice.\n self.movedFundsSweepRequests[\n uint256(\n keccak256(\n abi.encodePacked(\n processInfo.movingFundsTxHash,\n outputIndex\n )\n )\n )\n ] = MovedFundsSweepRequest(\n targetWalletPubKeyHash,\n outputsValues[outputIndex],\n /* solhint-disable-next-line not-rely-on-time */\n uint32(block.timestamp),\n MovedFundsSweepRequestState.Pending\n );\n // We added a new moved funds sweep request for the target wallet\n // so we must increment their request counter.\n self\n .registeredWallets[targetWalletPubKeyHash]\n .pendingMovedFundsSweepRequestsCount++;\n\n // Make the `outputStartingIndex` pointing to the next output by\n // increasing it by current output's length.\n outputStartingIndex += outputLength;\n }\n\n // Compute the indivisible remainder that remains after dividing the\n // outputs total value over all outputs evenly.\n uint256 outputsTotalValueRemainder = outputsTotalValue % outputsCount;\n // Compute the minimum allowed output value by dividing the outputs\n // total value (reduced by the remainder) by the number of outputs.\n uint256 minOutputValue = (outputsTotalValue -\n outputsTotalValueRemainder) / outputsCount;\n // Maximum possible value is the minimum value with the remainder included.\n uint256 maxOutputValue = minOutputValue + outputsTotalValueRemainder;\n\n for (uint256 i = 0; i < outputsCount; i++) {\n require(\n minOutputValue <= outputsValues[i] &&\n outputsValues[i] <= maxOutputValue,\n \"Transaction amount is not distributed evenly\"\n );\n }\n\n targetWalletsHash = keccak256(abi.encodePacked(targetWallets));\n\n return (targetWalletsHash, outputsTotalValue);\n }\n\n /// @notice Notifies about a timed out moving funds process. Terminates\n /// the wallet and slashes signing group members as a result.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state,\n /// - The moving funds timeout must be actually exceeded,\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events of the `WalletRegistry` contract.\n function notifyMovingFundsTimeout(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n uint32[] calldata walletMembersIDs\n ) external {\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n\n require(\n wallet.state == Wallets.WalletState.MovingFunds,\n \"ECDSA wallet must be in MovingFunds state\"\n );\n\n require(\n /* solhint-disable-next-line not-rely-on-time */\n block.timestamp >\n wallet.movingFundsRequestedAt + self.movingFundsTimeout,\n \"Moving funds has not timed out yet\"\n );\n\n self.terminateWallet(walletPubKeyHash);\n\n self.ecdsaWalletRegistry.seize(\n self.movingFundsTimeoutSlashingAmount,\n self.movingFundsTimeoutNotifierRewardMultiplier,\n msg.sender,\n wallet.ecdsaWalletID,\n walletMembersIDs\n );\n\n // slither-disable-next-line reentrancy-events\n emit MovingFundsTimedOut(walletPubKeyHash);\n }\n\n /// @notice Notifies about a moving funds wallet whose BTC balance is\n /// below the moving funds dust threshold. Ends the moving funds\n /// process and begins wallet closing immediately.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known\n /// on the Ethereum chain.\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state,\n /// - The `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// If the wallet has no main UTXO, this parameter can be empty as it\n /// is ignored,\n /// - The wallet BTC balance must be below the moving funds threshold.\n function notifyMovingFundsBelowDust(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata mainUtxo\n ) external {\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n\n require(\n wallet.state == Wallets.WalletState.MovingFunds,\n \"ECDSA wallet must be in MovingFunds state\"\n );\n\n uint64 walletBtcBalance = self.getWalletBtcBalance(\n walletPubKeyHash,\n mainUtxo\n );\n\n require(\n walletBtcBalance < self.movingFundsDustThreshold,\n \"Wallet BTC balance must be below the moving funds dust threshold\"\n );\n\n self.beginWalletClosing(walletPubKeyHash);\n\n // slither-disable-next-line reentrancy-events\n emit MovingFundsBelowDustReported(walletPubKeyHash);\n }\n\n /// @notice Used by the wallet to prove the BTC moved funds sweep\n /// transaction and to make the necessary state changes. Moved\n /// funds sweep is only accepted if it satisfies SPV proof.\n ///\n /// The function validates the sweep transaction structure by\n /// checking if it actually spends the moved funds UTXO and the\n /// sweeping wallet's main UTXO (optionally), and if it locks the\n /// value on the sweeping wallet's 20-byte public key hash using a\n /// reasonable transaction fee. If all preconditions are\n /// met, this function updates the sweeping wallet main UTXO, thus\n /// their BTC balance.\n ///\n /// It is possible to prove the given sweep transaction only\n /// one time.\n /// @param sweepTx Bitcoin sweep funds transaction data.\n /// @param sweepProof Bitcoin sweep funds proof data.\n /// @param mainUtxo Data of the sweeping wallet's main UTXO, as currently\n /// known on the Ethereum chain.\n /// @dev Requirements:\n /// - `sweepTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash,\n /// - The `sweepTx` should represent a Bitcoin transaction with\n /// the first input pointing to a wallet's sweep Pending request and,\n /// optionally, the second input pointing to the wallet's main UTXO,\n /// if the sweeping wallet has a main UTXO set. There should be only\n /// one output locking funds on the sweeping wallet 20-byte public\n /// key hash,\n /// - `sweepProof` components must match the expected structure.\n /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the sweeping wallet, as currently known on the Ethereum chain.\n /// If there is no main UTXO, this parameter is ignored,\n /// - The sweeping wallet must be in the Live or MovingFunds state,\n /// - The total Bitcoin transaction fee must be lesser or equal\n /// to `movedFundsSweepTxMaxTotalFee` governable parameter.\n function submitMovedFundsSweepProof(\n BridgeState.Storage storage self,\n BitcoinTx.Info calldata sweepTx,\n BitcoinTx.Proof calldata sweepProof,\n BitcoinTx.UTXO calldata mainUtxo\n ) external {\n // The actual transaction proof is performed here. After that point, we\n // can assume the transaction happened on Bitcoin chain and has\n // a sufficient number of confirmations as determined by\n // `txProofDifficultyFactor` constant.\n bytes32 sweepTxHash = self.validateProof(sweepTx, sweepProof);\n\n (\n bytes20 walletPubKeyHash,\n uint64 sweepTxOutputValue\n ) = processMovedFundsSweepTxOutput(self, sweepTx.outputVector);\n\n (\n Wallets.Wallet storage wallet,\n BitcoinTx.UTXO memory resolvedMainUtxo\n ) = resolveMovedFundsSweepingWallet(self, walletPubKeyHash, mainUtxo);\n\n uint256 sweepTxInputsTotalValue = processMovedFundsSweepTxInputs(\n self,\n sweepTx.inputVector,\n resolvedMainUtxo,\n walletPubKeyHash\n );\n\n require(\n sweepTxInputsTotalValue - sweepTxOutputValue <=\n self.movedFundsSweepTxMaxTotalFee,\n \"Transaction fee is too high\"\n );\n\n // Use the sweep transaction output as the new sweeping wallet's main UTXO.\n // Transaction output index is always 0 as sweep transaction always\n // contains only one output.\n wallet.mainUtxoHash = keccak256(\n abi.encodePacked(sweepTxHash, uint32(0), sweepTxOutputValue)\n );\n\n // slither-disable-next-line reentrancy-events\n emit MovedFundsSwept(walletPubKeyHash, sweepTxHash);\n }\n\n /// @notice Processes the Bitcoin moved funds sweep transaction output vector\n /// by extracting the single output and using it to gain additional\n /// information required for further processing (e.g. value and\n /// wallet public key hash).\n /// @param sweepTxOutputVector Bitcoin moved funds sweep transaction output\n /// vector.\n /// This function assumes vector's structure is valid so it must be\n /// validated using e.g. `BTCUtils.validateVout` function before\n /// it is passed here.\n /// @return walletPubKeyHash 20-byte wallet public key hash.\n /// @return value 8-byte moved funds sweep transaction output value.\n /// @dev Requirements:\n /// - Output vector must contain only one output,\n /// - The single output must be of P2PKH or P2WPKH type and lock the\n /// funds on a 20-byte public key hash.\n function processMovedFundsSweepTxOutput(\n BridgeState.Storage storage self,\n bytes memory sweepTxOutputVector\n ) internal view returns (bytes20 walletPubKeyHash, uint64 value) {\n // To determine the total number of sweep transaction outputs, we need to\n // parse the compactSize uint (VarInt) the output vector is prepended by.\n // That compactSize uint encodes the number of vector elements using the\n // format presented in:\n // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers\n // We don't need asserting the compactSize uint is parseable since it\n // was already checked during `validateVout` validation performed as\n // part of the `BitcoinTx.validateProof` call.\n // See `BitcoinTx.outputVector` docs for more details.\n (, uint256 outputsCount) = sweepTxOutputVector.parseVarInt();\n require(\n outputsCount == 1,\n \"Moved funds sweep transaction must have a single output\"\n );\n\n bytes memory output = sweepTxOutputVector.extractOutputAtIndex(0);\n walletPubKeyHash = self.extractPubKeyHash(output);\n value = output.extractValue();\n\n return (walletPubKeyHash, value);\n }\n\n /// @notice Resolves sweeping wallet based on the provided wallet public key\n /// hash. Validates the wallet state and current main UTXO, as\n /// currently known on the Ethereum chain.\n /// @param walletPubKeyHash public key hash of the wallet proving the sweep\n /// Bitcoin transaction.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain. If no main UTXO exists for the given wallet,\n /// this parameter is ignored.\n /// @return wallet Data of the sweeping wallet.\n /// @return resolvedMainUtxo The actual main UTXO of the sweeping wallet\n /// resolved by cross-checking the `mainUtxo` parameter with\n /// the chain state. If the validation went well, this is the\n /// plain-text main UTXO corresponding to the `wallet.mainUtxoHash`.\n /// @dev Requirements:\n /// - Sweeping wallet must be either in Live or MovingFunds state,\n /// - If the main UTXO of the sweeping wallet exists in the storage,\n /// the passed `mainUTXO` parameter must be equal to the stored one.\n function resolveMovedFundsSweepingWallet(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata mainUtxo\n )\n internal\n view\n returns (\n Wallets.Wallet storage wallet,\n BitcoinTx.UTXO memory resolvedMainUtxo\n )\n {\n wallet = self.registeredWallets[walletPubKeyHash];\n\n Wallets.WalletState walletState = wallet.state;\n require(\n walletState == Wallets.WalletState.Live ||\n walletState == Wallets.WalletState.MovingFunds,\n \"Wallet must be in Live or MovingFunds state\"\n );\n\n // Check if the main UTXO for given wallet exists. If so, validate\n // passed main UTXO data against the stored hash and use them for\n // further processing. If no main UTXO exists, use empty data.\n resolvedMainUtxo = BitcoinTx.UTXO(bytes32(0), 0, 0);\n bytes32 mainUtxoHash = wallet.mainUtxoHash;\n if (mainUtxoHash != bytes32(0)) {\n require(\n keccak256(\n abi.encodePacked(\n mainUtxo.txHash,\n mainUtxo.txOutputIndex,\n mainUtxo.txOutputValue\n )\n ) == mainUtxoHash,\n \"Invalid main UTXO data\"\n );\n resolvedMainUtxo = mainUtxo;\n }\n }\n\n /// @notice Processes the Bitcoin moved funds sweep transaction input vector.\n /// It extracts the first input and tries to match it with one of\n /// the moved funds sweep requests targeting the sweeping wallet.\n /// If the sweep request is an existing Pending request, this\n /// function marks it as Processed. If the sweeping wallet has a\n /// main UTXO, this function extracts the second input, makes sure\n /// it refers to the wallet main UTXO, and marks that main UTXO as\n /// correctly spent.\n /// @param sweepTxInputVector Bitcoin moved funds sweep transaction input vector.\n /// This function assumes vector's structure is valid so it must be\n /// validated using e.g. `BTCUtils.validateVin` function before\n /// it is passed here.\n /// @param mainUtxo Data of the sweeping wallet's main UTXO. If no main UTXO\n /// exists for the given the wallet, this parameter's fields should\n /// be zeroed to bypass the main UTXO validation.\n /// @param walletPubKeyHash 20-byte public key hash of the sweeping wallet.\n /// @return inputsTotalValue Total inputs value sum.\n /// @dev Requirements:\n /// - The input vector must consist of one mandatory and one optional\n /// input,\n /// - The mandatory input must be the first input in the vector,\n /// - The mandatory input must point to a Pending moved funds sweep\n /// request that is targeted to the sweeping wallet,\n /// - The optional output must be the second input in the vector,\n /// - The optional input is required if the sweeping wallet has a\n /// main UTXO (i.e. the `mainUtxo` is not zeroed). In that case,\n /// that input must point the the sweeping wallet main UTXO.\n function processMovedFundsSweepTxInputs(\n BridgeState.Storage storage self,\n bytes memory sweepTxInputVector,\n BitcoinTx.UTXO memory mainUtxo,\n bytes20 walletPubKeyHash\n ) internal returns (uint256 inputsTotalValue) {\n // To determine the total number of Bitcoin transaction inputs,\n // we need to parse the compactSize uint (VarInt) the input vector is\n // prepended by. That compactSize uint encodes the number of vector\n // elements using the format presented in:\n // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers\n // We don't need asserting the compactSize uint is parseable since it\n // was already checked during `validateVin` validation performed as\n // part of the `BitcoinTx.validateProof` call.\n // See `BitcoinTx.inputVector` docs for more details.\n (\n uint256 inputsCompactSizeUintLength,\n uint256 inputsCount\n ) = sweepTxInputVector.parseVarInt();\n\n // To determine the first input starting index, we must jump over\n // the compactSize uint which prepends the input vector. One byte\n // must be added because `BtcUtils.parseVarInt` does not include\n // compactSize uint tag in the returned length.\n //\n // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`\n // returns `0`, so we jump over one byte of compactSize uint.\n //\n // For >= 253 && <= 0xffff there is `0xfd` tag,\n // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no\n // tag byte included) so we need to jump over 1+2 bytes of\n // compactSize uint.\n //\n // Please refer `BTCUtils` library and compactSize uint\n // docs in `BitcoinTx` library for more details.\n uint256 inputStartingIndex = 1 + inputsCompactSizeUintLength;\n\n // We always expect the first input to be the swept UTXO. Additionally,\n // if the sweeping wallet has a main UTXO, that main UTXO should be\n // pointed by the second input.\n require(\n inputsCount == (mainUtxo.txHash != bytes32(0) ? 2 : 1),\n \"Moved funds sweep transaction must have a proper inputs count\"\n );\n\n // Parse the first input and extract its outpoint tx hash and index.\n (\n bytes32 firstInputOutpointTxHash,\n uint32 firstInputOutpointIndex,\n uint256 firstInputLength\n ) = parseMovedFundsSweepTxInputAt(\n sweepTxInputVector,\n inputStartingIndex\n );\n\n // Build the request key and fetch the corresponding moved funds sweep\n // request from contract storage.\n MovedFundsSweepRequest storage sweepRequest = self\n .movedFundsSweepRequests[\n uint256(\n keccak256(\n abi.encodePacked(\n firstInputOutpointTxHash,\n firstInputOutpointIndex\n )\n )\n )\n ];\n\n require(\n sweepRequest.state == MovedFundsSweepRequestState.Pending,\n \"Sweep request must be in Pending state\"\n );\n // We must check if the wallet extracted from the moved funds sweep\n // transaction output is truly the owner of the sweep request connected\n // with the swept UTXO. This is needed to prevent a case when a wallet\n // handles its own sweep request but locks the funds on another\n // wallet public key hash.\n require(\n sweepRequest.walletPubKeyHash == walletPubKeyHash,\n \"Sweep request belongs to another wallet\"\n );\n // If the validation passed, the sweep request must be marked as\n // processed and its value should be counted into the total inputs\n // value sum.\n sweepRequest.state = MovedFundsSweepRequestState.Processed;\n inputsTotalValue += sweepRequest.value;\n\n self\n .registeredWallets[walletPubKeyHash]\n .pendingMovedFundsSweepRequestsCount--;\n\n // If the main UTXO for the sweeping wallet exists, it must be processed.\n if (mainUtxo.txHash != bytes32(0)) {\n // The second input is supposed to point to that sweeping wallet\n // main UTXO. We need to parse that input.\n (\n bytes32 secondInputOutpointTxHash,\n uint32 secondInputOutpointIndex,\n\n ) = parseMovedFundsSweepTxInputAt(\n sweepTxInputVector,\n inputStartingIndex + firstInputLength\n );\n // Make sure the second input refers to the sweeping wallet main UTXO.\n require(\n mainUtxo.txHash == secondInputOutpointTxHash &&\n mainUtxo.txOutputIndex == secondInputOutpointIndex,\n \"Second input must point to the wallet's main UTXO\"\n );\n\n // If the validation passed, count the main UTXO value into the\n // total inputs value sum.\n inputsTotalValue += mainUtxo.txOutputValue;\n\n // Main UTXO used as an input, mark it as spent. This is needed\n // to defend against fraud challenges referring to this main UTXO.\n self.spentMainUTXOs[\n uint256(\n keccak256(\n abi.encodePacked(\n secondInputOutpointTxHash,\n secondInputOutpointIndex\n )\n )\n )\n ] = true;\n }\n\n return inputsTotalValue;\n }\n\n /// @notice Parses a Bitcoin transaction input starting at the given index.\n /// @param inputVector Bitcoin transaction input vector.\n /// @param inputStartingIndex Index the given input starts at.\n /// @return outpointTxHash 32-byte hash of the Bitcoin transaction which is\n /// pointed in the given input's outpoint.\n /// @return outpointIndex 4-byte index of the Bitcoin transaction output\n /// which is pointed in the given input's outpoint.\n /// @return inputLength Byte length of the given input.\n /// @dev This function assumes vector's structure is valid so it must be\n /// validated using e.g. `BTCUtils.validateVin` function before it\n /// is passed here.\n function parseMovedFundsSweepTxInputAt(\n bytes memory inputVector,\n uint256 inputStartingIndex\n )\n internal\n pure\n returns (\n bytes32 outpointTxHash,\n uint32 outpointIndex,\n uint256 inputLength\n )\n {\n outpointTxHash = inputVector.extractInputTxIdLeAt(inputStartingIndex);\n\n outpointIndex = BTCUtils.reverseUint32(\n uint32(inputVector.extractTxIndexLeAt(inputStartingIndex))\n );\n\n inputLength = inputVector.determineInputLengthAt(inputStartingIndex);\n\n return (outpointTxHash, outpointIndex, inputLength);\n }\n\n /// @notice Notifies about a timed out moved funds sweep process. If the\n /// wallet is not terminated yet, that function terminates\n /// the wallet and slashes signing group members as a result.\n /// Marks the given sweep request as TimedOut.\n /// @param movingFundsTxHash 32-byte hash of the moving funds transaction\n /// that caused the sweep request to be created.\n /// @param movingFundsTxOutputIndex Index of the moving funds transaction\n /// output that is subject of the sweep request.\n /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @dev Requirements:\n /// - The moved funds sweep request must be in the Pending state,\n /// - The moved funds sweep timeout must be actually exceeded,\n /// - The wallet must be either in the Live or MovingFunds or\n /// Terminated state,,\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events of the `WalletRegistry` contract.\n function notifyMovedFundsSweepTimeout(\n BridgeState.Storage storage self,\n bytes32 movingFundsTxHash,\n uint32 movingFundsTxOutputIndex,\n uint32[] calldata walletMembersIDs\n ) external {\n MovedFundsSweepRequest storage sweepRequest = self\n .movedFundsSweepRequests[\n uint256(\n keccak256(\n abi.encodePacked(\n movingFundsTxHash,\n movingFundsTxOutputIndex\n )\n )\n )\n ];\n\n require(\n sweepRequest.state == MovedFundsSweepRequestState.Pending,\n \"Sweep request must be in Pending state\"\n );\n\n require(\n /* solhint-disable-next-line not-rely-on-time */\n block.timestamp >\n sweepRequest.createdAt + self.movedFundsSweepTimeout,\n \"Sweep request has not timed out yet\"\n );\n\n bytes20 walletPubKeyHash = sweepRequest.walletPubKeyHash;\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n Wallets.WalletState walletState = wallet.state;\n\n require(\n walletState == Wallets.WalletState.Live ||\n walletState == Wallets.WalletState.MovingFunds ||\n walletState == Wallets.WalletState.Terminated,\n \"ECDSA wallet must be in Live or MovingFunds or Terminated state\"\n );\n\n sweepRequest.state = MovedFundsSweepRequestState.TimedOut;\n wallet.pendingMovedFundsSweepRequestsCount--;\n\n if (\n walletState == Wallets.WalletState.Live ||\n walletState == Wallets.WalletState.MovingFunds\n ) {\n self.terminateWallet(walletPubKeyHash);\n\n self.ecdsaWalletRegistry.seize(\n self.movedFundsSweepTimeoutSlashingAmount,\n self.movedFundsSweepTimeoutNotifierRewardMultiplier,\n msg.sender,\n wallet.ecdsaWalletID,\n walletMembersIDs\n );\n }\n\n // slither-disable-next-line reentrancy-events\n emit MovedFundsSweepTimedOut(\n walletPubKeyHash,\n movingFundsTxHash,\n movingFundsTxOutputIndex\n );\n }\n}\n"
162
+ },
163
+ "@keep-network/ecdsa/contracts/api/IWalletRegistry.sol": {
164
+ "content": "// SPDX-License-Identifier: MIT\n//\n// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄\n// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓\n// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓\n// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀\n// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌\n// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓\n//\n// Trust math, not hardware.\n\npragma solidity ^0.8.9;\n\nimport \"../libraries/EcdsaDkg.sol\";\n\ninterface IWalletRegistry {\n /// @notice Requests a new wallet creation.\n /// @dev Only the Wallet Owner can call this function.\n function requestNewWallet() external;\n\n /// @notice Closes an existing wallet.\n /// @param walletID ID of the wallet.\n /// @dev Only the Wallet Owner can call this function.\n function closeWallet(bytes32 walletID) external;\n\n /// @notice Adds all signing group members of the wallet with the given ID\n /// to the slashing queue of the staking contract. The notifier will\n /// receive reward per each group member from the staking contract\n /// notifiers treasury. The reward is scaled by the\n /// `rewardMultiplier` provided as a parameter.\n /// @param amount Amount of tokens to seize from each signing group member\n /// @param rewardMultiplier Fraction of the staking contract notifiers\n /// reward the notifier should receive; should be between [0, 100]\n /// @param notifier Address of the misbehavior notifier\n /// @param walletID ID of the wallet\n /// @param walletMembersIDs Identifiers of the wallet signing group members\n /// @dev Only the Wallet Owner can call this function.\n /// Requirements:\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events.\n /// - `rewardMultiplier` must be between [0, 100].\n /// - This function does revert if staking contract call reverts.\n /// The calling code needs to handle the potential revert.\n function seize(\n uint96 amount,\n uint256 rewardMultiplier,\n address notifier,\n bytes32 walletID,\n uint32[] calldata walletMembersIDs\n ) external;\n\n /// @notice Gets public key of a wallet with a given wallet ID.\n /// The public key is returned in an uncompressed format as a 64-byte\n /// concatenation of X and Y coordinates.\n /// @param walletID ID of the wallet.\n /// @return Uncompressed public key of the wallet.\n function getWalletPublicKey(bytes32 walletID)\n external\n view\n returns (bytes memory);\n\n /// @notice Check current wallet creation state.\n function getWalletCreationState() external view returns (EcdsaDkg.State);\n\n /// @notice Checks whether the given operator is a member of the given\n /// wallet signing group.\n /// @param walletID ID of the wallet\n /// @param walletMembersIDs Identifiers of the wallet signing group members\n /// @param operator Address of the checked operator\n /// @param walletMemberIndex Position of the operator in the wallet signing\n /// group members list\n /// @return True - if the operator is a member of the given wallet signing\n /// group. False - otherwise.\n /// @dev Requirements:\n /// - The `operator` parameter must be an actual sortition pool operator.\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events.\n /// - The `walletMemberIndex` must be in range [1, walletMembersIDs.length]\n function isWalletMember(\n bytes32 walletID,\n uint32[] calldata walletMembersIDs,\n address operator,\n uint256 walletMemberIndex\n ) external view returns (bool);\n}\n"
165
+ },
166
+ "@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol": {
167
+ "content": "pragma solidity ^0.8.4;\n\n/** @title BitcoinSPV */\n/** @author Summa (https://summa.one) */\n\nimport {BytesLib} from \"./BytesLib.sol\";\nimport {SafeMath} from \"./SafeMath.sol\";\n\nlibrary BTCUtils {\n using BytesLib for bytes;\n using SafeMath for uint256;\n\n // The target at minimum Difficulty. Also the target of the genesis block\n uint256 public constant DIFF1_TARGET = 0xffff0000000000000000000000000000000000000000000000000000;\n\n uint256 public constant RETARGET_PERIOD = 2 * 7 * 24 * 60 * 60; // 2 weeks in seconds\n uint256 public constant RETARGET_PERIOD_BLOCKS = 2016; // 2 weeks in blocks\n\n uint256 public constant ERR_BAD_ARG = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;\n\n /* ***** */\n /* UTILS */\n /* ***** */\n\n /// @notice Determines the length of a VarInt in bytes\n /// @dev A VarInt of >1 byte is prefixed with a flag indicating its length\n /// @param _flag The first byte of a VarInt\n /// @return The number of non-flag bytes in the VarInt\n function determineVarIntDataLength(bytes memory _flag) internal pure returns (uint8) {\n return determineVarIntDataLengthAt(_flag, 0);\n }\n\n /// @notice Determines the length of a VarInt in bytes\n /// @dev A VarInt of >1 byte is prefixed with a flag indicating its length\n /// @param _b The byte array containing a VarInt\n /// @param _at The position of the VarInt in the array\n /// @return The number of non-flag bytes in the VarInt\n function determineVarIntDataLengthAt(bytes memory _b, uint256 _at) internal pure returns (uint8) {\n if (uint8(_b[_at]) == 0xff) {\n return 8; // one-byte flag, 8 bytes data\n }\n if (uint8(_b[_at]) == 0xfe) {\n return 4; // one-byte flag, 4 bytes data\n }\n if (uint8(_b[_at]) == 0xfd) {\n return 2; // one-byte flag, 2 bytes data\n }\n\n return 0; // flag is data\n }\n\n /// @notice Parse a VarInt into its data length and the number it represents\n /// @dev Useful for Parsing Vins and Vouts. Returns ERR_BAD_ARG if insufficient bytes.\n /// Caller SHOULD explicitly handle this case (or bubble it up)\n /// @param _b A byte-string starting with a VarInt\n /// @return number of bytes in the encoding (not counting the tag), the encoded int\n function parseVarInt(bytes memory _b) internal pure returns (uint256, uint256) {\n return parseVarIntAt(_b, 0);\n }\n\n /// @notice Parse a VarInt into its data length and the number it represents\n /// @dev Useful for Parsing Vins and Vouts. Returns ERR_BAD_ARG if insufficient bytes.\n /// Caller SHOULD explicitly handle this case (or bubble it up)\n /// @param _b A byte-string containing a VarInt\n /// @param _at The position of the VarInt\n /// @return number of bytes in the encoding (not counting the tag), the encoded int\n function parseVarIntAt(bytes memory _b, uint256 _at) internal pure returns (uint256, uint256) {\n uint8 _dataLen = determineVarIntDataLengthAt(_b, _at);\n\n if (_dataLen == 0) {\n return (0, uint8(_b[_at]));\n }\n if (_b.length < 1 + _dataLen + _at) {\n return (ERR_BAD_ARG, 0);\n }\n uint256 _number;\n if (_dataLen == 2) {\n _number = reverseUint16(uint16(_b.slice2(1 + _at)));\n } else if (_dataLen == 4) {\n _number = reverseUint32(uint32(_b.slice4(1 + _at)));\n } else if (_dataLen == 8) {\n _number = reverseUint64(uint64(_b.slice8(1 + _at)));\n }\n return (_dataLen, _number);\n }\n\n /// @notice Changes the endianness of a byte array\n /// @dev Returns a new, backwards, bytes\n /// @param _b The bytes to reverse\n /// @return The reversed bytes\n function reverseEndianness(bytes memory _b) internal pure returns (bytes memory) {\n bytes memory _newValue = new bytes(_b.length);\n\n for (uint i = 0; i < _b.length; i++) {\n _newValue[_b.length - i - 1] = _b[i];\n }\n\n return _newValue;\n }\n\n /// @notice Changes the endianness of a uint256\n /// @dev https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel\n /// @param _b The unsigned integer to reverse\n /// @return v The reversed value\n function reverseUint256(uint256 _b) internal pure returns (uint256 v) {\n v = _b;\n\n // swap bytes\n v = ((v >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) |\n ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8);\n // swap 2-byte long pairs\n v = ((v >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) |\n ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16);\n // swap 4-byte long pairs\n v = ((v >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) |\n ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32);\n // swap 8-byte long pairs\n v = ((v >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) |\n ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64);\n // swap 16-byte long pairs\n v = (v >> 128) | (v << 128);\n }\n\n /// @notice Changes the endianness of a uint64\n /// @param _b The unsigned integer to reverse\n /// @return v The reversed value\n function reverseUint64(uint64 _b) internal pure returns (uint64 v) {\n v = _b;\n\n // swap bytes\n v = ((v >> 8) & 0x00FF00FF00FF00FF) |\n ((v & 0x00FF00FF00FF00FF) << 8);\n // swap 2-byte long pairs\n v = ((v >> 16) & 0x0000FFFF0000FFFF) |\n ((v & 0x0000FFFF0000FFFF) << 16);\n // swap 4-byte long pairs\n v = (v >> 32) | (v << 32);\n }\n\n /// @notice Changes the endianness of a uint32\n /// @param _b The unsigned integer to reverse\n /// @return v The reversed value\n function reverseUint32(uint32 _b) internal pure returns (uint32 v) {\n v = _b;\n\n // swap bytes\n v = ((v >> 8) & 0x00FF00FF) |\n ((v & 0x00FF00FF) << 8);\n // swap 2-byte long pairs\n v = (v >> 16) | (v << 16);\n }\n\n /// @notice Changes the endianness of a uint24\n /// @param _b The unsigned integer to reverse\n /// @return v The reversed value\n function reverseUint24(uint24 _b) internal pure returns (uint24 v) {\n v = (_b << 16) | (_b & 0x00FF00) | (_b >> 16);\n }\n\n /// @notice Changes the endianness of a uint16\n /// @param _b The unsigned integer to reverse\n /// @return v The reversed value\n function reverseUint16(uint16 _b) internal pure returns (uint16 v) {\n v = (_b << 8) | (_b >> 8);\n }\n\n\n /// @notice Converts big-endian bytes to a uint\n /// @dev Traverses the byte array and sums the bytes\n /// @param _b The big-endian bytes-encoded integer\n /// @return The integer representation\n function bytesToUint(bytes memory _b) internal pure returns (uint256) {\n uint256 _number;\n\n for (uint i = 0; i < _b.length; i++) {\n _number = _number + uint8(_b[i]) * (2 ** (8 * (_b.length - (i + 1))));\n }\n\n return _number;\n }\n\n /// @notice Get the last _num bytes from a byte array\n /// @param _b The byte array to slice\n /// @param _num The number of bytes to extract from the end\n /// @return The last _num bytes of _b\n function lastBytes(bytes memory _b, uint256 _num) internal pure returns (bytes memory) {\n uint256 _start = _b.length.sub(_num);\n\n return _b.slice(_start, _num);\n }\n\n /// @notice Implements bitcoin's hash160 (rmd160(sha2()))\n /// @dev abi.encodePacked changes the return to bytes instead of bytes32\n /// @param _b The pre-image\n /// @return The digest\n function hash160(bytes memory _b) internal pure returns (bytes memory) {\n return abi.encodePacked(ripemd160(abi.encodePacked(sha256(_b))));\n }\n\n /// @notice Implements bitcoin's hash160 (sha2 + ripemd160)\n /// @dev sha2 precompile at address(2), ripemd160 at address(3)\n /// @param _b The pre-image\n /// @return res The digest\n function hash160View(bytes memory _b) internal view returns (bytes20 res) {\n // solium-disable-next-line security/no-inline-assembly\n assembly {\n pop(staticcall(gas(), 2, add(_b, 32), mload(_b), 0x00, 32))\n pop(staticcall(gas(), 3, 0x00, 32, 0x00, 32))\n // read from position 12 = 0c\n res := mload(0x0c)\n }\n }\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\n function hash256(bytes memory _b) internal pure returns (bytes32) {\n return sha256(abi.encodePacked(sha256(_b)));\n }\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 res The digest\n function hash256View(bytes memory _b) internal view returns (bytes32 res) {\n // solium-disable-next-line security/no-inline-assembly\n assembly {\n pop(staticcall(gas(), 2, add(_b, 32), mload(_b), 0x00, 32))\n pop(staticcall(gas(), 2, 0x00, 32, 0x00, 32))\n res := mload(0x00)\n }\n }\n\n /// @notice Implements bitcoin's hash256 on a pair of bytes32\n /// @dev sha2 is precompiled smart contract located at address(2)\n /// @param _a The first bytes32 of the pre-image\n /// @param _b The second bytes32 of the pre-image\n /// @return res The digest\n function hash256Pair(bytes32 _a, bytes32 _b) internal view returns (bytes32 res) {\n // solium-disable-next-line security/no-inline-assembly\n assembly {\n mstore(0x00, _a)\n mstore(0x20, _b)\n pop(staticcall(gas(), 2, 0x00, 64, 0x00, 32))\n pop(staticcall(gas(), 2, 0x00, 32, 0x00, 32))\n res := mload(0x00)\n }\n }\n\n /* ************ */\n /* Legacy Input */\n /* ************ */\n\n /// @notice Extracts the nth input from the vin (0-indexed)\n /// @dev Iterates over the vin. If you need to extract several, write a custom function\n /// @param _vin The vin as a tightly-packed byte array\n /// @param _index The 0-indexed location of the input to extract\n /// @return The input as a byte array\n function extractInputAtIndex(bytes memory _vin, uint256 _index) internal pure returns (bytes memory) {\n uint256 _varIntDataLen;\n uint256 _nIns;\n\n (_varIntDataLen, _nIns) = parseVarInt(_vin);\n require(_varIntDataLen != ERR_BAD_ARG, \"Read overrun during VarInt parsing\");\n require(_index < _nIns, \"Vin read overrun\");\n\n uint256 _len = 0;\n uint256 _offset = 1 + _varIntDataLen;\n\n for (uint256 _i = 0; _i < _index; _i ++) {\n _len = determineInputLengthAt(_vin, _offset);\n require(_len != ERR_BAD_ARG, \"Bad VarInt in scriptSig\");\n _offset = _offset + _len;\n }\n\n _len = determineInputLengthAt(_vin, _offset);\n require(_len != ERR_BAD_ARG, \"Bad VarInt in scriptSig\");\n return _vin.slice(_offset, _len);\n }\n\n /// @notice Determines whether an input is legacy\n /// @dev False if no scriptSig, otherwise True\n /// @param _input The input\n /// @return True for legacy, False for witness\n function isLegacyInput(bytes memory _input) internal pure returns (bool) {\n return _input[36] != hex\"00\";\n }\n\n /// @notice Determines the length of a scriptSig in an input\n /// @dev Will return 0 if passed a witness input.\n /// @param _input The LEGACY input\n /// @return The length of the script sig\n function extractScriptSigLen(bytes memory _input) internal pure returns (uint256, uint256) {\n return extractScriptSigLenAt(_input, 0);\n }\n\n /// @notice Determines the length of a scriptSig in an input\n /// starting at the specified position\n /// @dev Will return 0 if passed a witness input.\n /// @param _input The byte array containing the LEGACY input\n /// @param _at The position of the input in the array\n /// @return The length of the script sig\n function extractScriptSigLenAt(bytes memory _input, uint256 _at) internal pure returns (uint256, uint256) {\n if (_input.length < 37 + _at) {\n return (ERR_BAD_ARG, 0);\n }\n\n uint256 _varIntDataLen;\n uint256 _scriptSigLen;\n (_varIntDataLen, _scriptSigLen) = parseVarIntAt(_input, _at + 36);\n\n return (_varIntDataLen, _scriptSigLen);\n }\n\n /// @notice Determines the length of an input from its scriptSig\n /// @dev 36 for outpoint, 1 for scriptSig length, 4 for sequence\n /// @param _input The input\n /// @return The length of the input in bytes\n function determineInputLength(bytes memory _input) internal pure returns (uint256) {\n return determineInputLengthAt(_input, 0);\n }\n\n /// @notice Determines the length of an input from its scriptSig,\n /// starting at the specified position\n /// @dev 36 for outpoint, 1 for scriptSig length, 4 for sequence\n /// @param _input The byte array containing the input\n /// @param _at The position of the input in the array\n /// @return The length of the input in bytes\n function determineInputLengthAt(bytes memory _input, uint256 _at) internal pure returns (uint256) {\n uint256 _varIntDataLen;\n uint256 _scriptSigLen;\n (_varIntDataLen, _scriptSigLen) = extractScriptSigLenAt(_input, _at);\n if (_varIntDataLen == ERR_BAD_ARG) {\n return ERR_BAD_ARG;\n }\n\n return 36 + 1 + _varIntDataLen + _scriptSigLen + 4;\n }\n\n /// @notice Extracts the LE sequence bytes from an input\n /// @dev Sequence is used for relative time locks\n /// @param _input The LEGACY input\n /// @return The sequence bytes (LE uint)\n function extractSequenceLELegacy(bytes memory _input) internal pure returns (bytes4) {\n uint256 _varIntDataLen;\n uint256 _scriptSigLen;\n (_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input);\n require(_varIntDataLen != ERR_BAD_ARG, \"Bad VarInt in scriptSig\");\n return _input.slice4(36 + 1 + _varIntDataLen + _scriptSigLen);\n }\n\n /// @notice Extracts the sequence from the input\n /// @dev Sequence is a 4-byte little-endian number\n /// @param _input The LEGACY input\n /// @return The sequence number (big-endian uint)\n function extractSequenceLegacy(bytes memory _input) internal pure returns (uint32) {\n uint32 _leSeqence = uint32(extractSequenceLELegacy(_input));\n uint32 _beSequence = reverseUint32(_leSeqence);\n return _beSequence;\n }\n /// @notice Extracts the VarInt-prepended scriptSig from the input in a tx\n /// @dev Will return hex\"00\" if passed a witness input\n /// @param _input The LEGACY input\n /// @return The length-prepended scriptSig\n function extractScriptSig(bytes memory _input) internal pure returns (bytes memory) {\n uint256 _varIntDataLen;\n uint256 _scriptSigLen;\n (_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input);\n require(_varIntDataLen != ERR_BAD_ARG, \"Bad VarInt in scriptSig\");\n return _input.slice(36, 1 + _varIntDataLen + _scriptSigLen);\n }\n\n\n /* ************* */\n /* Witness Input */\n /* ************* */\n\n /// @notice Extracts the LE sequence bytes from an input\n /// @dev Sequence is used for relative time locks\n /// @param _input The WITNESS input\n /// @return The sequence bytes (LE uint)\n function extractSequenceLEWitness(bytes memory _input) internal pure returns (bytes4) {\n return _input.slice4(37);\n }\n\n /// @notice Extracts the sequence from the input in a tx\n /// @dev Sequence is a 4-byte little-endian number\n /// @param _input The WITNESS input\n /// @return The sequence number (big-endian uint)\n function extractSequenceWitness(bytes memory _input) internal pure returns (uint32) {\n uint32 _leSeqence = uint32(extractSequenceLEWitness(_input));\n uint32 _inputeSequence = reverseUint32(_leSeqence);\n return _inputeSequence;\n }\n\n /// @notice Extracts the outpoint from the input in a tx\n /// @dev 32-byte tx id with 4-byte index\n /// @param _input The input\n /// @return The outpoint (LE bytes of prev tx hash + LE bytes of prev tx index)\n function extractOutpoint(bytes memory _input) internal pure returns (bytes memory) {\n return _input.slice(0, 36);\n }\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)\n function extractInputTxIdLE(bytes memory _input) internal pure returns (bytes32) {\n return _input.slice32(0);\n }\n\n /// @notice Extracts the outpoint tx id from an input\n /// starting at the specified position\n /// @dev 32-byte tx id\n /// @param _input The byte array containing the input\n /// @param _at The position of the input\n /// @return The tx id (little-endian bytes)\n function extractInputTxIdLeAt(bytes memory _input, uint256 _at) internal pure returns (bytes32) {\n return _input.slice32(_at);\n }\n\n /// @notice Extracts the LE tx input index from the input in a tx\n /// @dev 4-byte tx index\n /// @param _input The input\n /// @return The tx index (little-endian bytes)\n function extractTxIndexLE(bytes memory _input) internal pure returns (bytes4) {\n return _input.slice4(32);\n }\n\n /// @notice Extracts the LE tx input index from the input in a tx\n /// starting at the specified position\n /// @dev 4-byte tx index\n /// @param _input The byte array containing the input\n /// @param _at The position of the input\n /// @return The tx index (little-endian bytes)\n function extractTxIndexLeAt(bytes memory _input, uint256 _at) internal pure returns (bytes4) {\n return _input.slice4(32 + _at);\n }\n\n /* ****** */\n /* Output */\n /* ****** */\n\n /// @notice Determines the length of an output\n /// @dev Works with any properly formatted output\n /// @param _output The output\n /// @return The length indicated by the prefix, error if invalid length\n function determineOutputLength(bytes memory _output) internal pure returns (uint256) {\n return determineOutputLengthAt(_output, 0);\n }\n\n /// @notice Determines the length of an output\n /// starting at the specified position\n /// @dev Works with any properly formatted output\n /// @param _output The byte array containing the output\n /// @param _at The position of the output\n /// @return The length indicated by the prefix, error if invalid length\n function determineOutputLengthAt(bytes memory _output, uint256 _at) internal pure returns (uint256) {\n if (_output.length < 9 + _at) {\n return ERR_BAD_ARG;\n }\n uint256 _varIntDataLen;\n uint256 _scriptPubkeyLength;\n (_varIntDataLen, _scriptPubkeyLength) = parseVarIntAt(_output, 8 + _at);\n\n if (_varIntDataLen == ERR_BAD_ARG) {\n return ERR_BAD_ARG;\n }\n\n // 8-byte value, 1-byte for tag itself\n return 8 + 1 + _varIntDataLen + _scriptPubkeyLength;\n }\n\n /// @notice Extracts the output at a given index in the TxOuts vector\n /// @dev Iterates over the vout. If you need to extract multiple, write a custom function\n /// @param _vout The _vout to extract from\n /// @param _index The 0-indexed location of the output to extract\n /// @return The specified output\n function extractOutputAtIndex(bytes memory _vout, uint256 _index) internal pure returns (bytes memory) {\n uint256 _varIntDataLen;\n uint256 _nOuts;\n\n (_varIntDataLen, _nOuts) = parseVarInt(_vout);\n require(_varIntDataLen != ERR_BAD_ARG, \"Read overrun during VarInt parsing\");\n require(_index < _nOuts, \"Vout read overrun\");\n\n uint256 _len = 0;\n uint256 _offset = 1 + _varIntDataLen;\n\n for (uint256 _i = 0; _i < _index; _i ++) {\n _len = determineOutputLengthAt(_vout, _offset);\n require(_len != ERR_BAD_ARG, \"Bad VarInt in scriptPubkey\");\n _offset += _len;\n }\n\n _len = determineOutputLengthAt(_vout, _offset);\n require(_len != ERR_BAD_ARG, \"Bad VarInt in scriptPubkey\");\n return _vout.slice(_offset, _len);\n }\n\n /// @notice Extracts the value bytes from the output in a tx\n /// @dev Value is an 8-byte little-endian number\n /// @param _output The output\n /// @return The output value as LE bytes\n function extractValueLE(bytes memory _output) internal pure returns (bytes8) {\n return _output.slice8(0);\n }\n\n /// @notice Extracts the value from the output in a tx\n /// @dev Value is an 8-byte little-endian number\n /// @param _output The output\n /// @return The output value\n function extractValue(bytes memory _output) internal pure returns (uint64) {\n uint64 _leValue = uint64(extractValueLE(_output));\n uint64 _beValue = reverseUint64(_leValue);\n return _beValue;\n }\n\n /// @notice Extracts the data from an op return output\n /// @dev Returns hex\"\" if no data or not an op return\n /// @param _output The output\n /// @return Any data contained in the opreturn output, null if not an op return\n function extractOpReturnData(bytes memory _output) internal pure returns (bytes memory) {\n if (_output[9] != hex\"6a\") {\n return hex\"\";\n }\n bytes1 _dataLen = _output[10];\n return _output.slice(11, uint256(uint8(_dataLen)));\n }\n\n /// @notice Extracts the hash from the output script\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\n function extractHash(bytes memory _output) internal pure returns (bytes memory) {\n uint8 _scriptLen = uint8(_output[8]);\n\n // don't have to worry about overflow here.\n // if _scriptLen + 9 overflows, then output.length would have to be < 9\n // for this check to pass. if it's < 9, then we errored when assigning\n // _scriptLen\n if (_scriptLen + 9 != _output.length) {\n return hex\"\";\n }\n\n if (uint8(_output[9]) == 0) {\n if (_scriptLen < 2) {\n return hex\"\";\n }\n uint256 _payloadLen = uint8(_output[10]);\n // Check for maliciously formatted witness outputs.\n // No need to worry about underflow as long b/c of the `< 2` check\n if (_payloadLen != _scriptLen - 2 || (_payloadLen != 0x20 && _payloadLen != 0x14)) {\n return hex\"\";\n }\n return _output.slice(11, _payloadLen);\n } else {\n bytes3 _tag = _output.slice3(8);\n // p2pkh\n if (_tag == hex\"1976a9\") {\n // Check for maliciously formatted p2pkh\n // No need to worry about underflow, b/c of _scriptLen check\n if (uint8(_output[11]) != 0x14 ||\n _output.slice2(_output.length - 2) != hex\"88ac\") {\n return hex\"\";\n }\n return _output.slice(12, 20);\n //p2sh\n } else if (_tag == hex\"17a914\") {\n // Check for maliciously formatted p2sh\n // No need to worry about underflow, b/c of _scriptLen check\n if (uint8(_output[_output.length - 1]) != 0x87) {\n return hex\"\";\n }\n return _output.slice(11, 20);\n }\n }\n return hex\"\"; /* NB: will trigger on OPRETURN and any non-standard that doesn't overrun */\n }\n\n /* ********** */\n /* Witness TX */\n /* ********** */\n\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\n function validateVin(bytes memory _vin) internal pure returns (bool) {\n uint256 _varIntDataLen;\n uint256 _nIns;\n\n (_varIntDataLen, _nIns) = parseVarInt(_vin);\n\n // Not valid if it says there are too many or no inputs\n if (_nIns == 0 || _varIntDataLen == ERR_BAD_ARG) {\n return false;\n }\n\n uint256 _offset = 1 + _varIntDataLen;\n\n for (uint256 i = 0; i < _nIns; i++) {\n // If we're at the end, but still expect more\n if (_offset >= _vin.length) {\n return false;\n }\n\n // Grab the next input and determine its length.\n uint256 _nextLen = determineInputLengthAt(_vin, _offset);\n if (_nextLen == ERR_BAD_ARG) {\n return false;\n }\n\n // Increase the offset by that much\n _offset += _nextLen;\n }\n\n // Returns false if we're not exactly at the end\n return _offset == _vin.length;\n }\n\n /// @notice Checks that the vout passed up is properly formatted\n /// @dev Consider a vout with a valid scriptpubkey\n /// @param _vout Raw bytes length-prefixed output vector\n /// @return True if it represents a validly formatted vout\n function validateVout(bytes memory _vout) internal pure returns (bool) {\n uint256 _varIntDataLen;\n uint256 _nOuts;\n\n (_varIntDataLen, _nOuts) = parseVarInt(_vout);\n\n // Not valid if it says there are too many or no outputs\n if (_nOuts == 0 || _varIntDataLen == ERR_BAD_ARG) {\n return false;\n }\n\n uint256 _offset = 1 + _varIntDataLen;\n\n for (uint256 i = 0; i < _nOuts; i++) {\n // If we're at the end, but still expect more\n if (_offset >= _vout.length) {\n return false;\n }\n\n // Grab the next output and determine its length.\n // Increase the offset by that much\n uint256 _nextLen = determineOutputLengthAt(_vout, _offset);\n if (_nextLen == ERR_BAD_ARG) {\n return false;\n }\n\n _offset += _nextLen;\n }\n\n // Returns false if we're not exactly at the end\n return _offset == _vout.length;\n }\n\n\n\n /* ************ */\n /* Block Header */\n /* ************ */\n\n /// @notice Extracts the transaction merkle root from a block header\n /// @dev Use verifyHash256Merkle to verify proofs with this root\n /// @param _header The header\n /// @return The merkle root (little-endian)\n function extractMerkleRootLE(bytes memory _header) internal pure returns (bytes32) {\n return _header.slice32(36);\n }\n\n /// @notice Extracts the target from a block header\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\n function extractTarget(bytes memory _header) internal pure returns (uint256) {\n uint24 _m = uint24(_header.slice3(72));\n uint8 _e = uint8(_header[75]);\n uint256 _mantissa = uint256(reverseUint24(_m));\n uint _exponent = _e - 3;\n\n return _mantissa * (256 ** _exponent);\n }\n\n /// @notice Calculate difficulty from the difficulty 1 target and current target\n /// @dev Difficulty 1 is 0x1d00ffff on mainnet and testnet\n /// @dev Difficulty 1 is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent\n /// @param _target The current target\n /// @return The block difficulty (bdiff)\n function calculateDifficulty(uint256 _target) internal pure returns (uint256) {\n // Difficulty 1 calculated from 0x1d00ffff\n return DIFF1_TARGET.div(_target);\n }\n\n /// @notice Extracts the previous block's hash from a block header\n /// @dev Block headers do NOT include block number :(\n /// @param _header The header\n /// @return The previous block's hash (little-endian)\n function extractPrevBlockLE(bytes memory _header) internal pure returns (bytes32) {\n return _header.slice32(4);\n }\n\n /// @notice Extracts the timestamp from a block header\n /// @dev Time is not 100% reliable\n /// @param _header The header\n /// @return The timestamp (little-endian bytes)\n function extractTimestampLE(bytes memory _header) internal pure returns (bytes4) {\n return _header.slice4(68);\n }\n\n /// @notice Extracts the timestamp from a block header\n /// @dev Time is not 100% reliable\n /// @param _header The header\n /// @return The timestamp (uint)\n function extractTimestamp(bytes memory _header) internal pure returns (uint32) {\n return reverseUint32(uint32(extractTimestampLE(_header)));\n }\n\n /// @notice Extracts the expected difficulty from a block header\n /// @dev Does NOT verify the work\n /// @param _header The header\n /// @return The difficulty as an integer\n function extractDifficulty(bytes memory _header) internal pure returns (uint256) {\n return calculateDifficulty(extractTarget(_header));\n }\n\n /// @notice Concatenates and hashes two inputs for merkle proving\n /// @param _a The first hash\n /// @param _b The second hash\n /// @return The double-sha256 of the concatenated hashes\n function _hash256MerkleStep(bytes memory _a, bytes memory _b) internal view returns (bytes32) {\n return hash256View(abi.encodePacked(_a, _b));\n }\n\n /// @notice Concatenates and hashes two inputs for merkle proving\n /// @param _a The first hash\n /// @param _b The second hash\n /// @return The double-sha256 of the concatenated hashes\n function _hash256MerkleStep(bytes32 _a, bytes32 _b) internal view returns (bytes32) {\n return hash256Pair(_a, _b);\n }\n\n\n /// @notice Verifies a Bitcoin-style merkle tree\n /// @dev Leaves are 0-indexed. Inefficient version.\n /// @param _proof The proof. Tightly packed LE sha256 hashes. The last hash is the root\n /// @param _index The index of the leaf\n /// @return true if the proof is valid, else false\n function verifyHash256Merkle(bytes memory _proof, uint _index) internal view returns (bool) {\n // Not an even number of hashes\n if (_proof.length % 32 != 0) {\n return false;\n }\n\n // Special case for coinbase-only blocks\n if (_proof.length == 32) {\n return true;\n }\n\n // Should never occur\n if (_proof.length == 64) {\n return false;\n }\n\n bytes32 _root = _proof.slice32(_proof.length - 32);\n bytes32 _current = _proof.slice32(0);\n bytes memory _tree = _proof.slice(32, _proof.length - 64);\n\n return verifyHash256Merkle(_current, _tree, _root, _index);\n }\n\n /// @notice Verifies a Bitcoin-style merkle tree\n /// @dev Leaves are 0-indexed. Efficient version.\n /// @param _leaf The leaf of the proof. LE sha256 hash.\n /// @param _tree The intermediate nodes in the proof.\n /// Tightly packed LE sha256 hashes.\n /// @param _root The root of the proof. LE sha256 hash.\n /// @param _index The index of the leaf\n /// @return true if the proof is valid, else false\n function verifyHash256Merkle(\n bytes32 _leaf,\n bytes memory _tree,\n bytes32 _root,\n uint _index\n ) internal view returns (bool) {\n // Not an even number of hashes\n if (_tree.length % 32 != 0) {\n return false;\n }\n\n // Should never occur\n if (_tree.length == 0) {\n return false;\n }\n\n uint _idx = _index;\n bytes32 _current = _leaf;\n\n // i moves in increments of 32\n for (uint i = 0; i < _tree.length; i += 32) {\n if (_idx % 2 == 1) {\n _current = _hash256MerkleStep(_tree.slice32(i), _current);\n } else {\n _current = _hash256MerkleStep(_current, _tree.slice32(i));\n }\n _idx = _idx >> 1;\n }\n return _current == _root;\n }\n\n /*\n NB: https://github.com/bitcoin/bitcoin/blob/78dae8caccd82cfbfd76557f1fb7d7557c7b5edb/src/pow.cpp#L49-L72\n NB: We get a full-bitlength target from this. For comparison with\n header-encoded targets we need to mask it with the header target\n e.g. (full & truncated) == truncated\n */\n /// @notice performs the bitcoin difficulty retarget\n /// @dev implements the Bitcoin algorithm precisely\n /// @param _previousTarget the target of the previous period\n /// @param _firstTimestamp the timestamp of the first block in the difficulty period\n /// @param _secondTimestamp the timestamp of the last block in the difficulty period\n /// @return the new period's target threshold\n function retargetAlgorithm(\n uint256 _previousTarget,\n uint256 _firstTimestamp,\n uint256 _secondTimestamp\n ) internal pure returns (uint256) {\n uint256 _elapsedTime = _secondTimestamp.sub(_firstTimestamp);\n\n // Normalize ratio to factor of 4 if very long or very short\n if (_elapsedTime < RETARGET_PERIOD.div(4)) {\n _elapsedTime = RETARGET_PERIOD.div(4);\n }\n if (_elapsedTime > RETARGET_PERIOD.mul(4)) {\n _elapsedTime = RETARGET_PERIOD.mul(4);\n }\n\n /*\n NB: high targets e.g. ffff0020 can cause overflows here\n so we divide it by 256**2, then multiply by 256**2 later\n we know the target is evenly divisible by 256**2, so this isn't an issue\n */\n\n uint256 _adjusted = _previousTarget.div(65536).mul(_elapsedTime);\n return _adjusted.div(RETARGET_PERIOD).mul(65536);\n }\n}\n"
168
+ },
169
+ "@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol": {
170
+ "content": "pragma solidity ^0.8.4;\n\n/*\n\nhttps://github.com/GNSPS/solidity-bytes-utils/\n\nThis is free and unencumbered software released into the public domain.\n\nAnyone is free to copy, modify, publish, use, compile, sell, or\ndistribute this software, either in source code form or as a compiled\nbinary, for any purpose, commercial or non-commercial, and by any\nmeans.\n\nIn jurisdictions that recognize copyright laws, the author or authors\nof this software dedicate any and all copyright interest in the\nsoftware to the public domain. We make this dedication for the benefit\nof the public at large and to the detriment of our heirs and\nsuccessors. We intend this dedication to be an overt act of\nrelinquishment in perpetuity of all present and future rights to this\nsoftware under copyright law.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\nOTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n\nFor more information, please refer to <https://unlicense.org>\n*/\n\n\n/** @title BytesLib **/\n/** @author https://github.com/GNSPS **/\n\nlibrary BytesLib {\n function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) {\n bytes memory tempBytes;\n\n assembly {\n // Get a location of some free memory and store it in tempBytes as\n // Solidity does for memory variables.\n tempBytes := mload(0x40)\n\n // Store the length of the first bytes array at the beginning of\n // the memory for tempBytes.\n let length := mload(_preBytes)\n mstore(tempBytes, length)\n\n // Maintain a memory counter for the current write location in the\n // temp bytes array by adding the 32 bytes for the array length to\n // the starting location.\n let mc := add(tempBytes, 0x20)\n // Stop copying when the memory counter reaches the length of the\n // first bytes array.\n let end := add(mc, length)\n\n for {\n // Initialize a copy counter to the start of the _preBytes data,\n // 32 bytes into its memory.\n let cc := add(_preBytes, 0x20)\n } lt(mc, end) {\n // Increase both counters by 32 bytes each iteration.\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n // Write the _preBytes data into the tempBytes memory 32 bytes\n // at a time.\n mstore(mc, mload(cc))\n }\n\n // Add the length of _postBytes to the current length of tempBytes\n // and store it as the new length in the first 32 bytes of the\n // tempBytes memory.\n length := mload(_postBytes)\n mstore(tempBytes, add(length, mload(tempBytes)))\n\n // Move the memory counter back from a multiple of 0x20 to the\n // actual end of the _preBytes data.\n mc := end\n // Stop copying when the memory counter reaches the new combined\n // length of the arrays.\n end := add(mc, length)\n\n for {\n let cc := add(_postBytes, 0x20)\n } lt(mc, end) {\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n mstore(mc, mload(cc))\n }\n\n // Update the free-memory pointer by padding our last write location\n // to 32 bytes: add 31 bytes to the end of tempBytes to move to the\n // next 32 byte block, then round down to the nearest multiple of\n // 32. If the sum of the length of the two arrays is zero then add\n // one before rounding down to leave a blank 32 bytes (the length block with 0).\n mstore(0x40, and(\n add(add(end, iszero(add(length, mload(_preBytes)))), 31),\n not(31) // Round down to the nearest 32 bytes.\n ))\n }\n\n return tempBytes;\n }\n\n function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {\n assembly {\n // Read the first 32 bytes of _preBytes storage, which is the length\n // of the array. (We don't need to use the offset into the slot\n // because arrays use the entire slot.)\n let fslot := sload(_preBytes.slot)\n // Arrays of 31 bytes or less have an even value in their slot,\n // while longer arrays have an odd value. The actual length is\n // the slot divided by two for odd values, and the lowest order\n // byte divided by two for even values.\n // If the slot is even, bitwise and the slot with 255 and divide by\n // two to get the length. If the slot is odd, bitwise and the slot\n // with -1 and divide by two.\n let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)\n let mlength := mload(_postBytes)\n let newlength := add(slength, mlength)\n // slength can contain both the length and contents of the array\n // if length < 32 bytes so let's prepare for that\n // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage\n switch add(lt(slength, 32), lt(newlength, 32))\n case 2 {\n // Since the new array still fits in the slot, we just need to\n // update the contents of the slot.\n // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length\n sstore(\n _preBytes.slot,\n // all the modifications to the slot are inside this\n // next block\n add(\n // we can just add to the slot contents because the\n // bytes we want to change are the LSBs\n fslot,\n add(\n mul(\n div(\n // load the bytes from memory\n mload(add(_postBytes, 0x20)),\n // zero all bytes to the right\n exp(0x100, sub(32, mlength))\n ),\n // and now shift left the number of bytes to\n // leave space for the length in the slot\n exp(0x100, sub(32, newlength))\n ),\n // increase length by the double of the memory\n // bytes length\n mul(mlength, 2)\n )\n )\n )\n }\n case 1 {\n // The stored value fits in the slot, but the combined value\n // will exceed it.\n // get the keccak hash to get the contents of the array\n mstore(0x0, _preBytes.slot)\n let sc := add(keccak256(0x0, 0x20), div(slength, 32))\n\n // save new length\n sstore(_preBytes.slot, add(mul(newlength, 2), 1))\n\n // The contents of the _postBytes array start 32 bytes into\n // the structure. Our first read should obtain the `submod`\n // bytes that can fit into the unused space in the last word\n // of the stored array. To get this, we read 32 bytes starting\n // from `submod`, so the data we read overlaps with the array\n // contents by `submod` bytes. Masking the lowest-order\n // `submod` bytes allows us to add that value directly to the\n // stored value.\n\n let submod := sub(32, slength)\n let mc := add(_postBytes, submod)\n let end := add(_postBytes, mlength)\n let mask := sub(exp(0x100, submod), 1)\n\n sstore(\n sc,\n add(\n and(\n fslot,\n 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00\n ),\n and(mload(mc), mask)\n )\n )\n\n for {\n mc := add(mc, 0x20)\n sc := add(sc, 1)\n } lt(mc, end) {\n sc := add(sc, 1)\n mc := add(mc, 0x20)\n } {\n sstore(sc, mload(mc))\n }\n\n mask := exp(0x100, sub(mc, end))\n\n sstore(sc, mul(div(mload(mc), mask), mask))\n }\n default {\n // get the keccak hash to get the contents of the array\n mstore(0x0, _preBytes.slot)\n // Start copying to the last used word of the stored array.\n let sc := add(keccak256(0x0, 0x20), div(slength, 32))\n\n // save new length\n sstore(_preBytes.slot, add(mul(newlength, 2), 1))\n\n // Copy over the first `submod` bytes of the new data as in\n // case 1 above.\n let slengthmod := mod(slength, 32)\n let mlengthmod := mod(mlength, 32)\n let submod := sub(32, slengthmod)\n let mc := add(_postBytes, submod)\n let end := add(_postBytes, mlength)\n let mask := sub(exp(0x100, submod), 1)\n\n sstore(sc, add(sload(sc), and(mload(mc), mask)))\n\n for {\n sc := add(sc, 1)\n mc := add(mc, 0x20)\n } lt(mc, end) {\n sc := add(sc, 1)\n mc := add(mc, 0x20)\n } {\n sstore(sc, mload(mc))\n }\n\n mask := exp(0x100, sub(mc, end))\n\n sstore(sc, mul(div(mload(mc), mask), mask))\n }\n }\n }\n\n function slice(bytes memory _bytes, uint _start, uint _length) internal pure returns (bytes memory res) {\n if (_length == 0) {\n return hex\"\";\n }\n uint _end = _start + _length;\n require(_end > _start && _bytes.length >= _end, \"Slice out of bounds\");\n\n assembly {\n // Alloc bytes array with additional 32 bytes afterspace and assign it's size\n res := mload(0x40)\n mstore(0x40, add(add(res, 64), _length))\n mstore(res, _length)\n\n // Compute distance between source and destination pointers\n let diff := sub(res, add(_bytes, _start))\n\n for {\n let src := add(add(_bytes, 32), _start)\n let end := add(src, _length)\n } lt(src, end) {\n src := add(src, 32)\n } {\n mstore(add(src, diff), mload(src))\n }\n }\n }\n\n /// @notice Take a slice of the byte array, overwriting the destination.\n /// The length of the slice will equal the length of the destination array.\n /// @dev Make sure the destination array has afterspace if required.\n /// @param _bytes The source array\n /// @param _dest The destination array.\n /// @param _start The location to start in the source array.\n function sliceInPlace(\n bytes memory _bytes,\n bytes memory _dest,\n uint _start\n ) internal pure {\n uint _length = _dest.length;\n uint _end = _start + _length;\n require(_end > _start && _bytes.length >= _end, \"Slice out of bounds\");\n\n assembly {\n for {\n let src := add(add(_bytes, 32), _start)\n let res := add(_dest, 32)\n let end := add(src, _length)\n } lt(src, end) {\n src := add(src, 32)\n res := add(res, 32)\n } {\n mstore(res, mload(src))\n }\n }\n }\n\n // Static slice functions, no bounds checking\n /// @notice take a 32-byte slice from the specified position\n function slice32(bytes memory _bytes, uint _start) internal pure returns (bytes32 res) {\n assembly {\n res := mload(add(add(_bytes, 32), _start))\n }\n }\n\n /// @notice take a 20-byte slice from the specified position\n function slice20(bytes memory _bytes, uint _start) internal pure returns (bytes20) {\n return bytes20(slice32(_bytes, _start));\n }\n\n /// @notice take a 8-byte slice from the specified position\n function slice8(bytes memory _bytes, uint _start) internal pure returns (bytes8) {\n return bytes8(slice32(_bytes, _start));\n }\n\n /// @notice take a 4-byte slice from the specified position\n function slice4(bytes memory _bytes, uint _start) internal pure returns (bytes4) {\n return bytes4(slice32(_bytes, _start));\n }\n\n /// @notice take a 3-byte slice from the specified position\n function slice3(bytes memory _bytes, uint _start) internal pure returns (bytes3) {\n return bytes3(slice32(_bytes, _start));\n }\n\n /// @notice take a 2-byte slice from the specified position\n function slice2(bytes memory _bytes, uint _start) internal pure returns (bytes2) {\n return bytes2(slice32(_bytes, _start));\n }\n\n function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) {\n uint _totalLen = _start + 20;\n require(_totalLen > _start && _bytes.length >= _totalLen, \"Address conversion out of bounds.\");\n address tempAddress;\n\n assembly {\n tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)\n }\n\n return tempAddress;\n }\n\n function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) {\n uint _totalLen = _start + 32;\n require(_totalLen > _start && _bytes.length >= _totalLen, \"Uint conversion out of bounds.\");\n uint256 tempUint;\n\n assembly {\n tempUint := mload(add(add(_bytes, 0x20), _start))\n }\n\n return tempUint;\n }\n\n function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {\n bool success = true;\n\n assembly {\n let length := mload(_preBytes)\n\n // if lengths don't match the arrays are not equal\n switch eq(length, mload(_postBytes))\n case 1 {\n // cb is a circuit breaker in the for loop since there's\n // no said feature for inline assembly loops\n // cb = 1 - don't breaker\n // cb = 0 - break\n let cb := 1\n\n let mc := add(_preBytes, 0x20)\n let end := add(mc, length)\n\n for {\n let cc := add(_postBytes, 0x20)\n // the next line is the loop condition:\n // while(uint(mc < end) + cb == 2)\n } eq(add(lt(mc, end), cb), 2) {\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n // if any of these checks fails then arrays are not equal\n if iszero(eq(mload(mc), mload(cc))) {\n // unsuccess:\n success := 0\n cb := 0\n }\n }\n }\n default {\n // unsuccess:\n success := 0\n }\n }\n\n return success;\n }\n\n function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) {\n bool success = true;\n\n assembly {\n // we know _preBytes_offset is 0\n let fslot := sload(_preBytes.slot)\n // Decode the length of the stored array like in concatStorage().\n let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)\n let mlength := mload(_postBytes)\n\n // if lengths don't match the arrays are not equal\n switch eq(slength, mlength)\n case 1 {\n // slength can contain both the length and contents of the array\n // if length < 32 bytes so let's prepare for that\n // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage\n if iszero(iszero(slength)) {\n switch lt(slength, 32)\n case 1 {\n // blank the last byte which is the length\n fslot := mul(div(fslot, 0x100), 0x100)\n\n if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {\n // unsuccess:\n success := 0\n }\n }\n default {\n // cb is a circuit breaker in the for loop since there's\n // no said feature for inline assembly loops\n // cb = 1 - don't breaker\n // cb = 0 - break\n let cb := 1\n\n // get the keccak hash to get the contents of the array\n mstore(0x0, _preBytes.slot)\n let sc := keccak256(0x0, 0x20)\n\n let mc := add(_postBytes, 0x20)\n let end := add(mc, mlength)\n\n // the next line is the loop condition:\n // while(uint(mc < end) + cb == 2)\n for {} eq(add(lt(mc, end), cb), 2) {\n sc := add(sc, 1)\n mc := add(mc, 0x20)\n } {\n if iszero(eq(sload(sc), mload(mc))) {\n // unsuccess:\n success := 0\n cb := 0\n }\n }\n }\n }\n }\n default {\n // unsuccess:\n success := 0\n }\n }\n\n return success;\n }\n\n function 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 function keccak256Slice(bytes memory _bytes, uint _start, uint _length) pure internal returns (bytes32 result) {\n uint _end = _start + _length;\n require(_end > _start && _bytes.length >= _end, \"Slice out of bounds\");\n\n assembly {\n result := keccak256(add(add(_bytes, 32), _start), _length)\n }\n }\n}\n"
171
+ },
172
+ "@keep-network/bitcoin-spv-sol/contracts/SafeMath.sol": {
173
+ "content": "pragma solidity ^0.8.4;\n\n/*\nThe MIT License (MIT)\n\nCopyright (c) 2016 Smart Contract Solutions, Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\n\n\n/**\n * @title SafeMath\n * @dev Math operations with safety checks that throw on error\n */\nlibrary SafeMath {\n\n /**\n * @dev Multiplies two numbers, throws on overflow.\n */\n function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {\n // Gas optimization: this is cheaper than asserting 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522\n if (_a == 0) {\n return 0;\n }\n\n c = _a * _b;\n require(c / _a == _b, \"Overflow during multiplication.\");\n return c;\n }\n\n /**\n * @dev Integer division of two numbers, truncating the quotient.\n */\n function div(uint256 _a, uint256 _b) internal pure returns (uint256) {\n // assert(_b > 0); // Solidity automatically throws when dividing by 0\n // uint256 c = _a / _b;\n // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold\n return _a / _b;\n }\n\n /**\n * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).\n */\n function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {\n require(_b <= _a, \"Underflow during subtraction.\");\n return _a - _b;\n }\n\n /**\n * @dev Adds two numbers, throws on overflow.\n */\n function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {\n c = _a + _b;\n require(c >= _a, \"Overflow during addition.\");\n return c;\n }\n}\n"
174
+ },
175
+ "@keep-network/bitcoin-spv-sol/contracts/ValidateSPV.sol": {
176
+ "content": "pragma solidity ^0.8.4;\n\n/** @title ValidateSPV*/\n/** @author Summa (https://summa.one) */\n\nimport {BytesLib} from \"./BytesLib.sol\";\nimport {SafeMath} from \"./SafeMath.sol\";\nimport {BTCUtils} from \"./BTCUtils.sol\";\n\n\nlibrary ValidateSPV {\n\n using BTCUtils for bytes;\n using BTCUtils for uint256;\n using BytesLib for bytes;\n using SafeMath for uint256;\n\n enum InputTypes { NONE, LEGACY, COMPATIBILITY, WITNESS }\n enum OutputTypes { NONE, WPKH, WSH, OP_RETURN, PKH, SH, NONSTANDARD }\n\n uint256 constant ERR_BAD_LENGTH = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;\n uint256 constant ERR_INVALID_CHAIN = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe;\n uint256 constant ERR_LOW_WORK = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd;\n\n function getErrBadLength() internal pure returns (uint256) {\n return ERR_BAD_LENGTH;\n }\n\n function getErrInvalidChain() internal pure returns (uint256) {\n return ERR_INVALID_CHAIN;\n }\n\n function getErrLowWork() internal pure returns (uint256) {\n return ERR_LOW_WORK;\n }\n\n /// @notice Validates a tx inclusion in the block\n /// @dev `index` is not a reliable indicator of location within a block\n /// @param _txid The txid (LE)\n /// @param _merkleRoot The merkle root (as in the block header)\n /// @param _intermediateNodes The proof's intermediate nodes (digests between leaf and root)\n /// @param _index The leaf's index in the tree (0-indexed)\n /// @return true if fully valid, false otherwise\n function prove(\n bytes32 _txid,\n bytes32 _merkleRoot,\n bytes memory _intermediateNodes,\n uint _index\n ) internal view returns (bool) {\n // Shortcut the empty-block case\n if (_txid == _merkleRoot && _index == 0 && _intermediateNodes.length == 0) {\n return true;\n }\n\n // If the Merkle proof failed, bubble up error\n return BTCUtils.verifyHash256Merkle(\n _txid,\n _intermediateNodes,\n _merkleRoot,\n _index\n );\n }\n\n /// @notice Hashes transaction to get txid\n /// @dev Supports Legacy and Witness\n /// @param _version 4-bytes version\n /// @param _vin Raw bytes length-prefixed input vector\n /// @param _vout Raw bytes length-prefixed output vector\n /// @param _locktime 4-byte tx locktime\n /// @return 32-byte transaction id, little endian\n function calculateTxId(\n bytes4 _version,\n bytes memory _vin,\n bytes memory _vout,\n bytes4 _locktime\n ) internal view returns (bytes32) {\n // Get transaction hash double-Sha256(version + nIns + inputs + nOuts + outputs + locktime)\n return abi.encodePacked(_version, _vin, _vout, _locktime).hash256View();\n }\n\n /// @notice Checks validity of header chain\n /// @notice Compares the hash of each header to the prevHash in the next header\n /// @param _headers Raw byte array of header chain\n /// @return _totalDifficulty The total accumulated difficulty of the header chain, or an error code\n function validateHeaderChain(bytes memory _headers) internal view returns (uint256 _totalDifficulty) {\n\n // Check header chain length\n if (_headers.length % 80 != 0) {return ERR_BAD_LENGTH;}\n\n // Initialize header start index\n bytes32 _digest;\n\n _totalDifficulty = 0;\n\n bytes memory _header;\n\n // Allocate _header with extra space after it to fit 3 full words\n assembly {\n _header := mload(0x40)\n mstore(0x40, add(_header, add(32, 96)))\n mstore(_header, 80)\n }\n\n for (uint256 _start = 0; _start < _headers.length; _start += 80) {\n\n // ith header start index and ith header\n _headers.sliceInPlace(_header, _start);\n\n // After the first header, check that headers are in a chain\n if (_start != 0) {\n if (!validateHeaderPrevHash(_header, _digest)) {return ERR_INVALID_CHAIN;}\n }\n\n // ith header target\n uint256 _target = _header.extractTarget();\n\n // Require that the header has sufficient work\n _digest = _header.hash256View();\n if(uint256(_digest).reverseUint256() > _target) {\n return ERR_LOW_WORK;\n }\n\n // Add ith header difficulty to difficulty sum\n _totalDifficulty = _totalDifficulty.add(_target.calculateDifficulty());\n }\n }\n\n /// @notice Checks validity of header work\n /// @param _digest Header digest\n /// @param _target The target threshold\n /// @return true if header work is valid, false otherwise\n function validateHeaderWork(bytes32 _digest, uint256 _target) internal pure returns (bool) {\n if (_digest == bytes32(0)) {return false;}\n return (uint256(_digest).reverseUint256() < _target);\n }\n\n /// @notice Checks validity of header chain\n /// @dev Compares current header prevHash to previous header's digest\n /// @param _header The raw bytes header\n /// @param _prevHeaderDigest The previous header's digest\n /// @return true if the connect is valid, false otherwise\n function validateHeaderPrevHash(bytes memory _header, bytes32 _prevHeaderDigest) internal pure returns (bool) {\n\n // Extract prevHash of current header\n bytes32 _prevHash = _header.extractPrevBlockLE();\n\n // Compare prevHash of current header to previous header's digest\n if (_prevHash != _prevHeaderDigest) {return false;}\n\n return true;\n }\n}\n"
177
+ },
178
+ "@keep-network/bitcoin-spv-sol/contracts/CheckBitcoinSigs.sol": {
179
+ "content": "pragma solidity ^0.8.4;\n\n/** @title CheckBitcoinSigs */\n/** @author Summa (https://summa.one) */\n\nimport {BytesLib} from \"./BytesLib.sol\";\nimport {BTCUtils} from \"./BTCUtils.sol\";\n\n\nlibrary CheckBitcoinSigs {\n\n using BytesLib for bytes;\n using BTCUtils for bytes;\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\n function 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 /// @notice Calculates the p2wpkh output script of a pubkey\n /// @dev Compresses keys to 33 bytes as required by Bitcoin\n /// @param _pubkey The public key, compressed or uncompressed\n /// @return The p2wkph output script\n function p2wpkhFromPubkey(bytes memory _pubkey) internal view returns (bytes memory) {\n bytes memory _compressedPubkey;\n uint8 _prefix;\n\n if (_pubkey.length == 64) {\n _prefix = uint8(_pubkey[_pubkey.length - 1]) % 2 == 1 ? 3 : 2;\n _compressedPubkey = abi.encodePacked(_prefix, _pubkey.slice32(0));\n } else if (_pubkey.length == 65) {\n _prefix = uint8(_pubkey[_pubkey.length - 1]) % 2 == 1 ? 3 : 2;\n _compressedPubkey = abi.encodePacked(_prefix, _pubkey.slice32(1));\n } else {\n _compressedPubkey = _pubkey;\n }\n\n require(_compressedPubkey.length == 33, \"Witness PKH requires compressed keys\");\n\n bytes20 _pubkeyHash = _compressedPubkey.hash160View();\n return abi.encodePacked(hex\"0014\", _pubkeyHash);\n }\n\n /// @notice checks a signed message's validity under a pubkey\n /// @dev does this using ecrecover because Ethereum has no soul\n /// @param _pubkey the public key to check (64 bytes)\n /// @param _digest the message digest signed\n /// @param _v the signature recovery value\n /// @param _r the signature r value\n /// @param _s the signature s value\n /// @return true if signature is valid, else false\n function checkSig(\n bytes memory _pubkey,\n bytes32 _digest,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) internal pure returns (bool) {\n require(_pubkey.length == 64, \"Requires uncompressed unprefixed pubkey\");\n address _expected = accountFromPubkey(_pubkey);\n address _actual = ecrecover(_digest, _v, _r, _s);\n return _actual == _expected;\n }\n\n /// @notice checks a signed message against a bitcoin p2wpkh output script\n /// @dev does this my verifying the p2wpkh matches an ethereum account\n /// @param _p2wpkhOutputScript the bitcoin output script\n /// @param _pubkey the uncompressed, unprefixed public key to check\n /// @param _digest the message digest signed\n /// @param _v the signature recovery value\n /// @param _r the signature r value\n /// @param _s the signature s value\n /// @return true if signature is valid, else false\n function checkBitcoinSig(\n bytes memory _p2wpkhOutputScript,\n bytes memory _pubkey,\n bytes32 _digest,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) internal view returns (bool) {\n require(_pubkey.length == 64, \"Requires uncompressed unprefixed pubkey\");\n\n bool _isExpectedSigner = keccak256(p2wpkhFromPubkey(_pubkey)) == keccak256(_p2wpkhOutputScript); // is it the expected signer?\n if (!_isExpectedSigner) {return false;}\n\n bool _sigResult = checkSig(_pubkey, _digest, _v, _r, _s);\n return _sigResult;\n }\n\n /// @notice checks if a message is the sha256 preimage of a digest\n /// @dev this is NOT the hash256! this step is necessary for ECDSA security!\n /// @param _digest the digest\n /// @param _candidate the purported preimage\n /// @return true if the preimage matches the digest, else false\n function isSha256Preimage(\n bytes memory _candidate,\n bytes32 _digest\n ) internal pure returns (bool) {\n return sha256(_candidate) == _digest;\n }\n\n /// @notice checks if a message is the keccak256 preimage of a digest\n /// @dev this step is necessary for ECDSA security!\n /// @param _digest the digest\n /// @param _candidate the purported preimage\n /// @return true if the preimage matches the digest, else false\n function isKeccak256Preimage(\n bytes memory _candidate,\n bytes32 _digest\n ) internal pure returns (bool) {\n return keccak256(_candidate) == _digest;\n }\n\n /// @notice calculates the signature hash of a Bitcoin transaction with the provided details\n /// @dev documented in bip143. many values are hardcoded here\n /// @param _outpoint the bitcoin UTXO id (32-byte txid + 4-byte output index)\n /// @param _inputPKH the input pubkeyhash (hash160(sender_pubkey))\n /// @param _inputValue the value of the input in satoshi\n /// @param _outputValue the value of the output in satoshi\n /// @param _outputScript the length-prefixed output script\n /// @return the double-sha256 (hash256) signature hash as defined by bip143\n function 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 view 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\n bytes32 _hashOutputs = abi.encodePacked(\n _outputValue, // 8-byte LE\n _outputScript).hash256View();\n\n bytes memory _sighashPreimage = abi.encodePacked(\n hex\"01000000\", // version\n _outpoint.hash256View(), // hashPrevouts\n hex\"8cb9012517c817fead650287d61bdd9c68803b6bf9c64133dcab3e65b5a50cb9\", // hashSequence(00000000)\n _outpoint, // outpoint\n // p2wpkh script code\n hex\"1976a914\", // length, dup, hash160, pkh_length\n _inputPKH,\n hex\"88ac\", // equal, checksig\n // end 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.hash256View();\n }\n\n /// @notice calculates the signature hash of a Bitcoin transaction with the provided details\n /// @dev documented in bip143. many values are hardcoded here\n /// @param _outpoint the bitcoin UTXO id (32-byte txid + 4-byte output index)\n /// @param _inputPKH the input pubkeyhash (hash160(sender_pubkey))\n /// @param _inputValue the value of the input in satoshi\n /// @param _outputValue the value of the output in satoshi\n /// @param _outputPKH the output pubkeyhash (hash160(recipient_pubkey))\n /// @return the double-sha256 (hash256) signature hash as defined by bip143\n function wpkhToWpkhSighash(\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 bytes20 _outputPKH // 20-byte hash160\n ) internal view returns (bytes32) {\n return wpkhSpendSighash(\n _outpoint,\n _inputPKH,\n _inputValue,\n _outputValue,\n abi.encodePacked(\n hex\"160014\", // wpkh tag\n _outputPKH)\n );\n }\n\n /// @notice Preserved for API compatibility with older version\n /// @dev documented in bip143. many values are hardcoded here\n /// @param _outpoint the bitcoin UTXO id (32-byte txid + 4-byte output index)\n /// @param _inputPKH the input pubkeyhash (hash160(sender_pubkey))\n /// @param _inputValue the value of the input in satoshi\n /// @param _outputValue the value of the output in satoshi\n /// @param _outputPKH the output pubkeyhash (hash160(recipient_pubkey))\n /// @return the double-sha256 (hash256) signature hash as defined by bip143\n function oneInputOneOutputSighash(\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 bytes20 _outputPKH // 20-byte hash160\n ) internal view returns (bytes32) {\n return wpkhToWpkhSighash(_outpoint, _inputPKH, _inputValue, _outputValue, _outputPKH);\n }\n\n}\n"
180
+ },
181
+ "contracts/bridge/Heartbeat.sol": {
182
+ "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {BytesLib} from \"@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol\";\n\n/// @title Bridge wallet heartbeat\n/// @notice The library establishes expected format for heartbeat messages\n/// signed by wallet ECDSA signing group. Heartbeat messages are\n/// constructed in such a way that they can not be used as a Bitcoin\n/// transaction preimages.\n/// @dev The smallest Bitcoin non-coinbase transaction is a one spending an\n/// OP_TRUE anyonecanspend output and creating 1 OP_TRUE anyonecanspend\n/// output. Such a transaction has 61 bytes (see `BitcoinTx` documentation):\n/// 4 bytes for version\n/// 1 byte for tx_in_count\n/// 36 bytes for tx_in.previous_output\n/// 1 byte for tx_in.script_bytes (value: 0)\n/// 0 bytes for tx_in.signature_script\n/// 4 bytes for tx_in.sequence\n/// 1 byte for tx_out_count\n/// 8 bytes for tx_out.value\n/// 1 byte for tx_out.pk_script_bytes\n/// 1 byte for tx_out.pk_script\n/// 4 bytes for lock_time\n///\n///\n/// The smallest Bitcoin coinbase transaction is a one creating\n/// 1 OP_TRUE anyonecanspend output and having an empty coinbase script.\n/// Such a transaction has 65 bytes:\n/// 4 bytes for version\n/// 1 byte for tx_in_count\n/// 32 bytes for tx_in.hash (all 0x00)\n/// 4 bytes for tx_in.index (all 0xff)\n/// 1 byte for tx_in.script_bytes (value: 0)\n/// 4 bytes for tx_in.height\n/// 0 byte for tx_in.coinbase_script\n/// 4 bytes for tx_in.sequence\n/// 1 byte for tx_out_count\n/// 8 bytes for tx_out.value\n/// 1 byte for tx_out.pk_script_bytes\n/// 1 byte for tx_out.pk_script\n/// 4 bytes for lock_time\n///\n///\n/// A SIGHASH flag is used to indicate which part of the transaction is\n/// signed by the ECDSA signature. There are currently 3 flags:\n/// SIGHASH_ALL, SIGHASH_NONE, SIGHASH_SINGLE, and different combinations\n/// of these flags.\n///\n/// No matter the SIGHASH flag and no matter the combination, the following\n/// fields from the transaction are always included in the constructed\n/// preimage:\n/// 4 bytes for version\n/// 36 bytes for tx_in.previous_output (or tx_in.hash + tx_in.index for coinbase)\n/// 4 bytes for lock_time\n///\n/// Additionally, the last 4 bytes of the preimage determines the SIGHASH\n/// flag.\n///\n/// This is enough to say there is no way the preimage could be shorter\n/// than 4 + 36 + 4 + 4 = 48 bytes.\n///\n/// For this reason, we construct the heartbeat message, as a 16-byte\n/// message. The first 8 bytes are 0xffffffffffffffff. The last 8 bytes\n/// are for an arbitrary uint64, being a signed heartbeat nonce (for\n/// example, the last Ethereum block hash).\n///\n/// The message being signed by the wallet when executing the heartbeat\n/// protocol should be Bitcoin's hash256 (double SHA-256) of the heartbeat\n/// message:\n/// heartbeat_sighash = hash256(heartbeat_message)\nlibrary Heartbeat {\n using BytesLib for bytes;\n\n /// @notice Determines if the signed byte array is a valid, non-fraudulent\n /// heartbeat message.\n /// @param message Message signed by the wallet. It is a potential heartbeat\n /// message, Bitcoin transaction preimage, or an arbitrary signed\n /// bytes.\n /// @dev Wallet heartbeat message must be exactly 16 bytes long with the first\n /// 8 bytes set to 0xffffffffffffffff.\n /// @return True if valid heartbeat message, false otherwise.\n function isValidHeartbeatMessage(bytes calldata message)\n internal\n pure\n returns (bool)\n {\n if (message.length != 16) {\n return false;\n }\n\n if (message.slice8(0) != 0xffffffffffffffff) {\n return false;\n }\n\n return true;\n }\n}\n"
183
+ },
184
+ "@openzeppelin/contracts/utils/math/Math.sol": {
185
+ "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a >= b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds up instead\n * of rounding down.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a / b + (a % b == 0 ? 0 : 1);\n }\n}\n"
186
+ },
187
+ "contracts/test/TestRelay.sol": {
188
+ "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.9;\n\nimport \"../bridge/Bridge.sol\";\n\ncontract TestRelay is IRelay {\n uint256 private currentEpochDifficulty;\n uint256 private prevEpochDifficulty;\n\n function setCurrentEpochDifficulty(uint256 _difficulty) external {\n currentEpochDifficulty = _difficulty;\n }\n\n function setPrevEpochDifficulty(uint256 _difficulty) external {\n prevEpochDifficulty = _difficulty;\n }\n\n function getCurrentEpochDifficulty()\n external\n view\n override\n returns (uint256)\n {\n return currentEpochDifficulty;\n }\n\n function getPrevEpochDifficulty() external view override returns (uint256) {\n return prevEpochDifficulty;\n }\n}\n"
189
+ },
190
+ "contracts/test/BridgeStub.sol": {
191
+ "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.9;\n\nimport \"../bridge/BitcoinTx.sol\";\nimport \"../bridge/Bridge.sol\";\nimport \"../bridge/MovingFunds.sol\";\nimport \"../bridge/Wallets.sol\";\n\ncontract BridgeStub is Bridge {\n function setSweptDeposits(BitcoinTx.UTXO[] calldata utxos) external {\n for (uint256 i = 0; i < utxos.length; i++) {\n uint256 utxoKey = uint256(\n keccak256(\n abi.encodePacked(utxos[i].txHash, utxos[i].txOutputIndex)\n )\n );\n self.deposits[utxoKey].sweptAt = 1641650400;\n }\n }\n\n function setSpentMainUtxos(BitcoinTx.UTXO[] calldata utxos) external {\n for (uint256 i = 0; i < utxos.length; i++) {\n uint256 utxoKey = uint256(\n keccak256(\n abi.encodePacked(utxos[i].txHash, utxos[i].txOutputIndex)\n )\n );\n self.spentMainUTXOs[utxoKey] = true;\n }\n }\n\n function setProcessedMovedFundsSweepRequests(\n BitcoinTx.UTXO[] calldata utxos\n ) external {\n for (uint256 i = 0; i < utxos.length; i++) {\n uint256 utxoKey = uint256(\n keccak256(\n abi.encodePacked(utxos[i].txHash, utxos[i].txOutputIndex)\n )\n );\n self.movedFundsSweepRequests[utxoKey].state = MovingFunds\n .MovedFundsSweepRequestState\n .Processed;\n }\n }\n\n function setActiveWallet(bytes20 activeWalletPubKeyHash) external {\n self.activeWalletPubKeyHash = activeWalletPubKeyHash;\n }\n\n function setWalletMainUtxo(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata utxo\n ) external {\n self.registeredWallets[walletPubKeyHash].mainUtxoHash = keccak256(\n abi.encodePacked(\n utxo.txHash,\n utxo.txOutputIndex,\n utxo.txOutputValue\n )\n );\n }\n\n function setWallet(bytes20 walletPubKeyHash, Wallets.Wallet calldata wallet)\n external\n {\n self.registeredWallets[walletPubKeyHash] = wallet;\n\n if (wallet.state == Wallets.WalletState.Live) {\n self.liveWalletsCount++;\n }\n }\n\n function setDepositDustThreshold(uint64 _depositDustThreshold) external {\n self.depositDustThreshold = _depositDustThreshold;\n }\n\n function setDepositTxMaxFee(uint64 _depositTxMaxFee) external {\n self.depositTxMaxFee = _depositTxMaxFee;\n }\n\n function setRedemptionDustThreshold(uint64 _redemptionDustThreshold)\n external\n {\n self.redemptionDustThreshold = _redemptionDustThreshold;\n }\n\n function setRedemptionTreasuryFeeDivisor(\n uint64 _redemptionTreasuryFeeDivisor\n ) external {\n self.redemptionTreasuryFeeDivisor = _redemptionTreasuryFeeDivisor;\n }\n\n function setMovingFundsTxMaxTotalFee(uint64 _movingFundsTxMaxTotalFee)\n external\n {\n self.movingFundsTxMaxTotalFee = _movingFundsTxMaxTotalFee;\n }\n\n function setPendingMovedFundsSweepRequest(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata utxo\n ) external {\n uint256 requestKey = uint256(\n keccak256(abi.encodePacked(utxo.txHash, utxo.txOutputIndex))\n );\n\n self.movedFundsSweepRequests[requestKey] = MovingFunds\n .MovedFundsSweepRequest(\n walletPubKeyHash,\n utxo.txOutputValue,\n /* solhint-disable-next-line not-rely-on-time */\n uint32(block.timestamp),\n MovingFunds.MovedFundsSweepRequestState.Pending\n );\n\n self\n .registeredWallets[walletPubKeyHash]\n .pendingMovedFundsSweepRequestsCount++;\n }\n\n function processPendingMovedFundsSweepRequest(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata utxo\n ) external {\n uint256 requestKey = uint256(\n keccak256(abi.encodePacked(utxo.txHash, utxo.txOutputIndex))\n );\n\n MovingFunds.MovedFundsSweepRequest storage request = self\n .movedFundsSweepRequests[requestKey];\n\n require(\n request.state == MovingFunds.MovedFundsSweepRequestState.Pending,\n \"Stub sweep request must be in Pending state\"\n );\n\n request.state = MovingFunds.MovedFundsSweepRequestState.Processed;\n\n self\n .registeredWallets[walletPubKeyHash]\n .pendingMovedFundsSweepRequestsCount--;\n }\n\n function timeoutPendingMovedFundsSweepRequest(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata utxo\n ) external {\n uint256 requestKey = uint256(\n keccak256(abi.encodePacked(utxo.txHash, utxo.txOutputIndex))\n );\n\n MovingFunds.MovedFundsSweepRequest storage request = self\n .movedFundsSweepRequests[requestKey];\n\n require(\n request.state == MovingFunds.MovedFundsSweepRequestState.Pending,\n \"Stub sweep request must be in Pending state\"\n );\n\n request.state = MovingFunds.MovedFundsSweepRequestState.TimedOut;\n\n self\n .registeredWallets[walletPubKeyHash]\n .pendingMovedFundsSweepRequestsCount--;\n }\n\n function setMovedFundsSweepTxMaxTotalFee(\n uint64 _movedFundsSweepTxMaxTotalFee\n ) external {\n self.movedFundsSweepTxMaxTotalFee = _movedFundsSweepTxMaxTotalFee;\n }\n}\n"
192
+ },
193
+ "contracts/test/HeartbeatStub.sol": {
194
+ "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.9;\n\nimport \"../bridge/Heartbeat.sol\";\n\n/// @dev This is a contract implemented to test Heartbeat library directly.\ncontract HeartbeatStub {\n function isValidHeartbeatMessage(bytes calldata message)\n public\n pure\n returns (bool)\n {\n return Heartbeat.isValidHeartbeatMessage(message);\n }\n}\n"
195
+ },
196
+ "contracts/test/TestEcdsaLib.sol": {
197
+ "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.9;\n\nimport \"../bridge/EcdsaLib.sol\";\n\n// TODO: Rename to EcdsLibStub\n/// @dev This is a contract implemented to test EcdsaLib library directly.\ncontract TestEcdsaLib {\n function compressPublicKey(bytes32 x, bytes32 y)\n public\n pure\n returns (bytes memory)\n {\n return EcdsaLib.compressPublicKey(x, y);\n }\n}\n"
198
+ },
199
+ "@keep-network/ecdsa/contracts/libraries/EcdsaInactivity.sol": {
200
+ "content": "// SPDX-License-Identifier: MIT\n//\n// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄\n// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓\n// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓\n// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀\n// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌\n// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓\n//\n// Trust math, not hardware.\n\npragma solidity ^0.8.9;\n\nimport \"@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol\";\n\nimport \"@keep-network/random-beacon/contracts/libraries/BytesLib.sol\";\nimport \"@keep-network/sortition-pools/contracts/SortitionPool.sol\";\n\nimport \"./Wallets.sol\";\n\nlibrary EcdsaInactivity {\n using BytesLib for bytes;\n using ECDSAUpgradeable for bytes32;\n\n struct Claim {\n // ID of the wallet whose signing group is raising the inactivity claim.\n bytes32 walletID;\n // Indices of group members accused of being inactive. Indices must be in\n // range [1, groupMembers.length], unique, and sorted in ascending order.\n uint256[] inactiveMembersIndices;\n // Indicates if inactivity claim is a wallet-wide heartbeat failure.\n // If wallet failed a heartbeat, this is signalled to the wallet owner\n // who may decide to move responsibilities to another wallet\n // given that the wallet who failed the heartbeat is at risk of not\n // being able to sign messages soon.\n bool heartbeatFailed;\n // Concatenation of signatures from members supporting the claim.\n // The message to be signed by each member is keccak256 hash of the\n // concatenation of inactivity claim nonce for the given wallet, wallet\n // public key, inactive members indices, and boolean flag indicating\n // if this is a wallet-wide heartbeat failure. The calculated hash should\n // be prefixed with `\\x19Ethereum signed message:\\n` before signing, so\n // the message to sign is:\n // `\\x19Ethereum signed message:\\n${keccak256(\n // nonce | walletPubKey | inactiveMembersIndices | heartbeatFailed\n // )}`\n bytes signatures;\n // Indices of members corresponding to each signature. Indices must be\n // in range [1, groupMembers.length], unique, and sorted in ascending\n // order.\n uint256[] signingMembersIndices;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's calldata argument.\n }\n\n /// @notice The minimum number of wallet signing group members needed to\n /// interact according to the protocol to produce a valid inactivity\n /// claim.\n uint256 public constant groupThreshold = 51;\n\n /// @notice Size in bytes of a single signature produced by member\n /// supporting the inactivity claim.\n uint256 public constant signatureByteSize = 65;\n\n /// @notice Verifies the inactivity claim according to the rules defined in\n /// `Claim` struct documentation. Reverts if verification fails.\n /// @dev Wallet signing group members hash is validated upstream in\n /// `WalletRegistry.notifyOperatorInactivity()`\n /// @param sortitionPool Sortition pool reference\n /// @param claim Inactivity claim\n /// @param walletPubKey Public key of the wallet\n /// @param nonce Current inactivity nonce for wallet used in the claim\n /// @param groupMembers Identifiers of group members\n /// @return inactiveMembers Identifiers of members who are inactive\n function verifyClaim(\n SortitionPool sortitionPool,\n Claim calldata claim,\n bytes memory walletPubKey,\n uint256 nonce,\n uint32[] calldata groupMembers\n ) external view returns (uint32[] memory inactiveMembers) {\n // Validate inactive members indices. Maximum indices count is equal to\n // the group size and is not limited deliberately to leave a theoretical\n // possibility to accuse more members than `groupSize - groupThreshold`.\n validateMembersIndices(\n claim.inactiveMembersIndices,\n groupMembers.length\n );\n\n // Validate signatures array is properly formed and number of\n // signatures and signers is correct.\n uint256 signaturesCount = claim.signatures.length / signatureByteSize;\n require(claim.signatures.length != 0, \"No signatures provided\");\n require(\n claim.signatures.length % signatureByteSize == 0,\n \"Malformed signatures array\"\n );\n require(\n signaturesCount == claim.signingMembersIndices.length,\n \"Unexpected signatures count\"\n );\n require(signaturesCount >= groupThreshold, \"Too few signatures\");\n require(signaturesCount <= groupMembers.length, \"Too many signatures\");\n\n // Validate signing members indices. Note that `signingMembersIndices`\n // were already partially validated during `signatures` parameter\n // validation.\n validateMembersIndices(\n claim.signingMembersIndices,\n groupMembers.length\n );\n\n bytes32 signedMessageHash = keccak256(\n abi.encodePacked(\n nonce,\n walletPubKey,\n claim.inactiveMembersIndices,\n claim.heartbeatFailed\n )\n ).toEthSignedMessageHash();\n\n address[] memory groupMembersAddresses = sortitionPool.getIDOperators(\n groupMembers\n );\n\n // Verify each signature.\n bytes memory checkedSignature;\n bool senderSignatureExists = false;\n for (uint256 i = 0; i < signaturesCount; i++) {\n uint256 memberIndex = claim.signingMembersIndices[i];\n checkedSignature = claim.signatures.slice(\n signatureByteSize * i,\n signatureByteSize\n );\n address recoveredAddress = signedMessageHash.recover(\n checkedSignature\n );\n\n require(\n groupMembersAddresses[memberIndex - 1] == recoveredAddress,\n \"Invalid signature\"\n );\n\n if (!senderSignatureExists && msg.sender == recoveredAddress) {\n senderSignatureExists = true;\n }\n }\n\n require(senderSignatureExists, \"Sender must be claim signer\");\n\n inactiveMembers = new uint32[](claim.inactiveMembersIndices.length);\n for (uint256 i = 0; i < claim.inactiveMembersIndices.length; i++) {\n uint256 memberIndex = claim.inactiveMembersIndices[i];\n inactiveMembers[i] = groupMembers[memberIndex - 1];\n }\n\n return inactiveMembers;\n }\n\n /// @notice Validates members indices array. Array is considered valid\n /// if its size and each single index are in [1, groupSize] range,\n /// indexes are unique, and sorted in an ascending order.\n /// Reverts if validation fails.\n /// @param indices Array to validate.\n /// @param groupSize Group size used as reference.\n function validateMembersIndices(\n uint256[] calldata indices,\n uint256 groupSize\n ) internal view {\n require(\n indices.length > 0 && indices.length <= groupSize,\n \"Corrupted members indices\"\n );\n\n // Check if first and last indices are in range [1, groupSize].\n // This check combined with the loop below makes sure every single\n // index is in the correct range.\n require(\n indices[0] > 0 && indices[indices.length - 1] <= groupSize,\n \"Corrupted members indices\"\n );\n\n for (uint256 i = 0; i < indices.length - 1; i++) {\n // Check whether given index is smaller than the next one. This\n // way we are sure indexes are ordered in the ascending order\n // and there are no duplicates.\n require(indices[i] < indices[i + 1], \"Corrupted members indices\");\n }\n }\n}\n"
201
+ },
202
+ "@keep-network/ecdsa/contracts/libraries/Wallets.sol": {
203
+ "content": "// SPDX-License-Identifier: MIT\n//\n// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄\n// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓\n// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓\n// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀\n// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌\n// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓\n//\n// Trust math, not hardware.\n\npragma solidity ^0.8.9;\n\nlibrary Wallets {\n struct Wallet {\n // Keccak256 hash of group members identifiers array. Group members do not\n // include operators selected by the sortition pool that misbehaved during DKG.\n bytes32 membersIdsHash;\n // Uncompressed ECDSA public key stored as X and Y coordinates (32 bytes each).\n bytes32 publicKeyX;\n bytes32 publicKeyY;\n // This struct doesn't contain `__gap` property as the structure is stored\n // in a mapping, mappings store values in different slots and they are\n // not contiguous with other values.\n }\n\n struct Data {\n // Mapping of keccak256 hashes of wallet public keys to wallet details.\n // Hash of public key is considered an unique wallet identifier.\n mapping(bytes32 => Wallet) registry;\n // Reserved storage space in case we need to add more variables.\n // See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n // slither-disable-next-line unused-state\n uint256[49] __gap;\n }\n\n /// @notice Registers a new wallet.\n /// @dev Uses a public key hash as a unique identifier of a wallet.\n /// @param membersIdsHash Keccak256 hash of group members identifiers array\n /// @param publicKey Uncompressed public key\n /// @return walletID Wallet's ID\n /// @return publicKeyX Wallet's public key's X coordinate\n /// @return publicKeyY Wallet's public key's Y coordinate\n function addWallet(\n Data storage self,\n bytes32 membersIdsHash,\n bytes calldata publicKey\n )\n internal\n returns (\n bytes32 walletID,\n bytes32 publicKeyX,\n bytes32 publicKeyY\n )\n {\n walletID = keccak256(publicKey);\n\n require(\n self.registry[walletID].publicKeyX == bytes32(0),\n \"Wallet with the given public key already exists\"\n );\n require(publicKey.length == 64, \"Invalid length of the public key\");\n\n publicKeyX = bytes32(publicKey[:32]);\n publicKeyY = bytes32(publicKey[32:]);\n\n self.registry[walletID].membersIdsHash = membersIdsHash;\n self.registry[walletID].publicKeyX = publicKeyX;\n self.registry[walletID].publicKeyY = publicKeyY;\n }\n\n /// @notice Deletes wallet with the given ID from the registry. Reverts\n /// if wallet with the given ID has not been registered or if it\n /// has already been closed.\n function deleteWallet(Data storage self, bytes32 walletID) internal {\n require(\n isWalletRegistered(self, walletID),\n \"Wallet with the given ID has not been registered\"\n );\n\n delete self.registry[walletID];\n }\n\n /// @notice Checks if a wallet with the given ID is registered.\n /// @param walletID Wallet's ID\n /// @return True if a wallet is registered, false otherwise\n function isWalletRegistered(Data storage self, bytes32 walletID)\n internal\n view\n returns (bool)\n {\n return self.registry[walletID].publicKeyX != bytes32(0);\n }\n\n /// @notice Returns Keccak256 hash of the wallet signing group members\n /// identifiers array. Group members do not include operators\n /// selected by the sortition pool that misbehaved during DKG.\n /// Reverts if wallet with the given ID is not registered.\n /// @param walletID ID of the wallet\n /// @return Wallet signing group members hash\n function getWalletMembersIdsHash(Data storage self, bytes32 walletID)\n internal\n view\n returns (bytes32)\n {\n require(\n isWalletRegistered(self, walletID),\n \"Wallet with the given ID has not been registered\"\n );\n\n return self.registry[walletID].membersIdsHash;\n }\n\n /// @notice Gets public key of a wallet with the given wallet ID.\n /// The public key is returned as X and Y coordinates.\n /// Reverts if wallet with the given ID is not registered.\n /// @param walletID ID of the wallet\n /// @return x Public key X coordinate\n /// @return y Public key Y coordinate\n function getWalletPublicKeyCoordinates(Data storage self, bytes32 walletID)\n internal\n view\n returns (bytes32 x, bytes32 y)\n {\n require(\n isWalletRegistered(self, walletID),\n \"Wallet with the given ID has not been registered\"\n );\n\n Wallet storage wallet = self.registry[walletID];\n\n return (wallet.publicKeyX, wallet.publicKeyY);\n }\n\n /// @notice Gets public key of a wallet with the given wallet ID.\n /// The public key is returned in an uncompressed format as a 64-byte\n /// concatenation of X and Y coordinates.\n /// Reverts if wallet with the given ID is not registered.\n /// @param walletID ID of the wallet\n /// @return Uncompressed public key of the wallet\n function getWalletPublicKey(Data storage self, bytes32 walletID)\n internal\n view\n returns (bytes memory)\n {\n (bytes32 x, bytes32 y) = getWalletPublicKeyCoordinates(self, walletID);\n return bytes.concat(x, y);\n }\n}\n"
204
+ },
205
+ "@keep-network/ecdsa/contracts/libraries/EcdsaAuthorization.sol": {
206
+ "content": "// SPDX-License-Identifier: MIT\n//\n// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄\n// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓\n// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓\n// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀\n// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌\n// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓\n//\n//\n\npragma solidity ^0.8.9;\n\nimport \"@keep-network/sortition-pools/contracts/SortitionPool.sol\";\nimport \"@threshold-network/solidity-contracts/contracts/staking/IStaking.sol\";\n\n/// @notice Library managing the state of stake authorizations for ECDSA\n/// operator contract and the presence of operators in the sortition\n/// pool based on the stake authorized for them.\nlibrary EcdsaAuthorization {\n struct Parameters {\n // The minimum authorization required by ECDSA application so that\n // operator can join the sortition pool and do the work.\n uint96 minimumAuthorization;\n // Authorization decrease delay in seconds between the time\n // authorization decrease is requested and the time the authorization\n // decrease can be approved. It is always the same value, no matter if\n // authorization decrease amount is small, significant, or if it is\n // a decrease to zero.\n uint64 authorizationDecreaseDelay;\n // The time period before the authorization decrease delay end,\n // during which the authorization decrease request can be overwritten.\n //\n // When the request is overwritten, the authorization decrease delay is\n // reset.\n //\n // For example, if `authorizationDecraseChangePeriod` is set to 4\n // days, `authorizationDecreaseDelay` is set to 14 days, and someone\n // requested authorization decrease, it means they can not\n // request another decrease for the first 10 days. After 10 days pass,\n // they can request again and overwrite the previous authorization\n // decrease request. The delay time will reset for them and they\n // will have to wait another 10 days to alter it and 14 days to\n // approve it.\n //\n // This value protects against malicious operators who manipulate\n // their weight by overwriting authorization decrease request, and\n // lowering or increasing their eligible stake this way.\n //\n // If set to a value equal to `authorizationDecreaseDelay, it means\n // that authorization decrease request can be always overwritten.\n // If set to zero, it means authorization decrease request can not be\n // overwritten until the delay end, and one needs to wait for the entire\n // authorization decrease delay to approve their decrease and request\n // for another one or to overwrite the pending one.\n //\n // (1) authorization decrease requested timestamp\n // (2) from this moment authorization decrease request can be\n // overwritten\n // (3) from this moment authorization decrease request can be\n // approved, assuming it was NOT overwritten in (2)\n //\n // (1) (2) (3)\n // --x------------------------------x--------------------------x---->\n // | \\________________________/\n // | authorizationDecreaseChangePeriod\n // \\______________________________________________________/\n // authorizationDecreaseDelay\n //\n uint64 authorizationDecreaseChangePeriod;\n // This struct doesn't contain `__gap` property as the structure is\n // stored inside `Data` struct, that already have a gap that can be used\n // on upgrade.\n }\n\n struct AuthorizationDecrease {\n uint96 decreasingBy; // amount\n uint64 decreasingAt; // timestamp\n }\n\n struct Data {\n Parameters parameters;\n mapping(address => address) stakingProviderToOperator;\n mapping(address => address) operatorToStakingProvider;\n mapping(address => AuthorizationDecrease) pendingDecreases;\n // Reserved storage space in case we need to add more variables.\n // See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n // slither-disable-next-line unused-state\n uint256[46] __gap;\n }\n\n event OperatorRegistered(\n address indexed stakingProvider,\n address indexed operator\n );\n\n event AuthorizationIncreased(\n address indexed stakingProvider,\n address indexed operator,\n uint96 fromAmount,\n uint96 toAmount\n );\n\n event AuthorizationDecreaseRequested(\n address indexed stakingProvider,\n address indexed operator,\n uint96 fromAmount,\n uint96 toAmount,\n uint64 decreasingAt\n );\n\n event AuthorizationDecreaseApproved(address indexed stakingProvider);\n\n event InvoluntaryAuthorizationDecreaseFailed(\n address indexed stakingProvider,\n address indexed operator,\n uint96 fromAmount,\n uint96 toAmount\n );\n\n event OperatorJoinedSortitionPool(\n address indexed stakingProvider,\n address indexed operator\n );\n\n event OperatorStatusUpdated(\n address indexed stakingProvider,\n address indexed operator\n );\n\n /// @notice Sets the minimum authorization for ECDSA application. Without\n /// at least the minimum authorization, staking provider is not\n /// eligible to join and operate in the network.\n function setMinimumAuthorization(\n Data storage self,\n uint96 _minimumAuthorization\n ) internal {\n self.parameters.minimumAuthorization = _minimumAuthorization;\n }\n\n /// @notice Sets the authorization decrease delay. It is the time in seconds\n /// that needs to pass between the time authorization decrease is\n /// requested and the time the authorization decrease can be\n /// approved, no matter the authorization decrease amount.\n function setAuthorizationDecreaseDelay(\n Data storage self,\n uint64 _authorizationDecreaseDelay\n ) internal {\n self\n .parameters\n .authorizationDecreaseDelay = _authorizationDecreaseDelay;\n }\n\n /// @notice Sets the authorization decrease change period. It is the time\n /// period before the authorization decrease delay end,\n /// during which the authorization decrease request can be\n /// overwritten.\n function setAuthorizationDecreaseChangePeriod(\n Data storage self,\n uint64 _authorizationDecreaseChangePeriod\n ) internal {\n self\n .parameters\n .authorizationDecreaseChangePeriod = _authorizationDecreaseChangePeriod;\n }\n\n /// @notice Used by staking provider to set operator address that will\n /// operate ECDSA node. The given staking provider can set operator\n /// address only one time. The operator address can not be changed\n /// and must be unique. Reverts if the operator is already set for\n /// the staking provider or if the operator address is already in\n /// use. Reverts if there is a pending authorization decrease for\n /// the staking provider.\n function registerOperator(Data storage self, address operator) internal {\n address stakingProvider = msg.sender;\n\n require(operator != address(0), \"Operator can not be zero address\");\n require(\n self.stakingProviderToOperator[stakingProvider] == address(0),\n \"Operator already set for the staking provider\"\n );\n require(\n self.operatorToStakingProvider[operator] == address(0),\n \"Operator address already in use\"\n );\n\n // Authorization request for a staking provider who has not yet\n // registered their operator can be approved immediately.\n // We need to make sure that the approval happens before operator\n // is registered to do not let the operator join the sortition pool\n // with an unresolved authorization decrease request that can be\n // approved at any point.\n AuthorizationDecrease storage decrease = self.pendingDecreases[\n stakingProvider\n ];\n require(\n decrease.decreasingAt == 0,\n \"There is a pending authorization decrease request\"\n );\n\n emit OperatorRegistered(stakingProvider, operator);\n\n self.stakingProviderToOperator[stakingProvider] = operator;\n self.operatorToStakingProvider[operator] = stakingProvider;\n }\n\n /// @notice Used by T staking contract to inform the application that the\n /// authorized stake amount for the given staking provider increased.\n ///\n /// Reverts if the authorization amount is below the minimum.\n ///\n /// The function is not updating the sortition pool. Sortition pool\n /// state needs to be updated by the operator with a call to\n /// `joinSortitionPool` or `updateOperatorStatus`.\n ///\n /// @dev Should only be callable by T staking contract.\n function authorizationIncreased(\n Data storage self,\n address stakingProvider,\n uint96 fromAmount,\n uint96 toAmount\n ) internal {\n require(\n toAmount >= self.parameters.minimumAuthorization,\n \"Authorization below the minimum\"\n );\n\n // Note that this function does not require the operator address to be\n // set for the given staking provider. This allows the stake owner\n // who is also an authorizer to increase the authorization before the\n // staking provider sets the operator. This allows delegating stake\n // and increasing authorization immediately one after another without\n // having to wait for the staking provider to do their part.\n\n address operator = self.stakingProviderToOperator[stakingProvider];\n emit AuthorizationIncreased(\n stakingProvider,\n operator,\n fromAmount,\n toAmount\n );\n }\n\n /// @notice Used by T staking contract to inform the application that the\n /// authorization decrease for the given staking provider has been\n /// requested.\n ///\n /// Reverts if the amount after deauthorization would be non-zero\n /// and lower than the minimum authorization.\n ///\n /// Reverts if another authorization decrease request is pending for\n /// the staking provider and not enough time passed since the\n /// original request (see `authorizationDecreaseChangePeriod`).\n ///\n /// If the operator is not known (`registerOperator` was not called)\n /// it lets to `approveAuthorizationDecrease` immediately. If the\n /// operator is known (`registerOperator` was called), the operator\n /// needs to update state of the sortition pool with a call to\n /// `joinSortitionPool` or `updateOperatorStatus`. After the\n /// sortition pool state is in sync, authorization decrease delay\n /// starts.\n ///\n /// After authorization decrease delay passes, authorization\n /// decrease request needs to be approved with a call to\n /// `approveAuthorizationDecrease` function.\n ///\n /// If there is a pending authorization decrease request, it is\n /// overwritten, but only if enough time passed since the original\n /// request. Otherwise, the function reverts.\n ///\n /// @dev Should only be callable by T staking contract.\n function authorizationDecreaseRequested(\n Data storage self,\n address stakingProvider,\n uint96 fromAmount,\n uint96 toAmount\n ) internal {\n require(\n toAmount == 0 || toAmount >= self.parameters.minimumAuthorization,\n \"Authorization amount should be 0 or above the minimum\"\n );\n\n address operator = self.stakingProviderToOperator[stakingProvider];\n\n uint64 decreasingAt;\n\n if (operator == address(0)) {\n // Operator is not known. It means `registerOperator` was not\n // called yet, and there is no chance the operator could\n // call `joinSortitionPool`. We can let to approve authorization\n // decrease immediately because that operator was never in the\n // sortition pool.\n\n // solhint-disable-next-line not-rely-on-time\n decreasingAt = uint64(block.timestamp);\n } else {\n // Operator is known. It means that this operator is or was in\n // the sortition pool. Before authorization decrease delay starts,\n // the operator needs to update the state of the sortition pool\n // with a call to `joinSortitionPool` or `updateOperatorStatus`.\n // For now, we set `decreasingAt` as \"never decreasing\" and let\n // it be updated by `joinSortitionPool` or `updateOperatorStatus`\n // once we know the sortition pool is in sync.\n decreasingAt = type(uint64).max;\n }\n\n uint96 decreasingBy = fromAmount - toAmount;\n\n AuthorizationDecrease storage decreaseRequest = self.pendingDecreases[\n stakingProvider\n ];\n\n uint64 pendingDecreaseAt = decreaseRequest.decreasingAt;\n if (pendingDecreaseAt != 0 && pendingDecreaseAt != type(uint64).max) {\n // If there is already a pending authorization decrease request for\n // this staking provider and that request has been activated\n // (sortition pool was updated), require enough time to pass before\n // it can be overwritten.\n require(\n // solhint-disable-next-line not-rely-on-time\n block.timestamp >=\n pendingDecreaseAt -\n self.parameters.authorizationDecreaseChangePeriod,\n \"Not enough time passed since the original request\"\n );\n }\n\n decreaseRequest.decreasingBy = decreasingBy;\n decreaseRequest.decreasingAt = decreasingAt;\n\n emit AuthorizationDecreaseRequested(\n stakingProvider,\n operator,\n fromAmount,\n toAmount,\n decreasingAt\n );\n }\n\n /// @notice Approves the previously registered authorization decrease\n /// request. Reverts if authorization decrease delay have not passed\n /// yet or if the authorization decrease was not requested for the\n /// given staking provider.\n function approveAuthorizationDecrease(\n Data storage self,\n IStaking tokenStaking,\n address stakingProvider\n ) internal {\n AuthorizationDecrease storage decrease = self.pendingDecreases[\n stakingProvider\n ];\n require(\n decrease.decreasingAt > 0,\n \"Authorization decrease not requested\"\n );\n require(\n decrease.decreasingAt != type(uint64).max,\n \"Authorization decrease request not activated\"\n );\n require(\n // solhint-disable-next-line not-rely-on-time\n block.timestamp >= decrease.decreasingAt,\n \"Authorization decrease delay not passed\"\n );\n\n emit AuthorizationDecreaseApproved(stakingProvider);\n\n // slither-disable-next-line unused-return\n tokenStaking.approveAuthorizationDecrease(stakingProvider);\n delete self.pendingDecreases[stakingProvider];\n }\n\n /// @notice Used by T staking contract to inform the application the\n /// authorization has been decreased for the given staking provider\n /// involuntarily, as a result of slashing.\n ///\n /// If the operator is not known (`registerOperator` was not called)\n /// the function does nothing. The operator was never in a sortition\n /// pool so there is nothing to update.\n ///\n /// If the operator is known, sortition pool is unlocked, and the\n /// operator is in the sortition pool, the sortition pool state is\n /// updated. If the sortition pool is locked, update needs to be\n /// postponed. Every other staker is incentivized to call\n /// `updateOperatorStatus` for the problematic operator to increase\n /// their own rewards in the pool.\n ///\n /// @dev Should only be callable by T staking contract.\n function involuntaryAuthorizationDecrease(\n Data storage self,\n IStaking tokenStaking,\n SortitionPool sortitionPool,\n address stakingProvider,\n uint96 fromAmount,\n uint96 toAmount\n ) internal {\n address operator = self.stakingProviderToOperator[stakingProvider];\n\n if (operator == address(0)) {\n // Operator is not known. It means `registerOperator` was not\n // called yet, and there is no chance the operator could\n // call `joinSortitionPool`. We can just ignore this update because\n // operator was never in the sortition pool.\n return;\n } else {\n // Operator is known. It means that this operator is or was in the\n // sortition pool and the sortition pool may need to be updated.\n //\n // If the sortition pool is not locked and the operator is in the\n // sortition pool, we are updating it.\n //\n // To keep stakes synchronized between applications when staking\n // providers are slashed, without the risk of running out of gas,\n // the staking contract queues up slashings and let users process\n // the transactions. When an application slashes one or more staking\n // providers, it adds them to the slashing queue on the staking\n // contract. A queue entry contains the staking provider’s address\n // and the amount they are due to be slashed.\n //\n // When there is at least one staking provider in the slashing\n // queue, any account can submit a transaction processing one or\n // more staking providers' slashings, and collecting a reward for\n // doing so. A queued slashing is processed by updating the staking\n // provider’s stake to the post-slashing amount, updating authorized\n // amount for each affected application, and notifying all affected\n // applications that the staking provider’s authorized stake has\n // been reduced due to slashing.\n //\n // The entire idea is that the process transaction is expensive\n // because each application needs to be updated, so the reward for\n // the processor is hefty and comes from the slashed tokens.\n // Practically, it means that if the sortition pool is unlocked, and\n // can be updated, it should be updated because we already paid\n // someone for updating it.\n //\n // If the sortition pool is locked, update needs to wait. Other\n // sortition pool members are incentivized to call\n // `updateOperatorStatus` for the problematic operator because they\n // will increase their rewards this way.\n if (sortitionPool.isOperatorInPool(operator)) {\n if (sortitionPool.isLocked()) {\n emit InvoluntaryAuthorizationDecreaseFailed(\n stakingProvider,\n operator,\n fromAmount,\n toAmount\n );\n } else {\n updateOperatorStatus(\n self,\n tokenStaking,\n sortitionPool,\n operator\n );\n }\n }\n }\n }\n\n /// @notice Lets the operator join the sortition pool. The operator address\n /// must be known - before calling this function, it has to be\n /// appointed by the staking provider by calling `registerOperator`.\n /// Also, the operator must have the minimum authorization required\n /// by ECDSA. Function reverts if there is no minimum stake\n /// authorized or if the operator is not known. If there was an\n /// authorization decrease requested, it is activated by starting\n /// the authorization decrease delay.\n function joinSortitionPool(\n Data storage self,\n IStaking tokenStaking,\n SortitionPool sortitionPool\n ) internal {\n address operator = msg.sender;\n\n address stakingProvider = self.operatorToStakingProvider[operator];\n require(stakingProvider != address(0), \"Unknown operator\");\n\n AuthorizationDecrease storage decrease = self.pendingDecreases[\n stakingProvider\n ];\n\n uint96 _eligibleStake = eligibleStake(\n self,\n tokenStaking,\n stakingProvider,\n decrease.decreasingBy\n );\n\n require(_eligibleStake != 0, \"Authorization below the minimum\");\n\n emit OperatorJoinedSortitionPool(stakingProvider, operator);\n\n sortitionPool.insertOperator(operator, _eligibleStake);\n\n // If there is a pending authorization decrease request, activate it.\n // At this point, the sortition pool state is up to date so the\n // authorization decrease delay can start counting.\n if (decrease.decreasingAt == type(uint64).max) {\n decrease.decreasingAt =\n // solhint-disable-next-line not-rely-on-time\n uint64(block.timestamp) +\n self.parameters.authorizationDecreaseDelay;\n }\n }\n\n /// @notice Updates status of the operator in the sortition pool. If there\n /// was an authorization decrease requested, it is activated by\n /// starting the authorization decrease delay.\n /// Function reverts if the operator is not known.\n function updateOperatorStatus(\n Data storage self,\n IStaking tokenStaking,\n SortitionPool sortitionPool,\n address operator\n ) internal {\n address stakingProvider = self.operatorToStakingProvider[operator];\n require(stakingProvider != address(0), \"Unknown operator\");\n\n AuthorizationDecrease storage decrease = self.pendingDecreases[\n stakingProvider\n ];\n\n emit OperatorStatusUpdated(stakingProvider, operator);\n\n if (sortitionPool.isOperatorInPool(operator)) {\n uint96 _eligibleStake = eligibleStake(\n self,\n tokenStaking,\n stakingProvider,\n decrease.decreasingBy\n );\n\n sortitionPool.updateOperatorStatus(operator, _eligibleStake);\n }\n\n // If there is a pending authorization decrease request, activate it.\n // At this point, the sortition pool state is up to date so the\n // authorization decrease delay can start counting.\n if (decrease.decreasingAt == type(uint64).max) {\n decrease.decreasingAt =\n // solhint-disable-next-line not-rely-on-time\n uint64(block.timestamp) +\n self.parameters.authorizationDecreaseDelay;\n }\n }\n\n /// @notice Checks if the operator's authorized stake is in sync with\n /// operator's weight in the sortition pool.\n /// If the operator is not in the sortition pool and their\n /// authorized stake is non-zero, function returns false.\n function isOperatorUpToDate(\n Data storage self,\n IStaking tokenStaking,\n SortitionPool sortitionPool,\n address operator\n ) internal view returns (bool) {\n address stakingProvider = self.operatorToStakingProvider[operator];\n require(stakingProvider != address(0), \"Unknown operator\");\n\n AuthorizationDecrease storage decrease = self.pendingDecreases[\n stakingProvider\n ];\n\n uint96 _eligibleStake = eligibleStake(\n self,\n tokenStaking,\n stakingProvider,\n decrease.decreasingBy\n );\n\n if (!sortitionPool.isOperatorInPool(operator)) {\n return _eligibleStake == 0;\n } else {\n return sortitionPool.isOperatorUpToDate(operator, _eligibleStake);\n }\n }\n\n /// @notice Returns the current value of the staking provider's eligible\n /// stake. Eligible stake is defined as the currently authorized\n /// stake minus the pending authorization decrease. Eligible stake\n /// is what is used for operator's weight in the pool. If the\n /// authorized stake minus the pending authorization decrease is\n /// below the minimum authorization, eligible stake is 0.\n /// @dev This function can be exposed to the public in contrast to the\n /// second variant accepting `decreasingBy` as a parameter.\n function eligibleStake(\n Data storage self,\n IStaking tokenStaking,\n address stakingProvider\n ) internal view returns (uint96) {\n return\n eligibleStake(\n self,\n tokenStaking,\n stakingProvider,\n pendingAuthorizationDecrease(self, stakingProvider)\n );\n }\n\n /// @notice Returns the current value of the staking provider's eligible\n /// stake. Eligible stake is defined as the currently authorized\n /// stake minus the pending authorization decrease. Eligible stake\n /// is what is used for operator's weight in the pool. If the\n /// authorized stake minus the pending authorization decrease is\n /// below the minimum authorization, eligible stake is 0.\n /// @dev This function is not intended to be exposes to the public.\n /// `decreasingBy` must be fetched from `pendingDecreases` mapping and\n /// it is passed as a parameter to optimize gas usage of functions that\n /// call `eligibleStake` and need to use `AuthorizationDecrease`\n /// fetched from `pendingDecreases` for some additional logic.\n function eligibleStake(\n Data storage self,\n IStaking tokenStaking,\n address stakingProvider,\n uint96 decreasingBy\n ) internal view returns (uint96) {\n uint96 authorizedStake = tokenStaking.authorizedStake(\n stakingProvider,\n address(this)\n );\n\n uint96 _eligibleStake = authorizedStake > decreasingBy\n ? authorizedStake - decreasingBy\n : 0;\n\n if (_eligibleStake < self.parameters.minimumAuthorization) {\n return 0;\n } else {\n return _eligibleStake;\n }\n }\n\n /// @notice Returns the amount of stake that is pending authorization\n /// decrease for the given staking provider. If no authorization\n /// decrease has been requested, returns zero.\n function pendingAuthorizationDecrease(\n Data storage self,\n address stakingProvider\n ) internal view returns (uint96) {\n AuthorizationDecrease storage decrease = self.pendingDecreases[\n stakingProvider\n ];\n\n return decrease.decreasingBy;\n }\n\n /// @notice Returns the remaining time in seconds that needs to pass before\n /// the requested authorization decrease can be approved.\n /// If the sortition pool state was not updated yet by the operator\n /// after requesting the authorization decrease, returns\n /// `type(uint64).max`.\n function remainingAuthorizationDecreaseDelay(\n Data storage self,\n address stakingProvider\n ) internal view returns (uint64) {\n AuthorizationDecrease storage decrease = self.pendingDecreases[\n stakingProvider\n ];\n\n if (decrease.decreasingAt == type(uint64).max) {\n return type(uint64).max;\n }\n\n // solhint-disable-next-line not-rely-on-time\n uint64 _now = uint64(block.timestamp);\n return _now > decrease.decreasingAt ? 0 : decrease.decreasingAt - _now;\n }\n}\n"
207
+ },
208
+ "@threshold-network/solidity-contracts/contracts/staking/IStaking.sol": {
209
+ "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity 0.8.9;\n\n/// @title Interface of Threshold Network staking contract\n/// @notice The staking contract enables T owners to have their wallets offline\n/// and their stake managed by staking providers on their behalf.\n/// The staking contract does not define operator role. The operator\n/// responsible for running off-chain client software is appointed by\n/// the staking provider in the particular application utilizing the\n/// staking contract. All off-chain client software should be able\n/// to run without exposing operator's or staking provider’s private\n/// key and should not require any owner’s keys at all. The stake\n/// delegation optimizes the network throughput without compromising the\n/// security of the owners’ stake.\ninterface IStaking {\n enum StakeType {\n NU,\n KEEP,\n T\n }\n\n //\n //\n // Delegating a stake\n //\n //\n\n /// @notice Creates a delegation with `msg.sender` owner with the given\n /// staking provider, beneficiary, and authorizer. Transfers the\n /// given amount of T to the staking contract.\n /// @dev The owner of the delegation needs to have the amount approved to\n /// transfer to the staking contract.\n function stake(\n address stakingProvider,\n address payable beneficiary,\n address authorizer,\n uint96 amount\n ) external;\n\n /// @notice Copies delegation from the legacy KEEP staking contract to T\n /// staking contract. No tokens are transferred. Caches the active\n /// stake amount from KEEP staking contract. Can be called by\n /// anyone.\n /// @dev The staking provider in T staking contract is the legacy KEEP\n /// staking contract operator.\n function stakeKeep(address stakingProvider) external;\n\n /// @notice Copies delegation from the legacy NU staking contract to T\n /// staking contract, additionally appointing staking provider,\n /// beneficiary and authorizer roles. Caches the amount staked in NU\n /// staking contract. Can be called only by the original delegation\n /// owner.\n function stakeNu(\n address stakingProvider,\n address payable beneficiary,\n address authorizer\n ) external;\n\n /// @notice Refresh Keep stake owner. Can be called only by the old owner.\n /// @dev The staking provider in T staking contract is the legacy KEEP\n /// staking contract operator.\n function refreshKeepStakeOwner(address stakingProvider) external;\n\n /// @notice Allows the Governance to set the minimum required stake amount.\n /// This amount is required to protect against griefing the staking\n /// contract and individual applications are allowed to require\n /// higher minimum stakes if necessary.\n function setMinimumStakeAmount(uint96 amount) external;\n\n //\n //\n // Authorizing an application\n //\n //\n\n /// @notice Allows the Governance to approve the particular application\n /// before individual stake authorizers are able to authorize it.\n function approveApplication(address application) external;\n\n /// @notice Increases the authorization of the given staking provider for\n /// the given application by the given amount. Can only be called by\n /// the authorizer for that staking provider.\n /// @dev Calls `authorizationIncreased(address stakingProvider, uint256 amount)`\n /// on the given application to notify the application about\n /// authorization change. See `IApplication`.\n function increaseAuthorization(\n address stakingProvider,\n address application,\n uint96 amount\n ) external;\n\n /// @notice Requests decrease of the authorization for the given staking\n /// provider on the given application by the provided amount.\n /// It may not change the authorized amount immediatelly. When\n /// it happens depends on the application. Can only be called by the\n /// given staking provider’s authorizer. Overwrites pending\n /// authorization decrease for the given staking provider and\n /// application.\n /// @dev Calls `authorizationDecreaseRequested(address stakingProvider, uint256 amount)`\n /// on the given application. See `IApplication`.\n function requestAuthorizationDecrease(\n address stakingProvider,\n address application,\n uint96 amount\n ) external;\n\n /// @notice Requests decrease of all authorizations for the given staking\n /// provider on all applications by all authorized amount.\n /// It may not change the authorized amount immediatelly. When\n /// it happens depends on the application. Can only be called by the\n /// given staking provider’s authorizer. Overwrites pending\n /// authorization decrease for the given staking provider and\n /// application.\n /// @dev Calls `authorizationDecreaseRequested(address stakingProvider, uint256 amount)`\n /// for each authorized application. See `IApplication`.\n function requestAuthorizationDecrease(address stakingProvider) external;\n\n /// @notice Called by the application at its discretion to approve the\n /// previously requested authorization decrease request. Can only be\n /// called by the application that was previously requested to\n /// decrease the authorization for that staking provider.\n /// Returns resulting authorized amount for the application.\n function approveAuthorizationDecrease(address stakingProvider)\n external\n returns (uint96);\n\n /// @notice Decreases the authorization for the given `stakingProvider` on\n /// the given disabled `application`, for all authorized amount.\n /// Can be called by anyone.\n function forceDecreaseAuthorization(\n address stakingProvider,\n address application\n ) external;\n\n /// @notice Pauses the given application’s eligibility to slash stakes.\n /// Besides that stakers can't change authorization to the application.\n /// Can be called only by the Panic Button of the particular\n /// application. The paused application can not slash stakes until\n /// it is approved again by the Governance using `approveApplication`\n /// function. Should be used only in case of an emergency.\n function pauseApplication(address application) external;\n\n /// @notice Disables the given application. The disabled application can't\n /// slash stakers. Also stakers can't increase authorization to that\n /// application but can decrease without waiting by calling\n /// `requestAuthorizationDecrease` at any moment. Can be called only\n /// by the governance. The disabled application can't be approved\n /// again. Should be used only in case of an emergency.\n function disableApplication(address application) external;\n\n /// @notice Sets the Panic Button role for the given application to the\n /// provided address. Can only be called by the Governance. If the\n /// Panic Button for the given application should be disabled, the\n /// role address should be set to 0x0 address.\n function setPanicButton(address application, address panicButton) external;\n\n /// @notice Sets the maximum number of applications one staking provider can\n /// have authorized. Used to protect against DoSing slashing queue.\n /// Can only be called by the Governance.\n function setAuthorizationCeiling(uint256 ceiling) external;\n\n //\n //\n // Stake top-up\n //\n //\n\n /// @notice Increases the amount of the stake for the given staking provider.\n /// Can be called only by the owner or the staking provider.\n /// @dev The sender of this transaction needs to have the amount approved to\n /// transfer to the staking contract.\n function topUp(address stakingProvider, uint96 amount) external;\n\n /// @notice Propagates information about stake top-up from the legacy KEEP\n /// staking contract to T staking contract. Can be called only by\n /// the owner or the staking provider.\n function topUpKeep(address stakingProvider) external;\n\n /// @notice Propagates information about stake top-up from the legacy NU\n /// staking contract to T staking contract. Can be called only by\n /// the owner or the staking provider.\n function topUpNu(address stakingProvider) external;\n\n //\n //\n // Undelegating a stake (unstaking)\n //\n //\n\n /// @notice Reduces the liquid T stake amount by the provided amount and\n /// withdraws T to the owner. Reverts if there is at least one\n /// authorization higher than the sum of the legacy stake and\n /// remaining liquid T stake or if the unstake amount is higher than\n /// the liquid T stake amount. Can be called only by the delegation\n /// owner or the staking provider.\n function unstakeT(address stakingProvider, uint96 amount) external;\n\n /// @notice Sets the legacy KEEP staking contract active stake amount cached\n /// in T staking contract to 0. Reverts if the amount of liquid T\n /// staked in T staking contract is lower than the highest\n /// application authorization. This function allows to unstake from\n /// KEEP staking contract and still being able to operate in T\n /// network and earning rewards based on the liquid T staked. Can be\n /// called only by the delegation owner or the staking provider.\n function unstakeKeep(address stakingProvider) external;\n\n /// @notice Reduces cached legacy NU stake amount by the provided amount.\n /// Reverts if there is at least one authorization higher than the\n /// sum of remaining legacy NU stake and liquid T stake for that\n /// staking provider or if the untaked amount is higher than the\n /// cached legacy stake amount. If succeeded, the legacy NU stake\n /// can be partially or fully undelegated on the legacy staking\n /// contract. This function allows to unstake from NU staking\n /// contract and still being able to operate in T network and\n /// earning rewards based on the liquid T staked. Can be called only\n /// by the delegation owner or the staking provider.\n function unstakeNu(address stakingProvider, uint96 amount) external;\n\n /// @notice Sets cached legacy stake amount to 0, sets the liquid T stake\n /// amount to 0 and withdraws all liquid T from the stake to the\n /// owner. Reverts if there is at least one non-zero authorization.\n /// Can be called only by the delegation owner or the staking\n /// provider.\n function unstakeAll(address stakingProvider) external;\n\n //\n //\n // Keeping information in sync\n //\n //\n\n /// @notice Notifies about the discrepancy between legacy KEEP active stake\n /// and the amount cached in T staking contract. Slashes the staking\n /// provider in case the amount cached is higher than the actual\n /// active stake amount in KEEP staking contract. Needs to update\n /// authorizations of all affected applications and execute an\n /// involuntary allocation decrease on all affected applications.\n /// Can be called by anyone, notifier receives a reward.\n function notifyKeepStakeDiscrepancy(address stakingProvider) external;\n\n /// @notice Notifies about the discrepancy between legacy NU active stake\n /// and the amount cached in T staking contract. Slashes the\n /// staking provider in case the amount cached is higher than the\n /// actual active stake amount in NU staking contract. Needs to\n /// update authorizations of all affected applications and execute\n /// an involuntary allocation decrease on all affected applications.\n /// Can be called by anyone, notifier receives a reward.\n function notifyNuStakeDiscrepancy(address stakingProvider) external;\n\n /// @notice Sets the penalty amount for stake discrepancy and reward\n /// multiplier for reporting it. The penalty is seized from the\n /// delegated stake, and 5% of the penalty, scaled by the\n /// multiplier, is given to the notifier. The rest of the tokens are\n /// burned. Can only be called by the Governance. See `seize` function.\n function setStakeDiscrepancyPenalty(\n uint96 penalty,\n uint256 rewardMultiplier\n ) external;\n\n /// @notice Sets reward in T tokens for notification of misbehaviour\n /// of one staking provider. Can only be called by the governance.\n function setNotificationReward(uint96 reward) external;\n\n /// @notice Transfer some amount of T tokens as reward for notifications\n /// of misbehaviour\n function pushNotificationReward(uint96 reward) external;\n\n /// @notice Withdraw some amount of T tokens from notifiers treasury.\n /// Can only be called by the governance.\n function withdrawNotificationReward(address recipient, uint96 amount)\n external;\n\n /// @notice Adds staking providers to the slashing queue along with the\n /// amount that should be slashed from each one of them. Can only be\n /// called by application authorized for all staking providers in\n /// the array.\n function slash(uint96 amount, address[] memory stakingProviders) external;\n\n /// @notice Adds staking providers to the slashing queue along with the\n /// amount. The notifier will receive reward per each staking\n /// provider from notifiers treasury. Can only be called by\n /// application authorized for all staking providers in the array.\n function seize(\n uint96 amount,\n uint256 rewardMultipier,\n address notifier,\n address[] memory stakingProviders\n ) external;\n\n /// @notice Takes the given number of queued slashing operations and\n /// processes them. Receives 5% of the slashed amount.\n /// Executes `involuntaryAllocationDecrease` function on each\n /// affected application.\n function processSlashing(uint256 count) external;\n\n //\n //\n // Auxiliary functions\n //\n //\n\n /// @notice Returns the authorized stake amount of the staking provider for\n /// the application.\n function authorizedStake(address stakingProvider, address application)\n external\n view\n returns (uint96);\n\n /// @notice Returns staked amount of T, Keep and Nu for the specified\n /// staking provider.\n /// @dev All values are in T denomination\n function stakes(address stakingProvider)\n external\n view\n returns (\n uint96 tStake,\n uint96 keepInTStake,\n uint96 nuInTStake\n );\n\n /// @notice Returns start staking timestamp.\n /// @dev This value is set at most once.\n function getStartStakingTimestamp(address stakingProvider)\n external\n view\n returns (uint256);\n\n /// @notice Returns staked amount of NU for the specified staking provider.\n function stakedNu(address stakingProvider) external view returns (uint256);\n\n /// @notice Gets the stake owner, the beneficiary and the authorizer\n /// for the specified staking provider address.\n /// @return owner Stake owner address.\n /// @return beneficiary Beneficiary address.\n /// @return authorizer Authorizer address.\n function rolesOf(address stakingProvider)\n external\n view\n returns (\n address owner,\n address payable beneficiary,\n address authorizer\n );\n\n /// @notice Returns length of application array\n function getApplicationsLength() external view returns (uint256);\n\n /// @notice Returns length of slashing queue\n function getSlashingQueueLength() external view returns (uint256);\n\n /// @notice Returns minimum possible stake for T, KEEP or NU in T\n /// denomination.\n /// @dev For example, suppose the given staking provider has 10 T, 20 T\n /// worth of KEEP, and 30 T worth of NU all staked, and the maximum\n /// application authorization is 40 T, then `getMinStaked` for\n /// that staking provider returns:\n /// * 0 T if KEEP stake type specified i.e.\n /// min = 40 T max - (10 T + 30 T worth of NU) = 0 T\n /// * 10 T if NU stake type specified i.e.\n /// min = 40 T max - (10 T + 20 T worth of KEEP) = 10 T\n /// * 0 T if T stake type specified i.e.\n /// min = 40 T max - (20 T worth of KEEP + 30 T worth of NU) < 0 T\n /// In other words, the minimum stake amount for the specified\n /// stake type is the minimum amount of stake of the given type\n /// needed to satisfy the maximum application authorization given the\n /// staked amounts of the other stake types for that staking provider.\n function getMinStaked(address stakingProvider, StakeType stakeTypes)\n external\n view\n returns (uint96);\n\n /// @notice Returns available amount to authorize for the specified application\n function getAvailableToAuthorize(\n address stakingProvider,\n address application\n ) external view returns (uint96);\n}\n"
210
+ },
118
211
  "@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol": {
119
212
  "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (proxy/transparent/ProxyAdmin.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./TransparentUpgradeableProxy.sol\";\nimport \"../../access/Ownable.sol\";\n\n/**\n * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an\n * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.\n */\ncontract ProxyAdmin is Ownable {\n /**\n * @dev Returns the current implementation of `proxy`.\n *\n * Requirements:\n *\n * - This contract must be the admin of `proxy`.\n */\n function getProxyImplementation(TransparentUpgradeableProxy proxy) public view virtual returns (address) {\n // We need to manually run the static call since the getter cannot be flagged as view\n // bytes4(keccak256(\"implementation()\")) == 0x5c60da1b\n (bool success, bytes memory returndata) = address(proxy).staticcall(hex\"5c60da1b\");\n require(success);\n return abi.decode(returndata, (address));\n }\n\n /**\n * @dev Returns the current admin of `proxy`.\n *\n * Requirements:\n *\n * - This contract must be the admin of `proxy`.\n */\n function getProxyAdmin(TransparentUpgradeableProxy proxy) public view virtual returns (address) {\n // We need to manually run the static call since the getter cannot be flagged as view\n // bytes4(keccak256(\"admin()\")) == 0xf851a440\n (bool success, bytes memory returndata) = address(proxy).staticcall(hex\"f851a440\");\n require(success);\n return abi.decode(returndata, (address));\n }\n\n /**\n * @dev Changes the admin of `proxy` to `newAdmin`.\n *\n * Requirements:\n *\n * - This contract must be the current admin of `proxy`.\n */\n function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner {\n proxy.changeAdmin(newAdmin);\n }\n\n /**\n * @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}.\n *\n * Requirements:\n *\n * - This contract must be the admin of `proxy`.\n */\n function upgrade(TransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner {\n proxy.upgradeTo(implementation);\n }\n\n /**\n * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See\n * {TransparentUpgradeableProxy-upgradeToAndCall}.\n *\n * Requirements:\n *\n * - This contract must be the admin of `proxy`.\n */\n function upgradeAndCall(\n TransparentUpgradeableProxy proxy,\n address implementation,\n bytes memory data\n ) public payable virtual onlyOwner {\n proxy.upgradeToAndCall{value: msg.value}(implementation, data);\n }\n}\n"
120
213
  },
@@ -154,89 +247,35 @@
154
247
  "contracts/hardhat-dependency-compiler/@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol": {
155
248
  "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >0.0.0;\nimport '@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol';\n"
156
249
  },
157
- "contracts/bridge/Wallets.sol": {
158
- "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\nimport {EcdsaDkg} from \"@keep-network/ecdsa/contracts/libraries/EcdsaDkg.sol\";\nimport {Math} from \"@openzeppelin/contracts/utils/math/Math.sol\";\n\nimport \"./BitcoinTx.sol\";\nimport \"./EcdsaLib.sol\";\nimport \"./BridgeState.sol\";\n\n/// @title Wallet library\n/// @notice Library responsible for handling integration between Bridge\n/// contract and ECDSA wallets.\nlibrary Wallets {\n using BTCUtils for bytes;\n\n /// @notice Represents wallet state:\n enum WalletState {\n /// @dev The wallet is unknown to the Bridge.\n Unknown,\n /// @dev The wallet can sweep deposits and accept redemption requests.\n Live,\n /// @dev The wallet was deemed unhealthy and is expected to move their\n /// outstanding funds to another wallet. The wallet can still\n /// fulfill their pending redemption requests although new\n /// redemption requests and new deposit reveals are not accepted.\n MovingFunds,\n /// @dev The wallet moved or redeemed all their funds and is in the\n /// closing period where they can be subject of fraud challenges\n /// and must defend against them. This state is needed to protect\n /// against deposit frauds on deposits revealed but not swept.\n /// The closing period must be greater that the deposit refund\n /// time plus some time margin.\n Closing,\n /// @dev The wallet finalized the closing period successfully and\n /// cannot perform any action in the Bridge.\n Closed,\n /// @dev The wallet committed a fraud that was reported. The wallet is\n /// blocked and can not perform any actions in the Bridge.\n /// Off-chain coordination with the wallet operators is needed to\n /// recover funds.\n Terminated\n }\n\n /// @notice Holds information about a wallet.\n struct Wallet {\n // Identifier of a ECDSA Wallet registered in the ECDSA Wallet Registry.\n bytes32 ecdsaWalletID;\n // Latest wallet's main UTXO hash computed as\n // keccak256(txHash | txOutputIndex | txOutputValue). The `tx` prefix\n // refers to the transaction which created that main UTXO. The `txHash`\n // is `bytes32` (ordered as in Bitcoin internally), `txOutputIndex`\n // an `uint32`, and `txOutputValue` an `uint64` value.\n bytes32 mainUtxoHash;\n // The total redeemable value of pending redemption requests targeting\n // that wallet.\n uint64 pendingRedemptionsValue;\n // UNIX timestamp the wallet was created at.\n uint32 createdAt;\n // UNIX timestamp indicating the moment the wallet was requested to\n // move their funds.\n uint32 movingFundsRequestedAt;\n // UNIX timestamp indicating the moment the wallet's closing period\n // started.\n uint32 closingStartedAt;\n // Total count of pending moved funds sweep requests targeting this wallet.\n uint32 pendingMovedFundsSweepRequestsCount;\n // Current state of the wallet.\n WalletState state;\n // Moving funds target wallet commitment submitted by the wallet. It\n // is built by applying the keccak256 hash over the list of 20-byte\n // public key hashes of the target wallets.\n bytes32 movingFundsTargetWalletsCommitmentHash;\n // This struct doesn't contain `__gap` property as the structure is stored\n // in a mapping, mappings store values in different slots and they are\n // not contiguous with other values.\n }\n\n event NewWalletRequested();\n\n event NewWalletRegistered(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletMovingFunds(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletClosing(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletClosed(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletTerminated(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n /// @notice Requests creation of a new wallet. This function just\n /// forms a request and the creation process is performed\n /// asynchronously. Outcome of that process should be delivered\n /// using `registerNewWallet` function.\n /// @param activeWalletMainUtxo Data of the active wallet's main UTXO, as\n /// currently known on the Ethereum chain.\n /// @dev Requirements:\n /// - `activeWalletMainUtxo` components must point to the recent main\n /// UTXO of the given active wallet, as currently known on the\n /// Ethereum chain. If there is no active wallet at the moment, or\n /// the active wallet has no main UTXO, this parameter can be\n /// empty as it is ignored,\n /// - Wallet creation must not be in progress,\n /// - If the active wallet is set, one of the following\n /// conditions must be true:\n /// - The active wallet BTC balance is above the minimum threshold\n /// and the active wallet is old enough, i.e. the creation period\n /// was elapsed since its creation time,\n /// - The active wallet BTC balance is above the maximum threshold.\n function requestNewWallet(\n BridgeState.Storage storage self,\n BitcoinTx.UTXO calldata activeWalletMainUtxo\n ) external {\n require(\n self.ecdsaWalletRegistry.getWalletCreationState() ==\n EcdsaDkg.State.IDLE,\n \"Wallet creation already in progress\"\n );\n\n bytes20 activeWalletPubKeyHash = self.activeWalletPubKeyHash;\n\n // If the active wallet is set, fetch this wallet's details from\n // storage to perform conditions check. The `registerNewWallet`\n // function guarantees an active wallet is always one of the\n // registered ones.\n if (activeWalletPubKeyHash != bytes20(0)) {\n uint64 activeWalletBtcBalance = getWalletBtcBalance(\n self,\n activeWalletPubKeyHash,\n activeWalletMainUtxo\n );\n uint32 activeWalletCreatedAt = self\n .registeredWallets[activeWalletPubKeyHash]\n .createdAt;\n /* solhint-disable-next-line not-rely-on-time */\n bool activeWalletOldEnough = block.timestamp >=\n activeWalletCreatedAt + self.walletCreationPeriod;\n\n require(\n (activeWalletOldEnough &&\n activeWalletBtcBalance >=\n self.walletCreationMinBtcBalance) ||\n activeWalletBtcBalance >= self.walletCreationMaxBtcBalance,\n \"Wallet creation conditions are not met\"\n );\n }\n\n emit NewWalletRequested();\n\n self.ecdsaWalletRegistry.requestNewWallet();\n }\n\n /// @notice Gets BTC balance for given the wallet.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @param walletMainUtxo Data of the wallet's main UTXO, as currently\n /// known on the Ethereum chain.\n /// @return walletBtcBalance Current BTC balance for the given wallet.\n /// @dev Requirements:\n /// - `walletMainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// If the wallet has no main UTXO, this parameter can be empty as it\n /// is ignored.\n function getWalletBtcBalance(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata walletMainUtxo\n ) internal view returns (uint64 walletBtcBalance) {\n bytes32 walletMainUtxoHash = self\n .registeredWallets[walletPubKeyHash]\n .mainUtxoHash;\n\n // If the wallet has a main UTXO hash set, cross-check it with the\n // provided plain-text parameter and get the transaction output value\n // as BTC balance. Otherwise, the BTC balance is just zero.\n if (walletMainUtxoHash != bytes32(0)) {\n require(\n keccak256(\n abi.encodePacked(\n walletMainUtxo.txHash,\n walletMainUtxo.txOutputIndex,\n walletMainUtxo.txOutputValue\n )\n ) == walletMainUtxoHash,\n \"Invalid wallet main UTXO data\"\n );\n\n walletBtcBalance = walletMainUtxo.txOutputValue;\n }\n\n return walletBtcBalance;\n }\n\n /// @notice Registers a new wallet. This function should be called\n /// after the wallet creation process initiated using\n /// `requestNewWallet` completes and brings the outcomes.\n /// @param ecdsaWalletID Wallet's unique identifier.\n /// @param publicKeyX Wallet's public key's X coordinate.\n /// @param publicKeyY Wallet's public key's Y coordinate.\n /// @dev Requirements:\n /// - The only caller authorized to call this function is `registry`,\n /// - Given wallet data must not belong to an already registered wallet.\n function registerNewWallet(\n BridgeState.Storage storage self,\n bytes32 ecdsaWalletID,\n bytes32 publicKeyX,\n bytes32 publicKeyY\n ) external {\n require(\n msg.sender == address(self.ecdsaWalletRegistry),\n \"Caller is not the ECDSA Wallet Registry\"\n );\n\n // Compress wallet's public key and calculate Bitcoin's hash160 of it.\n bytes20 walletPubKeyHash = bytes20(\n EcdsaLib.compressPublicKey(publicKeyX, publicKeyY).hash160View()\n );\n\n Wallet storage wallet = self.registeredWallets[walletPubKeyHash];\n require(\n wallet.state == WalletState.Unknown,\n \"ECDSA wallet has been already registered\"\n );\n wallet.ecdsaWalletID = ecdsaWalletID;\n wallet.state = WalletState.Live;\n /* solhint-disable-next-line not-rely-on-time */\n wallet.createdAt = uint32(block.timestamp);\n\n // Set the freshly created wallet as the new active wallet.\n self.activeWalletPubKeyHash = walletPubKeyHash;\n\n self.liveWalletsCount++;\n\n emit NewWalletRegistered(ecdsaWalletID, walletPubKeyHash);\n }\n\n /// @notice Handles a notification about a wallet heartbeat failure and\n /// triggers the wallet moving funds process.\n /// @param publicKeyX Wallet's public key's X coordinate.\n /// @param publicKeyY Wallet's public key's Y coordinate.\n /// @dev Requirements:\n /// - The only caller authorized to call this function is `registry`,\n /// - Wallet must be in Live state.\n function notifyWalletHeartbeatFailed(\n BridgeState.Storage storage self,\n bytes32 publicKeyX,\n bytes32 publicKeyY\n ) external {\n require(\n msg.sender == address(self.ecdsaWalletRegistry),\n \"Caller is not the ECDSA Wallet Registry\"\n );\n\n // Compress wallet's public key and calculate Bitcoin's hash160 of it.\n bytes20 walletPubKeyHash = bytes20(\n EcdsaLib.compressPublicKey(publicKeyX, publicKeyY).hash160View()\n );\n\n require(\n self.registeredWallets[walletPubKeyHash].state == WalletState.Live,\n \"ECDSA wallet must be in Live state\"\n );\n\n moveFunds(self, walletPubKeyHash);\n }\n\n /// @notice Handles a notification about a wallet redemption timeout.\n /// Triggers the wallet moving funds process only if the wallet is\n /// still in the Live state. That means multiple action timeouts can\n /// be reported for the same wallet but only the first report\n /// requests the wallet to move their funds.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @dev Requirements:\n /// - The wallet must be in the `Live` or `MovingFunds` state.\n function notifyWalletTimedOutRedemption(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash\n ) internal {\n WalletState walletState = self\n .registeredWallets[walletPubKeyHash]\n .state;\n\n require(\n walletState == WalletState.Live ||\n walletState == WalletState.MovingFunds,\n \"ECDSA wallet must be in Live or MovingFunds state\"\n );\n\n if (walletState == WalletState.Live) {\n moveFunds(self, walletPubKeyHash);\n }\n }\n\n /// @notice Notifies that the wallet is either old enough or has too few\n /// satoshis left and qualifies to be closed.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @param walletMainUtxo Data of the wallet's main UTXO, as currently\n /// known on the Ethereum chain.\n /// @dev Requirements:\n /// - Wallet must not be set as the current active wallet,\n /// - Wallet must exceed the wallet maximum age OR the wallet BTC\n /// balance must be lesser than the minimum threshold. If the latter\n /// case is true, the `walletMainUtxo` components must point to the\n /// recent main UTXO of the given wallet, as currently known on the\n /// Ethereum chain. If the wallet has no main UTXO, this parameter\n /// can be empty as it is ignored since the wallet balance is\n /// assumed to be zero,\n /// - Wallet must be in Live state.\n function notifyCloseableWallet(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata walletMainUtxo\n ) external {\n require(\n self.activeWalletPubKeyHash != walletPubKeyHash,\n \"Active wallet cannot be considered closeable\"\n );\n\n Wallet storage wallet = self.registeredWallets[walletPubKeyHash];\n require(\n wallet.state == WalletState.Live,\n \"ECDSA wallet must be in Live state\"\n );\n\n /* solhint-disable-next-line not-rely-on-time */\n bool walletOldEnough = block.timestamp >=\n wallet.createdAt + self.walletMaxAge;\n\n require(\n walletOldEnough ||\n getWalletBtcBalance(self, walletPubKeyHash, walletMainUtxo) <\n self.walletClosureMinBtcBalance,\n \"Wallet needs to be old enough or have too few satoshis\"\n );\n\n moveFunds(self, walletPubKeyHash);\n }\n\n /// @notice Requests a wallet to move their funds. If the wallet balance\n /// is zero, the wallet closing begins immediately. If the move\n /// funds request refers to the current active wallet, such a wallet\n /// is no longer considered active and the active wallet slot\n /// is unset allowing to trigger a new wallet creation immediately.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @dev Requirements:\n /// - The caller must make sure that the wallet is in the Live state.\n function moveFunds(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash\n ) internal {\n Wallet storage wallet = self.registeredWallets[walletPubKeyHash];\n\n if (wallet.mainUtxoHash == bytes32(0)) {\n // If the wallet has no main UTXO, that means its BTC balance\n // is zero and the wallet closing should begin immediately.\n beginWalletClosing(self, walletPubKeyHash);\n } else {\n // Otherwise, initialize the moving funds process.\n wallet.state = WalletState.MovingFunds;\n /* solhint-disable-next-line not-rely-on-time */\n wallet.movingFundsRequestedAt = uint32(block.timestamp);\n\n emit WalletMovingFunds(wallet.ecdsaWalletID, walletPubKeyHash);\n }\n\n if (self.activeWalletPubKeyHash == walletPubKeyHash) {\n // If the move funds request refers to the current active wallet,\n // unset the active wallet and make the wallet creation process\n // possible in order to get a new healthy active wallet.\n delete self.activeWalletPubKeyHash;\n }\n\n self.liveWalletsCount--;\n }\n\n /// @notice Begins the closing period of the given wallet.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @dev Requirements:\n /// - The caller must make sure that the wallet is in the\n /// MovingFunds state.\n function beginWalletClosing(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash\n ) internal {\n Wallet storage wallet = self.registeredWallets[walletPubKeyHash];\n // Initialize the closing period.\n wallet.state = WalletState.Closing;\n /* solhint-disable-next-line not-rely-on-time */\n wallet.closingStartedAt = uint32(block.timestamp);\n\n emit WalletClosing(wallet.ecdsaWalletID, walletPubKeyHash);\n }\n\n /// @notice Notifies about the end of the closing period for the given wallet.\n /// Closes the wallet ultimately and notifies the ECDSA registry\n /// about this fact.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @dev Requirements:\n /// - The wallet must be in the Closing state,\n /// - The wallet closing period must have elapsed.\n function notifyWalletClosingPeriodElapsed(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash\n ) internal {\n Wallet storage wallet = self.registeredWallets[walletPubKeyHash];\n\n require(\n wallet.state == WalletState.Closing,\n \"ECDSA wallet must be in Closing state\"\n );\n\n require(\n /* solhint-disable-next-line not-rely-on-time */\n block.timestamp >\n wallet.closingStartedAt + self.walletClosingPeriod,\n \"Closing period has not elapsed yet\"\n );\n\n finalizeWalletClosing(self, walletPubKeyHash);\n }\n\n /// @notice Finalizes the closing period of the given wallet and notifies\n /// the ECDSA registry about this fact.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @dev Requirements:\n /// - The caller must make sure that the wallet is in the Closing state.\n function finalizeWalletClosing(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash\n ) internal {\n Wallet storage wallet = self.registeredWallets[walletPubKeyHash];\n\n wallet.state = WalletState.Closed;\n\n emit WalletClosed(wallet.ecdsaWalletID, walletPubKeyHash);\n\n self.ecdsaWalletRegistry.closeWallet(wallet.ecdsaWalletID);\n }\n\n /// @notice Terminates the given wallet and notifies the ECDSA registry\n /// about this fact. If the wallet termination refers to the current\n /// active wallet, such a wallet is no longer considered active and\n /// the active wallet slot is unset allowing to trigger a new wallet\n /// creation immediately.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @dev Requirements:\n /// - The caller must make sure that the wallet is in the\n /// Live or MovingFunds or Closing state.\n function terminateWallet(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash\n ) internal {\n Wallet storage wallet = self.registeredWallets[walletPubKeyHash];\n\n if (wallet.state == WalletState.Live) {\n self.liveWalletsCount--;\n }\n\n wallet.state = WalletState.Terminated;\n\n emit WalletTerminated(wallet.ecdsaWalletID, walletPubKeyHash);\n\n if (self.activeWalletPubKeyHash == walletPubKeyHash) {\n // If termination refers to the current active wallet,\n // unset the active wallet and make the wallet creation process\n // possible in order to get a new healthy active wallet.\n delete self.activeWalletPubKeyHash;\n }\n\n self.ecdsaWalletRegistry.closeWallet(wallet.ecdsaWalletID);\n }\n\n /// @notice Notifies that the wallet completed the moving funds process\n /// successfully. Checks if the funds were moved to the expected\n /// target wallets. Closes the source wallet if everything went\n /// good and reverts otherwise.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @param targetWalletsHash 32-byte keccak256 hash over the list of\n /// 20-byte public key hashes of the target wallets actually used\n /// within the moving funds transactions.\n /// @dev Requirements:\n /// - The caller must make sure the moving funds transaction actually\n /// happened on Bitcoin chain and fits the protocol requirements,\n /// - The source wallet must be in the MovingFunds state,\n /// - The target wallets commitment must be submitted by the source\n /// wallet,\n /// - The actual target wallets used in the moving funds transaction\n /// must be exactly the same as the target wallets commitment.\n function notifyWalletFundsMoved(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n bytes32 targetWalletsHash\n ) internal {\n Wallet storage wallet = self.registeredWallets[walletPubKeyHash];\n // Check that the wallet is in the MovingFunds state but don't check\n // if the moving funds timeout is exceeded. That should give a\n // possibility to move funds in case when timeout was hit but was\n // not reported yet.\n require(\n wallet.state == WalletState.MovingFunds,\n \"ECDSA wallet must be in MovingFunds state\"\n );\n\n bytes32 targetWalletsCommitmentHash = wallet\n .movingFundsTargetWalletsCommitmentHash;\n\n require(\n targetWalletsCommitmentHash != bytes32(0),\n \"Target wallets commitment not submitted yet\"\n );\n\n // Make sure that the target wallets where funds were moved to are\n // exactly the same as the ones the source wallet committed to.\n require(\n targetWalletsCommitmentHash == targetWalletsHash,\n \"Target wallets don't correspond to the commitment\"\n );\n\n // If funds were moved, the wallet has no longer a main UTXO.\n delete wallet.mainUtxoHash;\n\n beginWalletClosing(self, walletPubKeyHash);\n }\n}\n"
159
- },
160
- "@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol": {
161
- "content": "pragma solidity ^0.8.4;\n\n/** @title BitcoinSPV */\n/** @author Summa (https://summa.one) */\n\nimport {BytesLib} from \"./BytesLib.sol\";\nimport {SafeMath} from \"./SafeMath.sol\";\n\nlibrary BTCUtils {\n using BytesLib for bytes;\n using SafeMath for uint256;\n\n // The target at minimum Difficulty. Also the target of the genesis block\n uint256 public constant DIFF1_TARGET = 0xffff0000000000000000000000000000000000000000000000000000;\n\n uint256 public constant RETARGET_PERIOD = 2 * 7 * 24 * 60 * 60; // 2 weeks in seconds\n uint256 public constant RETARGET_PERIOD_BLOCKS = 2016; // 2 weeks in blocks\n\n uint256 public constant ERR_BAD_ARG = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;\n\n /* ***** */\n /* UTILS */\n /* ***** */\n\n /// @notice Determines the length of a VarInt in bytes\n /// @dev A VarInt of >1 byte is prefixed with a flag indicating its length\n /// @param _flag The first byte of a VarInt\n /// @return The number of non-flag bytes in the VarInt\n function determineVarIntDataLength(bytes memory _flag) internal pure returns (uint8) {\n return determineVarIntDataLengthAt(_flag, 0);\n }\n\n /// @notice Determines the length of a VarInt in bytes\n /// @dev A VarInt of >1 byte is prefixed with a flag indicating its length\n /// @param _b The byte array containing a VarInt\n /// @param _at The position of the VarInt in the array\n /// @return The number of non-flag bytes in the VarInt\n function determineVarIntDataLengthAt(bytes memory _b, uint256 _at) internal pure returns (uint8) {\n if (uint8(_b[_at]) == 0xff) {\n return 8; // one-byte flag, 8 bytes data\n }\n if (uint8(_b[_at]) == 0xfe) {\n return 4; // one-byte flag, 4 bytes data\n }\n if (uint8(_b[_at]) == 0xfd) {\n return 2; // one-byte flag, 2 bytes data\n }\n\n return 0; // flag is data\n }\n\n /// @notice Parse a VarInt into its data length and the number it represents\n /// @dev Useful for Parsing Vins and Vouts. Returns ERR_BAD_ARG if insufficient bytes.\n /// Caller SHOULD explicitly handle this case (or bubble it up)\n /// @param _b A byte-string starting with a VarInt\n /// @return number of bytes in the encoding (not counting the tag), the encoded int\n function parseVarInt(bytes memory _b) internal pure returns (uint256, uint256) {\n return parseVarIntAt(_b, 0);\n }\n\n /// @notice Parse a VarInt into its data length and the number it represents\n /// @dev Useful for Parsing Vins and Vouts. Returns ERR_BAD_ARG if insufficient bytes.\n /// Caller SHOULD explicitly handle this case (or bubble it up)\n /// @param _b A byte-string containing a VarInt\n /// @param _at The position of the VarInt\n /// @return number of bytes in the encoding (not counting the tag), the encoded int\n function parseVarIntAt(bytes memory _b, uint256 _at) internal pure returns (uint256, uint256) {\n uint8 _dataLen = determineVarIntDataLengthAt(_b, _at);\n\n if (_dataLen == 0) {\n return (0, uint8(_b[_at]));\n }\n if (_b.length < 1 + _dataLen + _at) {\n return (ERR_BAD_ARG, 0);\n }\n uint256 _number;\n if (_dataLen == 2) {\n _number = reverseUint16(uint16(_b.slice2(1 + _at)));\n } else if (_dataLen == 4) {\n _number = reverseUint32(uint32(_b.slice4(1 + _at)));\n } else if (_dataLen == 8) {\n _number = reverseUint64(uint64(_b.slice8(1 + _at)));\n }\n return (_dataLen, _number);\n }\n\n /// @notice Changes the endianness of a byte array\n /// @dev Returns a new, backwards, bytes\n /// @param _b The bytes to reverse\n /// @return The reversed bytes\n function reverseEndianness(bytes memory _b) internal pure returns (bytes memory) {\n bytes memory _newValue = new bytes(_b.length);\n\n for (uint i = 0; i < _b.length; i++) {\n _newValue[_b.length - i - 1] = _b[i];\n }\n\n return _newValue;\n }\n\n /// @notice Changes the endianness of a uint256\n /// @dev https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel\n /// @param _b The unsigned integer to reverse\n /// @return v The reversed value\n function reverseUint256(uint256 _b) internal pure returns (uint256 v) {\n v = _b;\n\n // swap bytes\n v = ((v >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) |\n ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8);\n // swap 2-byte long pairs\n v = ((v >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) |\n ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16);\n // swap 4-byte long pairs\n v = ((v >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) |\n ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32);\n // swap 8-byte long pairs\n v = ((v >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) |\n ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64);\n // swap 16-byte long pairs\n v = (v >> 128) | (v << 128);\n }\n\n /// @notice Changes the endianness of a uint64\n /// @param _b The unsigned integer to reverse\n /// @return v The reversed value\n function reverseUint64(uint64 _b) internal pure returns (uint64 v) {\n v = _b;\n\n // swap bytes\n v = ((v >> 8) & 0x00FF00FF00FF00FF) |\n ((v & 0x00FF00FF00FF00FF) << 8);\n // swap 2-byte long pairs\n v = ((v >> 16) & 0x0000FFFF0000FFFF) |\n ((v & 0x0000FFFF0000FFFF) << 16);\n // swap 4-byte long pairs\n v = (v >> 32) | (v << 32);\n }\n\n /// @notice Changes the endianness of a uint32\n /// @param _b The unsigned integer to reverse\n /// @return v The reversed value\n function reverseUint32(uint32 _b) internal pure returns (uint32 v) {\n v = _b;\n\n // swap bytes\n v = ((v >> 8) & 0x00FF00FF) |\n ((v & 0x00FF00FF) << 8);\n // swap 2-byte long pairs\n v = (v >> 16) | (v << 16);\n }\n\n /// @notice Changes the endianness of a uint24\n /// @param _b The unsigned integer to reverse\n /// @return v The reversed value\n function reverseUint24(uint24 _b) internal pure returns (uint24 v) {\n v = (_b << 16) | (_b & 0x00FF00) | (_b >> 16);\n }\n\n /// @notice Changes the endianness of a uint16\n /// @param _b The unsigned integer to reverse\n /// @return v The reversed value\n function reverseUint16(uint16 _b) internal pure returns (uint16 v) {\n v = (_b << 8) | (_b >> 8);\n }\n\n\n /// @notice Converts big-endian bytes to a uint\n /// @dev Traverses the byte array and sums the bytes\n /// @param _b The big-endian bytes-encoded integer\n /// @return The integer representation\n function bytesToUint(bytes memory _b) internal pure returns (uint256) {\n uint256 _number;\n\n for (uint i = 0; i < _b.length; i++) {\n _number = _number + uint8(_b[i]) * (2 ** (8 * (_b.length - (i + 1))));\n }\n\n return _number;\n }\n\n /// @notice Get the last _num bytes from a byte array\n /// @param _b The byte array to slice\n /// @param _num The number of bytes to extract from the end\n /// @return The last _num bytes of _b\n function lastBytes(bytes memory _b, uint256 _num) internal pure returns (bytes memory) {\n uint256 _start = _b.length.sub(_num);\n\n return _b.slice(_start, _num);\n }\n\n /// @notice Implements bitcoin's hash160 (rmd160(sha2()))\n /// @dev abi.encodePacked changes the return to bytes instead of bytes32\n /// @param _b The pre-image\n /// @return The digest\n function hash160(bytes memory _b) internal pure returns (bytes memory) {\n return abi.encodePacked(ripemd160(abi.encodePacked(sha256(_b))));\n }\n\n /// @notice Implements bitcoin's hash160 (sha2 + ripemd160)\n /// @dev sha2 precompile at address(2), ripemd160 at address(3)\n /// @param _b The pre-image\n /// @return res The digest\n function hash160View(bytes memory _b) internal view returns (bytes20 res) {\n // solium-disable-next-line security/no-inline-assembly\n assembly {\n pop(staticcall(gas(), 2, add(_b, 32), mload(_b), 0x00, 32))\n pop(staticcall(gas(), 3, 0x00, 32, 0x00, 32))\n // read from position 12 = 0c\n res := mload(0x0c)\n }\n }\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\n function hash256(bytes memory _b) internal pure returns (bytes32) {\n return sha256(abi.encodePacked(sha256(_b)));\n }\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 res The digest\n function hash256View(bytes memory _b) internal view returns (bytes32 res) {\n // solium-disable-next-line security/no-inline-assembly\n assembly {\n pop(staticcall(gas(), 2, add(_b, 32), mload(_b), 0x00, 32))\n pop(staticcall(gas(), 2, 0x00, 32, 0x00, 32))\n res := mload(0x00)\n }\n }\n\n /// @notice Implements bitcoin's hash256 on a pair of bytes32\n /// @dev sha2 is precompiled smart contract located at address(2)\n /// @param _a The first bytes32 of the pre-image\n /// @param _b The second bytes32 of the pre-image\n /// @return res The digest\n function hash256Pair(bytes32 _a, bytes32 _b) internal view returns (bytes32 res) {\n // solium-disable-next-line security/no-inline-assembly\n assembly {\n mstore(0x00, _a)\n mstore(0x20, _b)\n pop(staticcall(gas(), 2, 0x00, 64, 0x00, 32))\n pop(staticcall(gas(), 2, 0x00, 32, 0x00, 32))\n res := mload(0x00)\n }\n }\n\n /* ************ */\n /* Legacy Input */\n /* ************ */\n\n /// @notice Extracts the nth input from the vin (0-indexed)\n /// @dev Iterates over the vin. If you need to extract several, write a custom function\n /// @param _vin The vin as a tightly-packed byte array\n /// @param _index The 0-indexed location of the input to extract\n /// @return The input as a byte array\n function extractInputAtIndex(bytes memory _vin, uint256 _index) internal pure returns (bytes memory) {\n uint256 _varIntDataLen;\n uint256 _nIns;\n\n (_varIntDataLen, _nIns) = parseVarInt(_vin);\n require(_varIntDataLen != ERR_BAD_ARG, \"Read overrun during VarInt parsing\");\n require(_index < _nIns, \"Vin read overrun\");\n\n uint256 _len = 0;\n uint256 _offset = 1 + _varIntDataLen;\n\n for (uint256 _i = 0; _i < _index; _i ++) {\n _len = determineInputLengthAt(_vin, _offset);\n require(_len != ERR_BAD_ARG, \"Bad VarInt in scriptSig\");\n _offset = _offset + _len;\n }\n\n _len = determineInputLengthAt(_vin, _offset);\n require(_len != ERR_BAD_ARG, \"Bad VarInt in scriptSig\");\n return _vin.slice(_offset, _len);\n }\n\n /// @notice Determines whether an input is legacy\n /// @dev False if no scriptSig, otherwise True\n /// @param _input The input\n /// @return True for legacy, False for witness\n function isLegacyInput(bytes memory _input) internal pure returns (bool) {\n return _input[36] != hex\"00\";\n }\n\n /// @notice Determines the length of a scriptSig in an input\n /// @dev Will return 0 if passed a witness input.\n /// @param _input The LEGACY input\n /// @return The length of the script sig\n function extractScriptSigLen(bytes memory _input) internal pure returns (uint256, uint256) {\n return extractScriptSigLenAt(_input, 0);\n }\n\n /// @notice Determines the length of a scriptSig in an input\n /// starting at the specified position\n /// @dev Will return 0 if passed a witness input.\n /// @param _input The byte array containing the LEGACY input\n /// @param _at The position of the input in the array\n /// @return The length of the script sig\n function extractScriptSigLenAt(bytes memory _input, uint256 _at) internal pure returns (uint256, uint256) {\n if (_input.length < 37 + _at) {\n return (ERR_BAD_ARG, 0);\n }\n\n uint256 _varIntDataLen;\n uint256 _scriptSigLen;\n (_varIntDataLen, _scriptSigLen) = parseVarIntAt(_input, _at + 36);\n\n return (_varIntDataLen, _scriptSigLen);\n }\n\n /// @notice Determines the length of an input from its scriptSig\n /// @dev 36 for outpoint, 1 for scriptSig length, 4 for sequence\n /// @param _input The input\n /// @return The length of the input in bytes\n function determineInputLength(bytes memory _input) internal pure returns (uint256) {\n return determineInputLengthAt(_input, 0);\n }\n\n /// @notice Determines the length of an input from its scriptSig,\n /// starting at the specified position\n /// @dev 36 for outpoint, 1 for scriptSig length, 4 for sequence\n /// @param _input The byte array containing the input\n /// @param _at The position of the input in the array\n /// @return The length of the input in bytes\n function determineInputLengthAt(bytes memory _input, uint256 _at) internal pure returns (uint256) {\n uint256 _varIntDataLen;\n uint256 _scriptSigLen;\n (_varIntDataLen, _scriptSigLen) = extractScriptSigLenAt(_input, _at);\n if (_varIntDataLen == ERR_BAD_ARG) {\n return ERR_BAD_ARG;\n }\n\n return 36 + 1 + _varIntDataLen + _scriptSigLen + 4;\n }\n\n /// @notice Extracts the LE sequence bytes from an input\n /// @dev Sequence is used for relative time locks\n /// @param _input The LEGACY input\n /// @return The sequence bytes (LE uint)\n function extractSequenceLELegacy(bytes memory _input) internal pure returns (bytes4) {\n uint256 _varIntDataLen;\n uint256 _scriptSigLen;\n (_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input);\n require(_varIntDataLen != ERR_BAD_ARG, \"Bad VarInt in scriptSig\");\n return _input.slice4(36 + 1 + _varIntDataLen + _scriptSigLen);\n }\n\n /// @notice Extracts the sequence from the input\n /// @dev Sequence is a 4-byte little-endian number\n /// @param _input The LEGACY input\n /// @return The sequence number (big-endian uint)\n function extractSequenceLegacy(bytes memory _input) internal pure returns (uint32) {\n uint32 _leSeqence = uint32(extractSequenceLELegacy(_input));\n uint32 _beSequence = reverseUint32(_leSeqence);\n return _beSequence;\n }\n /// @notice Extracts the VarInt-prepended scriptSig from the input in a tx\n /// @dev Will return hex\"00\" if passed a witness input\n /// @param _input The LEGACY input\n /// @return The length-prepended scriptSig\n function extractScriptSig(bytes memory _input) internal pure returns (bytes memory) {\n uint256 _varIntDataLen;\n uint256 _scriptSigLen;\n (_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input);\n require(_varIntDataLen != ERR_BAD_ARG, \"Bad VarInt in scriptSig\");\n return _input.slice(36, 1 + _varIntDataLen + _scriptSigLen);\n }\n\n\n /* ************* */\n /* Witness Input */\n /* ************* */\n\n /// @notice Extracts the LE sequence bytes from an input\n /// @dev Sequence is used for relative time locks\n /// @param _input The WITNESS input\n /// @return The sequence bytes (LE uint)\n function extractSequenceLEWitness(bytes memory _input) internal pure returns (bytes4) {\n return _input.slice4(37);\n }\n\n /// @notice Extracts the sequence from the input in a tx\n /// @dev Sequence is a 4-byte little-endian number\n /// @param _input The WITNESS input\n /// @return The sequence number (big-endian uint)\n function extractSequenceWitness(bytes memory _input) internal pure returns (uint32) {\n uint32 _leSeqence = uint32(extractSequenceLEWitness(_input));\n uint32 _inputeSequence = reverseUint32(_leSeqence);\n return _inputeSequence;\n }\n\n /// @notice Extracts the outpoint from the input in a tx\n /// @dev 32-byte tx id with 4-byte index\n /// @param _input The input\n /// @return The outpoint (LE bytes of prev tx hash + LE bytes of prev tx index)\n function extractOutpoint(bytes memory _input) internal pure returns (bytes memory) {\n return _input.slice(0, 36);\n }\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)\n function extractInputTxIdLE(bytes memory _input) internal pure returns (bytes32) {\n return _input.slice32(0);\n }\n\n /// @notice Extracts the outpoint tx id from an input\n /// starting at the specified position\n /// @dev 32-byte tx id\n /// @param _input The byte array containing the input\n /// @param _at The position of the input\n /// @return The tx id (little-endian bytes)\n function extractInputTxIdLeAt(bytes memory _input, uint256 _at) internal pure returns (bytes32) {\n return _input.slice32(_at);\n }\n\n /// @notice Extracts the LE tx input index from the input in a tx\n /// @dev 4-byte tx index\n /// @param _input The input\n /// @return The tx index (little-endian bytes)\n function extractTxIndexLE(bytes memory _input) internal pure returns (bytes4) {\n return _input.slice4(32);\n }\n\n /// @notice Extracts the LE tx input index from the input in a tx\n /// starting at the specified position\n /// @dev 4-byte tx index\n /// @param _input The byte array containing the input\n /// @param _at The position of the input\n /// @return The tx index (little-endian bytes)\n function extractTxIndexLeAt(bytes memory _input, uint256 _at) internal pure returns (bytes4) {\n return _input.slice4(32 + _at);\n }\n\n /* ****** */\n /* Output */\n /* ****** */\n\n /// @notice Determines the length of an output\n /// @dev Works with any properly formatted output\n /// @param _output The output\n /// @return The length indicated by the prefix, error if invalid length\n function determineOutputLength(bytes memory _output) internal pure returns (uint256) {\n return determineOutputLengthAt(_output, 0);\n }\n\n /// @notice Determines the length of an output\n /// starting at the specified position\n /// @dev Works with any properly formatted output\n /// @param _output The byte array containing the output\n /// @param _at The position of the output\n /// @return The length indicated by the prefix, error if invalid length\n function determineOutputLengthAt(bytes memory _output, uint256 _at) internal pure returns (uint256) {\n if (_output.length < 9 + _at) {\n return ERR_BAD_ARG;\n }\n uint256 _varIntDataLen;\n uint256 _scriptPubkeyLength;\n (_varIntDataLen, _scriptPubkeyLength) = parseVarIntAt(_output, 8 + _at);\n\n if (_varIntDataLen == ERR_BAD_ARG) {\n return ERR_BAD_ARG;\n }\n\n // 8-byte value, 1-byte for tag itself\n return 8 + 1 + _varIntDataLen + _scriptPubkeyLength;\n }\n\n /// @notice Extracts the output at a given index in the TxOuts vector\n /// @dev Iterates over the vout. If you need to extract multiple, write a custom function\n /// @param _vout The _vout to extract from\n /// @param _index The 0-indexed location of the output to extract\n /// @return The specified output\n function extractOutputAtIndex(bytes memory _vout, uint256 _index) internal pure returns (bytes memory) {\n uint256 _varIntDataLen;\n uint256 _nOuts;\n\n (_varIntDataLen, _nOuts) = parseVarInt(_vout);\n require(_varIntDataLen != ERR_BAD_ARG, \"Read overrun during VarInt parsing\");\n require(_index < _nOuts, \"Vout read overrun\");\n\n uint256 _len = 0;\n uint256 _offset = 1 + _varIntDataLen;\n\n for (uint256 _i = 0; _i < _index; _i ++) {\n _len = determineOutputLengthAt(_vout, _offset);\n require(_len != ERR_BAD_ARG, \"Bad VarInt in scriptPubkey\");\n _offset += _len;\n }\n\n _len = determineOutputLengthAt(_vout, _offset);\n require(_len != ERR_BAD_ARG, \"Bad VarInt in scriptPubkey\");\n return _vout.slice(_offset, _len);\n }\n\n /// @notice Extracts the value bytes from the output in a tx\n /// @dev Value is an 8-byte little-endian number\n /// @param _output The output\n /// @return The output value as LE bytes\n function extractValueLE(bytes memory _output) internal pure returns (bytes8) {\n return _output.slice8(0);\n }\n\n /// @notice Extracts the value from the output in a tx\n /// @dev Value is an 8-byte little-endian number\n /// @param _output The output\n /// @return The output value\n function extractValue(bytes memory _output) internal pure returns (uint64) {\n uint64 _leValue = uint64(extractValueLE(_output));\n uint64 _beValue = reverseUint64(_leValue);\n return _beValue;\n }\n\n /// @notice Extracts the data from an op return output\n /// @dev Returns hex\"\" if no data or not an op return\n /// @param _output The output\n /// @return Any data contained in the opreturn output, null if not an op return\n function extractOpReturnData(bytes memory _output) internal pure returns (bytes memory) {\n if (_output[9] != hex\"6a\") {\n return hex\"\";\n }\n bytes1 _dataLen = _output[10];\n return _output.slice(11, uint256(uint8(_dataLen)));\n }\n\n /// @notice Extracts the hash from the output script\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\n function extractHash(bytes memory _output) internal pure returns (bytes memory) {\n uint8 _scriptLen = uint8(_output[8]);\n\n // don't have to worry about overflow here.\n // if _scriptLen + 9 overflows, then output.length would have to be < 9\n // for this check to pass. if it's < 9, then we errored when assigning\n // _scriptLen\n if (_scriptLen + 9 != _output.length) {\n return hex\"\";\n }\n\n if (uint8(_output[9]) == 0) {\n if (_scriptLen < 2) {\n return hex\"\";\n }\n uint256 _payloadLen = uint8(_output[10]);\n // Check for maliciously formatted witness outputs.\n // No need to worry about underflow as long b/c of the `< 2` check\n if (_payloadLen != _scriptLen - 2 || (_payloadLen != 0x20 && _payloadLen != 0x14)) {\n return hex\"\";\n }\n return _output.slice(11, _payloadLen);\n } else {\n bytes3 _tag = _output.slice3(8);\n // p2pkh\n if (_tag == hex\"1976a9\") {\n // Check for maliciously formatted p2pkh\n // No need to worry about underflow, b/c of _scriptLen check\n if (uint8(_output[11]) != 0x14 ||\n _output.slice2(_output.length - 2) != hex\"88ac\") {\n return hex\"\";\n }\n return _output.slice(12, 20);\n //p2sh\n } else if (_tag == hex\"17a914\") {\n // Check for maliciously formatted p2sh\n // No need to worry about underflow, b/c of _scriptLen check\n if (uint8(_output[_output.length - 1]) != 0x87) {\n return hex\"\";\n }\n return _output.slice(11, 20);\n }\n }\n return hex\"\"; /* NB: will trigger on OPRETURN and any non-standard that doesn't overrun */\n }\n\n /* ********** */\n /* Witness TX */\n /* ********** */\n\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\n function validateVin(bytes memory _vin) internal pure returns (bool) {\n uint256 _varIntDataLen;\n uint256 _nIns;\n\n (_varIntDataLen, _nIns) = parseVarInt(_vin);\n\n // Not valid if it says there are too many or no inputs\n if (_nIns == 0 || _varIntDataLen == ERR_BAD_ARG) {\n return false;\n }\n\n uint256 _offset = 1 + _varIntDataLen;\n\n for (uint256 i = 0; i < _nIns; i++) {\n // If we're at the end, but still expect more\n if (_offset >= _vin.length) {\n return false;\n }\n\n // Grab the next input and determine its length.\n uint256 _nextLen = determineInputLengthAt(_vin, _offset);\n if (_nextLen == ERR_BAD_ARG) {\n return false;\n }\n\n // Increase the offset by that much\n _offset += _nextLen;\n }\n\n // Returns false if we're not exactly at the end\n return _offset == _vin.length;\n }\n\n /// @notice Checks that the vout passed up is properly formatted\n /// @dev Consider a vout with a valid scriptpubkey\n /// @param _vout Raw bytes length-prefixed output vector\n /// @return True if it represents a validly formatted vout\n function validateVout(bytes memory _vout) internal pure returns (bool) {\n uint256 _varIntDataLen;\n uint256 _nOuts;\n\n (_varIntDataLen, _nOuts) = parseVarInt(_vout);\n\n // Not valid if it says there are too many or no outputs\n if (_nOuts == 0 || _varIntDataLen == ERR_BAD_ARG) {\n return false;\n }\n\n uint256 _offset = 1 + _varIntDataLen;\n\n for (uint256 i = 0; i < _nOuts; i++) {\n // If we're at the end, but still expect more\n if (_offset >= _vout.length) {\n return false;\n }\n\n // Grab the next output and determine its length.\n // Increase the offset by that much\n uint256 _nextLen = determineOutputLengthAt(_vout, _offset);\n if (_nextLen == ERR_BAD_ARG) {\n return false;\n }\n\n _offset += _nextLen;\n }\n\n // Returns false if we're not exactly at the end\n return _offset == _vout.length;\n }\n\n\n\n /* ************ */\n /* Block Header */\n /* ************ */\n\n /// @notice Extracts the transaction merkle root from a block header\n /// @dev Use verifyHash256Merkle to verify proofs with this root\n /// @param _header The header\n /// @return The merkle root (little-endian)\n function extractMerkleRootLE(bytes memory _header) internal pure returns (bytes32) {\n return _header.slice32(36);\n }\n\n /// @notice Extracts the target from a block header\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\n function extractTarget(bytes memory _header) internal pure returns (uint256) {\n uint24 _m = uint24(_header.slice3(72));\n uint8 _e = uint8(_header[75]);\n uint256 _mantissa = uint256(reverseUint24(_m));\n uint _exponent = _e - 3;\n\n return _mantissa * (256 ** _exponent);\n }\n\n /// @notice Calculate difficulty from the difficulty 1 target and current target\n /// @dev Difficulty 1 is 0x1d00ffff on mainnet and testnet\n /// @dev Difficulty 1 is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent\n /// @param _target The current target\n /// @return The block difficulty (bdiff)\n function calculateDifficulty(uint256 _target) internal pure returns (uint256) {\n // Difficulty 1 calculated from 0x1d00ffff\n return DIFF1_TARGET.div(_target);\n }\n\n /// @notice Extracts the previous block's hash from a block header\n /// @dev Block headers do NOT include block number :(\n /// @param _header The header\n /// @return The previous block's hash (little-endian)\n function extractPrevBlockLE(bytes memory _header) internal pure returns (bytes32) {\n return _header.slice32(4);\n }\n\n /// @notice Extracts the timestamp from a block header\n /// @dev Time is not 100% reliable\n /// @param _header The header\n /// @return The timestamp (little-endian bytes)\n function extractTimestampLE(bytes memory _header) internal pure returns (bytes4) {\n return _header.slice4(68);\n }\n\n /// @notice Extracts the timestamp from a block header\n /// @dev Time is not 100% reliable\n /// @param _header The header\n /// @return The timestamp (uint)\n function extractTimestamp(bytes memory _header) internal pure returns (uint32) {\n return reverseUint32(uint32(extractTimestampLE(_header)));\n }\n\n /// @notice Extracts the expected difficulty from a block header\n /// @dev Does NOT verify the work\n /// @param _header The header\n /// @return The difficulty as an integer\n function extractDifficulty(bytes memory _header) internal pure returns (uint256) {\n return calculateDifficulty(extractTarget(_header));\n }\n\n /// @notice Concatenates and hashes two inputs for merkle proving\n /// @param _a The first hash\n /// @param _b The second hash\n /// @return The double-sha256 of the concatenated hashes\n function _hash256MerkleStep(bytes memory _a, bytes memory _b) internal view returns (bytes32) {\n return hash256View(abi.encodePacked(_a, _b));\n }\n\n /// @notice Concatenates and hashes two inputs for merkle proving\n /// @param _a The first hash\n /// @param _b The second hash\n /// @return The double-sha256 of the concatenated hashes\n function _hash256MerkleStep(bytes32 _a, bytes32 _b) internal view returns (bytes32) {\n return hash256Pair(_a, _b);\n }\n\n\n /// @notice Verifies a Bitcoin-style merkle tree\n /// @dev Leaves are 0-indexed. Inefficient version.\n /// @param _proof The proof. Tightly packed LE sha256 hashes. The last hash is the root\n /// @param _index The index of the leaf\n /// @return true if the proof is valid, else false\n function verifyHash256Merkle(bytes memory _proof, uint _index) internal view returns (bool) {\n // Not an even number of hashes\n if (_proof.length % 32 != 0) {\n return false;\n }\n\n // Special case for coinbase-only blocks\n if (_proof.length == 32) {\n return true;\n }\n\n // Should never occur\n if (_proof.length == 64) {\n return false;\n }\n\n bytes32 _root = _proof.slice32(_proof.length - 32);\n bytes32 _current = _proof.slice32(0);\n bytes memory _tree = _proof.slice(32, _proof.length - 64);\n\n return verifyHash256Merkle(_current, _tree, _root, _index);\n }\n\n /// @notice Verifies a Bitcoin-style merkle tree\n /// @dev Leaves are 0-indexed. Efficient version.\n /// @param _leaf The leaf of the proof. LE sha256 hash.\n /// @param _tree The intermediate nodes in the proof.\n /// Tightly packed LE sha256 hashes.\n /// @param _root The root of the proof. LE sha256 hash.\n /// @param _index The index of the leaf\n /// @return true if the proof is valid, else false\n function verifyHash256Merkle(\n bytes32 _leaf,\n bytes memory _tree,\n bytes32 _root,\n uint _index\n ) internal view returns (bool) {\n // Not an even number of hashes\n if (_tree.length % 32 != 0) {\n return false;\n }\n\n // Should never occur\n if (_tree.length == 0) {\n return false;\n }\n\n uint _idx = _index;\n bytes32 _current = _leaf;\n\n // i moves in increments of 32\n for (uint i = 0; i < _tree.length; i += 32) {\n if (_idx % 2 == 1) {\n _current = _hash256MerkleStep(_tree.slice32(i), _current);\n } else {\n _current = _hash256MerkleStep(_current, _tree.slice32(i));\n }\n _idx = _idx >> 1;\n }\n return _current == _root;\n }\n\n /*\n NB: https://github.com/bitcoin/bitcoin/blob/78dae8caccd82cfbfd76557f1fb7d7557c7b5edb/src/pow.cpp#L49-L72\n NB: We get a full-bitlength target from this. For comparison with\n header-encoded targets we need to mask it with the header target\n e.g. (full & truncated) == truncated\n */\n /// @notice performs the bitcoin difficulty retarget\n /// @dev implements the Bitcoin algorithm precisely\n /// @param _previousTarget the target of the previous period\n /// @param _firstTimestamp the timestamp of the first block in the difficulty period\n /// @param _secondTimestamp the timestamp of the last block in the difficulty period\n /// @return the new period's target threshold\n function retargetAlgorithm(\n uint256 _previousTarget,\n uint256 _firstTimestamp,\n uint256 _secondTimestamp\n ) internal pure returns (uint256) {\n uint256 _elapsedTime = _secondTimestamp.sub(_firstTimestamp);\n\n // Normalize ratio to factor of 4 if very long or very short\n if (_elapsedTime < RETARGET_PERIOD.div(4)) {\n _elapsedTime = RETARGET_PERIOD.div(4);\n }\n if (_elapsedTime > RETARGET_PERIOD.mul(4)) {\n _elapsedTime = RETARGET_PERIOD.mul(4);\n }\n\n /*\n NB: high targets e.g. ffff0020 can cause overflows here\n so we divide it by 256**2, then multiply by 256**2 later\n we know the target is evenly divisible by 256**2, so this isn't an issue\n */\n\n uint256 _adjusted = _previousTarget.div(65536).mul(_elapsedTime);\n return _adjusted.div(RETARGET_PERIOD).mul(65536);\n }\n}\n"
162
- },
163
- "@openzeppelin/contracts/utils/math/Math.sol": {
164
- "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a >= b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds up instead\n * of rounding down.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a / b + (a % b == 0 ? 0 : 1);\n }\n}\n"
165
- },
166
- "contracts/bridge/BitcoinTx.sol": {
167
- "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\nimport {BytesLib} from \"@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol\";\nimport {ValidateSPV} from \"@keep-network/bitcoin-spv-sol/contracts/ValidateSPV.sol\";\n\nimport \"./BridgeState.sol\";\n\n/// @title Bitcoin transaction\n/// @notice Allows to reference Bitcoin raw transaction in Solidity.\n/// @dev See https://developer.bitcoin.org/reference/transactions.html#raw-transaction-format\n///\n/// Raw Bitcoin transaction data:\n///\n/// | Bytes | Name | BTC type | Description |\n/// |--------|--------------|------------------------|---------------------------|\n/// | 4 | version | int32_t (LE) | TX version number |\n/// | varies | tx_in_count | compactSize uint (LE) | Number of TX inputs |\n/// | varies | tx_in | txIn[] | TX inputs |\n/// | varies | tx_out_count | compactSize uint (LE) | Number of TX outputs |\n/// | varies | tx_out | txOut[] | TX outputs |\n/// | 4 | lock_time | uint32_t (LE) | Unix time or block number |\n///\n//\n/// Non-coinbase transaction input (txIn):\n///\n/// | Bytes | Name | BTC type | Description |\n/// |--------|------------------|------------------------|---------------------------------------------|\n/// | 36 | previous_output | outpoint | The previous outpoint being spent |\n/// | varies | script_bytes | compactSize uint (LE) | The number of bytes in the signature script |\n/// | varies | signature_script | char[] | The signature script, empty for P2WSH |\n/// | 4 | sequence | uint32_t (LE) | Sequence number |\n///\n///\n/// The reference to transaction being spent (outpoint):\n///\n/// | Bytes | Name | BTC type | Description |\n/// |-------|-------|---------------|------------------------------------------|\n/// | 32 | hash | char[32] | Hash of the transaction to spend |\n/// | 4 | index | uint32_t (LE) | Index of the specific output from the TX |\n///\n///\n/// Transaction output (txOut):\n///\n/// | Bytes | Name | BTC type | Description |\n/// |--------|-----------------|-----------------------|--------------------------------------|\n/// | 8 | value | int64_t (LE) | Number of satoshis to spend |\n/// | 1+ | pk_script_bytes | compactSize uint (LE) | Number of bytes in the pubkey script |\n/// | varies | pk_script | char[] | Pubkey script |\n///\n/// compactSize uint format:\n///\n/// | Value | Bytes | Format |\n/// |-----------------------------------------|-------|----------------------------------------------|\n/// | >= 0 && <= 252 | 1 | uint8_t |\n/// | >= 253 && <= 0xffff | 3 | 0xfd followed by the number as uint16_t (LE) |\n/// | >= 0x10000 && <= 0xffffffff | 5 | 0xfe followed by the number as uint32_t (LE) |\n/// | >= 0x100000000 && <= 0xffffffffffffffff | 9 | 0xff followed by the number as uint64_t (LE) |\n///\n/// (*) compactSize uint is often references as VarInt)\n///\n/// Coinbase transaction input (txIn):\n///\n/// | Bytes | Name | BTC type | Description |\n/// |--------|------------------|------------------------|---------------------------------------------|\n/// | 32 | hash | char[32] | A 32-byte 0x0 null (no previous_outpoint) |\n/// | 4 | index | uint32_t (LE) | 0xffffffff (no previous_outpoint) |\n/// | varies | script_bytes | compactSize uint (LE) | The number of bytes in the coinbase script |\n/// | varies | height | char[] | The block height of this block (BIP34) (*) |\n/// | varies | coinbase_script | none | Arbitrary data, max 100 bytes |\n/// | 4 | sequence | uint32_t (LE) | Sequence number\n///\n/// (*) Uses script language: starts with a data-pushing opcode that indicates how many bytes to push to\n/// the stack followed by the block height as a little-endian unsigned integer. This script must be as\n/// short as possible, otherwise it may be rejected. The data-pushing opcode will be 0x03 and the total\n/// size four bytes until block 16,777,216 about 300 years from now.\nlibrary BitcoinTx {\n using BTCUtils for bytes;\n using BTCUtils for uint256;\n using BytesLib for bytes;\n using ValidateSPV for bytes;\n using ValidateSPV for bytes32;\n\n /// @notice Represents Bitcoin transaction data.\n struct Info {\n /// @notice Bitcoin transaction version.\n /// @dev `version` from raw Bitcoin transaction data.\n /// Encoded as 4-bytes signed integer, little endian.\n bytes4 version;\n /// @notice All Bitcoin transaction inputs, prepended by the number of\n /// transaction inputs.\n /// @dev `tx_in_count | tx_in` from raw Bitcoin transaction data.\n ///\n /// The number of transaction inputs encoded as compactSize\n /// unsigned integer, little-endian.\n ///\n /// Note that some popular block explorers reverse the order of\n /// bytes from `outpoint`'s `hash` and display it as big-endian.\n /// Solidity code of Bridge expects hashes in little-endian, just\n /// like they are represented in a raw Bitcoin transaction.\n bytes inputVector;\n /// @notice All Bitcoin transaction outputs prepended by the number of\n /// transaction outputs.\n /// @dev `tx_out_count | tx_out` from raw Bitcoin transaction data.\n ///\n /// The number of transaction outputs encoded as a compactSize\n /// unsigned integer, little-endian.\n bytes outputVector;\n /// @notice Bitcoin transaction locktime.\n ///\n /// @dev `lock_time` from raw Bitcoin transaction data.\n /// Encoded as 4-bytes unsigned integer, little endian.\n bytes4 locktime;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's calldata argument.\n }\n\n /// @notice Represents data needed to perform a Bitcoin SPV proof.\n struct Proof {\n /// @notice The merkle proof of transaction inclusion in a block.\n bytes merkleProof;\n /// @notice Transaction index in the block (0-indexed).\n uint256 txIndexInBlock;\n /// @notice Single byte-string of 80-byte bitcoin headers,\n /// lowest height first.\n bytes bitcoinHeaders;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's calldata argument.\n }\n\n /// @notice Represents info about an unspent transaction output.\n struct UTXO {\n /// @notice Hash of the transaction the output belongs to.\n /// @dev Byte order corresponds to the Bitcoin internal byte order.\n bytes32 txHash;\n /// @notice Index of the transaction output (0-indexed).\n uint32 txOutputIndex;\n /// @notice Value of the transaction output.\n uint64 txOutputValue;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's calldata argument.\n }\n\n /// @notice Represents Bitcoin signature in the R/S/V format.\n struct RSVSignature {\n /// @notice Signature r value.\n bytes32 r;\n /// @notice Signature s value.\n bytes32 s;\n /// @notice Signature recovery value.\n uint8 v;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's calldata argument.\n }\n\n /// @notice Validates the SPV proof of the Bitcoin transaction.\n /// Reverts in case the validation or proof verification fail.\n /// @param txInfo Bitcoin transaction data.\n /// @param proof Bitcoin proof data.\n /// @return txHash Proven 32-byte transaction hash.\n function validateProof(\n BridgeState.Storage storage self,\n Info calldata txInfo,\n Proof calldata proof\n ) internal view returns (bytes32 txHash) {\n require(\n txInfo.inputVector.validateVin(),\n \"Invalid input vector provided\"\n );\n require(\n txInfo.outputVector.validateVout(),\n \"Invalid output vector provided\"\n );\n\n txHash = abi\n .encodePacked(\n txInfo.version,\n txInfo.inputVector,\n txInfo.outputVector,\n txInfo.locktime\n )\n .hash256View();\n\n require(\n txHash.prove(\n proof.bitcoinHeaders.extractMerkleRootLE(),\n proof.merkleProof,\n proof.txIndexInBlock\n ),\n \"Tx merkle proof is not valid for provided header and tx hash\"\n );\n\n evaluateProofDifficulty(self, proof.bitcoinHeaders);\n\n return txHash;\n }\n\n /// @notice Evaluates the given Bitcoin proof difficulty against the actual\n /// Bitcoin chain difficulty provided by the relay oracle.\n /// Reverts in case the evaluation fails.\n /// @param bitcoinHeaders Bitcoin headers chain being part of the SPV\n /// proof. Used to extract the observed proof difficulty.\n function evaluateProofDifficulty(\n BridgeState.Storage storage self,\n bytes memory bitcoinHeaders\n ) internal view {\n IRelay relay = self.relay;\n uint256 currentEpochDifficulty = relay.getCurrentEpochDifficulty();\n uint256 previousEpochDifficulty = relay.getPrevEpochDifficulty();\n\n uint256 requestedDiff = 0;\n uint256 firstHeaderDiff = bitcoinHeaders\n .extractTarget()\n .calculateDifficulty();\n\n if (firstHeaderDiff == currentEpochDifficulty) {\n requestedDiff = currentEpochDifficulty;\n } else if (firstHeaderDiff == previousEpochDifficulty) {\n requestedDiff = previousEpochDifficulty;\n } else {\n revert(\"Not at current or previous difficulty\");\n }\n\n uint256 observedDiff = bitcoinHeaders.validateHeaderChain();\n\n require(\n observedDiff != ValidateSPV.getErrBadLength(),\n \"Invalid length of the headers chain\"\n );\n require(\n observedDiff != ValidateSPV.getErrInvalidChain(),\n \"Invalid headers chain\"\n );\n require(\n observedDiff != ValidateSPV.getErrLowWork(),\n \"Insufficient work in a header\"\n );\n\n require(\n observedDiff >= requestedDiff * self.txProofDifficultyFactor,\n \"Insufficient accumulated difficulty in header chain\"\n );\n }\n\n /// @notice Extracts public key hash from the provided P2PKH or P2WPKH output.\n /// Reverts if the validation fails.\n /// @param output The transaction output.\n /// @return pubKeyHash 20-byte public key hash the output locks funds on.\n /// @dev Requirements:\n /// - The output must be of P2PKH or P2WPKH type and lock the funds\n /// on a 20-byte public key hash.\n function extractPubKeyHash(BridgeState.Storage storage, bytes memory output)\n internal\n view\n returns (bytes20 pubKeyHash)\n {\n bytes memory pubKeyHashBytes = output.extractHash();\n\n require(\n pubKeyHashBytes.length == 20,\n \"Output's public key hash must have 20 bytes\"\n );\n\n pubKeyHash = pubKeyHashBytes.slice20(0);\n\n // We need to make sure that the 20-byte public key hash\n // is actually used in the right context of a P2PKH or P2WPKH\n // output. To do so, we must extract the full script from the output\n // and compare with the expected P2PKH and P2WPKH scripts\n // referring to that 20-byte public key hash. The output consists\n // of an 8-byte value and a variable length script. To extract the\n // script we slice the output starting from 9th byte until the end.\n bytes32 outputScriptKeccak = keccak256(\n output.slice(8, output.length - 8)\n );\n // Build the expected P2PKH script which has the following byte\n // format: <0x1976a914> <20-byte PKH> <0x88ac>. According to\n // https://en.bitcoin.it/wiki/Script#Opcodes this translates to:\n // - 0x19: Byte length of the entire script\n // - 0x76: OP_DUP\n // - 0xa9: OP_HASH160\n // - 0x14: Byte length of the public key hash\n // - 0x88: OP_EQUALVERIFY\n // - 0xac: OP_CHECKSIG\n // which matches the P2PKH structure as per:\n // https://en.bitcoin.it/wiki/Transaction#Pay-to-PubkeyHash\n bytes32 P2PKHScriptKeccak = keccak256(\n abi.encodePacked(hex\"1976a914\", pubKeyHash, hex\"88ac\")\n );\n // Build the expected P2WPKH script which has the following format:\n // <0x160014> <20-byte PKH>. According to\n // https://en.bitcoin.it/wiki/Script#Opcodes this translates to:\n // - 0x16: Byte length of the entire script\n // - 0x00: OP_0\n // - 0x14: Byte length of the public key hash\n // which matches the P2WPKH structure as per:\n // https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#P2WPKH\n bytes32 P2WPKHScriptKeccak = keccak256(\n abi.encodePacked(hex\"160014\", pubKeyHash)\n );\n // Make sure the actual output script matches either the P2PKH\n // or P2WPKH format.\n require(\n outputScriptKeccak == P2PKHScriptKeccak ||\n outputScriptKeccak == P2WPKHScriptKeccak,\n \"Output must be P2PKH or P2WPKH\"\n );\n\n return pubKeyHash;\n }\n}\n"
168
- },
169
- "contracts/bridge/EcdsaLib.sol": {
170
- "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport \"@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol\";\n\nlibrary EcdsaLib {\n using BytesLib for bytes;\n\n /// @notice Converts public key X and Y coordinates (32-byte each) to a\n /// compressed public key (33-byte). Compressed public key is X\n /// coordinate prefixed with `02` or `03` based on the Y coordinate parity.\n /// It is expected that the uncompressed public key is stripped\n /// (i.e. it is not prefixed with `04`).\n /// @param x Wallet's public key's X coordinate.\n /// @param y Wallet's public key's Y coordinate.\n /// @return Compressed public key (33-byte), prefixed with `02` or `03`.\n function compressPublicKey(bytes32 x, bytes32 y)\n internal\n pure\n returns (bytes memory)\n {\n bytes1 prefix;\n if (uint256(y) % 2 == 0) {\n prefix = hex\"02\";\n } else {\n prefix = hex\"03\";\n }\n\n return bytes.concat(prefix, x);\n }\n}\n"
171
- },
172
- "contracts/bridge/BridgeState.sol": {
173
- "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {IWalletRegistry as EcdsaWalletRegistry} from \"@keep-network/ecdsa/contracts/api/IWalletRegistry.sol\";\n\nimport \"./IRelay.sol\";\nimport \"./Deposit.sol\";\nimport \"./Redemption.sol\";\nimport \"./Fraud.sol\";\nimport \"./Wallets.sol\";\nimport \"./MovingFunds.sol\";\n\nimport \"../bank/Bank.sol\";\n\nlibrary BridgeState {\n struct Storage {\n // Address of the Bank the Bridge belongs to.\n Bank bank;\n // Bitcoin relay providing the current Bitcoin network difficulty.\n IRelay relay;\n // ECDSA Wallet Registry contract handle.\n EcdsaWalletRegistry ecdsaWalletRegistry;\n // The number of confirmations on the Bitcoin chain required to\n // successfully evaluate an SPV proof.\n uint256 txProofDifficultyFactor;\n // Address where the deposit and redemption treasury fees will be sent\n // to. Treasury takes part in the operators rewarding process.\n address treasury;\n // The minimal amount that can be requested to deposit.\n // Value of this parameter must take into account the value of\n // `depositTreasuryFeeDivisor` and `depositTxMaxFee` parameters in order\n // to make requests that can incur the treasury and transaction fee and\n // still satisfy the depositor.\n uint64 depositDustThreshold;\n // Divisor used to compute the treasury fee taken from each deposit and\n // transferred to the treasury upon sweep proof submission. That fee is\n // computed as follows:\n // `treasuryFee = depositedAmount / depositTreasuryFeeDivisor`\n // For example, if the treasury fee needs to be 2% of each deposit,\n // the `depositTreasuryFeeDivisor` should be set to `50` because\n // `1/50 = 0.02 = 2%`.\n uint64 depositTreasuryFeeDivisor;\n // Maximum amount of BTC transaction fee that can be incurred by each\n // swept deposit being part of the given sweep transaction. If the\n // maximum BTC transaction fee is exceeded, such transaction is\n // considered a fraud.\n //\n // This is a per-deposit input max fee for the sweep transaction.\n uint64 depositTxMaxFee;\n // Collection of all revealed deposits indexed by\n // `keccak256(fundingTxHash | fundingOutputIndex)`.\n // The `fundingTxHash` is `bytes32` (ordered as in Bitcoin internally)\n // and `fundingOutputIndex` an `uint32`. This mapping may contain valid\n // and invalid deposits and the wallet is responsible for validating\n // them before attempting to execute a sweep.\n mapping(uint256 => Deposit.DepositRequest) deposits;\n // Indicates if the vault with the given address is trusted or not.\n // Depositors can route their revealed deposits only to trusted vaults\n // and have trusted vaults notified about new deposits as soon as these\n // deposits get swept. Vaults not trusted by the Bridge can still be\n // used by Bank balance owners on their own responsibility - anyone can\n // approve their Bank balance to any address.\n mapping(address => bool) isVaultTrusted;\n // Maximum amount of the total BTC transaction fee that is acceptable in\n // a single moving funds transaction.\n //\n // This is a TOTAL max fee for the moving funds transaction. Note\n // that `depositTxMaxFee` is per single deposit and `redemptionTxMaxFee`\n // if per single redemption. `movingFundsTxMaxTotalFee` is a total\n // fee for the entire transaction.\n uint64 movingFundsTxMaxTotalFee;\n // The minimal satoshi amount that makes sense to be transferred during\n // the moving funds process. Moving funds wallets having their BTC\n // balance below that value can begin closing immediately as\n // transferring such a low value may not be possible due to\n // BTC network fees. The value of this parameter must always be lower\n // than `redemptionDustThreshold` in order to prevent redemption requests\n // with values lower or equal to `movingFundsDustThreshold`.\n uint64 movingFundsDustThreshold;\n // Time after which the moving funds timeout can be reset in case the\n // target wallet commitment cannot be submitted due to a lack of live\n // wallets in the system. It is counted from the moment when the wallet\n // was requested to move their funds and switched to the MovingFunds\n // state or from the moment the timeout was reset the last time.\n // Value in seconds. This value should be lower than the value\n // of the `movingFundsTimeout`.\n uint32 movingFundsTimeoutResetDelay;\n // Time after which the moving funds process can be reported as\n // timed out. It is counted from the moment when the wallet\n // was requested to move their funds and switched to the MovingFunds\n // state. Value in seconds.\n uint32 movingFundsTimeout;\n // The amount of stake slashed from each member of a wallet for a moving\n // funds timeout.\n uint96 movingFundsTimeoutSlashingAmount;\n // The percentage of the notifier reward from the staking contract\n // the notifier of a moving funds timeout receives. The value is in the\n // range [0, 100].\n uint256 movingFundsTimeoutNotifierRewardMultiplier;\n // Maximum amount of the total BTC transaction fee that is acceptable in\n // a single moved funds sweep transaction.\n //\n // This is a TOTAL max fee for the moved funds sweep transaction. Note\n // that `depositTxMaxFee` is per single deposit and `redemptionTxMaxFee`\n // if per single redemption. `movedFundsSweepTxMaxTotalFee` is a total\n // fee for the entire transaction.\n uint64 movedFundsSweepTxMaxTotalFee;\n // Time after which the moved funds sweep process can be reported as\n // timed out. It is counted from the moment when the recipient wallet\n // was requested to sweep the received funds. Value in seconds.\n uint32 movedFundsSweepTimeout;\n // The amount of stake slashed from each member of a wallet for a moved\n // funds sweep timeout.\n uint96 movedFundsSweepTimeoutSlashingAmount;\n // The percentage of the notifier reward from the staking contract\n // the notifier of a moved funds sweep timeout receives. The value is\n // in the range [0, 100].\n uint256 movedFundsSweepTimeoutNotifierRewardMultiplier;\n // Collection of all moved funds sweep requests indexed by\n // `keccak256(movingFundsTxHash | movingFundsOutputIndex)`.\n // The `movingFundsTxHash` is `bytes32` (ordered as in Bitcoin\n // internally) and `movingFundsOutputIndex` an `uint32`. Each entry\n // is actually an UTXO representing the moved funds and is supposed\n // to be swept with the current main UTXO of the recipient wallet.\n mapping(uint256 => MovingFunds.MovedFundsSweepRequest) movedFundsSweepRequests;\n // The minimal amount that can be requested for redemption.\n // Value of this parameter must take into account the value of\n // `redemptionTreasuryFeeDivisor` and `redemptionTxMaxFee`\n // parameters in order to make requests that can incur the\n // treasury and transaction fee and still satisfy the redeemer.\n // Additionally, the value of this parameter must always be greater\n // than `movingFundsDustThreshold` in order to prevent redemption\n // requests with values lower or equal to `movingFundsDustThreshold`.\n uint64 redemptionDustThreshold;\n // Divisor used to compute the treasury fee taken from each\n // redemption request and transferred to the treasury upon\n // successful request finalization. That fee is computed as follows:\n // `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`\n // For example, if the treasury fee needs to be 2% of each\n // redemption request, the `redemptionTreasuryFeeDivisor` should\n // be set to `50` because `1/50 = 0.02 = 2%`.\n uint64 redemptionTreasuryFeeDivisor;\n // Maximum amount of BTC transaction fee that can be incurred by\n // each redemption request being part of the given redemption\n // transaction. If the maximum BTC transaction fee is exceeded, such\n // transaction is considered a fraud.\n //\n // This is a per-redemption output max fee for the redemption\n // transaction.\n uint64 redemptionTxMaxFee;\n // Time after which the redemption request can be reported as\n // timed out. It is counted from the moment when the redemption\n // request was created via `requestRedemption` call. Reported\n // timed out requests are cancelled and locked TBTC is returned\n // to the redeemer in full amount.\n uint256 redemptionTimeout;\n // The amount of stake slashed from each member of a wallet for a\n // redemption timeout.\n uint96 redemptionTimeoutSlashingAmount;\n // The percentage of the notifier reward from the staking contract\n // the notifier of a redemption timeout receives. The value is in the\n // range [0, 100].\n uint256 redemptionTimeoutNotifierRewardMultiplier;\n // Collection of all pending redemption requests indexed by\n // redemption key built as\n // `keccak256(walletPubKeyHash | redeemerOutputScript)`.\n // The `walletPubKeyHash` is the 20-byte wallet's public key hash\n // (computed using Bitcoin HASH160 over the compressed ECDSA\n // public key) and `redeemerOutputScript` is a Bitcoin script\n // (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock\n // redeemed BTC as requested by the redeemer. Requests are added\n // to this mapping by the `requestRedemption` method (duplicates\n // not allowed) and are removed by one of the following methods:\n // - `submitRedemptionProof` in case the request was handled\n // successfully,\n // - `notifyRedemptionTimeout` in case the request was reported\n // to be timed out.\n mapping(uint256 => Redemption.RedemptionRequest) pendingRedemptions;\n // Collection of all timed out redemptions requests indexed by\n // redemption key built as\n // `keccak256(walletPubKeyHash | redeemerOutputScript)`. The\n // `walletPubKeyHash` is the 20-byte wallet's public key hash\n // (computed using Bitcoin HASH160 over the compressed ECDSA\n // public key) and `redeemerOutputScript` is the Bitcoin script\n // (P2PKH, P2WPKH, P2SH or P2WSH) that is involved in the timed\n // out request. Timed out requests are stored in this mapping to\n // avoid slashing the wallets multiple times for the same timeout.\n // Only one method can add to this mapping:\n // - `notifyRedemptionTimeout` which puts the redemption key to this\n // mapping basing on a timed out request stored previously in\n // `pendingRedemptions` mapping.\n mapping(uint256 => Redemption.RedemptionRequest) timedOutRedemptions;\n // The amount of ETH in wei the party challenging the wallet for fraud\n // needs to deposit.\n uint256 fraudChallengeDepositAmount;\n // The amount of time the wallet has to defeat a fraud challenge.\n uint256 fraudChallengeDefeatTimeout;\n // The amount of stake slashed from each member of a wallet for a fraud.\n uint96 fraudSlashingAmount;\n // The percentage of the notifier reward from the staking contract\n // the notifier of a fraud receives. The value is in the range [0, 100].\n uint256 fraudNotifierRewardMultiplier;\n // Collection of all submitted fraud challenges indexed by challenge\n // key built as `keccak256(walletPublicKey|sighash)`.\n mapping(uint256 => Fraud.FraudChallenge) fraudChallenges;\n // Collection of main UTXOs that are honestly spent indexed by\n // `keccak256(fundingTxHash | fundingOutputIndex)`. The `fundingTxHash`\n // is `bytes32` (ordered as in Bitcoin internally) and\n // `fundingOutputIndex` an `uint32`. A main UTXO is considered honestly\n // spent if it was used as an input of a transaction that have been\n // proven in the Bridge.\n mapping(uint256 => bool) spentMainUTXOs;\n // Determines how frequently a new wallet creation can be requested.\n // Value in seconds.\n uint32 walletCreationPeriod;\n // The minimum BTC threshold in satoshi that is used to decide about\n // wallet creation. Specifically, we allow for the creation of a new\n // wallet if the active wallet is old enough and their amount of BTC\n // is greater than or equal this threshold.\n uint64 walletCreationMinBtcBalance;\n // The maximum BTC threshold in satoshi that is used to decide about\n // wallet creation. Specifically, we allow for the creation of a new\n // wallet if the active wallet's amount of BTC is greater than or equal\n // this threshold, regardless of the active wallet's age.\n uint64 walletCreationMaxBtcBalance;\n // The minimum BTC threshold in satoshi that is used to decide about\n // wallet closing. Specifically, we allow for the closure of the given\n // wallet if their amount of BTC is lesser than this threshold,\n // regardless of the wallet's age.\n uint64 walletClosureMinBtcBalance;\n // The maximum age of a wallet in seconds, after which the wallet\n // moving funds process can be requested.\n uint32 walletMaxAge;\n // 20-byte wallet public key hash being reference to the currently\n // active wallet. Can be unset to the zero value under certain\n // circumstances.\n bytes20 activeWalletPubKeyHash;\n // The current number of wallets in the Live state.\n uint32 liveWalletsCount;\n // The maximum BTC amount in satoshi than can be transferred to a single\n // target wallet during the moving funds process.\n uint64 walletMaxBtcTransfer;\n // Determines the length of the wallet closing period, i.e. the period\n // when the wallet remains in the Closing state and can be subject\n // of deposit fraud challenges. This value is in seconds and should be\n // greater than the deposit refund time plus some time margin.\n uint32 walletClosingPeriod;\n // Maps the 20-byte wallet public key hash (computed using Bitcoin\n // HASH160 over the compressed ECDSA public key) to the basic wallet\n // information like state and pending redemptions value.\n mapping(bytes20 => Wallets.Wallet) registeredWallets;\n // Reserved storage space in case we need to add more variables.\n // The convention from OpenZeppelin suggests the storage space should\n // add up to 50 slots. Here we want to have more slots as there are\n // planned upgrades of the Bridge contract. If more entires are added to\n // the struct in the upcoming versions we need to reduce the array size.\n // See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n // slither-disable-next-line unused-state\n uint256[50] __gap;\n }\n\n event DepositParametersUpdated(\n uint64 depositDustThreshold,\n uint64 depositTreasuryFeeDivisor,\n uint64 depositTxMaxFee\n );\n\n event RedemptionParametersUpdated(\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint256 redemptionTimeout,\n uint96 redemptionTimeoutSlashingAmount,\n uint256 redemptionTimeoutNotifierRewardMultiplier\n );\n\n event MovingFundsParametersUpdated(\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeoutResetDelay,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint256 movingFundsTimeoutNotifierRewardMultiplier,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint256 movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n\n event WalletParametersUpdated(\n uint32 walletCreationPeriod,\n uint64 walletCreationMinBtcBalance,\n uint64 walletCreationMaxBtcBalance,\n uint64 walletClosureMinBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n );\n\n event FraudParametersUpdated(\n uint256 fraudChallengeDepositAmount,\n uint256 fraudChallengeDefeatTimeout,\n uint96 fraudSlashingAmount,\n uint256 fraudNotifierRewardMultiplier\n );\n\n /// @notice Updates parameters of deposits.\n /// @param _depositDustThreshold New value of the deposit dust threshold in\n /// satoshis. It is the minimal amount that can be requested to\n //// deposit. Value of this parameter must take into account the value\n /// of `depositTreasuryFeeDivisor` and `depositTxMaxFee` parameters\n /// in order to make requests that can incur the treasury and\n /// transaction fee and still satisfy the depositor.\n /// @param _depositTreasuryFeeDivisor New value of the treasury fee divisor.\n /// It is the divisor used to compute the treasury fee taken from\n /// each deposit and transferred to the treasury upon sweep proof\n /// submission. That fee is computed as follows:\n /// `treasuryFee = depositedAmount / depositTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each deposit,\n /// the `depositTreasuryFeeDivisor` should be set to `50`\n /// because `1/50 = 0.02 = 2%`.\n /// @param _depositTxMaxFee New value of the deposit tx max fee in satoshis.\n /// It is the maximum amount of BTC transaction fee that can\n /// be incurred by each swept deposit being part of the given sweep\n /// transaction. If the maximum BTC transaction fee is exceeded,\n /// such transaction is considered a fraud.\n /// @dev Requirements:\n /// - Deposit dust threshold must be greater than zero,\n /// - Deposit treasury fee divisor must be greater than zero,\n /// - Deposit transaction max fee must be greater than zero.\n function updateDepositParameters(\n Storage storage self,\n uint64 _depositDustThreshold,\n uint64 _depositTreasuryFeeDivisor,\n uint64 _depositTxMaxFee\n ) internal {\n require(\n _depositDustThreshold > 0,\n \"Deposit dust threshold must be greater than zero\"\n );\n\n require(\n _depositTreasuryFeeDivisor > 0,\n \"Deposit treasury fee divisor must be greater than zero\"\n );\n\n require(\n _depositTxMaxFee > 0,\n \"Deposit transaction max fee must be greater than zero\"\n );\n\n self.depositDustThreshold = _depositDustThreshold;\n self.depositTreasuryFeeDivisor = _depositTreasuryFeeDivisor;\n self.depositTxMaxFee = _depositTxMaxFee;\n\n emit DepositParametersUpdated(\n _depositDustThreshold,\n _depositTreasuryFeeDivisor,\n _depositTxMaxFee\n );\n }\n\n /// @notice Updates parameters of redemptions.\n /// @param _redemptionDustThreshold New value of the redemption dust\n /// threshold in satoshis. It is the minimal amount that can be\n /// requested for redemption. Value of this parameter must take into\n /// account the value of `redemptionTreasuryFeeDivisor` and\n /// `redemptionTxMaxFee` parameters in order to make requests that\n /// can incur the treasury and transaction fee and still satisfy the\n /// redeemer.\n /// @param _redemptionTreasuryFeeDivisor New value of the redemption\n /// treasury fee divisor. It is the divisor used to compute the\n /// treasury fee taken from each redemption request and transferred\n /// to the treasury upon successful request finalization. That fee is\n /// computed as follows:\n /// `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each\n /// redemption request, the `redemptionTreasuryFeeDivisor` should\n /// be set to `50` because `1/50 = 0.02 = 2%`.\n /// @param _redemptionTxMaxFee New value of the redemption transaction max\n /// fee in satoshis. It is the maximum amount of BTC transaction fee\n /// that can be incurred by each redemption request being part of the\n /// given redemption transaction. If the maximum BTC transaction fee\n /// is exceeded, such transaction is considered a fraud.\n /// This is a per-redemption output max fee for the redemption\n /// transaction.\n /// @param _redemptionTimeout New value of the redemption timeout in seconds.\n /// It is the time after which the redemption request can be reported\n /// as timed out. It is counted from the moment when the redemption\n /// request was created via `requestRedemption` call. Reported timed\n /// out requests are cancelled and locked TBTC is returned to the\n /// redeemer in full amount.\n /// @param _redemptionTimeoutSlashingAmount New value of the redemption\n /// timeout slashing amount in T, it is the amount slashed from each\n /// wallet member for redemption timeout.\n /// @param _redemptionTimeoutNotifierRewardMultiplier New value of the\n /// redemption timeout notifier reward multiplier as percentage,\n /// it determines the percentage of the notifier reward from the\n /// staking contact the notifier of a redemption timeout receives.\n /// The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Redemption dust threshold must be greater than moving funds dust\n /// threshold,\n /// - Redemption treasury fee divisor must be greater than zero,\n /// - Redemption transaction max fee must be greater than zero,\n /// - Redemption timeout must be greater than zero,\n /// - Redemption timeout notifier reward multiplier must be in the\n /// range [0, 100].\n function updateRedemptionParameters(\n Storage storage self,\n uint64 _redemptionDustThreshold,\n uint64 _redemptionTreasuryFeeDivisor,\n uint64 _redemptionTxMaxFee,\n uint256 _redemptionTimeout,\n uint96 _redemptionTimeoutSlashingAmount,\n uint256 _redemptionTimeoutNotifierRewardMultiplier\n ) internal {\n require(\n _redemptionDustThreshold > self.movingFundsDustThreshold,\n \"Redemption dust threshold must be greater than moving funds dust threshold\"\n );\n\n require(\n _redemptionTreasuryFeeDivisor > 0,\n \"Redemption treasury fee divisor must be greater than zero\"\n );\n\n require(\n _redemptionTxMaxFee > 0,\n \"Redemption transaction max fee must be greater than zero\"\n );\n\n require(\n _redemptionTimeout > 0,\n \"Redemption timeout must be greater than zero\"\n );\n\n require(\n _redemptionTimeoutNotifierRewardMultiplier <= 100,\n \"Redemption timeout notifier reward multiplier must be in the range [0, 100]\"\n );\n\n self.redemptionDustThreshold = _redemptionDustThreshold;\n self.redemptionTreasuryFeeDivisor = _redemptionTreasuryFeeDivisor;\n self.redemptionTxMaxFee = _redemptionTxMaxFee;\n self.redemptionTimeout = _redemptionTimeout;\n self.redemptionTimeoutSlashingAmount = _redemptionTimeoutSlashingAmount;\n self\n .redemptionTimeoutNotifierRewardMultiplier = _redemptionTimeoutNotifierRewardMultiplier;\n\n emit RedemptionParametersUpdated(\n _redemptionDustThreshold,\n _redemptionTreasuryFeeDivisor,\n _redemptionTxMaxFee,\n _redemptionTimeout,\n _redemptionTimeoutSlashingAmount,\n _redemptionTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Updates parameters of moving funds.\n /// @param _movingFundsTxMaxTotalFee New value of the moving funds transaction\n /// max total fee in satoshis. It is the maximum amount of the total\n /// BTC transaction fee that is acceptable in a single moving funds\n /// transaction. This is a _total_ max fee for the entire moving\n /// funds transaction.\n /// @param _movingFundsDustThreshold New value of the moving funds dust\n /// threshold. It is the minimal satoshi amount that makes sense to\n /// be transferred during the moving funds process. Moving funds\n /// wallets having their BTC balance below that value can begin\n /// closing immediately as transferring such a low value may not be\n /// possible due to BTC network fees.\n /// @param _movingFundsTimeoutResetDelay New value of the moving funds\n /// timeout reset delay in seconds. It is the time after which the\n /// moving funds timeout can be reset in case the target wallet\n /// commitment cannot be submitted due to a lack of live wallets\n /// in the system. It is counted from the moment when the wallet\n /// was requested to move their funds and switched to the MovingFunds\n /// state or from the moment the timeout was reset the last time.\n /// @param _movingFundsTimeout New value of the moving funds timeout in\n /// seconds. It is the time after which the moving funds process can\n /// be reported as timed out. It is counted from the moment when the\n /// wallet was requested to move their funds and switched to the\n /// MovingFunds state.\n /// @param _movingFundsTimeoutSlashingAmount New value of the moving funds\n /// timeout slashing amount in T, it is the amount slashed from each\n /// wallet member for moving funds timeout.\n /// @param _movingFundsTimeoutNotifierRewardMultiplier New value of the\n /// moving funds timeout notifier reward multiplier as percentage,\n /// it determines the percentage of the notifier reward from the\n /// staking contact the notifier of a moving funds timeout receives.\n /// The value must be in the range [0, 100].\n /// @param _movedFundsSweepTxMaxTotalFee New value of the moved funds sweep\n /// transaction max total fee in satoshis. It is the maximum amount\n /// of the total BTC transaction fee that is acceptable in a single\n /// moved funds sweep transaction. This is a _total_ max fee for the\n /// entire moved funds sweep transaction.\n /// @param _movedFundsSweepTimeout New value of the moved funds sweep\n /// timeout in seconds. It is the time after which the moved funds\n /// sweep process can be reported as timed out. It is counted from\n /// the moment when the wallet was requested to sweep the received\n /// funds.\n /// @param _movedFundsSweepTimeoutSlashingAmount New value of the moved\n /// funds sweep timeout slashing amount in T, it is the amount\n /// slashed from each wallet member for moved funds sweep timeout.\n /// @param _movedFundsSweepTimeoutNotifierRewardMultiplier New value of\n /// the moved funds sweep timeout notifier reward multiplier as\n /// percentage, it determines the percentage of the notifier reward\n /// from the staking contact the notifier of a moved funds sweep\n /// timeout receives. The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Moving funds transaction max total fee must be greater than zero,\n /// - Moving funds dust threshold must be greater than zero and lower\n /// than the redemption dust threshold,\n /// - Moving funds timeout reset delay must be greater than zero,\n /// - Moving funds timeout must be greater than the moving funds\n /// timeout reset delay,\n /// - Moving funds timeout notifier reward multiplier must be in the\n /// range [0, 100],\n /// - Moved funds sweep transaction max total fee must be greater than zero,\n /// - Moved funds sweep timeout must be greater than zero,\n /// - Moved funds sweep timeout notifier reward multiplier must be in the\n /// range [0, 100].\n function updateMovingFundsParameters(\n Storage storage self,\n uint64 _movingFundsTxMaxTotalFee,\n uint64 _movingFundsDustThreshold,\n uint32 _movingFundsTimeoutResetDelay,\n uint32 _movingFundsTimeout,\n uint96 _movingFundsTimeoutSlashingAmount,\n uint256 _movingFundsTimeoutNotifierRewardMultiplier,\n uint64 _movedFundsSweepTxMaxTotalFee,\n uint32 _movedFundsSweepTimeout,\n uint96 _movedFundsSweepTimeoutSlashingAmount,\n uint256 _movedFundsSweepTimeoutNotifierRewardMultiplier\n ) internal {\n require(\n _movingFundsTxMaxTotalFee > 0,\n \"Moving funds transaction max total fee must be greater than zero\"\n );\n\n require(\n _movingFundsDustThreshold > 0 &&\n _movingFundsDustThreshold < self.redemptionDustThreshold,\n \"Moving funds dust threshold must be greater than zero and lower than redemption dust threshold\"\n );\n\n require(\n _movingFundsTimeoutResetDelay > 0,\n \"Moving funds timeout reset delay must be greater than zero\"\n );\n\n require(\n _movingFundsTimeout > _movingFundsTimeoutResetDelay,\n \"Moving funds timeout must be greater than its reset delay\"\n );\n\n require(\n _movingFundsTimeoutNotifierRewardMultiplier <= 100,\n \"Moving funds timeout notifier reward multiplier must be in the range [0, 100]\"\n );\n\n require(\n _movedFundsSweepTxMaxTotalFee > 0,\n \"Moved funds sweep transaction max total fee must be greater than zero\"\n );\n\n require(\n _movedFundsSweepTimeout > 0,\n \"Moved funds sweep timeout must be greater than zero\"\n );\n\n require(\n _movedFundsSweepTimeoutNotifierRewardMultiplier <= 100,\n \"Moved funds sweep timeout notifier reward multiplier must be in the range [0, 100]\"\n );\n\n self.movingFundsTxMaxTotalFee = _movingFundsTxMaxTotalFee;\n self.movingFundsDustThreshold = _movingFundsDustThreshold;\n self.movingFundsTimeoutResetDelay = _movingFundsTimeoutResetDelay;\n self.movingFundsTimeout = _movingFundsTimeout;\n self\n .movingFundsTimeoutSlashingAmount = _movingFundsTimeoutSlashingAmount;\n self\n .movingFundsTimeoutNotifierRewardMultiplier = _movingFundsTimeoutNotifierRewardMultiplier;\n self.movedFundsSweepTxMaxTotalFee = _movedFundsSweepTxMaxTotalFee;\n self.movedFundsSweepTimeout = _movedFundsSweepTimeout;\n self\n .movedFundsSweepTimeoutSlashingAmount = _movedFundsSweepTimeoutSlashingAmount;\n self\n .movedFundsSweepTimeoutNotifierRewardMultiplier = _movedFundsSweepTimeoutNotifierRewardMultiplier;\n\n emit MovingFundsParametersUpdated(\n _movingFundsTxMaxTotalFee,\n _movingFundsDustThreshold,\n _movingFundsTimeoutResetDelay,\n _movingFundsTimeout,\n _movingFundsTimeoutSlashingAmount,\n _movingFundsTimeoutNotifierRewardMultiplier,\n _movedFundsSweepTxMaxTotalFee,\n _movedFundsSweepTimeout,\n _movedFundsSweepTimeoutSlashingAmount,\n _movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Updates parameters of wallets.\n /// @param _walletCreationPeriod New value of the wallet creation period in\n /// seconds, determines how frequently a new wallet creation can be\n /// requested.\n /// @param _walletCreationMinBtcBalance New value of the wallet minimum BTC\n /// balance in satoshi, used to decide about wallet creation.\n /// @param _walletCreationMaxBtcBalance New value of the wallet maximum BTC\n /// balance in satoshi, used to decide about wallet creation.\n /// @param _walletClosureMinBtcBalance New value of the wallet minimum BTC\n /// balance in satoshi, used to decide about wallet closure.\n /// @param _walletMaxAge New value of the wallet maximum age in seconds,\n /// indicates the maximum age of a wallet in seconds, after which\n /// the wallet moving funds process can be requested.\n /// @param _walletMaxBtcTransfer New value of the wallet maximum BTC transfer\n /// in satoshi, determines the maximum amount that can be transferred\n /// to a single target wallet during the moving funds process.\n /// @param _walletClosingPeriod New value of the wallet closing period in\n /// seconds, determines the length of the wallet closing period,\n // i.e. the period when the wallet remains in the Closing state\n // and can be subject of deposit fraud challenges.\n /// @dev Requirements:\n /// - Wallet minimum BTC balance must be greater than zero,\n /// - Wallet maximum BTC balance must be greater than the wallet\n /// minimum BTC balance,\n /// - Wallet maximum BTC transfer must be greater than zero,\n /// - Wallet closing period must be greater than zero.\n function updateWalletParameters(\n Storage storage self,\n uint32 _walletCreationPeriod,\n uint64 _walletCreationMinBtcBalance,\n uint64 _walletCreationMaxBtcBalance,\n uint64 _walletClosureMinBtcBalance,\n uint32 _walletMaxAge,\n uint64 _walletMaxBtcTransfer,\n uint32 _walletClosingPeriod\n ) internal {\n require(\n _walletCreationMaxBtcBalance > _walletCreationMinBtcBalance,\n \"Wallet creation maximum BTC balance must be greater than the creation minimum BTC balance\"\n );\n require(\n _walletClosureMinBtcBalance > 0,\n \"Wallet closure minimum BTC balance must be greater than zero\"\n );\n require(\n _walletMaxBtcTransfer > 0,\n \"Wallet maximum BTC transfer must be greater than zero\"\n );\n require(\n _walletClosingPeriod > 0,\n \"Wallet closing period must be greater than zero\"\n );\n\n self.walletCreationPeriod = _walletCreationPeriod;\n self.walletCreationMinBtcBalance = _walletCreationMinBtcBalance;\n self.walletCreationMaxBtcBalance = _walletCreationMaxBtcBalance;\n self.walletClosureMinBtcBalance = _walletClosureMinBtcBalance;\n self.walletMaxAge = _walletMaxAge;\n self.walletMaxBtcTransfer = _walletMaxBtcTransfer;\n self.walletClosingPeriod = _walletClosingPeriod;\n\n emit WalletParametersUpdated(\n _walletCreationPeriod,\n _walletCreationMinBtcBalance,\n _walletCreationMaxBtcBalance,\n _walletClosureMinBtcBalance,\n _walletMaxAge,\n _walletMaxBtcTransfer,\n _walletClosingPeriod\n );\n }\n\n /// @notice Updates parameters related to frauds.\n /// @param _fraudChallengeDepositAmount New value of the fraud challenge\n /// deposit amount in wei, it is the amount of ETH the party\n /// challenging the wallet for fraud needs to deposit.\n /// @param _fraudChallengeDefeatTimeout New value of the challenge defeat\n /// timeout in seconds, it is the amount of time the wallet has to\n /// defeat a fraud challenge. The value must be greater than zero.\n /// @param _fraudSlashingAmount New value of the fraud slashing amount in T,\n /// it is the amount slashed from each wallet member for committing\n /// a fraud.\n /// @param _fraudNotifierRewardMultiplier New value of the fraud notifier\n /// reward multiplier as percentage, it determines the percentage of\n /// the notifier reward from the staking contact the notifier of\n /// a fraud receives. The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Fraud challenge defeat timeout must be greater than 0,\n /// - Fraud notifier reward multiplier must be in the range [0, 100].\n function updateFraudParameters(\n Storage storage self,\n uint256 _fraudChallengeDepositAmount,\n uint256 _fraudChallengeDefeatTimeout,\n uint96 _fraudSlashingAmount,\n uint256 _fraudNotifierRewardMultiplier\n ) internal {\n require(\n _fraudChallengeDefeatTimeout > 0,\n \"Fraud challenge defeat timeout must be greater than zero\"\n );\n\n require(\n _fraudNotifierRewardMultiplier <= 100,\n \"Fraud notifier reward multiplier must be in the range [0, 100]\"\n );\n\n self.fraudChallengeDepositAmount = _fraudChallengeDepositAmount;\n self.fraudChallengeDefeatTimeout = _fraudChallengeDefeatTimeout;\n self.fraudSlashingAmount = _fraudSlashingAmount;\n self.fraudNotifierRewardMultiplier = _fraudNotifierRewardMultiplier;\n\n emit FraudParametersUpdated(\n _fraudChallengeDepositAmount,\n _fraudChallengeDefeatTimeout,\n _fraudSlashingAmount,\n _fraudNotifierRewardMultiplier\n );\n }\n}\n"
174
- },
175
- "@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol": {
176
- "content": "pragma solidity ^0.8.4;\n\n/*\n\nhttps://github.com/GNSPS/solidity-bytes-utils/\n\nThis is free and unencumbered software released into the public domain.\n\nAnyone is free to copy, modify, publish, use, compile, sell, or\ndistribute this software, either in source code form or as a compiled\nbinary, for any purpose, commercial or non-commercial, and by any\nmeans.\n\nIn jurisdictions that recognize copyright laws, the author or authors\nof this software dedicate any and all copyright interest in the\nsoftware to the public domain. We make this dedication for the benefit\nof the public at large and to the detriment of our heirs and\nsuccessors. We intend this dedication to be an overt act of\nrelinquishment in perpetuity of all present and future rights to this\nsoftware under copyright law.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\nOTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n\nFor more information, please refer to <https://unlicense.org>\n*/\n\n\n/** @title BytesLib **/\n/** @author https://github.com/GNSPS **/\n\nlibrary BytesLib {\n function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) {\n bytes memory tempBytes;\n\n assembly {\n // Get a location of some free memory and store it in tempBytes as\n // Solidity does for memory variables.\n tempBytes := mload(0x40)\n\n // Store the length of the first bytes array at the beginning of\n // the memory for tempBytes.\n let length := mload(_preBytes)\n mstore(tempBytes, length)\n\n // Maintain a memory counter for the current write location in the\n // temp bytes array by adding the 32 bytes for the array length to\n // the starting location.\n let mc := add(tempBytes, 0x20)\n // Stop copying when the memory counter reaches the length of the\n // first bytes array.\n let end := add(mc, length)\n\n for {\n // Initialize a copy counter to the start of the _preBytes data,\n // 32 bytes into its memory.\n let cc := add(_preBytes, 0x20)\n } lt(mc, end) {\n // Increase both counters by 32 bytes each iteration.\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n // Write the _preBytes data into the tempBytes memory 32 bytes\n // at a time.\n mstore(mc, mload(cc))\n }\n\n // Add the length of _postBytes to the current length of tempBytes\n // and store it as the new length in the first 32 bytes of the\n // tempBytes memory.\n length := mload(_postBytes)\n mstore(tempBytes, add(length, mload(tempBytes)))\n\n // Move the memory counter back from a multiple of 0x20 to the\n // actual end of the _preBytes data.\n mc := end\n // Stop copying when the memory counter reaches the new combined\n // length of the arrays.\n end := add(mc, length)\n\n for {\n let cc := add(_postBytes, 0x20)\n } lt(mc, end) {\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n mstore(mc, mload(cc))\n }\n\n // Update the free-memory pointer by padding our last write location\n // to 32 bytes: add 31 bytes to the end of tempBytes to move to the\n // next 32 byte block, then round down to the nearest multiple of\n // 32. If the sum of the length of the two arrays is zero then add\n // one before rounding down to leave a blank 32 bytes (the length block with 0).\n mstore(0x40, and(\n add(add(end, iszero(add(length, mload(_preBytes)))), 31),\n not(31) // Round down to the nearest 32 bytes.\n ))\n }\n\n return tempBytes;\n }\n\n function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {\n assembly {\n // Read the first 32 bytes of _preBytes storage, which is the length\n // of the array. (We don't need to use the offset into the slot\n // because arrays use the entire slot.)\n let fslot := sload(_preBytes.slot)\n // Arrays of 31 bytes or less have an even value in their slot,\n // while longer arrays have an odd value. The actual length is\n // the slot divided by two for odd values, and the lowest order\n // byte divided by two for even values.\n // If the slot is even, bitwise and the slot with 255 and divide by\n // two to get the length. If the slot is odd, bitwise and the slot\n // with -1 and divide by two.\n let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)\n let mlength := mload(_postBytes)\n let newlength := add(slength, mlength)\n // slength can contain both the length and contents of the array\n // if length < 32 bytes so let's prepare for that\n // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage\n switch add(lt(slength, 32), lt(newlength, 32))\n case 2 {\n // Since the new array still fits in the slot, we just need to\n // update the contents of the slot.\n // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length\n sstore(\n _preBytes.slot,\n // all the modifications to the slot are inside this\n // next block\n add(\n // we can just add to the slot contents because the\n // bytes we want to change are the LSBs\n fslot,\n add(\n mul(\n div(\n // load the bytes from memory\n mload(add(_postBytes, 0x20)),\n // zero all bytes to the right\n exp(0x100, sub(32, mlength))\n ),\n // and now shift left the number of bytes to\n // leave space for the length in the slot\n exp(0x100, sub(32, newlength))\n ),\n // increase length by the double of the memory\n // bytes length\n mul(mlength, 2)\n )\n )\n )\n }\n case 1 {\n // The stored value fits in the slot, but the combined value\n // will exceed it.\n // get the keccak hash to get the contents of the array\n mstore(0x0, _preBytes.slot)\n let sc := add(keccak256(0x0, 0x20), div(slength, 32))\n\n // save new length\n sstore(_preBytes.slot, add(mul(newlength, 2), 1))\n\n // The contents of the _postBytes array start 32 bytes into\n // the structure. Our first read should obtain the `submod`\n // bytes that can fit into the unused space in the last word\n // of the stored array. To get this, we read 32 bytes starting\n // from `submod`, so the data we read overlaps with the array\n // contents by `submod` bytes. Masking the lowest-order\n // `submod` bytes allows us to add that value directly to the\n // stored value.\n\n let submod := sub(32, slength)\n let mc := add(_postBytes, submod)\n let end := add(_postBytes, mlength)\n let mask := sub(exp(0x100, submod), 1)\n\n sstore(\n sc,\n add(\n and(\n fslot,\n 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00\n ),\n and(mload(mc), mask)\n )\n )\n\n for {\n mc := add(mc, 0x20)\n sc := add(sc, 1)\n } lt(mc, end) {\n sc := add(sc, 1)\n mc := add(mc, 0x20)\n } {\n sstore(sc, mload(mc))\n }\n\n mask := exp(0x100, sub(mc, end))\n\n sstore(sc, mul(div(mload(mc), mask), mask))\n }\n default {\n // get the keccak hash to get the contents of the array\n mstore(0x0, _preBytes.slot)\n // Start copying to the last used word of the stored array.\n let sc := add(keccak256(0x0, 0x20), div(slength, 32))\n\n // save new length\n sstore(_preBytes.slot, add(mul(newlength, 2), 1))\n\n // Copy over the first `submod` bytes of the new data as in\n // case 1 above.\n let slengthmod := mod(slength, 32)\n let mlengthmod := mod(mlength, 32)\n let submod := sub(32, slengthmod)\n let mc := add(_postBytes, submod)\n let end := add(_postBytes, mlength)\n let mask := sub(exp(0x100, submod), 1)\n\n sstore(sc, add(sload(sc), and(mload(mc), mask)))\n\n for {\n sc := add(sc, 1)\n mc := add(mc, 0x20)\n } lt(mc, end) {\n sc := add(sc, 1)\n mc := add(mc, 0x20)\n } {\n sstore(sc, mload(mc))\n }\n\n mask := exp(0x100, sub(mc, end))\n\n sstore(sc, mul(div(mload(mc), mask), mask))\n }\n }\n }\n\n function slice(bytes memory _bytes, uint _start, uint _length) internal pure returns (bytes memory res) {\n if (_length == 0) {\n return hex\"\";\n }\n uint _end = _start + _length;\n require(_end > _start && _bytes.length >= _end, \"Slice out of bounds\");\n\n assembly {\n // Alloc bytes array with additional 32 bytes afterspace and assign it's size\n res := mload(0x40)\n mstore(0x40, add(add(res, 64), _length))\n mstore(res, _length)\n\n // Compute distance between source and destination pointers\n let diff := sub(res, add(_bytes, _start))\n\n for {\n let src := add(add(_bytes, 32), _start)\n let end := add(src, _length)\n } lt(src, end) {\n src := add(src, 32)\n } {\n mstore(add(src, diff), mload(src))\n }\n }\n }\n\n /// @notice Take a slice of the byte array, overwriting the destination.\n /// The length of the slice will equal the length of the destination array.\n /// @dev Make sure the destination array has afterspace if required.\n /// @param _bytes The source array\n /// @param _dest The destination array.\n /// @param _start The location to start in the source array.\n function sliceInPlace(\n bytes memory _bytes,\n bytes memory _dest,\n uint _start\n ) internal pure {\n uint _length = _dest.length;\n uint _end = _start + _length;\n require(_end > _start && _bytes.length >= _end, \"Slice out of bounds\");\n\n assembly {\n for {\n let src := add(add(_bytes, 32), _start)\n let res := add(_dest, 32)\n let end := add(src, _length)\n } lt(src, end) {\n src := add(src, 32)\n res := add(res, 32)\n } {\n mstore(res, mload(src))\n }\n }\n }\n\n // Static slice functions, no bounds checking\n /// @notice take a 32-byte slice from the specified position\n function slice32(bytes memory _bytes, uint _start) internal pure returns (bytes32 res) {\n assembly {\n res := mload(add(add(_bytes, 32), _start))\n }\n }\n\n /// @notice take a 20-byte slice from the specified position\n function slice20(bytes memory _bytes, uint _start) internal pure returns (bytes20) {\n return bytes20(slice32(_bytes, _start));\n }\n\n /// @notice take a 8-byte slice from the specified position\n function slice8(bytes memory _bytes, uint _start) internal pure returns (bytes8) {\n return bytes8(slice32(_bytes, _start));\n }\n\n /// @notice take a 4-byte slice from the specified position\n function slice4(bytes memory _bytes, uint _start) internal pure returns (bytes4) {\n return bytes4(slice32(_bytes, _start));\n }\n\n /// @notice take a 3-byte slice from the specified position\n function slice3(bytes memory _bytes, uint _start) internal pure returns (bytes3) {\n return bytes3(slice32(_bytes, _start));\n }\n\n /// @notice take a 2-byte slice from the specified position\n function slice2(bytes memory _bytes, uint _start) internal pure returns (bytes2) {\n return bytes2(slice32(_bytes, _start));\n }\n\n function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) {\n uint _totalLen = _start + 20;\n require(_totalLen > _start && _bytes.length >= _totalLen, \"Address conversion out of bounds.\");\n address tempAddress;\n\n assembly {\n tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)\n }\n\n return tempAddress;\n }\n\n function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) {\n uint _totalLen = _start + 32;\n require(_totalLen > _start && _bytes.length >= _totalLen, \"Uint conversion out of bounds.\");\n uint256 tempUint;\n\n assembly {\n tempUint := mload(add(add(_bytes, 0x20), _start))\n }\n\n return tempUint;\n }\n\n function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {\n bool success = true;\n\n assembly {\n let length := mload(_preBytes)\n\n // if lengths don't match the arrays are not equal\n switch eq(length, mload(_postBytes))\n case 1 {\n // cb is a circuit breaker in the for loop since there's\n // no said feature for inline assembly loops\n // cb = 1 - don't breaker\n // cb = 0 - break\n let cb := 1\n\n let mc := add(_preBytes, 0x20)\n let end := add(mc, length)\n\n for {\n let cc := add(_postBytes, 0x20)\n // the next line is the loop condition:\n // while(uint(mc < end) + cb == 2)\n } eq(add(lt(mc, end), cb), 2) {\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n // if any of these checks fails then arrays are not equal\n if iszero(eq(mload(mc), mload(cc))) {\n // unsuccess:\n success := 0\n cb := 0\n }\n }\n }\n default {\n // unsuccess:\n success := 0\n }\n }\n\n return success;\n }\n\n function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) {\n bool success = true;\n\n assembly {\n // we know _preBytes_offset is 0\n let fslot := sload(_preBytes.slot)\n // Decode the length of the stored array like in concatStorage().\n let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)\n let mlength := mload(_postBytes)\n\n // if lengths don't match the arrays are not equal\n switch eq(slength, mlength)\n case 1 {\n // slength can contain both the length and contents of the array\n // if length < 32 bytes so let's prepare for that\n // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage\n if iszero(iszero(slength)) {\n switch lt(slength, 32)\n case 1 {\n // blank the last byte which is the length\n fslot := mul(div(fslot, 0x100), 0x100)\n\n if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {\n // unsuccess:\n success := 0\n }\n }\n default {\n // cb is a circuit breaker in the for loop since there's\n // no said feature for inline assembly loops\n // cb = 1 - don't breaker\n // cb = 0 - break\n let cb := 1\n\n // get the keccak hash to get the contents of the array\n mstore(0x0, _preBytes.slot)\n let sc := keccak256(0x0, 0x20)\n\n let mc := add(_postBytes, 0x20)\n let end := add(mc, mlength)\n\n // the next line is the loop condition:\n // while(uint(mc < end) + cb == 2)\n for {} eq(add(lt(mc, end), cb), 2) {\n sc := add(sc, 1)\n mc := add(mc, 0x20)\n } {\n if iszero(eq(sload(sc), mload(mc))) {\n // unsuccess:\n success := 0\n cb := 0\n }\n }\n }\n }\n }\n default {\n // unsuccess:\n success := 0\n }\n }\n\n return success;\n }\n\n function 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 function keccak256Slice(bytes memory _bytes, uint _start, uint _length) pure internal returns (bytes32 result) {\n uint _end = _start + _length;\n require(_end > _start && _bytes.length >= _end, \"Slice out of bounds\");\n\n assembly {\n result := keccak256(add(add(_bytes, 32), _start), _length)\n }\n }\n}\n"
177
- },
178
- "@keep-network/bitcoin-spv-sol/contracts/SafeMath.sol": {
179
- "content": "pragma solidity ^0.8.4;\n\n/*\nThe MIT License (MIT)\n\nCopyright (c) 2016 Smart Contract Solutions, Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\n\n\n/**\n * @title SafeMath\n * @dev Math operations with safety checks that throw on error\n */\nlibrary SafeMath {\n\n /**\n * @dev Multiplies two numbers, throws on overflow.\n */\n function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {\n // Gas optimization: this is cheaper than asserting 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522\n if (_a == 0) {\n return 0;\n }\n\n c = _a * _b;\n require(c / _a == _b, \"Overflow during multiplication.\");\n return c;\n }\n\n /**\n * @dev Integer division of two numbers, truncating the quotient.\n */\n function div(uint256 _a, uint256 _b) internal pure returns (uint256) {\n // assert(_b > 0); // Solidity automatically throws when dividing by 0\n // uint256 c = _a / _b;\n // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold\n return _a / _b;\n }\n\n /**\n * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).\n */\n function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {\n require(_b <= _a, \"Underflow during subtraction.\");\n return _a - _b;\n }\n\n /**\n * @dev Adds two numbers, throws on overflow.\n */\n function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {\n c = _a + _b;\n require(c >= _a, \"Overflow during addition.\");\n return c;\n }\n}\n"
180
- },
181
- "@keep-network/bitcoin-spv-sol/contracts/ValidateSPV.sol": {
182
- "content": "pragma solidity ^0.8.4;\n\n/** @title ValidateSPV*/\n/** @author Summa (https://summa.one) */\n\nimport {BytesLib} from \"./BytesLib.sol\";\nimport {SafeMath} from \"./SafeMath.sol\";\nimport {BTCUtils} from \"./BTCUtils.sol\";\n\n\nlibrary ValidateSPV {\n\n using BTCUtils for bytes;\n using BTCUtils for uint256;\n using BytesLib for bytes;\n using SafeMath for uint256;\n\n enum InputTypes { NONE, LEGACY, COMPATIBILITY, WITNESS }\n enum OutputTypes { NONE, WPKH, WSH, OP_RETURN, PKH, SH, NONSTANDARD }\n\n uint256 constant ERR_BAD_LENGTH = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;\n uint256 constant ERR_INVALID_CHAIN = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe;\n uint256 constant ERR_LOW_WORK = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd;\n\n function getErrBadLength() internal pure returns (uint256) {\n return ERR_BAD_LENGTH;\n }\n\n function getErrInvalidChain() internal pure returns (uint256) {\n return ERR_INVALID_CHAIN;\n }\n\n function getErrLowWork() internal pure returns (uint256) {\n return ERR_LOW_WORK;\n }\n\n /// @notice Validates a tx inclusion in the block\n /// @dev `index` is not a reliable indicator of location within a block\n /// @param _txid The txid (LE)\n /// @param _merkleRoot The merkle root (as in the block header)\n /// @param _intermediateNodes The proof's intermediate nodes (digests between leaf and root)\n /// @param _index The leaf's index in the tree (0-indexed)\n /// @return true if fully valid, false otherwise\n function prove(\n bytes32 _txid,\n bytes32 _merkleRoot,\n bytes memory _intermediateNodes,\n uint _index\n ) internal view returns (bool) {\n // Shortcut the empty-block case\n if (_txid == _merkleRoot && _index == 0 && _intermediateNodes.length == 0) {\n return true;\n }\n\n // If the Merkle proof failed, bubble up error\n return BTCUtils.verifyHash256Merkle(\n _txid,\n _intermediateNodes,\n _merkleRoot,\n _index\n );\n }\n\n /// @notice Hashes transaction to get txid\n /// @dev Supports Legacy and Witness\n /// @param _version 4-bytes version\n /// @param _vin Raw bytes length-prefixed input vector\n /// @param _vout Raw bytes length-prefixed output vector\n /// @param _locktime 4-byte tx locktime\n /// @return 32-byte transaction id, little endian\n function calculateTxId(\n bytes4 _version,\n bytes memory _vin,\n bytes memory _vout,\n bytes4 _locktime\n ) internal view returns (bytes32) {\n // Get transaction hash double-Sha256(version + nIns + inputs + nOuts + outputs + locktime)\n return abi.encodePacked(_version, _vin, _vout, _locktime).hash256View();\n }\n\n /// @notice Checks validity of header chain\n /// @notice Compares the hash of each header to the prevHash in the next header\n /// @param _headers Raw byte array of header chain\n /// @return _totalDifficulty The total accumulated difficulty of the header chain, or an error code\n function validateHeaderChain(bytes memory _headers) internal view returns (uint256 _totalDifficulty) {\n\n // Check header chain length\n if (_headers.length % 80 != 0) {return ERR_BAD_LENGTH;}\n\n // Initialize header start index\n bytes32 _digest;\n\n _totalDifficulty = 0;\n\n bytes memory _header;\n\n // Allocate _header with extra space after it to fit 3 full words\n assembly {\n _header := mload(0x40)\n mstore(0x40, add(_header, add(32, 96)))\n mstore(_header, 80)\n }\n\n for (uint256 _start = 0; _start < _headers.length; _start += 80) {\n\n // ith header start index and ith header\n _headers.sliceInPlace(_header, _start);\n\n // After the first header, check that headers are in a chain\n if (_start != 0) {\n if (!validateHeaderPrevHash(_header, _digest)) {return ERR_INVALID_CHAIN;}\n }\n\n // ith header target\n uint256 _target = _header.extractTarget();\n\n // Require that the header has sufficient work\n _digest = _header.hash256View();\n if(uint256(_digest).reverseUint256() > _target) {\n return ERR_LOW_WORK;\n }\n\n // Add ith header difficulty to difficulty sum\n _totalDifficulty = _totalDifficulty.add(_target.calculateDifficulty());\n }\n }\n\n /// @notice Checks validity of header work\n /// @param _digest Header digest\n /// @param _target The target threshold\n /// @return true if header work is valid, false otherwise\n function validateHeaderWork(bytes32 _digest, uint256 _target) internal pure returns (bool) {\n if (_digest == bytes32(0)) {return false;}\n return (uint256(_digest).reverseUint256() < _target);\n }\n\n /// @notice Checks validity of header chain\n /// @dev Compares current header prevHash to previous header's digest\n /// @param _header The raw bytes header\n /// @param _prevHeaderDigest The previous header's digest\n /// @return true if the connect is valid, false otherwise\n function validateHeaderPrevHash(bytes memory _header, bytes32 _prevHeaderDigest) internal pure returns (bool) {\n\n // Extract prevHash of current header\n bytes32 _prevHash = _header.extractPrevBlockLE();\n\n // Compare prevHash of current header to previous header's digest\n if (_prevHash != _prevHeaderDigest) {return false;}\n\n return true;\n }\n}\n"
183
- },
184
- "@keep-network/ecdsa/contracts/api/IWalletRegistry.sol": {
185
- "content": "// SPDX-License-Identifier: MIT\n//\n// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄\n// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓\n// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓\n// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀\n// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌\n// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓\n//\n// Trust math, not hardware.\n\npragma solidity ^0.8.9;\n\nimport \"../libraries/EcdsaDkg.sol\";\n\ninterface IWalletRegistry {\n /// @notice Requests a new wallet creation.\n /// @dev Only the Wallet Owner can call this function.\n function requestNewWallet() external;\n\n /// @notice Closes an existing wallet.\n /// @param walletID ID of the wallet.\n /// @dev Only the Wallet Owner can call this function.\n function closeWallet(bytes32 walletID) external;\n\n /// @notice Adds all signing group members of the wallet with the given ID\n /// to the slashing queue of the staking contract. The notifier will\n /// receive reward per each group member from the staking contract\n /// notifiers treasury. The reward is scaled by the\n /// `rewardMultiplier` provided as a parameter.\n /// @param amount Amount of tokens to seize from each signing group member\n /// @param rewardMultiplier Fraction of the staking contract notifiers\n /// reward the notifier should receive; should be between [0, 100]\n /// @param notifier Address of the misbehavior notifier\n /// @param walletID ID of the wallet\n /// @param walletMembersIDs Identifiers of the wallet signing group members\n /// @dev Only the Wallet Owner can call this function.\n /// Requirements:\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events.\n /// - `rewardMultiplier` must be between [0, 100].\n /// - This function does revert if staking contract call reverts.\n /// The calling code needs to handle the potential revert.\n function seize(\n uint96 amount,\n uint256 rewardMultiplier,\n address notifier,\n bytes32 walletID,\n uint32[] calldata walletMembersIDs\n ) external;\n\n /// @notice Gets public key of a wallet with a given wallet ID.\n /// The public key is returned in an uncompressed format as a 64-byte\n /// concatenation of X and Y coordinates.\n /// @param walletID ID of the wallet.\n /// @return Uncompressed public key of the wallet.\n function getWalletPublicKey(bytes32 walletID)\n external\n view\n returns (bytes memory);\n\n /// @notice Check current wallet creation state.\n function getWalletCreationState() external view returns (EcdsaDkg.State);\n\n /// @notice Checks whether the given operator is a member of the given\n /// wallet signing group.\n /// @param walletID ID of the wallet\n /// @param walletMembersIDs Identifiers of the wallet signing group members\n /// @param operator Address of the checked operator\n /// @param walletMemberIndex Position of the operator in the wallet signing\n /// group members list\n /// @return True - if the operator is a member of the given wallet signing\n /// group. False - otherwise.\n /// @dev Requirements:\n /// - The `operator` parameter must be an actual sortition pool operator.\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events.\n /// - The `walletMemberIndex` must be in range [1, walletMembersIDs.length]\n function isWalletMember(\n bytes32 walletID,\n uint32[] calldata walletMembersIDs,\n address operator,\n uint256 walletMemberIndex\n ) external view returns (bool);\n}\n"
186
- },
187
- "contracts/bridge/IRelay.sol": {
188
- "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\n/// @title Interface for the Bitcoin relay\n/// @notice Contains only the methods needed by tBTC v2. The Bitcoin relay\n/// provides the difficulty of the previous and current epoch. One\n/// difficulty epoch spans 2016 blocks.\ninterface IRelay {\n /// @notice Returns the difficulty of the current epoch.\n function getCurrentEpochDifficulty() external view returns (uint256);\n\n /// @notice Returns the difficulty of the previous epoch.\n function getPrevEpochDifficulty() external view returns (uint256);\n}\n"
189
- },
190
- "contracts/bridge/Deposit.sol": {
191
- "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\nimport {BytesLib} from \"@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol\";\n\nimport \"./BitcoinTx.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Wallets.sol\";\n\n/// @title Bridge deposit\n/// @notice The library handles the logic for revealing Bitcoin deposits to\n/// the Bridge.\n/// @dev The depositor puts together a P2SH or P2WSH address to deposit the\n/// funds. This script is unique to each depositor and looks like this:\n///\n/// ```\n/// <depositorAddress> DROP\n/// <blindingFactor> DROP\n/// DUP HASH160 <walletPubKeyHash> EQUAL\n/// IF\n/// CHECKSIG\n/// ELSE\n/// DUP HASH160 <refundPubkeyHash> EQUALVERIFY\n/// <refundLocktime> CHECKLOCKTIMEVERIFY DROP\n/// CHECKSIG\n/// ENDIF\n/// ```\n///\n/// Since each depositor has their own Ethereum address and their own\n/// secret blinding factor, each depositor’s script is unique, and the hash\n/// of each depositor’s script is unique.\nlibrary Deposit {\n using BTCUtils for bytes;\n using BytesLib for bytes;\n\n /// @notice Represents data which must be revealed by the depositor during\n /// deposit reveal.\n struct DepositRevealInfo {\n // Index of the funding output belonging to the funding transaction.\n uint32 fundingOutputIndex;\n // Ethereum depositor address.\n address depositor;\n // The blinding factor as 8 bytes. Byte endianness doesn't matter\n // as this factor is not interpreted as uint.\n bytes8 blindingFactor;\n // The compressed Bitcoin public key (33 bytes and 02 or 03 prefix)\n // of the deposit's wallet hashed in the HASH160 Bitcoin opcode style.\n bytes20 walletPubKeyHash;\n // The compressed Bitcoin public key (33 bytes and 02 or 03 prefix)\n // that can be used to make the deposit refund after the refund\n // locktime passes. Hashed in the HASH160 Bitcoin opcode style.\n bytes20 refundPubKeyHash;\n // The refund locktime (4-byte LE). Interpreted according to locktime\n // parsing rules described in:\n // https://developer.bitcoin.org/devguide/transactions.html#locktime-and-sequence-number\n // and used with OP_CHECKLOCKTIMEVERIFY opcode as described in:\n // https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki\n bytes4 refundLocktime;\n // Address of the Bank vault to which the deposit is routed to.\n // Optional, can be 0x0. The vault must be trusted by the Bridge.\n address vault;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's calldata argument.\n }\n\n /// @notice Represents tBTC deposit request data.\n struct DepositRequest {\n // Ethereum depositor address.\n address depositor;\n // Deposit amount in satoshi.\n uint64 amount;\n // UNIX timestamp the deposit was revealed at.\n uint32 revealedAt;\n // Address of the Bank vault the deposit is routed to.\n // Optional, can be 0x0.\n address vault;\n // Treasury TBTC fee in satoshi at the moment of deposit reveal.\n uint64 treasuryFee;\n // UNIX timestamp the deposit was swept at. Note this is not the\n // time when the deposit was swept on the Bitcoin chain but actually\n // the time when the sweep proof was delivered to the Ethereum chain.\n uint32 sweptAt;\n // This struct doesn't contain `__gap` property as the structure is stored\n // in a mapping, mappings store values in different slots and they are\n // not contiguous with other values.\n }\n\n event DepositRevealed(\n bytes32 fundingTxHash,\n uint32 fundingOutputIndex,\n address indexed depositor,\n uint64 amount,\n bytes8 blindingFactor,\n bytes20 indexed walletPubKeyHash,\n bytes20 refundPubKeyHash,\n bytes4 refundLocktime,\n address vault\n );\n\n /// @notice Used by the depositor to reveal information about their P2(W)SH\n /// Bitcoin deposit to the Bridge on Ethereum chain. The off-chain\n /// wallet listens for revealed deposit events and may decide to\n /// include the revealed deposit in the next executed sweep.\n /// Information about the Bitcoin deposit can be revealed before or\n /// after the Bitcoin transaction with P2(W)SH deposit is mined on\n /// the Bitcoin chain. Worth noting, the gas cost of this function\n /// scales with the number of P2(W)SH transaction inputs and\n /// outputs. The deposit may be routed to one of the trusted vaults.\n /// When a deposit is routed to a vault, vault gets notified when\n /// the deposit gets swept and it may execute the appropriate action.\n /// @param fundingTx Bitcoin funding transaction data, see `BitcoinTx.Info`.\n /// @param reveal Deposit reveal data, see `RevealInfo struct.\n /// @dev Requirements:\n /// - `reveal.walletPubKeyHash` must identify a `Live` wallet,\n /// - `reveal.vault` must be 0x0 or point to a trusted vault,\n /// - `reveal.fundingOutputIndex` must point to the actual P2(W)SH\n /// output of the BTC deposit transaction,\n /// - `reveal.depositor` must be the Ethereum address used in the\n /// P2(W)SH BTC deposit transaction,\n /// - `reveal.blindingFactor` must be the blinding factor used in the\n /// P2(W)SH BTC deposit transaction,\n /// - `reveal.walletPubKeyHash` must be the wallet pub key hash used in\n /// the P2(W)SH BTC deposit transaction,\n /// - `reveal.refundPubKeyHash` must be the refund pub key hash used in\n /// the P2(W)SH BTC deposit transaction,\n /// - `reveal.refundLocktime` must be the refund locktime used in the\n /// P2(W)SH BTC deposit transaction,\n /// - BTC deposit for the given `fundingTxHash`, `fundingOutputIndex`\n /// can be revealed only one time.\n ///\n /// If any of these requirements is not met, the wallet _must_ refuse\n /// to sweep the deposit and the depositor has to wait until the\n /// deposit script unlocks to receive their BTC back.\n function revealDeposit(\n BridgeState.Storage storage self,\n BitcoinTx.Info calldata fundingTx,\n DepositRevealInfo calldata reveal\n ) external {\n require(\n self.registeredWallets[reveal.walletPubKeyHash].state ==\n Wallets.WalletState.Live,\n \"Wallet must be in Live state\"\n );\n\n require(\n reveal.vault == address(0) || self.isVaultTrusted[reveal.vault],\n \"Vault is not trusted\"\n );\n\n bytes memory expectedScript = abi.encodePacked(\n hex\"14\", // Byte length of depositor Ethereum address.\n reveal.depositor,\n hex\"75\", // OP_DROP\n hex\"08\", // Byte length of blinding factor value.\n reveal.blindingFactor,\n hex\"75\", // OP_DROP\n hex\"76\", // OP_DUP\n hex\"a9\", // OP_HASH160\n hex\"14\", // Byte length of a compressed Bitcoin public key hash.\n reveal.walletPubKeyHash,\n hex\"87\", // OP_EQUAL\n hex\"63\", // OP_IF\n hex\"ac\", // OP_CHECKSIG\n hex\"67\", // OP_ELSE\n hex\"76\", // OP_DUP\n hex\"a9\", // OP_HASH160\n hex\"14\", // Byte length of a compressed Bitcoin public key hash.\n reveal.refundPubKeyHash,\n hex\"88\", // OP_EQUALVERIFY\n hex\"04\", // Byte length of refund locktime value.\n reveal.refundLocktime,\n hex\"b1\", // OP_CHECKLOCKTIMEVERIFY\n hex\"75\", // OP_DROP\n hex\"ac\", // OP_CHECKSIG\n hex\"68\" // OP_ENDIF\n );\n\n bytes memory fundingOutput = fundingTx\n .outputVector\n .extractOutputAtIndex(reveal.fundingOutputIndex);\n bytes memory fundingOutputHash = fundingOutput.extractHash();\n\n if (fundingOutputHash.length == 20) {\n // A 20-byte output hash is used by P2SH. That hash is constructed\n // by applying OP_HASH160 on the locking script. A 20-byte output\n // hash is used as well by P2PKH and P2WPKH (OP_HASH160 on the\n // public key). However, since we compare the actual output hash\n // with an expected locking script hash, this check will succeed only\n // for P2SH transaction type with expected script hash value. For\n // P2PKH and P2WPKH, it will fail on the output hash comparison with\n // the expected locking script hash.\n require(\n fundingOutputHash.slice20(0) == expectedScript.hash160View(),\n \"Wrong 20-byte script hash\"\n );\n } else if (fundingOutputHash.length == 32) {\n // A 32-byte output hash is used by P2WSH. That hash is constructed\n // by applying OP_SHA256 on the locking script.\n require(\n fundingOutputHash.toBytes32() == sha256(expectedScript),\n \"Wrong 32-byte script hash\"\n );\n } else {\n revert(\"Wrong script hash length\");\n }\n\n // Resulting TX hash is in native Bitcoin little-endian format.\n bytes32 fundingTxHash = abi\n .encodePacked(\n fundingTx.version,\n fundingTx.inputVector,\n fundingTx.outputVector,\n fundingTx.locktime\n )\n .hash256View();\n\n DepositRequest storage deposit = self.deposits[\n uint256(\n keccak256(\n abi.encodePacked(fundingTxHash, reveal.fundingOutputIndex)\n )\n )\n ];\n require(deposit.revealedAt == 0, \"Deposit already revealed\");\n\n uint64 fundingOutputAmount = fundingOutput.extractValue();\n\n require(\n fundingOutputAmount >= self.depositDustThreshold,\n \"Deposit amount too small\"\n );\n\n deposit.amount = fundingOutputAmount;\n deposit.depositor = reveal.depositor;\n /* solhint-disable-next-line not-rely-on-time */\n deposit.revealedAt = uint32(block.timestamp);\n deposit.vault = reveal.vault;\n deposit.treasuryFee = self.depositTreasuryFeeDivisor > 0\n ? fundingOutputAmount / self.depositTreasuryFeeDivisor\n : 0;\n // slither-disable-next-line reentrancy-events\n emit DepositRevealed(\n fundingTxHash,\n reveal.fundingOutputIndex,\n reveal.depositor,\n fundingOutputAmount,\n reveal.blindingFactor,\n reveal.walletPubKeyHash,\n reveal.refundPubKeyHash,\n reveal.refundLocktime,\n reveal.vault\n );\n }\n}\n"
192
- },
193
- "contracts/bridge/Redemption.sol": {
194
- "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\nimport {BytesLib} from \"@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol\";\n\nimport \"./BitcoinTx.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Wallets.sol\";\n\nimport \"../bank/Bank.sol\";\n\n/// @notice Aggregates functions common to the redemption transaction proof\n/// validation and to the moving funds transaction proof validation.\nlibrary OutboundTx {\n using BTCUtils for bytes;\n\n /// @notice Checks whether an outbound Bitcoin transaction performed from\n /// the given wallet has an input vector that contains a single\n /// input referring to the wallet's main UTXO. Marks that main UTXO\n /// as correctly spent if the validation succeeds. Reverts otherwise.\n /// There are two outbound transactions from a wallet possible: a\n /// redemption transaction or a moving funds to another wallet\n /// transaction.\n /// @param walletOutboundTxInputVector Bitcoin outbound transaction's input\n /// vector. This function assumes vector's structure is valid so it\n /// must be validated using e.g. `BTCUtils.validateVin` function\n /// before it is passed here.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n // HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the outbound transaction.\n function processWalletOutboundTxInput(\n BridgeState.Storage storage self,\n bytes memory walletOutboundTxInputVector,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes20 walletPubKeyHash\n ) internal {\n // Assert that main UTXO for passed wallet exists in storage.\n bytes32 mainUtxoHash = self\n .registeredWallets[walletPubKeyHash]\n .mainUtxoHash;\n require(mainUtxoHash != bytes32(0), \"No main UTXO for given wallet\");\n\n // Assert that passed main UTXO parameter is the same as in storage and\n // can be used for further processing.\n require(\n keccak256(\n abi.encodePacked(\n mainUtxo.txHash,\n mainUtxo.txOutputIndex,\n mainUtxo.txOutputValue\n )\n ) == mainUtxoHash,\n \"Invalid main UTXO data\"\n );\n\n // Assert that the single outbound transaction input actually\n // refers to the wallet's main UTXO.\n (\n bytes32 outpointTxHash,\n uint32 outpointIndex\n ) = parseWalletOutboundTxInput(walletOutboundTxInputVector);\n require(\n mainUtxo.txHash == outpointTxHash &&\n mainUtxo.txOutputIndex == outpointIndex,\n \"Outbound transaction input must point to the wallet's main UTXO\"\n );\n\n // Main UTXO used as an input, mark it as spent.\n self.spentMainUTXOs[\n uint256(\n keccak256(\n abi.encodePacked(mainUtxo.txHash, mainUtxo.txOutputIndex)\n )\n )\n ] = true;\n }\n\n /// @notice Parses the input vector of an outbound Bitcoin transaction\n /// performed from the given wallet. It extracts the single input\n /// then the transaction hash and output index from its outpoint.\n /// There are two outbound transactions from a wallet possible: a\n /// redemption transaction or a moving funds to another wallet\n /// transaction.\n /// @param walletOutboundTxInputVector Bitcoin outbound transaction input\n /// vector. This function assumes vector's structure is valid so it\n /// must be validated using e.g. `BTCUtils.validateVin` function\n /// before it is passed here.\n /// @return outpointTxHash 32-byte hash of the Bitcoin transaction which is\n /// pointed in the input's outpoint.\n /// @return outpointIndex 4-byte index of the Bitcoin transaction output\n /// which is pointed in the input's outpoint.\n function parseWalletOutboundTxInput(\n bytes memory walletOutboundTxInputVector\n ) internal pure returns (bytes32 outpointTxHash, uint32 outpointIndex) {\n // To determine the total number of Bitcoin transaction inputs,\n // we need to parse the compactSize uint (VarInt) the input vector is\n // prepended by. That compactSize uint encodes the number of vector\n // elements using the format presented in:\n // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers\n // We don't need asserting the compactSize uint is parseable since it\n // was already checked during `validateVin` validation.\n // See `BitcoinTx.inputVector` docs for more details.\n (, uint256 inputsCount) = walletOutboundTxInputVector.parseVarInt();\n require(\n inputsCount == 1,\n \"Outbound transaction must have a single input\"\n );\n\n bytes memory input = walletOutboundTxInputVector.extractInputAtIndex(0);\n\n outpointTxHash = input.extractInputTxIdLE();\n\n outpointIndex = BTCUtils.reverseUint32(\n uint32(input.extractTxIndexLE())\n );\n\n // There is only one input in the transaction. Input has an outpoint\n // field that is a reference to the transaction being spent (see\n // `BitcoinTx` docs). The outpoint contains the hash of the transaction\n // to spend (`outpointTxHash`) and the index of the specific output\n // from that transaction (`outpointIndex`).\n return (outpointTxHash, outpointIndex);\n }\n}\n\n/// @title Bridge redemption\n/// @notice The library handles the logic for redeeming Bitcoin balances from\n/// the Bridge.\n/// @dev To initiate a redemption, a user with a Bank balance supplies\n/// a Bitcoin address. Then, the system calculates the redemption fee, and\n/// releases balance to the provided Bitcoin address. Just like in case of\n/// sweeps of revealed deposits, redemption requests are processed in\n/// batches and require SPV proof to be submitted to the Bridge.\nlibrary Redemption {\n using BridgeState for BridgeState.Storage;\n using Wallets for BridgeState.Storage;\n using BitcoinTx for BridgeState.Storage;\n\n using BTCUtils for bytes;\n using BytesLib for bytes;\n\n /// @notice Represents a redemption request.\n struct RedemptionRequest {\n // ETH address of the redeemer who created the request.\n address redeemer;\n // Requested TBTC amount in satoshi.\n uint64 requestedAmount;\n // Treasury TBTC fee in satoshi at the moment of request creation.\n uint64 treasuryFee;\n // Transaction maximum BTC fee in satoshi at the moment of request\n // creation.\n uint64 txMaxFee;\n // UNIX timestamp the request was created at.\n uint32 requestedAt;\n // This struct doesn't contain `__gap` property as the structure is stored\n // in a mapping, mappings store values in different slots and they are\n // not contiguous with other values.\n }\n\n /// @notice Represents an outcome of the redemption Bitcoin transaction\n /// outputs processing.\n struct RedemptionTxOutputsInfo {\n // Total TBTC value in satoshi that should be burned by the Bridge.\n // It includes the total amount of all BTC redeemed in the transaction\n // and the fee paid to BTC miners for the redemption transaction.\n uint64 totalBurnableValue;\n // Total TBTC value in satoshi that should be transferred to\n // the treasury. It is a sum of all treasury fees paid by all\n // redeemers included in the redemption transaction.\n uint64 totalTreasuryFee;\n // Index of the change output. The change output becomes\n // the new main wallet's UTXO.\n uint32 changeIndex;\n // Value in satoshi of the change output.\n uint64 changeValue;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's memory argument.\n }\n\n /// @notice Represents temporary information needed during the processing of\n /// the redemption Bitcoin transaction outputs. This structure is an\n /// internal one and should not be exported outside of the redemption\n /// transaction processing code.\n /// @dev Allows to mitigate \"stack too deep\" errors on EVM.\n struct RedemptionTxOutputsProcessingInfo {\n // The first output starting index in the transaction.\n uint256 outputStartingIndex;\n // The number of outputs in the transaction.\n uint256 outputsCount;\n // P2PKH script for the wallet. Needed to determine the change output.\n bytes32 walletP2PKHScriptKeccak;\n // P2WPKH script for the wallet. Needed to determine the change output.\n bytes32 walletP2WPKHScriptKeccak;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's memory argument.\n }\n\n event RedemptionRequested(\n bytes20 indexed walletPubKeyHash,\n bytes redeemerOutputScript,\n address indexed redeemer,\n uint64 requestedAmount,\n uint64 treasuryFee,\n uint64 txMaxFee\n );\n\n event RedemptionsCompleted(\n bytes20 indexed walletPubKeyHash,\n bytes32 redemptionTxHash\n );\n\n event RedemptionTimedOut(\n bytes20 indexed walletPubKeyHash,\n bytes redeemerOutputScript\n );\n\n /// @notice Requests redemption of the given amount from the specified\n /// wallet to the redeemer Bitcoin output script.\n /// @param walletPubKeyHash The 20-byte wallet public key hash (computed\n /// using Bitcoin HASH160 over the compressed ECDSA public key).\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain.\n /// @param redeemerOutputScript The redeemer's length-prefixed output\n /// script (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock\n /// redeemed BTC.\n /// @param amount Requested amount in satoshi. This is also the TBTC amount\n /// that is taken from redeemer's balance in the Bank upon request.\n /// Once the request is handled, the actual amount of BTC locked\n /// on the redeemer output script will be always lower than this value\n /// since the treasury and Bitcoin transaction fees must be incurred.\n /// The minimal amount satisfying the request can be computed as:\n /// `amount - (amount / redemptionTreasuryFeeDivisor) - redemptionTxMaxFee`.\n /// Fees values are taken at the moment of request creation.\n /// @dev Requirements:\n /// - Wallet behind `walletPubKeyHash` must be live,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain,\n /// - `redeemerOutputScript` must be a proper Bitcoin script,\n /// - `redeemerOutputScript` cannot have wallet PKH as payload,\n /// - `amount` must be above or equal the `redemptionDustThreshold`,\n /// - Given `walletPubKeyHash` and `redeemerOutputScript` pair can be\n /// used for only one pending request at the same time,\n /// - Wallet must have enough Bitcoin balance to proceed the request,\n /// - Redeemer must make an allowance in the Bank that the Bridge\n /// contract can spend the given `amount`.\n function requestRedemption(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes calldata redeemerOutputScript,\n uint64 amount\n ) external {\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n\n require(\n wallet.state == Wallets.WalletState.Live,\n \"Wallet must be in Live state\"\n );\n\n bytes32 mainUtxoHash = wallet.mainUtxoHash;\n require(\n mainUtxoHash != bytes32(0),\n \"No main UTXO for the given wallet\"\n );\n require(\n keccak256(\n abi.encodePacked(\n mainUtxo.txHash,\n mainUtxo.txOutputIndex,\n mainUtxo.txOutputValue\n )\n ) == mainUtxoHash,\n \"Invalid main UTXO data\"\n );\n\n // Validate if redeemer output script is a correct standard type\n // (P2PKH, P2WPKH, P2SH or P2WSH). This is done by building a stub\n // output with 0 as value and using `BTCUtils.extractHash` on it. Such\n // a function extracts the payload properly only from standard outputs\n // so if it succeeds, we have a guarantee the redeemer output script\n // is proper. Worth to note `extractHash` ignores the value at all\n // so this is why we can use 0 safely. This way of validation is the\n // same as in tBTC v1.\n bytes memory redeemerOutputScriptPayload = abi\n .encodePacked(bytes8(0), redeemerOutputScript)\n .extractHash();\n require(\n redeemerOutputScriptPayload.length > 0,\n \"Redeemer output script must be a standard type\"\n );\n // Check if the redeemer output script payload does not point to the\n // wallet public key hash.\n require(\n keccak256(abi.encodePacked(walletPubKeyHash)) !=\n keccak256(redeemerOutputScriptPayload),\n \"Redeemer output script must not point to the wallet PKH\"\n );\n\n require(\n amount >= self.redemptionDustThreshold,\n \"Redemption amount too small\"\n );\n\n // The redemption key is built on top of the wallet public key hash\n // and redeemer output script pair. That means there can be only one\n // request asking for redemption from the given wallet to the given\n // BTC script at the same time.\n uint256 redemptionKey = uint256(\n keccak256(abi.encodePacked(walletPubKeyHash, redeemerOutputScript))\n );\n\n // Check if given redemption key is not used by a pending redemption.\n // There is no need to check for existence in `timedOutRedemptions`\n // since the wallet's state is changed to other than Live after\n // first time out is reported so making new requests is not possible.\n // slither-disable-next-line incorrect-equality\n require(\n self.pendingRedemptions[redemptionKey].requestedAt == 0,\n \"There is a pending redemption request from this wallet to the same address\"\n );\n\n // No need to check whether `amount - treasuryFee - txMaxFee > 0`\n // since the `redemptionDustThreshold` should force that condition\n // to be always true.\n uint64 treasuryFee = self.redemptionTreasuryFeeDivisor > 0\n ? amount / self.redemptionTreasuryFeeDivisor\n : 0;\n uint64 txMaxFee = self.redemptionTxMaxFee;\n\n // The main wallet UTXO's value doesn't include all pending redemptions.\n // To determine if the requested redemption can be performed by the\n // wallet we need to subtract the total value of all pending redemptions\n // from that wallet's main UTXO value. Given that the treasury fee is\n // not redeemed from the wallet, we are subtracting it.\n wallet.pendingRedemptionsValue += amount - treasuryFee;\n require(\n mainUtxo.txOutputValue >= wallet.pendingRedemptionsValue,\n \"Insufficient wallet funds\"\n );\n\n self.pendingRedemptions[redemptionKey] = RedemptionRequest(\n msg.sender,\n amount,\n treasuryFee,\n txMaxFee,\n /* solhint-disable-next-line not-rely-on-time */\n uint32(block.timestamp)\n );\n\n emit RedemptionRequested(\n walletPubKeyHash,\n redeemerOutputScript,\n msg.sender,\n amount,\n treasuryFee,\n txMaxFee\n );\n\n self.bank.transferBalanceFrom(msg.sender, address(this), amount);\n }\n\n /// @notice Used by the wallet to prove the BTC redemption transaction\n /// and to make the necessary bookkeeping. Redemption is only\n /// accepted if it satisfies SPV proof.\n ///\n /// The function is performing Bank balance updates by burning\n /// the total redeemed Bitcoin amount from Bridge balance and\n /// transferring the treasury fee sum to the treasury address.\n ///\n /// It is possible to prove the given redemption only one time.\n /// @param redemptionTx Bitcoin redemption transaction data.\n /// @param redemptionProof Bitcoin redemption proof data.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n /// HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the redemption transaction.\n /// @dev Requirements:\n /// - `redemptionTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash,\n /// - The `redemptionTx` should represent a Bitcoin transaction with\n /// exactly 1 input that refers to the wallet's main UTXO. That\n /// transaction should have 1..n outputs handling existing pending\n /// redemption requests or pointing to reported timed out requests.\n /// There can be also 1 optional output representing the\n /// change and pointing back to the 20-byte wallet public key hash.\n /// The change should be always present if the redeemed value sum\n /// is lower than the total wallet's BTC balance,\n /// - `redemptionProof` components must match the expected structure.\n /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// Additionally, the recent main UTXO on Ethereum must be set,\n /// - `walletPubKeyHash` must be connected with the main UTXO used\n /// as transaction single input.\n /// Other remarks:\n /// - Putting the change output as the first transaction output can\n /// save some gas because the output processing loop begins each\n /// iteration by checking whether the given output is the change\n /// thus uses some gas for making the comparison. Once the change\n /// is identified, that check is omitted in further iterations.\n function submitRedemptionProof(\n BridgeState.Storage storage self,\n BitcoinTx.Info calldata redemptionTx,\n BitcoinTx.Proof calldata redemptionProof,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes20 walletPubKeyHash\n ) external {\n // The actual transaction proof is performed here. After that point, we\n // can assume the transaction happened on Bitcoin chain and has\n // a sufficient number of confirmations as determined by\n // `txProofDifficultyFactor` constant.\n bytes32 redemptionTxHash = self.validateProof(\n redemptionTx,\n redemptionProof\n );\n\n // Process the redemption transaction input. Specifically, check if it\n // refers to the expected wallet's main UTXO.\n OutboundTx.processWalletOutboundTxInput(\n self,\n redemptionTx.inputVector,\n mainUtxo,\n walletPubKeyHash\n );\n\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n\n Wallets.WalletState walletState = wallet.state;\n require(\n walletState == Wallets.WalletState.Live ||\n walletState == Wallets.WalletState.MovingFunds,\n \"Wallet must be in Live or MovingFunds state\"\n );\n\n // Process redemption transaction outputs to extract some info required\n // for further processing.\n RedemptionTxOutputsInfo memory outputsInfo = processRedemptionTxOutputs(\n self,\n redemptionTx.outputVector,\n walletPubKeyHash\n );\n\n if (outputsInfo.changeValue > 0) {\n // If the change value is grater than zero, it means the change\n // output exists and can be used as new wallet's main UTXO.\n wallet.mainUtxoHash = keccak256(\n abi.encodePacked(\n redemptionTxHash,\n outputsInfo.changeIndex,\n outputsInfo.changeValue\n )\n );\n } else {\n // If the change value is zero, it means the change output doesn't\n // exists and no funds left on the wallet. Delete the main UTXO\n // for that wallet to represent that state in a proper way.\n delete wallet.mainUtxoHash;\n }\n\n wallet.pendingRedemptionsValue -= outputsInfo.totalBurnableValue;\n\n emit RedemptionsCompleted(walletPubKeyHash, redemptionTxHash);\n\n self.bank.decreaseBalance(outputsInfo.totalBurnableValue);\n self.bank.transferBalance(self.treasury, outputsInfo.totalTreasuryFee);\n }\n\n /// @notice Processes the Bitcoin redemption transaction output vector.\n /// It extracts each output and tries to identify it as a pending\n /// redemption request, reported timed out request, or change.\n /// Reverts if one of the outputs cannot be recognized properly.\n /// This function also marks each request as processed by removing\n /// them from `pendingRedemptions` mapping.\n /// @param redemptionTxOutputVector Bitcoin redemption transaction output\n /// vector. This function assumes vector's structure is valid so it\n /// must be validated using e.g. `BTCUtils.validateVout` function\n /// before it is passed here.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n // HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the redemption transaction.\n /// @return info Outcomes of the processing.\n function processRedemptionTxOutputs(\n BridgeState.Storage storage self,\n bytes memory redemptionTxOutputVector,\n bytes20 walletPubKeyHash\n ) internal returns (RedemptionTxOutputsInfo memory info) {\n // Determining the total number of redemption transaction outputs in\n // the same way as for number of inputs. See `BitcoinTx.outputVector`\n // docs for more details.\n (\n uint256 outputsCompactSizeUintLength,\n uint256 outputsCount\n ) = redemptionTxOutputVector.parseVarInt();\n\n // To determine the first output starting index, we must jump over\n // the compactSize uint which prepends the output vector. One byte\n // must be added because `BtcUtils.parseVarInt` does not include\n // compactSize uint tag in the returned length.\n //\n // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`\n // returns `0`, so we jump over one byte of compactSize uint.\n //\n // For >= 253 && <= 0xffff there is `0xfd` tag,\n // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no\n // tag byte included) so we need to jump over 1+2 bytes of\n // compactSize uint.\n //\n // Please refer `BTCUtils` library and compactSize uint\n // docs in `BitcoinTx` library for more details.\n uint256 outputStartingIndex = 1 + outputsCompactSizeUintLength;\n\n // Calculate the keccak256 for two possible wallet's P2PKH or P2WPKH\n // scripts that can be used to lock the change. This is done upfront to\n // save on gas. Both scripts have a strict format defined by Bitcoin.\n //\n // The P2PKH script has the byte format: <0x1976a914> <20-byte PKH> <0x88ac>.\n // According to https://en.bitcoin.it/wiki/Script#Opcodes this translates to:\n // - 0x19: Byte length of the entire script\n // - 0x76: OP_DUP\n // - 0xa9: OP_HASH160\n // - 0x14: Byte length of the public key hash\n // - 0x88: OP_EQUALVERIFY\n // - 0xac: OP_CHECKSIG\n // which matches the P2PKH structure as per:\n // https://en.bitcoin.it/wiki/Transaction#Pay-to-PubkeyHash\n bytes32 walletP2PKHScriptKeccak = keccak256(\n abi.encodePacked(hex\"1976a914\", walletPubKeyHash, hex\"88ac\")\n );\n // The P2WPKH script has the byte format: <0x160014> <20-byte PKH>.\n // According to https://en.bitcoin.it/wiki/Script#Opcodes this translates to:\n // - 0x16: Byte length of the entire script\n // - 0x00: OP_0\n // - 0x14: Byte length of the public key hash\n // which matches the P2WPKH structure as per:\n // https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#P2WPKH\n bytes32 walletP2WPKHScriptKeccak = keccak256(\n abi.encodePacked(hex\"160014\", walletPubKeyHash)\n );\n\n return\n processRedemptionTxOutputs(\n self,\n redemptionTxOutputVector,\n walletPubKeyHash,\n RedemptionTxOutputsProcessingInfo(\n outputStartingIndex,\n outputsCount,\n walletP2PKHScriptKeccak,\n walletP2WPKHScriptKeccak\n )\n );\n }\n\n /// @notice Processes all outputs from the redemption transaction. Tries to\n /// identify output as a change output, pending redemption request\n // or reported redemption. Reverts if one of the outputs cannot be\n /// recognized properly. Marks each request as processed by removing\n /// them from `pendingRedemptions` mapping.\n /// @param redemptionTxOutputVector Bitcoin redemption transaction output\n /// vector. This function assumes vector's structure is valid so it\n /// must be validated using e.g. `BTCUtils.validateVout` function\n /// before it is passed here.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n // HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the redemption transaction.\n /// @param processInfo RedemptionTxOutputsProcessingInfo identifying output\n /// starting index, the number of outputs and possible wallet change\n /// P2PKH and P2WPKH scripts.\n function processRedemptionTxOutputs(\n BridgeState.Storage storage self,\n bytes memory redemptionTxOutputVector,\n bytes20 walletPubKeyHash,\n RedemptionTxOutputsProcessingInfo memory processInfo\n ) internal returns (RedemptionTxOutputsInfo memory resultInfo) {\n // Helper flag indicating whether there was at least one redemption\n // output present (redemption must be either pending or reported as\n // timed out).\n bool redemptionPresent = false;\n\n // Outputs processing loop.\n for (uint256 i = 0; i < processInfo.outputsCount; i++) {\n // TODO: Check if we can optimize gas costs by adding\n // `extractValueAt` and `extractHashAt` in `bitcoin-spv-sol`\n // in order to avoid allocating bytes in memory.\n // https://github.com/keep-network/tbtc-v2/issues/257\n uint256 outputLength = redemptionTxOutputVector\n .determineOutputLengthAt(processInfo.outputStartingIndex);\n bytes memory output = redemptionTxOutputVector.slice(\n processInfo.outputStartingIndex,\n outputLength\n );\n\n // Extract the value from given output.\n uint64 outputValue = output.extractValue();\n // The output consists of an 8-byte value and a variable length\n // script. To extract that script we slice the output starting from\n // 9th byte until the end.\n bytes memory outputScript = output.slice(8, output.length - 8);\n\n if (\n resultInfo.changeValue == 0 &&\n (keccak256(outputScript) ==\n processInfo.walletP2PKHScriptKeccak ||\n keccak256(outputScript) ==\n processInfo.walletP2WPKHScriptKeccak) &&\n outputValue > 0\n ) {\n // If we entered here, that means the change output with a\n // proper non-zero value was found.\n resultInfo.changeIndex = uint32(i);\n resultInfo.changeValue = outputValue;\n } else {\n // If we entered here, that the means the given output is\n // supposed to represent a redemption.\n (\n uint64 burnableValue,\n uint64 treasuryFee\n ) = processNonChangeRedemptionTxOutput(\n self,\n walletPubKeyHash,\n outputScript,\n outputValue\n );\n resultInfo.totalBurnableValue += burnableValue;\n resultInfo.totalTreasuryFee += treasuryFee;\n redemptionPresent = true;\n }\n\n // Make the `outputStartingIndex` pointing to the next output by\n // increasing it by current output's length.\n processInfo.outputStartingIndex += outputLength;\n }\n\n // Protect against the cases when there is only a single change output\n // referring back to the wallet PKH and just burning main UTXO value\n // for transaction fees.\n require(\n redemptionPresent,\n \"Redemption transaction must process at least one redemption\"\n );\n }\n\n /// @notice Processes a single redemption transaction output. Tries to\n /// identify output as a pending redemption request or reported\n /// redemption timeout. Output script passed to this function must\n /// not be the change output. Such output needs to be identified\n /// separately before calling this function.\n /// Reverts if output is neither requested pending redemption nor\n /// requested and reported timed-out redemption.\n /// This function also marks each pending request as processed by\n /// removing them from `pendingRedemptions` mapping.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n // HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the redemption transaction.\n /// @param outputScript Non-change output script to be processed.\n /// @param outputValue Value of the output being processed.\n /// @return burnableValue The value burnable as a result of processing this\n /// single redemption output. This value needs to be summed up with\n /// burnable values of all other outputs to evaluate total burnable\n /// value for the entire redemption transaction. This value is 0\n /// for a timed-out redemption request.\n /// @return treasuryFee The treasury fee from this single redemption output.\n /// This value needs to be summed up with treasury fees of all other\n /// outputs to evaluate the total treasury fee for the entire\n /// redemption transaction. This value is 0 for a timed-out\n /// redemption request.\n function processNonChangeRedemptionTxOutput(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n bytes memory outputScript,\n uint64 outputValue\n ) internal returns (uint64 burnableValue, uint64 treasuryFee) {\n // This function should be called only if the given output is\n // supposed to represent a redemption. Build the redemption key\n // to perform that check.\n uint256 redemptionKey = uint256(\n keccak256(abi.encodePacked(walletPubKeyHash, outputScript))\n );\n\n if (self.pendingRedemptions[redemptionKey].requestedAt != 0) {\n // If we entered here, that means the output was identified\n // as a pending redemption request.\n RedemptionRequest storage request = self.pendingRedemptions[\n redemptionKey\n ];\n // Compute the request's redeemable amount as the requested\n // amount reduced by the treasury fee. The request's\n // minimal amount is then the redeemable amount reduced by\n // the maximum transaction fee.\n uint64 redeemableAmount = request.requestedAmount -\n request.treasuryFee;\n // Output value must fit between the request's redeemable\n // and minimal amounts to be deemed valid.\n require(\n redeemableAmount - request.txMaxFee <= outputValue &&\n outputValue <= redeemableAmount,\n \"Output value is not within the acceptable range of the pending request\"\n );\n // Add the redeemable amount to the total burnable value\n // the Bridge will use to decrease its balance in the Bank.\n burnableValue = redeemableAmount;\n // Add the request's treasury fee to the total treasury fee\n // value the Bridge will transfer to the treasury.\n treasuryFee = request.treasuryFee;\n // Request was properly handled so remove its redemption\n // key from the mapping to make it reusable for further\n // requests.\n delete self.pendingRedemptions[redemptionKey];\n } else {\n // If we entered here, the output is not a redemption\n // request but there is still a chance the given output is\n // related to a reported timed out redemption request.\n // If so, check if the output value matches the request\n // amount to confirm this is an overdue request fulfillment\n // then bypass this output and process the subsequent\n // ones. That also means the wallet was already punished\n // for the inactivity. Otherwise, just revert.\n RedemptionRequest storage request = self.timedOutRedemptions[\n redemptionKey\n ];\n\n require(\n request.requestedAt != 0,\n \"Output is a non-requested redemption\"\n );\n\n uint64 redeemableAmount = request.requestedAmount -\n request.treasuryFee;\n\n require(\n redeemableAmount - request.txMaxFee <= outputValue &&\n outputValue <= redeemableAmount,\n \"Output value is not within the acceptable range of the timed out request\"\n );\n }\n }\n\n /// @notice Notifies that there is a pending redemption request associated\n /// with the given wallet, that has timed out. The redemption\n /// request is identified by the key built as\n /// `keccak256(walletPubKeyHash | redeemerOutputScript)`.\n /// The results of calling this function:\n /// - the pending redemptions value for the wallet will be decreased\n /// by the requested amount (minus treasury fee),\n /// - the tokens taken from the redeemer on redemption request will\n /// be returned to the redeemer,\n /// - the request will be moved from pending redemptions to\n /// timed-out redemptions,\n /// - if the state of the wallet is `Live` or `MovingFunds`, the\n /// wallet operators will be slashed and the notifier will be\n /// rewarded,\n /// - if the state of wallet is `Live`, the wallet will be closed or\n /// marked as `MovingFunds` (depending on the presence or absence\n /// of the wallet's main UTXO) and the wallet will no longer be\n /// marked as the active wallet (if it was marked as such).\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @param redeemerOutputScript The redeemer's length-prefixed output\n /// script (P2PKH, P2WPKH, P2SH or P2WSH).\n /// @dev Requirements:\n /// - The wallet must be in the Live or MovingFunds or Terminated state,\n /// - The redemption request identified by `walletPubKeyHash` and\n /// `redeemerOutputScript` must exist,\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events of the `WalletRegistry` contract,\n /// - The amount of time defined by `redemptionTimeout` must have\n /// passed since the redemption was requested (the request must be\n /// timed-out).\n function notifyRedemptionTimeout(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n uint32[] calldata walletMembersIDs,\n bytes calldata redeemerOutputScript\n ) external {\n uint256 redemptionKey = uint256(\n keccak256(abi.encodePacked(walletPubKeyHash, redeemerOutputScript))\n );\n Redemption.RedemptionRequest memory request = self.pendingRedemptions[\n redemptionKey\n ];\n\n require(request.requestedAt > 0, \"Redemption request does not exist\");\n require(\n /* solhint-disable-next-line not-rely-on-time */\n request.requestedAt + self.redemptionTimeout < block.timestamp,\n \"Redemption request has not timed out\"\n );\n\n // Update the wallet's pending redemptions value\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n wallet.pendingRedemptionsValue -=\n request.requestedAmount -\n request.treasuryFee;\n\n require(\n wallet.state == Wallets.WalletState.Live ||\n wallet.state == Wallets.WalletState.MovingFunds ||\n wallet.state == Wallets.WalletState.Terminated,\n \"The wallet must be in Live, MovingFunds or Terminated state\"\n );\n\n // It is worth noting that there is no need to check if\n // `timedOutRedemption` mapping already contains the given redemption\n // key. There is no possibility to re-use a key of a reported timed-out\n // redemption because the wallet responsible for causing the timeout is\n // moved to a state that prevents it to receive new redemption requests.\n\n // Move the redemption from pending redemptions to timed-out redemptions\n self.timedOutRedemptions[redemptionKey] = request;\n delete self.pendingRedemptions[redemptionKey];\n\n if (\n wallet.state == Wallets.WalletState.Live ||\n wallet.state == Wallets.WalletState.MovingFunds\n ) {\n // Propagate timeout consequences to the wallet\n self.notifyWalletTimedOutRedemption(walletPubKeyHash);\n\n // Slash the wallet operators and reward the notifier\n self.ecdsaWalletRegistry.seize(\n self.redemptionTimeoutSlashingAmount,\n self.redemptionTimeoutNotifierRewardMultiplier,\n msg.sender,\n wallet.ecdsaWalletID,\n walletMembersIDs\n );\n }\n\n // slither-disable-next-line reentrancy-events\n emit RedemptionTimedOut(walletPubKeyHash, redeemerOutputScript);\n\n // Return the requested amount of tokens to the redeemer\n self.bank.transferBalance(request.redeemer, request.requestedAmount);\n }\n}\n"
195
- },
196
- "contracts/bridge/Fraud.sol": {
197
- "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {BytesLib} from \"@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol\";\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\nimport {CheckBitcoinSigs} from \"@keep-network/bitcoin-spv-sol/contracts/CheckBitcoinSigs.sol\";\n\nimport \"./BitcoinTx.sol\";\nimport \"./EcdsaLib.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Heartbeat.sol\";\nimport \"./MovingFunds.sol\";\nimport \"./Wallets.sol\";\n\n/// @title Bridge fraud\n/// @notice The library handles the logic for challenging Bridge wallets that\n/// committed fraud.\n/// @dev Anyone can submit a fraud challenge indicating that a UTXO being under\n/// the wallet control was unlocked by the wallet but was not used\n/// according to the protocol rules. That means the wallet signed\n/// a transaction input pointing to that UTXO and there is a unique\n/// sighash and signature pair associated with that input.\n///\n/// In order to defeat the challenge, the same wallet public key and\n/// signature must be provided as were used to calculate the sighash during\n/// the challenge. The wallet provides the preimage which produces sighash\n/// used to generate the ECDSA signature that is the subject of the fraud\n/// claim.\n///\n/// The fraud challenge defeat attempt will succeed if the inputs in the\n/// preimage are considered honestly spent by the wallet. Therefore the\n/// transaction spending the UTXO must be proven in the Bridge before\n/// a challenge defeat is called.\n///\n/// Another option is when a malicious wallet member used a signed heartbeat\n/// message periodically produced by the wallet off-chain to challenge the\n/// wallet for a fraud. Anyone from the wallet can defeat the challenge by\n/// proving the sighash and signature were produced for a heartbeat message\n/// following a strict format.\nlibrary Fraud {\n using Wallets for BridgeState.Storage;\n\n using BytesLib for bytes;\n using BTCUtils for bytes;\n using BTCUtils for uint32;\n using EcdsaLib for bytes;\n\n struct FraudChallenge {\n // The address of the party challenging the wallet.\n address challenger;\n // The amount of ETH the challenger deposited.\n uint256 depositAmount;\n // The timestamp the challenge was submitted at.\n uint32 reportedAt;\n // The flag indicating whether the challenge has been resolved.\n bool resolved;\n // This struct doesn't contain `__gap` property as the structure is stored\n // in a mapping, mappings store values in different slots and they are\n // not contiguous with other values.\n }\n\n event FraudChallengeSubmitted(\n bytes20 indexed walletPubKeyHash,\n bytes32 sighash,\n uint8 v,\n bytes32 r,\n bytes32 s\n );\n\n event FraudChallengeDefeated(\n bytes20 indexed walletPubKeyHash,\n bytes32 sighash\n );\n\n event FraudChallengeDefeatTimedOut(\n bytes20 indexed walletPubKeyHash,\n // Sighash calculated as a Bitcoin's hash256 (double sha2) of:\n // - a preimage of a transaction spending UTXO according to the protocol\n // rules OR\n // - a valid heartbeat message produced by the wallet off-chain.\n bytes32 sighash\n );\n\n /// @notice Submits a fraud challenge indicating that a UTXO being under\n /// wallet control was unlocked by the wallet but was not used\n /// according to the protocol rules. That means the wallet signed\n /// a transaction input pointing to that UTXO and there is a unique\n /// sighash and signature pair associated with that input. This\n /// function uses those parameters to create a fraud accusation that\n /// proves a given transaction input unlocking the given UTXO was\n /// actually signed by the wallet. This function cannot determine\n /// whether the transaction was actually broadcast and the input was\n /// consumed in a fraudulent way so it just opens a challenge period\n /// during which the wallet can defeat the challenge by submitting\n /// proof of a transaction that consumes the given input according\n /// to protocol rules. To prevent spurious allegations, the caller\n /// must deposit ETH that is returned back upon justified fraud\n /// challenge or confiscated otherwise.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes).\n /// @param preimageSha256 The hash that was generated by applying SHA-256\n /// one time over the preimage used during input signing. The preimage\n /// is a serialized subset of the transaction and its structure\n /// depends on the transaction input (see BIP-143 for reference).\n /// Notice that applying SHA-256 over the `preimageSha256` results\n /// in `sighash`. The path from `preimage` to `sighash` looks like\n /// this:\n /// preimage -> (SHA-256) -> preimageSha256 -> (SHA-256) -> sighash.\n /// @param signature Bitcoin signature in the R/S/V format\n /// @dev Requirements:\n /// - Wallet behind `walletPublicKey` must be in Live or MovingFunds\n /// or Closing state,\n /// - The challenger must send appropriate amount of ETH used as\n /// fraud challenge deposit,\n /// - The signature (represented by r, s and v) must be generated by\n /// the wallet behind `walletPubKey` during signing of `sighash`\n /// which was calculated from `preimageSha256`,\n /// - Wallet can be challenged for the given signature only once.\n function submitFraudChallenge(\n BridgeState.Storage storage self,\n bytes calldata walletPublicKey,\n bytes memory preimageSha256,\n BitcoinTx.RSVSignature calldata signature\n ) external {\n require(\n msg.value >= self.fraudChallengeDepositAmount,\n \"The amount of ETH deposited is too low\"\n );\n\n // To prevent ECDSA signature forgery `sighash` must be calculated\n // inside the function and not passed as a function parameter.\n // Signature forgery could result in a wrongful fraud accusation\n // against a wallet.\n bytes32 sighash = sha256(preimageSha256);\n\n require(\n CheckBitcoinSigs.checkSig(\n walletPublicKey,\n sighash,\n signature.v,\n signature.r,\n signature.s\n ),\n \"Signature verification failure\"\n );\n\n bytes memory compressedWalletPublicKey = EcdsaLib.compressPublicKey(\n walletPublicKey.slice32(0),\n walletPublicKey.slice32(32)\n );\n bytes20 walletPubKeyHash = compressedWalletPublicKey.hash160View();\n\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n\n require(\n wallet.state == Wallets.WalletState.Live ||\n wallet.state == Wallets.WalletState.MovingFunds ||\n wallet.state == Wallets.WalletState.Closing,\n \"Wallet must be in Live or MovingFunds or Closing state\"\n );\n\n uint256 challengeKey = uint256(\n keccak256(abi.encodePacked(walletPublicKey, sighash))\n );\n\n FraudChallenge storage challenge = self.fraudChallenges[challengeKey];\n require(challenge.reportedAt == 0, \"Fraud challenge already exists\");\n\n challenge.challenger = msg.sender;\n challenge.depositAmount = msg.value;\n /* solhint-disable-next-line not-rely-on-time */\n challenge.reportedAt = uint32(block.timestamp);\n challenge.resolved = false;\n // slither-disable-next-line reentrancy-events\n emit FraudChallengeSubmitted(\n walletPubKeyHash,\n sighash,\n signature.v,\n signature.r,\n signature.s\n );\n }\n\n /// @notice Allows to defeat a pending fraud challenge against a wallet if\n /// the transaction that spends the UTXO follows the protocol rules.\n /// In order to defeat the challenge the same `walletPublicKey` and\n /// signature (represented by `r`, `s` and `v`) must be provided as\n /// were used to calculate the sighash during input signing.\n /// The fraud challenge defeat attempt will only succeed if the\n /// inputs in the preimage are considered honestly spent by the\n /// wallet. Therefore the transaction spending the UTXO must be\n /// proven in the Bridge before a challenge defeat is called.\n /// If successfully defeated, the fraud challenge is marked as\n /// resolved and the amount of ether deposited by the challenger is\n /// sent to the treasury.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes).\n /// @param preimage The preimage which produces sighash used to generate the\n /// ECDSA signature that is the subject of the fraud claim. It is a\n /// serialized subset of the transaction. The exact subset used as\n /// the preimage depends on the transaction input the signature is\n /// produced for. See BIP-143 for reference.\n /// @param witness Flag indicating whether the preimage was produced for a\n /// witness input. True for witness, false for non-witness input.\n /// @dev Requirements:\n /// - `walletPublicKey` and `sighash` calculated as `hash256(preimage)`\n /// must identify an open fraud challenge,\n /// - the preimage must be a valid preimage of a transaction generated\n /// according to the protocol rules and already proved in the Bridge,\n /// - before a defeat attempt is made the transaction that spends the\n /// given UTXO must be proven in the Bridge.\n function defeatFraudChallenge(\n BridgeState.Storage storage self,\n bytes calldata walletPublicKey,\n bytes calldata preimage,\n bool witness\n ) external {\n bytes32 sighash = preimage.hash256();\n\n uint256 challengeKey = uint256(\n keccak256(abi.encodePacked(walletPublicKey, sighash))\n );\n\n FraudChallenge storage challenge = self.fraudChallenges[challengeKey];\n\n require(challenge.reportedAt > 0, \"Fraud challenge does not exist\");\n require(\n !challenge.resolved,\n \"Fraud challenge has already been resolved\"\n );\n\n // Ensure SIGHASH_ALL type was used during signing, which is represented\n // by type value `1`.\n require(extractSighashType(preimage) == 1, \"Wrong sighash type\");\n\n uint256 utxoKey = witness\n ? extractUtxoKeyFromWitnessPreimage(preimage)\n : extractUtxoKeyFromNonWitnessPreimage(preimage);\n\n // Check that the UTXO key identifies a correctly spent UTXO.\n require(\n self.deposits[utxoKey].sweptAt > 0 ||\n self.spentMainUTXOs[utxoKey] ||\n self.movedFundsSweepRequests[utxoKey].state ==\n MovingFunds.MovedFundsSweepRequestState.Processed,\n \"Spent UTXO not found among correctly spent UTXOs\"\n );\n\n resolveFraudChallenge(self, walletPublicKey, challenge, sighash);\n }\n\n /// @notice Allows to defeat a pending fraud challenge against a wallet by\n /// proving the sighash and signature were produced for an off-chain\n /// wallet heartbeat message following a strict format.\n /// In order to defeat the challenge the same `walletPublicKey` and\n /// signature (represented by `r`, `s` and `v`) must be provided as\n /// were used to calculate the sighash during heartbeat message\n /// signing. The fraud challenge defeat attempt will only succeed if\n /// the signed message follows a strict format required for\n /// heartbeat messages. If successfully defeated, the fraud\n /// challenge is marked as resolved and the amount of ether\n /// deposited by the challenger is sent to the treasury.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes),\n /// @param heartbeatMessage Off-chain heartbeat message meeting the heartbeat\n /// message format requirements which produces sighash used to\n /// generate the ECDSA signature that is the subject of the fraud\n /// claim.\n /// @dev Requirements:\n /// - `walletPublicKey` and `sighash` calculated as\n /// `hash256(heartbeatMessage)` must identify an open fraud challenge,\n /// - `heartbeatMessage` must follow a strict format of heartbeat\n /// messages.\n function defeatFraudChallengeWithHeartbeat(\n BridgeState.Storage storage self,\n bytes calldata walletPublicKey,\n bytes calldata heartbeatMessage\n ) external {\n bytes32 sighash = heartbeatMessage.hash256();\n\n uint256 challengeKey = uint256(\n keccak256(abi.encodePacked(walletPublicKey, sighash))\n );\n\n FraudChallenge storage challenge = self.fraudChallenges[challengeKey];\n\n require(challenge.reportedAt > 0, \"Fraud challenge does not exist\");\n require(\n !challenge.resolved,\n \"Fraud challenge has already been resolved\"\n );\n\n require(\n Heartbeat.isValidHeartbeatMessage(heartbeatMessage),\n \"Not a valid heartbeat message\"\n );\n\n resolveFraudChallenge(self, walletPublicKey, challenge, sighash);\n }\n\n /// @notice Called only for successfully defeated fraud challenges.\n /// The fraud challenge is marked as resolved and the amount of\n /// ether deposited by the challenger is sent to the treasury.\n /// @dev Requirements:\n /// - Must be called only for successfully defeated fraud challenges.\n function resolveFraudChallenge(\n BridgeState.Storage storage self,\n bytes calldata walletPublicKey,\n FraudChallenge storage challenge,\n bytes32 sighash\n ) internal {\n // Mark the challenge as resolved as it was successfully defeated\n challenge.resolved = true;\n\n // Send the ether deposited by the challenger to the treasury\n /* solhint-disable avoid-low-level-calls */\n // slither-disable-next-line low-level-calls,unchecked-lowlevel,arbitrary-send\n self.treasury.call{gas: 100000, value: challenge.depositAmount}(\"\");\n /* solhint-enable avoid-low-level-calls */\n\n bytes memory compressedWalletPublicKey = EcdsaLib.compressPublicKey(\n walletPublicKey.slice32(0),\n walletPublicKey.slice32(32)\n );\n bytes20 walletPubKeyHash = compressedWalletPublicKey.hash160View();\n\n // slither-disable-next-line reentrancy-events\n emit FraudChallengeDefeated(walletPubKeyHash, sighash);\n }\n\n /// @notice Notifies about defeat timeout for the given fraud challenge.\n /// Can be called only if there was a fraud challenge identified by\n /// the provided `walletPublicKey` and `sighash` and it was not\n /// defeated on time. The amount of time that needs to pass after\n /// a fraud challenge is reported is indicated by the\n /// `challengeDefeatTimeout`. After a successful fraud challenge\n /// defeat timeout notification the fraud challenge is marked as\n /// resolved, the stake of each operator is slashed, the ether\n /// deposited is returned to the challenger and the challenger is\n /// rewarded.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes).\n /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @param preimageSha256 The hash that was generated by applying SHA-256\n /// one time over the preimage used during input signing. The preimage\n /// is a serialized subset of the transaction and its structure\n /// depends on the transaction input (see BIP-143 for reference).\n /// Notice that applying SHA-256 over the `preimageSha256` results\n /// in `sighash`. The path from `preimage` to `sighash` looks like\n /// this:\n /// preimage -> (SHA-256) -> preimageSha256 -> (SHA-256) -> sighash.\n /// @dev Requirements:\n /// - The wallet must be in the Live or MovingFunds or Closing or\n /// Terminated state,\n /// - The `walletPublicKey` and `sighash` calculated from\n /// `preimageSha256` must identify an open fraud challenge,\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events of the `WalletRegistry` contract,\n /// - The amount of time indicated by `challengeDefeatTimeout` must pass\n /// after the challenge was reported.\n function notifyFraudChallengeDefeatTimeout(\n BridgeState.Storage storage self,\n bytes calldata walletPublicKey,\n uint32[] calldata walletMembersIDs,\n bytes memory preimageSha256\n ) external {\n bytes32 sighash = sha256(preimageSha256);\n\n uint256 challengeKey = uint256(\n keccak256(abi.encodePacked(walletPublicKey, sighash))\n );\n\n FraudChallenge storage challenge = self.fraudChallenges[challengeKey];\n\n require(challenge.reportedAt > 0, \"Fraud challenge does not exist\");\n\n require(\n !challenge.resolved,\n \"Fraud challenge has already been resolved\"\n );\n\n require(\n /* solhint-disable-next-line not-rely-on-time */\n block.timestamp >=\n challenge.reportedAt + self.fraudChallengeDefeatTimeout,\n \"Fraud challenge defeat period did not time out yet\"\n );\n\n challenge.resolved = true;\n // Return the ether deposited by the challenger\n /* solhint-disable avoid-low-level-calls */\n // slither-disable-next-line low-level-calls,unchecked-lowlevel\n challenge.challenger.call{gas: 100000, value: challenge.depositAmount}(\n \"\"\n );\n /* solhint-enable avoid-low-level-calls */\n\n bytes memory compressedWalletPublicKey = EcdsaLib.compressPublicKey(\n walletPublicKey.slice32(0),\n walletPublicKey.slice32(32)\n );\n bytes20 walletPubKeyHash = compressedWalletPublicKey.hash160View();\n\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n\n Wallets.WalletState walletState = wallet.state;\n\n if (\n walletState == Wallets.WalletState.Live ||\n walletState == Wallets.WalletState.MovingFunds ||\n walletState == Wallets.WalletState.Closing\n ) {\n self.terminateWallet(walletPubKeyHash);\n\n self.ecdsaWalletRegistry.seize(\n self.fraudSlashingAmount,\n self.fraudNotifierRewardMultiplier,\n challenge.challenger,\n wallet.ecdsaWalletID,\n walletMembersIDs\n );\n } else if (walletState == Wallets.WalletState.Terminated) {\n // This is a special case when the wallet was already terminated\n // due to a previous deliberate protocol violation. In that\n // case, this function should be still callable for other fraud\n // challenges timeouts in order to let the challenger unlock its\n // ETH deposit back. However, the wallet termination logic is\n // not called and the challenger is not rewarded.\n } else {\n revert(\n \"Wallet must be in Live or MovingFunds or Closing or Terminated state\"\n );\n }\n\n // slither-disable-next-line reentrancy-events\n emit FraudChallengeDefeatTimedOut(walletPubKeyHash, sighash);\n }\n\n /// @notice Extracts the UTXO keys from the given preimage used during\n /// signing of a witness input.\n /// @param preimage The preimage which produces sighash used to generate the\n /// ECDSA signature that is the subject of the fraud claim. It is a\n /// serialized subset of the transaction. The exact subset used as\n /// the preimage depends on the transaction input the signature is\n /// produced for. See BIP-143 for reference\n /// @return utxoKey UTXO key that identifies spent input.\n function extractUtxoKeyFromWitnessPreimage(bytes calldata preimage)\n internal\n pure\n returns (uint256 utxoKey)\n {\n // The expected structure of the preimage created during signing of a\n // witness input:\n // - transaction version (4 bytes)\n // - hash of previous outpoints of all inputs (32 bytes)\n // - hash of sequences of all inputs (32 bytes)\n // - outpoint (hash + index) of the input being signed (36 bytes)\n // - the unlocking script of the input (variable length)\n // - value of the outpoint (8 bytes)\n // - sequence of the input being signed (4 bytes)\n // - hash of all outputs (32 bytes)\n // - transaction locktime (4 bytes)\n // - sighash type (4 bytes)\n\n // See Bitcoin's BIP-143 for reference:\n // https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki.\n\n // The outpoint (hash and index) is located at the constant offset of\n // 68 (4 + 32 + 32).\n bytes32 outpointTxHash = preimage.extractInputTxIdLeAt(68);\n uint32 outpointIndex = BTCUtils.reverseUint32(\n uint32(preimage.extractTxIndexLeAt(68))\n );\n\n return\n uint256(keccak256(abi.encodePacked(outpointTxHash, outpointIndex)));\n }\n\n /// @notice Extracts the UTXO key from the given preimage used during\n /// signing of a non-witness input.\n /// @param preimage The preimage which produces sighash used to generate the\n /// ECDSA signature that is the subject of the fraud claim. It is a\n /// serialized subset of the transaction. The exact subset used as\n /// the preimage depends on the transaction input the signature is\n /// produced for. See BIP-143 for reference.\n /// @return utxoKey UTXO key that identifies spent input.\n function extractUtxoKeyFromNonWitnessPreimage(bytes calldata preimage)\n internal\n pure\n returns (uint256 utxoKey)\n {\n // The expected structure of the preimage created during signing of a\n // non-witness input:\n // - transaction version (4 bytes)\n // - number of inputs written as compactSize uint (1 byte, 3 bytes,\n // 5 bytes or 9 bytes)\n // - for each input\n // - outpoint (hash and index) (36 bytes)\n // - unlocking script for the input being signed (variable length)\n // or `00` for all other inputs (1 byte)\n // - input sequence (4 bytes)\n // - number of outputs written as compactSize uint (1 byte, 3 bytes,\n // 5 bytes or 9 bytes)\n // - outputs (variable length)\n // - transaction locktime (4 bytes)\n // - sighash type (4 bytes)\n\n // See example for reference:\n // https://en.bitcoin.it/wiki/OP_CHECKSIG#Code_samples_and_raw_dumps.\n\n // The input data begins at the constant offset of 4 (the first 4 bytes\n // are for the transaction version).\n (uint256 inputsCompactSizeUintLength, uint256 inputsCount) = preimage\n .parseVarIntAt(4);\n\n // To determine the first input starting index, we must jump 4 bytes\n // over the transaction version length and the compactSize uint which\n // prepends the input vector. One byte must be added because\n // `BtcUtils.parseVarInt` does not include compactSize uint tag in the\n // returned length.\n //\n // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`\n // returns `0`, so we jump over one byte of compactSize uint.\n //\n // For >= 253 && <= 0xffff there is `0xfd` tag,\n // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no\n // tag byte included) so we need to jump over 1+2 bytes of\n // compactSize uint.\n //\n // Please refer `BTCUtils` library and compactSize uint\n // docs in `BitcoinTx` library for more details.\n uint256 inputStartingIndex = 4 + 1 + inputsCompactSizeUintLength;\n\n for (uint256 i = 0; i < inputsCount; i++) {\n uint256 inputLength = preimage.determineInputLengthAt(\n inputStartingIndex\n );\n\n (, uint256 scriptSigLength) = preimage.extractScriptSigLenAt(\n inputStartingIndex\n );\n\n if (scriptSigLength > 0) {\n // The input this preimage was generated for was found.\n // All the other inputs in the preimage are marked with a null\n // scriptSig (\"00\") which has length of 1.\n bytes32 outpointTxHash = preimage.extractInputTxIdLeAt(\n inputStartingIndex\n );\n uint32 outpointIndex = BTCUtils.reverseUint32(\n uint32(preimage.extractTxIndexLeAt(inputStartingIndex))\n );\n\n utxoKey = uint256(\n keccak256(abi.encodePacked(outpointTxHash, outpointIndex))\n );\n\n break;\n }\n\n inputStartingIndex += inputLength;\n }\n\n return utxoKey;\n }\n\n /// @notice Extracts the sighash type from the given preimage.\n /// @param preimage Serialized subset of the transaction. See BIP-143 for\n /// reference.\n /// @dev Sighash type is stored as the last 4 bytes in the preimage (little\n /// endian).\n /// @return sighashType Sighash type as a 32-bit integer.\n function extractSighashType(bytes calldata preimage)\n internal\n pure\n returns (uint32 sighashType)\n {\n bytes4 sighashTypeBytes = preimage.slice4(preimage.length - 4);\n uint32 sighashTypeLE = uint32(sighashTypeBytes);\n return sighashTypeLE.reverseUint32();\n }\n}\n"
198
- },
199
- "contracts/bridge/MovingFunds.sol": {
200
- "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\nimport {BytesLib} from \"@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol\";\n\nimport \"./BitcoinTx.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Redemption.sol\";\nimport \"./Wallets.sol\";\n\n/// @title Moving Bridge wallet funds\n/// @notice The library handles the logic for moving Bitcoin between Bridge\n/// wallets.\n/// @dev A wallet that failed a heartbeat, did not process requested redemption\n/// on time, or qualifies to be closed, begins the procedure of moving\n/// funds to other wallets in the Bridge. The wallet needs to commit to\n/// which other Live wallets it is moving the funds to and then, provide an\n/// SPV proof of moving funds to the previously committed wallets.\n/// Once the proof is submitted, all target wallets are supposed to\n/// sweep the received UTXOs with their own main UTXOs in order to\n/// update their BTC balances.\nlibrary MovingFunds {\n using BridgeState for BridgeState.Storage;\n using Wallets for BridgeState.Storage;\n using BitcoinTx for BridgeState.Storage;\n\n using BTCUtils for bytes;\n using BytesLib for bytes;\n\n /// @notice Represents temporary information needed during the processing\n /// of the moving funds Bitcoin transaction outputs. This structure\n /// is an internal one and should not be exported outside of the\n /// moving funds transaction processing code.\n /// @dev Allows to mitigate \"stack too deep\" errors on EVM.\n struct MovingFundsTxOutputsProcessingInfo {\n // 32-byte hash of the moving funds Bitcoin transaction.\n bytes32 movingFundsTxHash;\n // Output vector of the moving funds Bitcoin transaction. It is\n // assumed the vector's structure is valid so it must be validated\n // using e.g. `BTCUtils.validateVout` function before being used\n // during the processing. The validation is usually done as part\n // of the `BitcoinTx.validateProof` call that checks the SPV proof.\n bytes movingFundsTxOutputVector;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's memory argument.\n }\n\n /// @notice Represents moved funds sweep request state.\n enum MovedFundsSweepRequestState {\n /// @dev The request is unknown to the Bridge.\n Unknown,\n /// @dev Request is pending and can become either processed or timed out.\n Pending,\n /// @dev Request was processed by the target wallet.\n Processed,\n /// @dev Request was not processed in the given time window and\n /// the timeout was reported.\n TimedOut\n }\n\n /// @notice Represents a moved funds sweep request. The request is\n /// registered in `submitMovingFundsProof` where we know funds\n /// have been moved to the target wallet and the only step left is\n /// to have the target wallet sweep them.\n struct MovedFundsSweepRequest {\n // 20-byte public key hash of the wallet supposed to sweep the UTXO\n // representing the received funds with their own main UTXO\n bytes20 walletPubKeyHash;\n // Value of the received funds.\n uint64 value;\n // UNIX timestamp the request was created at.\n uint32 createdAt;\n // The current state of the request.\n MovedFundsSweepRequestState state;\n // This struct doesn't contain `__gap` property as the structure is stored\n // in a mapping, mappings store values in different slots and they are\n // not contiguous with other values.\n }\n\n event MovingFundsCommitmentSubmitted(\n bytes20 indexed walletPubKeyHash,\n bytes20[] targetWallets,\n address submitter\n );\n\n event MovingFundsTimeoutReset(bytes20 indexed walletPubKeyHash);\n\n event MovingFundsCompleted(\n bytes20 indexed walletPubKeyHash,\n bytes32 movingFundsTxHash\n );\n\n event MovingFundsTimedOut(bytes20 indexed walletPubKeyHash);\n\n event MovingFundsBelowDustReported(bytes20 indexed walletPubKeyHash);\n\n event MovedFundsSwept(\n bytes20 indexed walletPubKeyHash,\n bytes32 sweepTxHash\n );\n\n event MovedFundsSweepTimedOut(\n bytes20 indexed walletPubKeyHash,\n bytes32 movingFundsTxHash,\n uint32 movingFundsTxOutputIndex\n );\n\n /// @notice Submits the moving funds target wallets commitment.\n /// Once all requirements are met, that function registers the\n /// target wallets commitment and opens the way for moving funds\n /// proof submission.\n /// @param walletPubKeyHash 20-byte public key hash of the source wallet.\n /// @param walletMainUtxo Data of the source wallet's main UTXO, as\n /// currently known on the Ethereum chain.\n /// @param walletMembersIDs Identifiers of the source wallet signing group\n /// members.\n /// @param walletMemberIndex Position of the caller in the source wallet\n /// signing group members list.\n /// @param targetWallets List of 20-byte public key hashes of the target\n /// wallets that the source wallet commits to move the funds to.\n /// @dev Requirements:\n /// - The source wallet must be in the MovingFunds state,\n /// - The source wallet must not have pending redemption requests,\n /// - The source wallet must not have pending moved funds sweep requests,\n /// - The source wallet must not have submitted its commitment already,\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given source wallet in the ECDSA registry. Those IDs are\n /// not directly stored in the contract for gas efficiency purposes\n /// but they can be read from appropriate `DkgResultSubmitted`\n /// and `DkgResultApproved` events,\n /// - The `walletMemberIndex` must be in range [1, walletMembersIDs.length],\n /// - The caller must be the member of the source wallet signing group\n /// at the position indicated by `walletMemberIndex` parameter,\n /// - The `walletMainUtxo` components must point to the recent main\n /// UTXO of the source wallet, as currently known on the Ethereum\n /// chain,\n /// - Source wallet BTC balance must be greater than zero,\n /// - At least one Live wallet must exist in the system,\n /// - Submitted target wallets count must match the expected count\n /// `N = min(liveWalletsCount, ceil(walletBtcBalance / walletMaxBtcTransfer))`\n /// where `N > 0`,\n /// - Each target wallet must be not equal to the source wallet,\n /// - Each target wallet must follow the expected order i.e. all\n /// target wallets 20-byte public key hashes represented as numbers\n /// must form a strictly increasing sequence without duplicates,\n /// - Each target wallet must be in Live state.\n function submitMovingFundsCommitment(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata walletMainUtxo,\n uint32[] calldata walletMembersIDs,\n uint256 walletMemberIndex,\n bytes20[] calldata targetWallets\n ) external {\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n\n require(\n wallet.state == Wallets.WalletState.MovingFunds,\n \"Source wallet must be in MovingFunds state\"\n );\n\n require(\n wallet.pendingRedemptionsValue == 0,\n \"Source wallet must handle all pending redemptions first\"\n );\n\n require(\n wallet.pendingMovedFundsSweepRequestsCount == 0,\n \"Source wallet must handle all pending moved funds sweep requests first\"\n );\n\n require(\n wallet.movingFundsTargetWalletsCommitmentHash == bytes32(0),\n \"Target wallets commitment already submitted\"\n );\n\n require(\n self.ecdsaWalletRegistry.isWalletMember(\n wallet.ecdsaWalletID,\n walletMembersIDs,\n msg.sender,\n walletMemberIndex\n ),\n \"Caller is not a member of the source wallet\"\n );\n\n uint64 walletBtcBalance = self.getWalletBtcBalance(\n walletPubKeyHash,\n walletMainUtxo\n );\n\n require(walletBtcBalance > 0, \"Wallet BTC balance is zero\");\n\n uint256 expectedTargetWalletsCount = Math.min(\n self.liveWalletsCount,\n Math.ceilDiv(walletBtcBalance, self.walletMaxBtcTransfer)\n );\n\n // This requirement fails only when `liveWalletsCount` is zero. In\n // that case, the system cannot accept the commitment and must provide\n // new wallets first. However, the wallet supposed to submit the\n // commitment can keep resetting the moving funds timeout until then.\n require(expectedTargetWalletsCount > 0, \"No target wallets available\");\n\n require(\n targetWallets.length == expectedTargetWalletsCount,\n \"Submitted target wallets count is other than expected\"\n );\n\n uint160 lastProcessedTargetWallet = 0;\n\n for (uint256 i = 0; i < targetWallets.length; i++) {\n bytes20 targetWallet = targetWallets[i];\n\n require(\n targetWallet != walletPubKeyHash,\n \"Submitted target wallet cannot be equal to the source wallet\"\n );\n\n require(\n uint160(targetWallet) > lastProcessedTargetWallet,\n \"Submitted target wallet breaks the expected order\"\n );\n\n require(\n self.registeredWallets[targetWallet].state ==\n Wallets.WalletState.Live,\n \"Submitted target wallet must be in Live state\"\n );\n\n lastProcessedTargetWallet = uint160(targetWallet);\n }\n\n wallet.movingFundsTargetWalletsCommitmentHash = keccak256(\n abi.encodePacked(targetWallets)\n );\n\n emit MovingFundsCommitmentSubmitted(\n walletPubKeyHash,\n targetWallets,\n msg.sender\n );\n }\n\n /// @notice Resets the moving funds timeout for the given wallet if the\n /// target wallet commitment cannot be submitted due to a lack\n /// of live wallets in the system.\n /// @param walletPubKeyHash 20-byte public key hash of the moving funds wallet\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state,\n /// - The target wallets commitment must not be already submitted for\n /// the given moving funds wallet,\n /// - Live wallets count must be zero,\n /// - The moving funds timeout reset delay must be elapsed.\n function resetMovingFundsTimeout(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash\n ) external {\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n\n require(\n wallet.state == Wallets.WalletState.MovingFunds,\n \"ECDSA wallet must be in MovingFunds state\"\n );\n\n // If the moving funds wallet already submitted their target wallets\n // commitment, there is no point to reset the timeout since the\n // wallet can make the BTC transaction and submit the proof.\n require(\n wallet.movingFundsTargetWalletsCommitmentHash == bytes32(0),\n \"Target wallets commitment already submitted\"\n );\n\n require(self.liveWalletsCount == 0, \"Live wallets count must be zero\");\n\n require(\n /* solhint-disable-next-line not-rely-on-time */\n block.timestamp >\n wallet.movingFundsRequestedAt +\n self.movingFundsTimeoutResetDelay,\n \"Moving funds timeout cannot be reset yet\"\n );\n\n /* solhint-disable-next-line not-rely-on-time */\n wallet.movingFundsRequestedAt = uint32(block.timestamp);\n\n emit MovingFundsTimeoutReset(walletPubKeyHash);\n }\n\n /// @notice Used by the wallet to prove the BTC moving funds transaction\n /// and to make the necessary state changes. Moving funds is only\n /// accepted if it satisfies SPV proof.\n ///\n /// The function validates the moving funds transaction structure\n /// by checking if it actually spends the main UTXO of the declared\n /// wallet and locks the value on the pre-committed target wallets\n /// using a reasonable transaction fee. If all preconditions are\n /// met, this functions closes the source wallet.\n ///\n /// It is possible to prove the given moving funds transaction only\n /// one time.\n /// @param movingFundsTx Bitcoin moving funds transaction data.\n /// @param movingFundsProof Bitcoin moving funds proof data.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n /// HASH160 over the compressed ECDSA public key) of the wallet\n /// which performed the moving funds transaction.\n /// @dev Requirements:\n /// - `movingFundsTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash,\n /// - The `movingFundsTx` should represent a Bitcoin transaction with\n /// exactly 1 input that refers to the wallet's main UTXO. That\n /// transaction should have 1..n outputs corresponding to the\n /// pre-committed target wallets. Outputs must be ordered in the\n /// same way as their corresponding target wallets are ordered\n /// within the target wallets commitment,\n /// - `movingFundsProof` components must match the expected structure.\n /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// Additionally, the recent main UTXO on Ethereum must be set,\n /// - `walletPubKeyHash` must be connected with the main UTXO used\n /// as transaction single input,\n /// - The wallet that `walletPubKeyHash` points to must be in the\n /// MovingFunds state,\n /// - The target wallets commitment must be submitted by the wallet\n /// that `walletPubKeyHash` points to,\n /// - The total Bitcoin transaction fee must be lesser or equal\n /// to `movingFundsTxMaxTotalFee` governable parameter.\n function submitMovingFundsProof(\n BridgeState.Storage storage self,\n BitcoinTx.Info calldata movingFundsTx,\n BitcoinTx.Proof calldata movingFundsProof,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes20 walletPubKeyHash\n ) external {\n // The actual transaction proof is performed here. After that point, we\n // can assume the transaction happened on Bitcoin chain and has\n // a sufficient number of confirmations as determined by\n // `txProofDifficultyFactor` constant.\n bytes32 movingFundsTxHash = self.validateProof(\n movingFundsTx,\n movingFundsProof\n );\n\n // Process the moving funds transaction input. Specifically, check if\n // it refers to the expected wallet's main UTXO.\n OutboundTx.processWalletOutboundTxInput(\n self,\n movingFundsTx.inputVector,\n mainUtxo,\n walletPubKeyHash\n );\n\n (\n bytes32 targetWalletsHash,\n uint256 outputsTotalValue\n ) = processMovingFundsTxOutputs(\n self,\n MovingFundsTxOutputsProcessingInfo(\n movingFundsTxHash,\n movingFundsTx.outputVector\n )\n );\n\n require(\n mainUtxo.txOutputValue - outputsTotalValue <=\n self.movingFundsTxMaxTotalFee,\n \"Transaction fee is too high\"\n );\n\n self.notifyWalletFundsMoved(walletPubKeyHash, targetWalletsHash);\n // slither-disable-next-line reentrancy-events\n emit MovingFundsCompleted(walletPubKeyHash, movingFundsTxHash);\n }\n\n /// @notice Processes the moving funds Bitcoin transaction output vector\n /// and extracts information required for further processing.\n /// @param processInfo Processing info containing the moving funds tx\n /// hash and output vector.\n /// @return targetWalletsHash keccak256 hash over the list of actual\n /// target wallets used in the transaction.\n /// @return outputsTotalValue Sum of all outputs values.\n /// @dev Requirements:\n /// - The `movingFundsTxOutputVector` must be parseable, i.e. must\n /// be validated by the caller as stated in their parameter doc,\n /// - Each output must refer to a 20-byte public key hash,\n /// - The total outputs value must be evenly divided over all outputs.\n function processMovingFundsTxOutputs(\n BridgeState.Storage storage self,\n MovingFundsTxOutputsProcessingInfo memory processInfo\n ) internal returns (bytes32 targetWalletsHash, uint256 outputsTotalValue) {\n // Determining the total number of Bitcoin transaction outputs in\n // the same way as for number of inputs. See `BitcoinTx.outputVector`\n // docs for more details.\n (\n uint256 outputsCompactSizeUintLength,\n uint256 outputsCount\n ) = processInfo.movingFundsTxOutputVector.parseVarInt();\n\n // To determine the first output starting index, we must jump over\n // the compactSize uint which prepends the output vector. One byte\n // must be added because `BtcUtils.parseVarInt` does not include\n // compactSize uint tag in the returned length.\n //\n // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`\n // returns `0`, so we jump over one byte of compactSize uint.\n //\n // For >= 253 && <= 0xffff there is `0xfd` tag,\n // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no\n // tag byte included) so we need to jump over 1+2 bytes of\n // compactSize uint.\n //\n // Please refer `BTCUtils` library and compactSize uint\n // docs in `BitcoinTx` library for more details.\n uint256 outputStartingIndex = 1 + outputsCompactSizeUintLength;\n\n bytes20[] memory targetWallets = new bytes20[](outputsCount);\n uint64[] memory outputsValues = new uint64[](outputsCount);\n\n // Outputs processing loop. Note that the `outputIndex` must be\n // `uint32` to build proper `movedFundsSweepRequests` keys.\n for (\n uint32 outputIndex = 0;\n outputIndex < outputsCount;\n outputIndex++\n ) {\n uint256 outputLength = processInfo\n .movingFundsTxOutputVector\n .determineOutputLengthAt(outputStartingIndex);\n\n bytes memory output = processInfo.movingFundsTxOutputVector.slice(\n outputStartingIndex,\n outputLength\n );\n\n bytes20 targetWalletPubKeyHash = self.extractPubKeyHash(output);\n\n // Add the wallet public key hash to the list that will be used\n // to build the result list hash. There is no need to check if\n // given output is a change here because the actual target wallet\n // list must be exactly the same as the pre-committed target wallet\n // list which is guaranteed to be valid.\n targetWallets[outputIndex] = targetWalletPubKeyHash;\n\n // Extract the value from given output.\n outputsValues[outputIndex] = output.extractValue();\n outputsTotalValue += outputsValues[outputIndex];\n\n // Register a moved funds sweep request that must be handled\n // by the target wallet. The target wallet must sweep the\n // received funds with their own main UTXO in order to update\n // their BTC balance. Worth noting there is no need to check\n // if the sweep request already exists in the system because\n // the moving funds wallet is moved to the Closing state after\n // submitting the moving funds proof so there is no possibility\n // to submit the proof again and register the sweep request twice.\n self.movedFundsSweepRequests[\n uint256(\n keccak256(\n abi.encodePacked(\n processInfo.movingFundsTxHash,\n outputIndex\n )\n )\n )\n ] = MovedFundsSweepRequest(\n targetWalletPubKeyHash,\n outputsValues[outputIndex],\n /* solhint-disable-next-line not-rely-on-time */\n uint32(block.timestamp),\n MovedFundsSweepRequestState.Pending\n );\n // We added a new moved funds sweep request for the target wallet\n // so we must increment their request counter.\n self\n .registeredWallets[targetWalletPubKeyHash]\n .pendingMovedFundsSweepRequestsCount++;\n\n // Make the `outputStartingIndex` pointing to the next output by\n // increasing it by current output's length.\n outputStartingIndex += outputLength;\n }\n\n // Compute the indivisible remainder that remains after dividing the\n // outputs total value over all outputs evenly.\n uint256 outputsTotalValueRemainder = outputsTotalValue % outputsCount;\n // Compute the minimum allowed output value by dividing the outputs\n // total value (reduced by the remainder) by the number of outputs.\n uint256 minOutputValue = (outputsTotalValue -\n outputsTotalValueRemainder) / outputsCount;\n // Maximum possible value is the minimum value with the remainder included.\n uint256 maxOutputValue = minOutputValue + outputsTotalValueRemainder;\n\n for (uint256 i = 0; i < outputsCount; i++) {\n require(\n minOutputValue <= outputsValues[i] &&\n outputsValues[i] <= maxOutputValue,\n \"Transaction amount is not distributed evenly\"\n );\n }\n\n targetWalletsHash = keccak256(abi.encodePacked(targetWallets));\n\n return (targetWalletsHash, outputsTotalValue);\n }\n\n /// @notice Notifies about a timed out moving funds process. Terminates\n /// the wallet and slashes signing group members as a result.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state,\n /// - The moving funds timeout must be actually exceeded,\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events of the `WalletRegistry` contract.\n function notifyMovingFundsTimeout(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n uint32[] calldata walletMembersIDs\n ) external {\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n\n require(\n wallet.state == Wallets.WalletState.MovingFunds,\n \"ECDSA wallet must be in MovingFunds state\"\n );\n\n require(\n /* solhint-disable-next-line not-rely-on-time */\n block.timestamp >\n wallet.movingFundsRequestedAt + self.movingFundsTimeout,\n \"Moving funds has not timed out yet\"\n );\n\n self.terminateWallet(walletPubKeyHash);\n\n self.ecdsaWalletRegistry.seize(\n self.movingFundsTimeoutSlashingAmount,\n self.movingFundsTimeoutNotifierRewardMultiplier,\n msg.sender,\n wallet.ecdsaWalletID,\n walletMembersIDs\n );\n\n // slither-disable-next-line reentrancy-events\n emit MovingFundsTimedOut(walletPubKeyHash);\n }\n\n /// @notice Notifies about a moving funds wallet whose BTC balance is\n /// below the moving funds dust threshold. Ends the moving funds\n /// process and begins wallet closing immediately.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known\n /// on the Ethereum chain.\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state,\n /// - The `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// If the wallet has no main UTXO, this parameter can be empty as it\n /// is ignored,\n /// - The wallet BTC balance must be below the moving funds threshold.\n function notifyMovingFundsBelowDust(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata mainUtxo\n ) external {\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n\n require(\n wallet.state == Wallets.WalletState.MovingFunds,\n \"ECDSA wallet must be in MovingFunds state\"\n );\n\n uint64 walletBtcBalance = self.getWalletBtcBalance(\n walletPubKeyHash,\n mainUtxo\n );\n\n require(\n walletBtcBalance < self.movingFundsDustThreshold,\n \"Wallet BTC balance must be below the moving funds dust threshold\"\n );\n\n self.beginWalletClosing(walletPubKeyHash);\n\n // slither-disable-next-line reentrancy-events\n emit MovingFundsBelowDustReported(walletPubKeyHash);\n }\n\n /// @notice Used by the wallet to prove the BTC moved funds sweep\n /// transaction and to make the necessary state changes. Moved\n /// funds sweep is only accepted if it satisfies SPV proof.\n ///\n /// The function validates the sweep transaction structure by\n /// checking if it actually spends the moved funds UTXO and the\n /// sweeping wallet's main UTXO (optionally), and if it locks the\n /// value on the sweeping wallet's 20-byte public key hash using a\n /// reasonable transaction fee. If all preconditions are\n /// met, this function updates the sweeping wallet main UTXO, thus\n /// their BTC balance.\n ///\n /// It is possible to prove the given sweep transaction only\n /// one time.\n /// @param sweepTx Bitcoin sweep funds transaction data.\n /// @param sweepProof Bitcoin sweep funds proof data.\n /// @param mainUtxo Data of the sweeping wallet's main UTXO, as currently\n /// known on the Ethereum chain.\n /// @dev Requirements:\n /// - `sweepTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash,\n /// - The `sweepTx` should represent a Bitcoin transaction with\n /// the first input pointing to a wallet's sweep Pending request and,\n /// optionally, the second input pointing to the wallet's main UTXO,\n /// if the sweeping wallet has a main UTXO set. There should be only\n /// one output locking funds on the sweeping wallet 20-byte public\n /// key hash,\n /// - `sweepProof` components must match the expected structure.\n /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the sweeping wallet, as currently known on the Ethereum chain.\n /// If there is no main UTXO, this parameter is ignored,\n /// - The sweeping wallet must be in the Live or MovingFunds state,\n /// - The total Bitcoin transaction fee must be lesser or equal\n /// to `movedFundsSweepTxMaxTotalFee` governable parameter.\n function submitMovedFundsSweepProof(\n BridgeState.Storage storage self,\n BitcoinTx.Info calldata sweepTx,\n BitcoinTx.Proof calldata sweepProof,\n BitcoinTx.UTXO calldata mainUtxo\n ) external {\n // The actual transaction proof is performed here. After that point, we\n // can assume the transaction happened on Bitcoin chain and has\n // a sufficient number of confirmations as determined by\n // `txProofDifficultyFactor` constant.\n bytes32 sweepTxHash = self.validateProof(sweepTx, sweepProof);\n\n (\n bytes20 walletPubKeyHash,\n uint64 sweepTxOutputValue\n ) = processMovedFundsSweepTxOutput(self, sweepTx.outputVector);\n\n (\n Wallets.Wallet storage wallet,\n BitcoinTx.UTXO memory resolvedMainUtxo\n ) = resolveMovedFundsSweepingWallet(self, walletPubKeyHash, mainUtxo);\n\n uint256 sweepTxInputsTotalValue = processMovedFundsSweepTxInputs(\n self,\n sweepTx.inputVector,\n resolvedMainUtxo,\n walletPubKeyHash\n );\n\n require(\n sweepTxInputsTotalValue - sweepTxOutputValue <=\n self.movedFundsSweepTxMaxTotalFee,\n \"Transaction fee is too high\"\n );\n\n // Use the sweep transaction output as the new sweeping wallet's main UTXO.\n // Transaction output index is always 0 as sweep transaction always\n // contains only one output.\n wallet.mainUtxoHash = keccak256(\n abi.encodePacked(sweepTxHash, uint32(0), sweepTxOutputValue)\n );\n\n // slither-disable-next-line reentrancy-events\n emit MovedFundsSwept(walletPubKeyHash, sweepTxHash);\n }\n\n /// @notice Processes the Bitcoin moved funds sweep transaction output vector\n /// by extracting the single output and using it to gain additional\n /// information required for further processing (e.g. value and\n /// wallet public key hash).\n /// @param sweepTxOutputVector Bitcoin moved funds sweep transaction output\n /// vector.\n /// This function assumes vector's structure is valid so it must be\n /// validated using e.g. `BTCUtils.validateVout` function before\n /// it is passed here.\n /// @return walletPubKeyHash 20-byte wallet public key hash.\n /// @return value 8-byte moved funds sweep transaction output value.\n /// @dev Requirements:\n /// - Output vector must contain only one output,\n /// - The single output must be of P2PKH or P2WPKH type and lock the\n /// funds on a 20-byte public key hash.\n function processMovedFundsSweepTxOutput(\n BridgeState.Storage storage self,\n bytes memory sweepTxOutputVector\n ) internal view returns (bytes20 walletPubKeyHash, uint64 value) {\n // To determine the total number of sweep transaction outputs, we need to\n // parse the compactSize uint (VarInt) the output vector is prepended by.\n // That compactSize uint encodes the number of vector elements using the\n // format presented in:\n // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers\n // We don't need asserting the compactSize uint is parseable since it\n // was already checked during `validateVout` validation performed as\n // part of the `BitcoinTx.validateProof` call.\n // See `BitcoinTx.outputVector` docs for more details.\n (, uint256 outputsCount) = sweepTxOutputVector.parseVarInt();\n require(\n outputsCount == 1,\n \"Moved funds sweep transaction must have a single output\"\n );\n\n bytes memory output = sweepTxOutputVector.extractOutputAtIndex(0);\n walletPubKeyHash = self.extractPubKeyHash(output);\n value = output.extractValue();\n\n return (walletPubKeyHash, value);\n }\n\n /// @notice Resolves sweeping wallet based on the provided wallet public key\n /// hash. Validates the wallet state and current main UTXO, as\n /// currently known on the Ethereum chain.\n /// @param walletPubKeyHash public key hash of the wallet proving the sweep\n /// Bitcoin transaction.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain. If no main UTXO exists for the given wallet,\n /// this parameter is ignored.\n /// @return wallet Data of the sweeping wallet.\n /// @return resolvedMainUtxo The actual main UTXO of the sweeping wallet\n /// resolved by cross-checking the `mainUtxo` parameter with\n /// the chain state. If the validation went well, this is the\n /// plain-text main UTXO corresponding to the `wallet.mainUtxoHash`.\n /// @dev Requirements:\n /// - Sweeping wallet must be either in Live or MovingFunds state,\n /// - If the main UTXO of the sweeping wallet exists in the storage,\n /// the passed `mainUTXO` parameter must be equal to the stored one.\n function resolveMovedFundsSweepingWallet(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata mainUtxo\n )\n internal\n view\n returns (\n Wallets.Wallet storage wallet,\n BitcoinTx.UTXO memory resolvedMainUtxo\n )\n {\n wallet = self.registeredWallets[walletPubKeyHash];\n\n Wallets.WalletState walletState = wallet.state;\n require(\n walletState == Wallets.WalletState.Live ||\n walletState == Wallets.WalletState.MovingFunds,\n \"Wallet must be in Live or MovingFunds state\"\n );\n\n // Check if the main UTXO for given wallet exists. If so, validate\n // passed main UTXO data against the stored hash and use them for\n // further processing. If no main UTXO exists, use empty data.\n resolvedMainUtxo = BitcoinTx.UTXO(bytes32(0), 0, 0);\n bytes32 mainUtxoHash = wallet.mainUtxoHash;\n if (mainUtxoHash != bytes32(0)) {\n require(\n keccak256(\n abi.encodePacked(\n mainUtxo.txHash,\n mainUtxo.txOutputIndex,\n mainUtxo.txOutputValue\n )\n ) == mainUtxoHash,\n \"Invalid main UTXO data\"\n );\n resolvedMainUtxo = mainUtxo;\n }\n }\n\n /// @notice Processes the Bitcoin moved funds sweep transaction input vector.\n /// It extracts the first input and tries to match it with one of\n /// the moved funds sweep requests targeting the sweeping wallet.\n /// If the sweep request is an existing Pending request, this\n /// function marks it as Processed. If the sweeping wallet has a\n /// main UTXO, this function extracts the second input, makes sure\n /// it refers to the wallet main UTXO, and marks that main UTXO as\n /// correctly spent.\n /// @param sweepTxInputVector Bitcoin moved funds sweep transaction input vector.\n /// This function assumes vector's structure is valid so it must be\n /// validated using e.g. `BTCUtils.validateVin` function before\n /// it is passed here.\n /// @param mainUtxo Data of the sweeping wallet's main UTXO. If no main UTXO\n /// exists for the given the wallet, this parameter's fields should\n /// be zeroed to bypass the main UTXO validation.\n /// @param walletPubKeyHash 20-byte public key hash of the sweeping wallet.\n /// @return inputsTotalValue Total inputs value sum.\n /// @dev Requirements:\n /// - The input vector must consist of one mandatory and one optional\n /// input,\n /// - The mandatory input must be the first input in the vector,\n /// - The mandatory input must point to a Pending moved funds sweep\n /// request that is targeted to the sweeping wallet,\n /// - The optional output must be the second input in the vector,\n /// - The optional input is required if the sweeping wallet has a\n /// main UTXO (i.e. the `mainUtxo` is not zeroed). In that case,\n /// that input must point the the sweeping wallet main UTXO.\n function processMovedFundsSweepTxInputs(\n BridgeState.Storage storage self,\n bytes memory sweepTxInputVector,\n BitcoinTx.UTXO memory mainUtxo,\n bytes20 walletPubKeyHash\n ) internal returns (uint256 inputsTotalValue) {\n // To determine the total number of Bitcoin transaction inputs,\n // we need to parse the compactSize uint (VarInt) the input vector is\n // prepended by. That compactSize uint encodes the number of vector\n // elements using the format presented in:\n // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers\n // We don't need asserting the compactSize uint is parseable since it\n // was already checked during `validateVin` validation performed as\n // part of the `BitcoinTx.validateProof` call.\n // See `BitcoinTx.inputVector` docs for more details.\n (\n uint256 inputsCompactSizeUintLength,\n uint256 inputsCount\n ) = sweepTxInputVector.parseVarInt();\n\n // To determine the first input starting index, we must jump over\n // the compactSize uint which prepends the input vector. One byte\n // must be added because `BtcUtils.parseVarInt` does not include\n // compactSize uint tag in the returned length.\n //\n // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`\n // returns `0`, so we jump over one byte of compactSize uint.\n //\n // For >= 253 && <= 0xffff there is `0xfd` tag,\n // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no\n // tag byte included) so we need to jump over 1+2 bytes of\n // compactSize uint.\n //\n // Please refer `BTCUtils` library and compactSize uint\n // docs in `BitcoinTx` library for more details.\n uint256 inputStartingIndex = 1 + inputsCompactSizeUintLength;\n\n // We always expect the first input to be the swept UTXO. Additionally,\n // if the sweeping wallet has a main UTXO, that main UTXO should be\n // pointed by the second input.\n require(\n inputsCount == (mainUtxo.txHash != bytes32(0) ? 2 : 1),\n \"Moved funds sweep transaction must have a proper inputs count\"\n );\n\n // Parse the first input and extract its outpoint tx hash and index.\n (\n bytes32 firstInputOutpointTxHash,\n uint32 firstInputOutpointIndex,\n uint256 firstInputLength\n ) = parseMovedFundsSweepTxInputAt(\n sweepTxInputVector,\n inputStartingIndex\n );\n\n // Build the request key and fetch the corresponding moved funds sweep\n // request from contract storage.\n MovedFundsSweepRequest storage sweepRequest = self\n .movedFundsSweepRequests[\n uint256(\n keccak256(\n abi.encodePacked(\n firstInputOutpointTxHash,\n firstInputOutpointIndex\n )\n )\n )\n ];\n\n require(\n sweepRequest.state == MovedFundsSweepRequestState.Pending,\n \"Sweep request must be in Pending state\"\n );\n // We must check if the wallet extracted from the moved funds sweep\n // transaction output is truly the owner of the sweep request connected\n // with the swept UTXO. This is needed to prevent a case when a wallet\n // handles its own sweep request but locks the funds on another\n // wallet public key hash.\n require(\n sweepRequest.walletPubKeyHash == walletPubKeyHash,\n \"Sweep request belongs to another wallet\"\n );\n // If the validation passed, the sweep request must be marked as\n // processed and its value should be counted into the total inputs\n // value sum.\n sweepRequest.state = MovedFundsSweepRequestState.Processed;\n inputsTotalValue += sweepRequest.value;\n\n self\n .registeredWallets[walletPubKeyHash]\n .pendingMovedFundsSweepRequestsCount--;\n\n // If the main UTXO for the sweeping wallet exists, it must be processed.\n if (mainUtxo.txHash != bytes32(0)) {\n // The second input is supposed to point to that sweeping wallet\n // main UTXO. We need to parse that input.\n (\n bytes32 secondInputOutpointTxHash,\n uint32 secondInputOutpointIndex,\n\n ) = parseMovedFundsSweepTxInputAt(\n sweepTxInputVector,\n inputStartingIndex + firstInputLength\n );\n // Make sure the second input refers to the sweeping wallet main UTXO.\n require(\n mainUtxo.txHash == secondInputOutpointTxHash &&\n mainUtxo.txOutputIndex == secondInputOutpointIndex,\n \"Second input must point to the wallet's main UTXO\"\n );\n\n // If the validation passed, count the main UTXO value into the\n // total inputs value sum.\n inputsTotalValue += mainUtxo.txOutputValue;\n\n // Main UTXO used as an input, mark it as spent. This is needed\n // to defend against fraud challenges referring to this main UTXO.\n self.spentMainUTXOs[\n uint256(\n keccak256(\n abi.encodePacked(\n secondInputOutpointTxHash,\n secondInputOutpointIndex\n )\n )\n )\n ] = true;\n }\n\n return inputsTotalValue;\n }\n\n /// @notice Parses a Bitcoin transaction input starting at the given index.\n /// @param inputVector Bitcoin transaction input vector.\n /// @param inputStartingIndex Index the given input starts at.\n /// @return outpointTxHash 32-byte hash of the Bitcoin transaction which is\n /// pointed in the given input's outpoint.\n /// @return outpointIndex 4-byte index of the Bitcoin transaction output\n /// which is pointed in the given input's outpoint.\n /// @return inputLength Byte length of the given input.\n /// @dev This function assumes vector's structure is valid so it must be\n /// validated using e.g. `BTCUtils.validateVin` function before it\n /// is passed here.\n function parseMovedFundsSweepTxInputAt(\n bytes memory inputVector,\n uint256 inputStartingIndex\n )\n internal\n pure\n returns (\n bytes32 outpointTxHash,\n uint32 outpointIndex,\n uint256 inputLength\n )\n {\n outpointTxHash = inputVector.extractInputTxIdLeAt(inputStartingIndex);\n\n outpointIndex = BTCUtils.reverseUint32(\n uint32(inputVector.extractTxIndexLeAt(inputStartingIndex))\n );\n\n inputLength = inputVector.determineInputLengthAt(inputStartingIndex);\n\n return (outpointTxHash, outpointIndex, inputLength);\n }\n\n /// @notice Notifies about a timed out moved funds sweep process. If the\n /// wallet is not terminated yet, that function terminates\n /// the wallet and slashes signing group members as a result.\n /// Marks the given sweep request as TimedOut.\n /// @param movingFundsTxHash 32-byte hash of the moving funds transaction\n /// that caused the sweep request to be created.\n /// @param movingFundsTxOutputIndex Index of the moving funds transaction\n /// output that is subject of the sweep request.\n /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @dev Requirements:\n /// - The moved funds sweep request must be in the Pending state,\n /// - The moved funds sweep timeout must be actually exceeded,\n /// - The wallet must be either in the Live or MovingFunds or\n /// Terminated state,,\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events of the `WalletRegistry` contract.\n function notifyMovedFundsSweepTimeout(\n BridgeState.Storage storage self,\n bytes32 movingFundsTxHash,\n uint32 movingFundsTxOutputIndex,\n uint32[] calldata walletMembersIDs\n ) external {\n MovedFundsSweepRequest storage sweepRequest = self\n .movedFundsSweepRequests[\n uint256(\n keccak256(\n abi.encodePacked(\n movingFundsTxHash,\n movingFundsTxOutputIndex\n )\n )\n )\n ];\n\n require(\n sweepRequest.state == MovedFundsSweepRequestState.Pending,\n \"Sweep request must be in Pending state\"\n );\n\n require(\n /* solhint-disable-next-line not-rely-on-time */\n block.timestamp >\n sweepRequest.createdAt + self.movedFundsSweepTimeout,\n \"Sweep request has not timed out yet\"\n );\n\n bytes20 walletPubKeyHash = sweepRequest.walletPubKeyHash;\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n Wallets.WalletState walletState = wallet.state;\n\n require(\n walletState == Wallets.WalletState.Live ||\n walletState == Wallets.WalletState.MovingFunds ||\n walletState == Wallets.WalletState.Terminated,\n \"ECDSA wallet must be in Live or MovingFunds or Terminated state\"\n );\n\n sweepRequest.state = MovedFundsSweepRequestState.TimedOut;\n wallet.pendingMovedFundsSweepRequestsCount--;\n\n if (\n walletState == Wallets.WalletState.Live ||\n walletState == Wallets.WalletState.MovingFunds\n ) {\n self.terminateWallet(walletPubKeyHash);\n\n self.ecdsaWalletRegistry.seize(\n self.movedFundsSweepTimeoutSlashingAmount,\n self.movedFundsSweepTimeoutNotifierRewardMultiplier,\n msg.sender,\n wallet.ecdsaWalletID,\n walletMembersIDs\n );\n }\n\n // slither-disable-next-line reentrancy-events\n emit MovedFundsSweepTimedOut(\n walletPubKeyHash,\n movingFundsTxHash,\n movingFundsTxOutputIndex\n );\n }\n}\n"
201
- },
202
- "@keep-network/bitcoin-spv-sol/contracts/CheckBitcoinSigs.sol": {
203
- "content": "pragma solidity ^0.8.4;\n\n/** @title CheckBitcoinSigs */\n/** @author Summa (https://summa.one) */\n\nimport {BytesLib} from \"./BytesLib.sol\";\nimport {BTCUtils} from \"./BTCUtils.sol\";\n\n\nlibrary CheckBitcoinSigs {\n\n using BytesLib for bytes;\n using BTCUtils for bytes;\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\n function 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 /// @notice Calculates the p2wpkh output script of a pubkey\n /// @dev Compresses keys to 33 bytes as required by Bitcoin\n /// @param _pubkey The public key, compressed or uncompressed\n /// @return The p2wkph output script\n function p2wpkhFromPubkey(bytes memory _pubkey) internal view returns (bytes memory) {\n bytes memory _compressedPubkey;\n uint8 _prefix;\n\n if (_pubkey.length == 64) {\n _prefix = uint8(_pubkey[_pubkey.length - 1]) % 2 == 1 ? 3 : 2;\n _compressedPubkey = abi.encodePacked(_prefix, _pubkey.slice32(0));\n } else if (_pubkey.length == 65) {\n _prefix = uint8(_pubkey[_pubkey.length - 1]) % 2 == 1 ? 3 : 2;\n _compressedPubkey = abi.encodePacked(_prefix, _pubkey.slice32(1));\n } else {\n _compressedPubkey = _pubkey;\n }\n\n require(_compressedPubkey.length == 33, \"Witness PKH requires compressed keys\");\n\n bytes20 _pubkeyHash = _compressedPubkey.hash160View();\n return abi.encodePacked(hex\"0014\", _pubkeyHash);\n }\n\n /// @notice checks a signed message's validity under a pubkey\n /// @dev does this using ecrecover because Ethereum has no soul\n /// @param _pubkey the public key to check (64 bytes)\n /// @param _digest the message digest signed\n /// @param _v the signature recovery value\n /// @param _r the signature r value\n /// @param _s the signature s value\n /// @return true if signature is valid, else false\n function checkSig(\n bytes memory _pubkey,\n bytes32 _digest,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) internal pure returns (bool) {\n require(_pubkey.length == 64, \"Requires uncompressed unprefixed pubkey\");\n address _expected = accountFromPubkey(_pubkey);\n address _actual = ecrecover(_digest, _v, _r, _s);\n return _actual == _expected;\n }\n\n /// @notice checks a signed message against a bitcoin p2wpkh output script\n /// @dev does this my verifying the p2wpkh matches an ethereum account\n /// @param _p2wpkhOutputScript the bitcoin output script\n /// @param _pubkey the uncompressed, unprefixed public key to check\n /// @param _digest the message digest signed\n /// @param _v the signature recovery value\n /// @param _r the signature r value\n /// @param _s the signature s value\n /// @return true if signature is valid, else false\n function checkBitcoinSig(\n bytes memory _p2wpkhOutputScript,\n bytes memory _pubkey,\n bytes32 _digest,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) internal view returns (bool) {\n require(_pubkey.length == 64, \"Requires uncompressed unprefixed pubkey\");\n\n bool _isExpectedSigner = keccak256(p2wpkhFromPubkey(_pubkey)) == keccak256(_p2wpkhOutputScript); // is it the expected signer?\n if (!_isExpectedSigner) {return false;}\n\n bool _sigResult = checkSig(_pubkey, _digest, _v, _r, _s);\n return _sigResult;\n }\n\n /// @notice checks if a message is the sha256 preimage of a digest\n /// @dev this is NOT the hash256! this step is necessary for ECDSA security!\n /// @param _digest the digest\n /// @param _candidate the purported preimage\n /// @return true if the preimage matches the digest, else false\n function isSha256Preimage(\n bytes memory _candidate,\n bytes32 _digest\n ) internal pure returns (bool) {\n return sha256(_candidate) == _digest;\n }\n\n /// @notice checks if a message is the keccak256 preimage of a digest\n /// @dev this step is necessary for ECDSA security!\n /// @param _digest the digest\n /// @param _candidate the purported preimage\n /// @return true if the preimage matches the digest, else false\n function isKeccak256Preimage(\n bytes memory _candidate,\n bytes32 _digest\n ) internal pure returns (bool) {\n return keccak256(_candidate) == _digest;\n }\n\n /// @notice calculates the signature hash of a Bitcoin transaction with the provided details\n /// @dev documented in bip143. many values are hardcoded here\n /// @param _outpoint the bitcoin UTXO id (32-byte txid + 4-byte output index)\n /// @param _inputPKH the input pubkeyhash (hash160(sender_pubkey))\n /// @param _inputValue the value of the input in satoshi\n /// @param _outputValue the value of the output in satoshi\n /// @param _outputScript the length-prefixed output script\n /// @return the double-sha256 (hash256) signature hash as defined by bip143\n function 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 view 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\n bytes32 _hashOutputs = abi.encodePacked(\n _outputValue, // 8-byte LE\n _outputScript).hash256View();\n\n bytes memory _sighashPreimage = abi.encodePacked(\n hex\"01000000\", // version\n _outpoint.hash256View(), // hashPrevouts\n hex\"8cb9012517c817fead650287d61bdd9c68803b6bf9c64133dcab3e65b5a50cb9\", // hashSequence(00000000)\n _outpoint, // outpoint\n // p2wpkh script code\n hex\"1976a914\", // length, dup, hash160, pkh_length\n _inputPKH,\n hex\"88ac\", // equal, checksig\n // end 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.hash256View();\n }\n\n /// @notice calculates the signature hash of a Bitcoin transaction with the provided details\n /// @dev documented in bip143. many values are hardcoded here\n /// @param _outpoint the bitcoin UTXO id (32-byte txid + 4-byte output index)\n /// @param _inputPKH the input pubkeyhash (hash160(sender_pubkey))\n /// @param _inputValue the value of the input in satoshi\n /// @param _outputValue the value of the output in satoshi\n /// @param _outputPKH the output pubkeyhash (hash160(recipient_pubkey))\n /// @return the double-sha256 (hash256) signature hash as defined by bip143\n function wpkhToWpkhSighash(\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 bytes20 _outputPKH // 20-byte hash160\n ) internal view returns (bytes32) {\n return wpkhSpendSighash(\n _outpoint,\n _inputPKH,\n _inputValue,\n _outputValue,\n abi.encodePacked(\n hex\"160014\", // wpkh tag\n _outputPKH)\n );\n }\n\n /// @notice Preserved for API compatibility with older version\n /// @dev documented in bip143. many values are hardcoded here\n /// @param _outpoint the bitcoin UTXO id (32-byte txid + 4-byte output index)\n /// @param _inputPKH the input pubkeyhash (hash160(sender_pubkey))\n /// @param _inputValue the value of the input in satoshi\n /// @param _outputValue the value of the output in satoshi\n /// @param _outputPKH the output pubkeyhash (hash160(recipient_pubkey))\n /// @return the double-sha256 (hash256) signature hash as defined by bip143\n function oneInputOneOutputSighash(\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 bytes20 _outputPKH // 20-byte hash160\n ) internal view returns (bytes32) {\n return wpkhToWpkhSighash(_outpoint, _inputPKH, _inputValue, _outputValue, _outputPKH);\n }\n\n}\n"
204
- },
205
- "contracts/bridge/Heartbeat.sol": {
206
- "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {BytesLib} from \"@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol\";\n\n/// @title Bridge wallet heartbeat\n/// @notice The library establishes expected format for heartbeat messages\n/// signed by wallet ECDSA signing group. Heartbeat messages are\n/// constructed in such a way that they can not be used as a Bitcoin\n/// transaction preimages.\n/// @dev The smallest Bitcoin non-coinbase transaction is a one spending an\n/// OP_TRUE anyonecanspend output and creating 1 OP_TRUE anyonecanspend\n/// output. Such a transaction has 61 bytes (see `BitcoinTx` documentation):\n/// 4 bytes for version\n/// 1 byte for tx_in_count\n/// 36 bytes for tx_in.previous_output\n/// 1 byte for tx_in.script_bytes (value: 0)\n/// 0 bytes for tx_in.signature_script\n/// 4 bytes for tx_in.sequence\n/// 1 byte for tx_out_count\n/// 8 bytes for tx_out.value\n/// 1 byte for tx_out.pk_script_bytes\n/// 1 byte for tx_out.pk_script\n/// 4 bytes for lock_time\n///\n///\n/// The smallest Bitcoin coinbase transaction is a one creating\n/// 1 OP_TRUE anyonecanspend output and having an empty coinbase script.\n/// Such a transaction has 65 bytes:\n/// 4 bytes for version\n/// 1 byte for tx_in_count\n/// 32 bytes for tx_in.hash (all 0x00)\n/// 4 bytes for tx_in.index (all 0xff)\n/// 1 byte for tx_in.script_bytes (value: 0)\n/// 4 bytes for tx_in.height\n/// 0 byte for tx_in.coinbase_script\n/// 4 bytes for tx_in.sequence\n/// 1 byte for tx_out_count\n/// 8 bytes for tx_out.value\n/// 1 byte for tx_out.pk_script_bytes\n/// 1 byte for tx_out.pk_script\n/// 4 bytes for lock_time\n///\n///\n/// A SIGHASH flag is used to indicate which part of the transaction is\n/// signed by the ECDSA signature. There are currently 3 flags:\n/// SIGHASH_ALL, SIGHASH_NONE, SIGHASH_SINGLE, and different combinations\n/// of these flags.\n///\n/// No matter the SIGHASH flag and no matter the combination, the following\n/// fields from the transaction are always included in the constructed\n/// preimage:\n/// 4 bytes for version\n/// 36 bytes for tx_in.previous_output (or tx_in.hash + tx_in.index for coinbase)\n/// 4 bytes for lock_time\n///\n/// Additionally, the last 4 bytes of the preimage determines the SIGHASH\n/// flag.\n///\n/// This is enough to say there is no way the preimage could be shorter\n/// than 4 + 36 + 4 + 4 = 48 bytes.\n///\n/// For this reason, we construct the heartbeat message, as a 16-byte\n/// message. The first 8 bytes are 0xffffffffffffffff. The last 8 bytes\n/// are for an arbitrary uint64, being a signed heartbeat nonce (for\n/// example, the last Ethereum block hash).\n///\n/// The message being signed by the wallet when executing the heartbeat\n/// protocol should be Bitcoin's hash256 (double SHA-256) of the heartbeat\n/// message:\n/// heartbeat_sighash = hash256(heartbeat_message)\nlibrary Heartbeat {\n using BytesLib for bytes;\n\n /// @notice Determines if the signed byte array is a valid, non-fraudulent\n /// heartbeat message.\n /// @param message Message signed by the wallet. It is a potential heartbeat\n /// message, Bitcoin transaction preimage, or an arbitrary signed\n /// bytes.\n /// @dev Wallet heartbeat message must be exactly 16 bytes long with the first\n /// 8 bytes set to 0xffffffffffffffff.\n /// @return True if valid heartbeat message, false otherwise.\n function isValidHeartbeatMessage(bytes calldata message)\n internal\n pure\n returns (bool)\n {\n if (message.length != 16) {\n return false;\n }\n\n if (message.slice8(0) != 0xffffffffffffffff) {\n return false;\n }\n\n return true;\n }\n}\n"
207
- },
208
- "contracts/test/BridgeStub.sol": {
209
- "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.9;\n\nimport \"../bridge/BitcoinTx.sol\";\nimport \"../bridge/Bridge.sol\";\nimport \"../bridge/MovingFunds.sol\";\nimport \"../bridge/Wallets.sol\";\n\ncontract BridgeStub is Bridge {\n function setSweptDeposits(BitcoinTx.UTXO[] calldata utxos) external {\n for (uint256 i = 0; i < utxos.length; i++) {\n uint256 utxoKey = uint256(\n keccak256(\n abi.encodePacked(utxos[i].txHash, utxos[i].txOutputIndex)\n )\n );\n self.deposits[utxoKey].sweptAt = 1641650400;\n }\n }\n\n function setSpentMainUtxos(BitcoinTx.UTXO[] calldata utxos) external {\n for (uint256 i = 0; i < utxos.length; i++) {\n uint256 utxoKey = uint256(\n keccak256(\n abi.encodePacked(utxos[i].txHash, utxos[i].txOutputIndex)\n )\n );\n self.spentMainUTXOs[utxoKey] = true;\n }\n }\n\n function setProcessedMovedFundsSweepRequests(\n BitcoinTx.UTXO[] calldata utxos\n ) external {\n for (uint256 i = 0; i < utxos.length; i++) {\n uint256 utxoKey = uint256(\n keccak256(\n abi.encodePacked(utxos[i].txHash, utxos[i].txOutputIndex)\n )\n );\n self.movedFundsSweepRequests[utxoKey].state = MovingFunds\n .MovedFundsSweepRequestState\n .Processed;\n }\n }\n\n function setActiveWallet(bytes20 activeWalletPubKeyHash) external {\n self.activeWalletPubKeyHash = activeWalletPubKeyHash;\n }\n\n function setWalletMainUtxo(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata utxo\n ) external {\n self.registeredWallets[walletPubKeyHash].mainUtxoHash = keccak256(\n abi.encodePacked(\n utxo.txHash,\n utxo.txOutputIndex,\n utxo.txOutputValue\n )\n );\n }\n\n function setWallet(bytes20 walletPubKeyHash, Wallets.Wallet calldata wallet)\n external\n {\n self.registeredWallets[walletPubKeyHash] = wallet;\n\n if (wallet.state == Wallets.WalletState.Live) {\n self.liveWalletsCount++;\n }\n }\n\n function setDepositDustThreshold(uint64 _depositDustThreshold) external {\n self.depositDustThreshold = _depositDustThreshold;\n }\n\n function setDepositTxMaxFee(uint64 _depositTxMaxFee) external {\n self.depositTxMaxFee = _depositTxMaxFee;\n }\n\n function setRedemptionDustThreshold(uint64 _redemptionDustThreshold)\n external\n {\n self.redemptionDustThreshold = _redemptionDustThreshold;\n }\n\n function setRedemptionTreasuryFeeDivisor(\n uint64 _redemptionTreasuryFeeDivisor\n ) external {\n self.redemptionTreasuryFeeDivisor = _redemptionTreasuryFeeDivisor;\n }\n\n function setMovingFundsTxMaxTotalFee(uint64 _movingFundsTxMaxTotalFee)\n external\n {\n self.movingFundsTxMaxTotalFee = _movingFundsTxMaxTotalFee;\n }\n\n function setPendingMovedFundsSweepRequest(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata utxo\n ) external {\n uint256 requestKey = uint256(\n keccak256(abi.encodePacked(utxo.txHash, utxo.txOutputIndex))\n );\n\n self.movedFundsSweepRequests[requestKey] = MovingFunds\n .MovedFundsSweepRequest(\n walletPubKeyHash,\n utxo.txOutputValue,\n /* solhint-disable-next-line not-rely-on-time */\n uint32(block.timestamp),\n MovingFunds.MovedFundsSweepRequestState.Pending\n );\n\n self\n .registeredWallets[walletPubKeyHash]\n .pendingMovedFundsSweepRequestsCount++;\n }\n\n function processPendingMovedFundsSweepRequest(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata utxo\n ) external {\n uint256 requestKey = uint256(\n keccak256(abi.encodePacked(utxo.txHash, utxo.txOutputIndex))\n );\n\n MovingFunds.MovedFundsSweepRequest storage request = self\n .movedFundsSweepRequests[requestKey];\n\n require(\n request.state == MovingFunds.MovedFundsSweepRequestState.Pending,\n \"Stub sweep request must be in Pending state\"\n );\n\n request.state = MovingFunds.MovedFundsSweepRequestState.Processed;\n\n self\n .registeredWallets[walletPubKeyHash]\n .pendingMovedFundsSweepRequestsCount--;\n }\n\n function timeoutPendingMovedFundsSweepRequest(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata utxo\n ) external {\n uint256 requestKey = uint256(\n keccak256(abi.encodePacked(utxo.txHash, utxo.txOutputIndex))\n );\n\n MovingFunds.MovedFundsSweepRequest storage request = self\n .movedFundsSweepRequests[requestKey];\n\n require(\n request.state == MovingFunds.MovedFundsSweepRequestState.Pending,\n \"Stub sweep request must be in Pending state\"\n );\n\n request.state = MovingFunds.MovedFundsSweepRequestState.TimedOut;\n\n self\n .registeredWallets[walletPubKeyHash]\n .pendingMovedFundsSweepRequestsCount--;\n }\n\n function setMovedFundsSweepTxMaxTotalFee(\n uint64 _movedFundsSweepTxMaxTotalFee\n ) external {\n self.movedFundsSweepTxMaxTotalFee = _movedFundsSweepTxMaxTotalFee;\n }\n}\n"
250
+ "@keep-network/random-beacon/contracts/ReimbursementPool.sol": {
251
+ "content": "// SPDX-License-Identifier: MIT\n//\n// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄\n// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓\n// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓\n// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀\n// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌\n// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓\n//\n// Trust math, not hardware.\n\npragma solidity ^0.8.9;\n\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\nimport \"@openzeppelin/contracts/security/ReentrancyGuard.sol\";\n\ncontract ReimbursementPool is Ownable, ReentrancyGuard {\n /// @notice Authorized contracts that can interact with the reimbursment pool.\n /// Authorization can be granted and removed by the owner.\n mapping(address => bool) public isAuthorized;\n\n /// @notice Static gas includes:\n /// - cost of the refund function\n /// - base transaction cost\n uint256 public staticGas;\n\n /// @notice Max gas price used to reimburse a transaction submitter. Protects\n /// against malicious operator-miners.\n uint256 public maxGasPrice;\n\n event StaticGasUpdated(uint256 newStaticGas);\n\n event MaxGasPriceUpdated(uint256 newMaxGasPrice);\n\n event SendingEtherFailed(uint256 refundAmount, address receiver);\n\n event AuthorizedContract(address thirdPartyContract);\n\n event UnauthorizedContract(address thirdPartyContract);\n\n event FundsWithdrawn(uint256 withdrawnAmount, address receiver);\n\n constructor(uint256 _staticGas, uint256 _maxGasPrice) {\n staticGas = _staticGas;\n maxGasPrice = _maxGasPrice;\n }\n\n /// @notice Receive ETH\n receive() external payable {}\n\n /// @notice Refunds ETH to a spender for executing specific transactions.\n /// @dev Ignoring the result of sending ETH to a receiver is made on purpose.\n /// For EOA receiving ETH should always work. If a receiver is a smart\n /// contract, then we do not want to fail a transaction, because in some\n /// cases the refund is done at the very end of multiple calls where all\n /// the previous calls were already paid off. It is a receiver's smart\n /// contract resposibility to make sure it can receive ETH.\n /// @dev Only authorized contracts are allowed calling this function.\n /// @param gasSpent Gas spent on a transaction that needs to be reimbursed.\n /// @param receiver Address where the reimbursment is sent.\n function refund(uint256 gasSpent, address receiver) external nonReentrant {\n require(\n isAuthorized[msg.sender],\n \"Contract is not authorized for a refund\"\n );\n require(receiver != address(0), \"Receiver's address cannot be zero\");\n\n uint256 gasPrice = tx.gasprice < maxGasPrice\n ? tx.gasprice\n : maxGasPrice;\n\n uint256 refundAmount = (gasSpent + staticGas) * gasPrice;\n\n /* solhint-disable avoid-low-level-calls */\n // slither-disable-next-line low-level-calls,unchecked-lowlevel\n (bool sent, ) = receiver.call{value: refundAmount}(\"\");\n /* solhint-enable avoid-low-level-calls */\n if (!sent) {\n // slither-disable-next-line reentrancy-events\n emit SendingEtherFailed(refundAmount, receiver);\n }\n }\n\n /// @notice Authorize a contract that can interact with this reimbursment pool.\n /// Can be authorized by the owner only.\n /// @param _contract Authorized contract.\n function authorize(address _contract) external onlyOwner {\n isAuthorized[_contract] = true;\n\n emit AuthorizedContract(_contract);\n }\n\n /// @notice Unauthorize a contract that was previously authorized to interact\n /// with this reimbursment pool. Can be unauthorized by the\n /// owner only.\n /// @param _contract Authorized contract.\n function unauthorize(address _contract) external onlyOwner {\n delete isAuthorized[_contract];\n\n emit UnauthorizedContract(_contract);\n }\n\n /// @notice Setting a static gas cost for executing a transaction. Can be set\n /// by the owner only.\n /// @param _staticGas Static gas cost.\n function setStaticGas(uint256 _staticGas) external onlyOwner {\n staticGas = _staticGas;\n\n emit StaticGasUpdated(_staticGas);\n }\n\n /// @notice Setting a max gas price for transactions. Can be set by the\n /// owner only.\n /// @param _maxGasPrice Max gas price used to reimburse tx submitters.\n function setMaxGasPrice(uint256 _maxGasPrice) external onlyOwner {\n maxGasPrice = _maxGasPrice;\n\n emit MaxGasPriceUpdated(_maxGasPrice);\n }\n\n /// @notice Withdraws all ETH from this pool which are sent to a given\n /// address. Can be set by the owner only.\n /// @param receiver An address where ETH is sent.\n function withdrawAll(address receiver) external onlyOwner {\n withdraw(address(this).balance, receiver);\n }\n\n /// @notice Withdraws ETH amount from this pool which are sent to a given\n /// address. Can be set by the owner only.\n /// @param amount Amount to withdraw from the pool.\n /// @param receiver An address where ETH is sent.\n function withdraw(uint256 amount, address receiver) public onlyOwner {\n require(\n address(this).balance >= amount,\n \"Insufficient contract balance\"\n );\n require(receiver != address(0), \"Receiver's address cannot be zero\");\n\n emit FundsWithdrawn(amount, receiver);\n\n /* solhint-disable avoid-low-level-calls */\n // slither-disable-next-line low-level-calls,arbitrary-send\n (bool sent, ) = receiver.call{value: amount}(\"\");\n /* solhint-enable avoid-low-level-calls */\n require(sent, \"Failed to send Ether\");\n }\n}\n"
210
252
  },
211
- "contracts/bridge/Bridge.sol": {
212
- "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport \"@keep-network/random-beacon/contracts/Governable.sol\";\nimport {IWalletOwner as EcdsaWalletOwner} from \"@keep-network/ecdsa/contracts/api/IWalletOwner.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\nimport \"./IRelay.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Deposit.sol\";\nimport \"./DepositSweep.sol\";\nimport \"./Redemption.sol\";\nimport \"./BitcoinTx.sol\";\nimport \"./EcdsaLib.sol\";\nimport \"./Wallets.sol\";\nimport \"./Fraud.sol\";\nimport \"./MovingFunds.sol\";\n\nimport \"../bank/Bank.sol\";\n\n/// @title Bitcoin Bridge\n/// @notice Bridge manages BTC deposit and redemption flow and is increasing and\n/// decreasing balances in the Bank as a result of BTC deposit and\n/// redemption operations performed by depositors and redeemers.\n///\n/// Depositors send BTC funds to the most recently created off-chain\n/// ECDSA wallet of the bridge using pay-to-script-hash (P2SH) or\n/// pay-to-witness-script-hash (P2WSH) containing hashed information\n/// about the depositor’s Ethereum address. Then, the depositor reveals\n/// their Ethereum address along with their deposit blinding factor,\n/// refund public key hash and refund locktime to the Bridge on Ethereum\n/// chain. The off-chain ECDSA wallet listens for these sorts of\n/// messages and when it gets one, it checks the Bitcoin network to make\n/// sure the deposit lines up. If it does, the off-chain ECDSA wallet\n/// may decide to pick the deposit transaction for sweeping, and when\n/// the sweep operation is confirmed on the Bitcoin network, the ECDSA\n/// wallet informs the Bridge about the sweep increasing appropriate\n/// balances in the Bank.\n/// @dev Bridge is an upgradeable component of the Bank. The order of\n/// functionalities in this contract is: deposit, sweep, redemption,\n/// moving funds, wallet lifecycle, frauds, parameters.\ncontract Bridge is Governable, EcdsaWalletOwner, Initializable {\n using BridgeState for BridgeState.Storage;\n using Deposit for BridgeState.Storage;\n using DepositSweep for BridgeState.Storage;\n using Redemption for BridgeState.Storage;\n using MovingFunds for BridgeState.Storage;\n using Wallets for BridgeState.Storage;\n using Fraud for BridgeState.Storage;\n\n BridgeState.Storage internal self;\n\n event DepositRevealed(\n bytes32 fundingTxHash,\n uint32 fundingOutputIndex,\n address indexed depositor,\n uint64 amount,\n bytes8 blindingFactor,\n bytes20 indexed walletPubKeyHash,\n bytes20 refundPubKeyHash,\n bytes4 refundLocktime,\n address vault\n );\n\n event DepositsSwept(bytes20 walletPubKeyHash, bytes32 sweepTxHash);\n\n event RedemptionRequested(\n bytes20 indexed walletPubKeyHash,\n bytes redeemerOutputScript,\n address indexed redeemer,\n uint64 requestedAmount,\n uint64 treasuryFee,\n uint64 txMaxFee\n );\n\n event RedemptionsCompleted(\n bytes20 indexed walletPubKeyHash,\n bytes32 redemptionTxHash\n );\n\n event RedemptionTimedOut(\n bytes20 indexed walletPubKeyHash,\n bytes redeemerOutputScript\n );\n\n event WalletMovingFunds(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event MovingFundsCommitmentSubmitted(\n bytes20 indexed walletPubKeyHash,\n bytes20[] targetWallets,\n address submitter\n );\n\n event MovingFundsTimeoutReset(bytes20 indexed walletPubKeyHash);\n\n event MovingFundsCompleted(\n bytes20 indexed walletPubKeyHash,\n bytes32 movingFundsTxHash\n );\n\n event MovingFundsTimedOut(bytes20 indexed walletPubKeyHash);\n\n event MovingFundsBelowDustReported(bytes20 indexed walletPubKeyHash);\n\n event MovedFundsSwept(\n bytes20 indexed walletPubKeyHash,\n bytes32 sweepTxHash\n );\n\n event MovedFundsSweepTimedOut(\n bytes20 indexed walletPubKeyHash,\n bytes32 movingFundsTxHash,\n uint32 movingFundsTxOutputIndex\n );\n\n event NewWalletRequested();\n\n event NewWalletRegistered(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletClosing(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletClosed(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletTerminated(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event FraudChallengeSubmitted(\n bytes20 indexed walletPubKeyHash,\n bytes32 sighash,\n uint8 v,\n bytes32 r,\n bytes32 s\n );\n\n event FraudChallengeDefeated(\n bytes20 indexed walletPubKeyHash,\n bytes32 sighash\n );\n\n event FraudChallengeDefeatTimedOut(\n bytes20 indexed walletPubKeyHash,\n bytes32 sighash\n );\n\n event VaultStatusUpdated(address indexed vault, bool isTrusted);\n\n event DepositParametersUpdated(\n uint64 depositDustThreshold,\n uint64 depositTreasuryFeeDivisor,\n uint64 depositTxMaxFee\n );\n\n event RedemptionParametersUpdated(\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint256 redemptionTimeout,\n uint96 redemptionTimeoutSlashingAmount,\n uint256 redemptionTimeoutNotifierRewardMultiplier\n );\n\n event MovingFundsParametersUpdated(\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeoutResetDelay,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint256 movingFundsTimeoutNotifierRewardMultiplier,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint256 movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n\n event WalletParametersUpdated(\n uint32 walletCreationPeriod,\n uint64 walletCreationMinBtcBalance,\n uint64 walletCreationMaxBtcBalance,\n uint64 walletClosureMinBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n );\n\n event FraudParametersUpdated(\n uint256 fraudChallengeDepositAmount,\n uint256 fraudChallengeDefeatTimeout,\n uint96 fraudSlashingAmount,\n uint256 fraudNotifierRewardMultiplier\n );\n\n /// @dev Initializes upgradable contract on deployment.\n /// @param _bank Address of the Bank the Bridge belongs to.\n /// @param _relay Address of the Bitcoin relay providing the current Bitcoin\n /// network difficulty.\n /// @param _treasury Address where the deposit and redemption treasury fees\n /// will be sent to.\n /// @param _ecdsaWalletRegistry Address of the ECDSA Wallet Registry contract.\n /// @param _txProofDifficultyFactor The number of confirmations on the Bitcoin\n /// chain required to successfully evaluate an SPV proof.\n function initialize(\n address _bank,\n address _relay,\n address _treasury,\n address _ecdsaWalletRegistry,\n uint256 _txProofDifficultyFactor\n ) external initializer {\n require(_bank != address(0), \"Bank address cannot be zero\");\n self.bank = Bank(_bank);\n\n require(_relay != address(0), \"Relay address cannot be zero\");\n self.relay = IRelay(_relay);\n\n require(\n _ecdsaWalletRegistry != address(0),\n \"ECDSA Wallet Registry address cannot be zero\"\n );\n self.ecdsaWalletRegistry = EcdsaWalletRegistry(_ecdsaWalletRegistry);\n\n require(_treasury != address(0), \"Treasury address cannot be zero\");\n self.treasury = _treasury;\n\n self.txProofDifficultyFactor = _txProofDifficultyFactor;\n\n // TODO: Revisit initial values.\n // https://github.com/keep-network/tbtc-v2/issues/258\n self.depositDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC\n self.depositTxMaxFee = 10000; // 10000 satoshi\n self.depositTreasuryFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005\n self.redemptionDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC\n self.redemptionTreasuryFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005\n self.redemptionTxMaxFee = 10000; // 10000 satoshi\n self.redemptionTimeout = 172800; // 48 hours\n self.redemptionTimeoutSlashingAmount = 10000 * 1e18; // 10000 T\n self.redemptionTimeoutNotifierRewardMultiplier = 100; // 100%\n self.movingFundsTxMaxTotalFee = 10000; // 10000 satoshi\n self.movingFundsDustThreshold = 20000; // 20000 satoshi\n self.movingFundsTimeoutResetDelay = 6 days;\n self.movingFundsTimeout = 7 days;\n self.movingFundsTimeoutSlashingAmount = 10000 * 1e18; // 10000 T\n self.movingFundsTimeoutNotifierRewardMultiplier = 100; //100%\n self.movedFundsSweepTxMaxTotalFee = 10000; // 10000 satoshi\n self.movedFundsSweepTimeout = 7 days;\n self.movedFundsSweepTimeoutSlashingAmount = 10000 * 1e18; // 10000 T\n self.movedFundsSweepTimeoutNotifierRewardMultiplier = 100; //100%\n self.fraudChallengeDepositAmount = 2 ether;\n self.fraudChallengeDefeatTimeout = 7 days;\n self.fraudSlashingAmount = 10000 * 1e18; // 10000 T\n self.fraudNotifierRewardMultiplier = 100; // 100%\n self.walletCreationPeriod = 1 weeks;\n self.walletCreationMinBtcBalance = 1e8; // 1 BTC\n self.walletCreationMaxBtcBalance = 100e8; // 100 BTC\n self.walletClosureMinBtcBalance = 5 * 1e7; // 0.5 BTC\n self.walletMaxAge = 26 weeks; // ~6 months\n self.walletMaxBtcTransfer = 10e8; // 10 BTC\n self.walletClosingPeriod = 40 days;\n\n _transferGovernance(msg.sender);\n }\n\n /// @notice Used by the depositor to reveal information about their P2(W)SH\n /// Bitcoin deposit to the Bridge on Ethereum chain. The off-chain\n /// wallet listens for revealed deposit events and may decide to\n /// include the revealed deposit in the next executed sweep.\n /// Information about the Bitcoin deposit can be revealed before or\n /// after the Bitcoin transaction with P2(W)SH deposit is mined on\n /// the Bitcoin chain. Worth noting, the gas cost of this function\n /// scales with the number of P2(W)SH transaction inputs and\n /// outputs. The deposit may be routed to one of the trusted vaults.\n /// When a deposit is routed to a vault, vault gets notified when\n /// the deposit gets swept and it may execute the appropriate action.\n /// @param fundingTx Bitcoin funding transaction data, see `BitcoinTx.Info`.\n /// @param reveal Deposit reveal data, see `RevealInfo struct.\n /// @dev Requirements:\n /// - `reveal.walletPubKeyHash` must identify a `Live` wallet,\n /// - `reveal.vault` must be 0x0 or point to a trusted vault,\n /// - `reveal.fundingOutputIndex` must point to the actual P2(W)SH\n /// output of the BTC deposit transaction,\n /// - `reveal.depositor` must be the Ethereum address used in the\n /// P2(W)SH BTC deposit transaction,\n /// - `reveal.blindingFactor` must be the blinding factor used in the\n /// P2(W)SH BTC deposit transaction,\n /// - `reveal.walletPubKeyHash` must be the wallet pub key hash used in\n /// the P2(W)SH BTC deposit transaction,\n /// - `reveal.refundPubKeyHash` must be the refund pub key hash used in\n /// the P2(W)SH BTC deposit transaction,\n /// - `reveal.refundLocktime` must be the refund locktime used in the\n /// P2(W)SH BTC deposit transaction,\n /// - BTC deposit for the given `fundingTxHash`, `fundingOutputIndex`\n /// can be revealed only one time.\n ///\n /// If any of these requirements is not met, the wallet _must_ refuse\n /// to sweep the deposit and the depositor has to wait until the\n /// deposit script unlocks to receive their BTC back.\n function revealDeposit(\n BitcoinTx.Info calldata fundingTx,\n Deposit.DepositRevealInfo calldata reveal\n ) external {\n self.revealDeposit(fundingTx, reveal);\n }\n\n /// @notice Used by the wallet to prove the BTC deposit sweep transaction\n /// and to update Bank balances accordingly. Sweep is only accepted\n /// if it satisfies SPV proof.\n ///\n /// The function is performing Bank balance updates by first\n /// computing the Bitcoin fee for the sweep transaction. The fee is\n /// divided evenly between all swept deposits. Each depositor\n /// receives a balance in the bank equal to the amount inferred\n /// during the reveal transaction, minus their fee share.\n ///\n /// It is possible to prove the given sweep only one time.\n /// @param sweepTx Bitcoin sweep transaction data.\n /// @param sweepProof Bitcoin sweep proof data.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain. If no main UTXO exists for the given wallet,\n /// this parameter is ignored.\n /// @param vault Optional address of the vault where all swept deposits\n /// should be routed to. All deposits swept as part of the transaction\n /// must have their `vault` parameters set to the same address.\n /// If this parameter is set to an address of a trusted vault, swept\n /// deposits are routed to that vault.\n /// If this parameter is set to the zero address or to an address\n /// of a non-trusted vault, swept deposits are not routed to a\n /// vault but depositors' balances are increased in the Bank\n /// individually.\n /// @dev Requirements:\n /// - `sweepTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash,\n /// - The `sweepTx` should represent a Bitcoin transaction with 1..n\n /// inputs. If the wallet has no main UTXO, all n inputs should\n /// correspond to P2(W)SH revealed deposits UTXOs. If the wallet has\n /// an existing main UTXO, one of the n inputs must point to that\n /// main UTXO and remaining n-1 inputs should correspond to P2(W)SH\n /// revealed deposits UTXOs. That transaction must have only\n /// one P2(W)PKH output locking funds on the 20-byte wallet public\n /// key hash,\n /// - All revealed deposits that are swept by `sweepTx` must have\n /// their `vault` parameters set to the same address as the address\n /// passed in the `vault` function parameter,\n /// - `sweepProof` components must match the expected structure. See\n /// `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// If there is no main UTXO, this parameter is ignored.\n function submitDepositSweepProof(\n BitcoinTx.Info calldata sweepTx,\n BitcoinTx.Proof calldata sweepProof,\n BitcoinTx.UTXO calldata mainUtxo,\n address vault\n ) external {\n self.submitDepositSweepProof(sweepTx, sweepProof, mainUtxo, vault);\n }\n\n /// @notice Requests redemption of the given amount from the specified\n /// wallet to the redeemer Bitcoin output script.\n /// @param walletPubKeyHash The 20-byte wallet public key hash (computed\n /// using Bitcoin HASH160 over the compressed ECDSA public key).\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain.\n /// @param redeemerOutputScript The redeemer's length-prefixed output\n /// script (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock\n /// redeemed BTC.\n /// @param amount Requested amount in satoshi. This is also the TBTC amount\n /// that is taken from redeemer's balance in the Bank upon request.\n /// Once the request is handled, the actual amount of BTC locked\n /// on the redeemer output script will be always lower than this value\n /// since the treasury and Bitcoin transaction fees must be incurred.\n /// The minimal amount satisfying the request can be computed as:\n /// `amount - (amount / redemptionTreasuryFeeDivisor) - redemptionTxMaxFee`.\n /// Fees values are taken at the moment of request creation.\n /// @dev Requirements:\n /// - Wallet behind `walletPubKeyHash` must be live,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain,\n /// - `redeemerOutputScript` must be a proper Bitcoin script,\n /// - `redeemerOutputScript` cannot have wallet PKH as payload,\n /// - `amount` must be above or equal the `redemptionDustThreshold`,\n /// - Given `walletPubKeyHash` and `redeemerOutputScript` pair can be\n /// used for only one pending request at the same time,\n /// - Wallet must have enough Bitcoin balance to proceed the request,\n /// - Redeemer must make an allowance in the Bank that the Bridge\n /// contract can spend the given `amount`.\n function requestRedemption(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes calldata redeemerOutputScript,\n uint64 amount\n ) external {\n self.requestRedemption(\n walletPubKeyHash,\n mainUtxo,\n redeemerOutputScript,\n amount\n );\n }\n\n /// @notice Used by the wallet to prove the BTC redemption transaction\n /// and to make the necessary bookkeeping. Redemption is only\n /// accepted if it satisfies SPV proof.\n ///\n /// The function is performing Bank balance updates by burning\n /// the total redeemed Bitcoin amount from Bridge balance and\n /// transferring the treasury fee sum to the treasury address.\n ///\n /// It is possible to prove the given redemption only one time.\n /// @param redemptionTx Bitcoin redemption transaction data.\n /// @param redemptionProof Bitcoin redemption proof data.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n /// HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the redemption transaction.\n /// @dev Requirements:\n /// - `redemptionTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash,\n /// - The `redemptionTx` should represent a Bitcoin transaction with\n /// exactly 1 input that refers to the wallet's main UTXO. That\n /// transaction should have 1..n outputs handling existing pending\n /// redemption requests or pointing to reported timed out requests.\n /// There can be also 1 optional output representing the\n /// change and pointing back to the 20-byte wallet public key hash.\n /// The change should be always present if the redeemed value sum\n /// is lower than the total wallet's BTC balance,\n /// - `redemptionProof` components must match the expected structure.\n /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// Additionally, the recent main UTXO on Ethereum must be set,\n /// - `walletPubKeyHash` must be connected with the main UTXO used\n /// as transaction single input.\n /// Other remarks:\n /// - Putting the change output as the first transaction output can\n /// save some gas because the output processing loop begins each\n /// iteration by checking whether the given output is the change\n /// thus uses some gas for making the comparison. Once the change\n /// is identified, that check is omitted in further iterations.\n function submitRedemptionProof(\n BitcoinTx.Info calldata redemptionTx,\n BitcoinTx.Proof calldata redemptionProof,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes20 walletPubKeyHash\n ) external {\n self.submitRedemptionProof(\n redemptionTx,\n redemptionProof,\n mainUtxo,\n walletPubKeyHash\n );\n }\n\n /// @notice Notifies that there is a pending redemption request associated\n /// with the given wallet, that has timed out. The redemption\n /// request is identified by the key built as\n /// `keccak256(walletPubKeyHash | redeemerOutputScript)`.\n /// The results of calling this function:\n /// - The pending redemptions value for the wallet will be decreased\n /// by the requested amount (minus treasury fee),\n /// - The tokens taken from the redeemer on redemption request will\n /// be returned to the redeemer,\n /// - The request will be moved from pending redemptions to\n /// timed-out redemptions,\n /// - If the state of the wallet is `Live` or `MovingFunds`, the\n /// wallet operators will be slashed and the notifier will be\n /// rewarded,\n /// - If the state of wallet is `Live`, the wallet will be closed or\n /// marked as `MovingFunds` (depending on the presence or absence\n /// of the wallet's main UTXO) and the wallet will no longer be\n /// marked as the active wallet (if it was marked as such).\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @param redeemerOutputScript The redeemer's length-prefixed output\n /// script (P2PKH, P2WPKH, P2SH or P2WSH).\n /// @dev Requirements:\n /// - The wallet must be in the Live or MovingFunds or Terminated state,\n /// - The redemption request identified by `walletPubKeyHash` and\n /// `redeemerOutputScript` must exist,\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events of the `WalletRegistry` contract,\n /// - The amount of time defined by `redemptionTimeout` must have\n /// passed since the redemption was requested (the request must be\n /// timed-out).\n function notifyRedemptionTimeout(\n bytes20 walletPubKeyHash,\n uint32[] calldata walletMembersIDs,\n bytes calldata redeemerOutputScript\n ) external {\n self.notifyRedemptionTimeout(\n walletPubKeyHash,\n walletMembersIDs,\n redeemerOutputScript\n );\n }\n\n /// @notice Submits the moving funds target wallets commitment.\n /// Once all requirements are met, that function registers the\n /// target wallets commitment and opens the way for moving funds\n /// proof submission.\n /// @param walletPubKeyHash 20-byte public key hash of the source wallet.\n /// @param walletMainUtxo Data of the source wallet's main UTXO, as\n /// currently known on the Ethereum chain.\n /// @param walletMembersIDs Identifiers of the source wallet signing group\n /// members.\n /// @param walletMemberIndex Position of the caller in the source wallet\n /// signing group members list.\n /// @param targetWallets List of 20-byte public key hashes of the target\n /// wallets that the source wallet commits to move the funds to.\n /// @dev Requirements:\n /// - The source wallet must be in the MovingFunds state,\n /// - The source wallet must not have pending redemption requests,\n /// - The source wallet must not have pending moved funds sweep requests,\n /// - The source wallet must not have submitted its commitment already,\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given source wallet in the ECDSA registry. Those IDs are\n /// not directly stored in the contract for gas efficiency purposes\n /// but they can be read from appropriate `DkgResultSubmitted`\n /// and `DkgResultApproved` events,\n /// - The `walletMemberIndex` must be in range [1, walletMembersIDs.length],\n /// - The caller must be the member of the source wallet signing group\n /// at the position indicated by `walletMemberIndex` parameter,\n /// - The `walletMainUtxo` components must point to the recent main\n /// UTXO of the source wallet, as currently known on the Ethereum\n /// chain,\n /// - Source wallet BTC balance must be greater than zero,\n /// - At least one Live wallet must exist in the system,\n /// - Submitted target wallets count must match the expected count\n /// `N = min(liveWalletsCount, ceil(walletBtcBalance / walletMaxBtcTransfer))`\n /// where `N > 0`,\n /// - Each target wallet must be not equal to the source wallet,\n /// - Each target wallet must follow the expected order i.e. all\n /// target wallets 20-byte public key hashes represented as numbers\n /// must form a strictly increasing sequence without duplicates,\n /// - Each target wallet must be in Live state.\n function submitMovingFundsCommitment(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata walletMainUtxo,\n uint32[] calldata walletMembersIDs,\n uint256 walletMemberIndex,\n bytes20[] calldata targetWallets\n ) external {\n self.submitMovingFundsCommitment(\n walletPubKeyHash,\n walletMainUtxo,\n walletMembersIDs,\n walletMemberIndex,\n targetWallets\n );\n }\n\n /// @notice Resets the moving funds timeout for the given wallet if the\n /// target wallet commitment cannot be submitted due to a lack\n /// of live wallets in the system.\n /// @param walletPubKeyHash 20-byte public key hash of the moving funds wallet.\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state,\n /// - The target wallets commitment must not be already submitted for\n /// the given moving funds wallet,\n /// - Live wallets count must be zero,\n /// - The moving funds timeout reset delay must be elapsed.\n function resetMovingFundsTimeout(bytes20 walletPubKeyHash) external {\n self.resetMovingFundsTimeout(walletPubKeyHash);\n }\n\n /// @notice Used by the wallet to prove the BTC moving funds transaction\n /// and to make the necessary state changes. Moving funds is only\n /// accepted if it satisfies SPV proof.\n ///\n /// The function validates the moving funds transaction structure\n /// by checking if it actually spends the main UTXO of the declared\n /// wallet and locks the value on the pre-committed target wallets\n /// using a reasonable transaction fee. If all preconditions are\n /// met, this functions closes the source wallet.\n ///\n /// It is possible to prove the given moving funds transaction only\n /// one time.\n /// @param movingFundsTx Bitcoin moving funds transaction data.\n /// @param movingFundsProof Bitcoin moving funds proof data.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n /// HASH160 over the compressed ECDSA public key) of the wallet\n /// which performed the moving funds transaction.\n /// @dev Requirements:\n /// - `movingFundsTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash,\n /// - The `movingFundsTx` should represent a Bitcoin transaction with\n /// exactly 1 input that refers to the wallet's main UTXO. That\n /// transaction should have 1..n outputs corresponding to the\n /// pre-committed target wallets. Outputs must be ordered in the\n /// same way as their corresponding target wallets are ordered\n /// within the target wallets commitment,\n /// - `movingFundsProof` components must match the expected structure.\n /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// Additionally, the recent main UTXO on Ethereum must be set,\n /// - `walletPubKeyHash` must be connected with the main UTXO used\n /// as transaction single input,\n /// - The wallet that `walletPubKeyHash` points to must be in the\n /// MovingFunds state,\n /// - The target wallets commitment must be submitted by the wallet\n /// that `walletPubKeyHash` points to,\n /// - The total Bitcoin transaction fee must be lesser or equal\n /// to `movingFundsTxMaxTotalFee` governable parameter.\n function submitMovingFundsProof(\n BitcoinTx.Info calldata movingFundsTx,\n BitcoinTx.Proof calldata movingFundsProof,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes20 walletPubKeyHash\n ) external {\n self.submitMovingFundsProof(\n movingFundsTx,\n movingFundsProof,\n mainUtxo,\n walletPubKeyHash\n );\n }\n\n /// @notice Notifies about a timed out moving funds process. Terminates\n /// the wallet and slashes signing group members as a result.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state,\n /// - The moving funds timeout must be actually exceeded,\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events of the `WalletRegistry` contract.\n function notifyMovingFundsTimeout(\n bytes20 walletPubKeyHash,\n uint32[] calldata walletMembersIDs\n ) external {\n self.notifyMovingFundsTimeout(walletPubKeyHash, walletMembersIDs);\n }\n\n /// @notice Notifies about a moving funds wallet whose BTC balance is\n /// below the moving funds dust threshold. Ends the moving funds\n /// process and begins wallet closing immediately.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known\n /// on the Ethereum chain.\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state,\n /// - The `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// If the wallet has no main UTXO, this parameter can be empty as it\n /// is ignored,\n /// - The wallet BTC balance must be below the moving funds threshold.\n function notifyMovingFundsBelowDust(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata mainUtxo\n ) external {\n self.notifyMovingFundsBelowDust(walletPubKeyHash, mainUtxo);\n }\n\n /// @notice Used by the wallet to prove the BTC moved funds sweep\n /// transaction and to make the necessary state changes. Moved\n /// funds sweep is only accepted if it satisfies SPV proof.\n ///\n /// The function validates the sweep transaction structure by\n /// checking if it actually spends the moved funds UTXO and the\n /// sweeping wallet's main UTXO (optionally), and if it locks the\n /// value on the sweeping wallet's 20-byte public key hash using a\n /// reasonable transaction fee. If all preconditions are\n /// met, this function updates the sweeping wallet main UTXO, thus\n /// their BTC balance.\n ///\n /// It is possible to prove the given sweep transaction only\n /// one time.\n /// @param sweepTx Bitcoin sweep funds transaction data.\n /// @param sweepProof Bitcoin sweep funds proof data.\n /// @param mainUtxo Data of the sweeping wallet's main UTXO, as currently\n /// known on the Ethereum chain.\n /// @dev Requirements:\n /// - `sweepTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash,\n /// - The `sweepTx` should represent a Bitcoin transaction with\n /// the first input pointing to a moved funds sweep request targeted\n /// to the wallet, and optionally, the second input pointing to the\n /// wallet's main UTXO, if the sweeping wallet has a main UTXO set.\n /// There should be only one output locking funds on the sweeping\n /// wallet 20-byte public key hash,\n /// - `sweepProof` components must match the expected structure.\n /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the sweeping wallet, as currently known on the Ethereum chain.\n /// If there is no main UTXO, this parameter is ignored,\n /// - The sweeping wallet must be in the Live or MovingFunds state,\n /// - The total Bitcoin transaction fee must be lesser or equal\n /// to `movedFundsSweepTxMaxTotalFee` governable parameter.\n function submitMovedFundsSweepProof(\n BitcoinTx.Info calldata sweepTx,\n BitcoinTx.Proof calldata sweepProof,\n BitcoinTx.UTXO calldata mainUtxo\n ) external {\n self.submitMovedFundsSweepProof(sweepTx, sweepProof, mainUtxo);\n }\n\n /// @notice Notifies about a timed out moved funds sweep process. If the\n /// wallet is not terminated yet, that function terminates\n /// the wallet and slashes signing group members as a result.\n /// Marks the given sweep request as TimedOut.\n /// @param movingFundsTxHash 32-byte hash of the moving funds transaction\n /// that caused the sweep request to be created.\n /// @param movingFundsTxOutputIndex Index of the moving funds transaction\n /// output that is subject of the sweep request.\n /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @dev Requirements:\n /// - The moved funds sweep request must be in the Pending state,\n /// - The moved funds sweep timeout must be actually exceeded,\n /// - The wallet must be either in the Live or MovingFunds or\n /// Terminated state,\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events of the `WalletRegistry` contract.\n function notifyMovedFundsSweepTimeout(\n bytes32 movingFundsTxHash,\n uint32 movingFundsTxOutputIndex,\n uint32[] calldata walletMembersIDs\n ) external {\n self.notifyMovedFundsSweepTimeout(\n movingFundsTxHash,\n movingFundsTxOutputIndex,\n walletMembersIDs\n );\n }\n\n /// @notice Requests creation of a new wallet. This function just\n /// forms a request and the creation process is performed\n /// asynchronously. Once a wallet is created, the ECDSA Wallet\n /// Registry will notify this contract by calling the\n /// `__ecdsaWalletCreatedCallback` function.\n /// @param activeWalletMainUtxo Data of the active wallet's main UTXO, as\n /// currently known on the Ethereum chain.\n /// @dev Requirements:\n /// - `activeWalletMainUtxo` components must point to the recent main\n /// UTXO of the given active wallet, as currently known on the\n /// Ethereum chain. If there is no active wallet at the moment, or\n /// the active wallet has no main UTXO, this parameter can be\n /// empty as it is ignored,\n /// - Wallet creation must not be in progress,\n /// - If the active wallet is set, one of the following\n /// conditions must be true:\n /// - The active wallet BTC balance is above the minimum threshold\n /// and the active wallet is old enough, i.e. the creation period\n /// was elapsed since its creation time,\n /// - The active wallet BTC balance is above the maximum threshold.\n function requestNewWallet(BitcoinTx.UTXO calldata activeWalletMainUtxo)\n external\n {\n self.requestNewWallet(activeWalletMainUtxo);\n }\n\n /// @notice A callback function that is called by the ECDSA Wallet Registry\n /// once a new ECDSA wallet is created.\n /// @param ecdsaWalletID Wallet's unique identifier.\n /// @param publicKeyX Wallet's public key's X coordinate.\n /// @param publicKeyY Wallet's public key's Y coordinate.\n /// @dev Requirements:\n /// - The only caller authorized to call this function is `registry`,\n /// - Given wallet data must not belong to an already registered wallet.\n function __ecdsaWalletCreatedCallback(\n bytes32 ecdsaWalletID,\n bytes32 publicKeyX,\n bytes32 publicKeyY\n ) external override {\n self.registerNewWallet(ecdsaWalletID, publicKeyX, publicKeyY);\n }\n\n /// @notice A callback function that is called by the ECDSA Wallet Registry\n /// once a wallet heartbeat failure is detected.\n /// @param publicKeyX Wallet's public key's X coordinate.\n /// @param publicKeyY Wallet's public key's Y coordinate.\n /// @dev Requirements:\n /// - The only caller authorized to call this function is `registry`,\n /// - Wallet must be in Live state.\n function __ecdsaWalletHeartbeatFailedCallback(\n bytes32,\n bytes32 publicKeyX,\n bytes32 publicKeyY\n ) external override {\n self.notifyWalletHeartbeatFailed(publicKeyX, publicKeyY);\n }\n\n /// @notice Notifies that the wallet is either old enough or has too few\n /// satoshi left and qualifies to be closed.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @param walletMainUtxo Data of the wallet's main UTXO, as currently\n /// known on the Ethereum chain.\n /// @dev Requirements:\n /// - Wallet must not be set as the current active wallet,\n /// - Wallet must exceed the wallet maximum age OR the wallet BTC\n /// balance must be lesser than the minimum threshold. If the latter\n /// case is true, the `walletMainUtxo` components must point to the\n /// recent main UTXO of the given wallet, as currently known on the\n /// Ethereum chain. If the wallet has no main UTXO, this parameter\n /// can be empty as it is ignored since the wallet balance is\n /// assumed to be zero,\n /// - Wallet must be in Live state.\n function notifyCloseableWallet(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata walletMainUtxo\n ) external {\n self.notifyCloseableWallet(walletPubKeyHash, walletMainUtxo);\n }\n\n /// @notice Notifies about the end of the closing period for the given wallet.\n /// Closes the wallet ultimately and notifies the ECDSA registry\n /// about this fact.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @dev Requirements:\n /// - The wallet must be in the Closing state,\n /// - The wallet closing period must have elapsed.\n function notifyWalletClosingPeriodElapsed(bytes20 walletPubKeyHash)\n external\n {\n self.notifyWalletClosingPeriodElapsed(walletPubKeyHash);\n }\n\n /// @notice Submits a fraud challenge indicating that a UTXO being under\n /// wallet control was unlocked by the wallet but was not used\n /// according to the protocol rules. That means the wallet signed\n /// a transaction input pointing to that UTXO and there is a unique\n /// sighash and signature pair associated with that input. This\n /// function uses those parameters to create a fraud accusation that\n /// proves a given transaction input unlocking the given UTXO was\n /// actually signed by the wallet. This function cannot determine\n /// whether the transaction was actually broadcast and the input was\n /// consumed in a fraudulent way so it just opens a challenge period\n /// during which the wallet can defeat the challenge by submitting\n /// proof of a transaction that consumes the given input according\n /// to protocol rules. To prevent spurious allegations, the caller\n /// must deposit ETH that is returned back upon justified fraud\n /// challenge or confiscated otherwise.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes).\n /// @param preimageSha256 The hash that was generated by applying SHA-256\n /// one time over the preimage used during input signing. The preimage\n /// is a serialized subset of the transaction and its structure\n /// depends on the transaction input (see BIP-143 for reference).\n /// Notice that applying SHA-256 over the `preimageSha256` results\n /// in `sighash`. The path from `preimage` to `sighash` looks like\n /// this:\n /// preimage -> (SHA-256) -> preimageSha256 -> (SHA-256) -> sighash.\n /// @param signature Bitcoin signature in the R/S/V format.\n /// @dev Requirements:\n /// - Wallet behind `walletPublicKey` must be in Live or MovingFunds\n /// or Closing state,\n /// - The challenger must send appropriate amount of ETH used as\n /// fraud challenge deposit,\n /// - The signature (represented by r, s and v) must be generated by\n /// the wallet behind `walletPubKey` during signing of `sighash`\n /// which was calculated from `preimageSha256`,\n /// - Wallet can be challenged for the given signature only once.\n function submitFraudChallenge(\n bytes calldata walletPublicKey,\n bytes memory preimageSha256,\n BitcoinTx.RSVSignature calldata signature\n ) external payable {\n self.submitFraudChallenge(walletPublicKey, preimageSha256, signature);\n }\n\n /// @notice Allows to defeat a pending fraud challenge against a wallet if\n /// the transaction that spends the UTXO follows the protocol rules.\n /// In order to defeat the challenge the same `walletPublicKey` and\n /// signature (represented by `r`, `s` and `v`) must be provided as\n /// were used to calculate the sighash during input signing.\n /// The fraud challenge defeat attempt will only succeed if the\n /// inputs in the preimage are considered honestly spent by the\n /// wallet. Therefore the transaction spending the UTXO must be\n /// proven in the Bridge before a challenge defeat is called.\n /// If successfully defeated, the fraud challenge is marked as\n /// resolved and the amount of ether deposited by the challenger is\n /// sent to the treasury.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes).\n /// @param preimage The preimage which produces sighash used to generate the\n /// ECDSA signature that is the subject of the fraud claim. It is a\n /// serialized subset of the transaction. The exact subset used as\n /// the preimage depends on the transaction input the signature is\n /// produced for. See BIP-143 for reference.\n /// @param witness Flag indicating whether the preimage was produced for a\n /// witness input. True for witness, false for non-witness input.\n /// @dev Requirements:\n /// - `walletPublicKey` and `sighash` calculated as `hash256(preimage)`\n /// must identify an open fraud challenge,\n /// - the preimage must be a valid preimage of a transaction generated\n /// according to the protocol rules and already proved in the Bridge,\n /// - before a defeat attempt is made the transaction that spends the\n /// given UTXO must be proven in the Bridge.\n function defeatFraudChallenge(\n bytes calldata walletPublicKey,\n bytes calldata preimage,\n bool witness\n ) external {\n self.defeatFraudChallenge(walletPublicKey, preimage, witness);\n }\n\n /// @notice Allows to defeat a pending fraud challenge against a wallet by\n /// proving the sighash and signature were produced for an off-chain\n /// wallet heartbeat message following a strict format.\n /// In order to defeat the challenge the same `walletPublicKey` and\n /// signature (represented by `r`, `s` and `v`) must be provided as\n /// were used to calculate the sighash during heartbeat message\n /// signing. The fraud challenge defeat attempt will only succeed if\n /// the signed message follows a strict format required for\n /// heartbeat messages. If successfully defeated, the fraud\n /// challenge is marked as resolved and the amount of ether\n /// deposited by the challenger is sent to the treasury.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes).\n /// @param heartbeatMessage Off-chain heartbeat message meeting the heartbeat\n /// message format requirements which produces sighash used to\n /// generate the ECDSA signature that is the subject of the fraud\n /// claim.\n /// @dev Requirements:\n /// - `walletPublicKey` and `sighash` calculated as\n /// `hash256(heartbeatMessage)` must identify an open fraud challenge,\n /// - `heartbeatMessage` must follow a strict format of heartbeat\n /// messages.\n function defeatFraudChallengeWithHeartbeat(\n bytes calldata walletPublicKey,\n bytes calldata heartbeatMessage\n ) external {\n self.defeatFraudChallengeWithHeartbeat(\n walletPublicKey,\n heartbeatMessage\n );\n }\n\n /// @notice Notifies about defeat timeout for the given fraud challenge.\n /// Can be called only if there was a fraud challenge identified by\n /// the provided `walletPublicKey` and `sighash` and it was not\n /// defeated on time. The amount of time that needs to pass after\n /// a fraud challenge is reported is indicated by the\n /// `challengeDefeatTimeout`. After a successful fraud challenge\n /// defeat timeout notification the fraud challenge is marked as\n /// resolved, the stake of each operator is slashed, the ether\n /// deposited is returned to the challenger and the challenger is\n /// rewarded.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes).\n /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @param preimageSha256 The hash that was generated by applying SHA-256\n /// one time over the preimage used during input signing. The preimage\n /// is a serialized subset of the transaction and its structure\n /// depends on the transaction input (see BIP-143 for reference).\n /// Notice that applying SHA-256 over the `preimageSha256` results\n /// in `sighash`. The path from `preimage` to `sighash` looks like\n /// this:\n /// preimage -> (SHA-256) -> preimageSha256 -> (SHA-256) -> sighash.\n /// @dev Requirements:\n /// - The wallet must be in the Live or MovingFunds or Closing or\n /// Terminated state,\n /// - The `walletPublicKey` and `sighash` calculated from\n /// `preimageSha256` must identify an open fraud challenge,\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events of the `WalletRegistry` contract,\n /// - The amount of time indicated by `challengeDefeatTimeout` must pass\n /// after the challenge was reported.\n function notifyFraudChallengeDefeatTimeout(\n bytes calldata walletPublicKey,\n uint32[] calldata walletMembersIDs,\n bytes memory preimageSha256\n ) external {\n self.notifyFraudChallengeDefeatTimeout(\n walletPublicKey,\n walletMembersIDs,\n preimageSha256\n );\n }\n\n /// @notice Allows the Governance to mark the given vault address as trusted\n /// or no longer trusted. Vaults are not trusted by default.\n /// Trusted vault must meet the following criteria:\n /// - `IVault.receiveBalanceIncrease` must have a known, low gas\n /// cost,\n /// - `IVault.receiveBalanceIncrease` must never revert.\n /// @dev Without restricting reveal only to trusted vaults, malicious\n /// vaults not meeting the criteria would be able to nuke sweep proof\n /// transactions executed by ECDSA wallet with deposits routed to\n /// them.\n /// @param vault The address of the vault.\n /// @param isTrusted flag indicating whether the vault is trusted or not.\n /// @dev Can only be called by the Governance.\n function setVaultStatus(address vault, bool isTrusted)\n external\n onlyGovernance\n {\n self.isVaultTrusted[vault] = isTrusted;\n emit VaultStatusUpdated(vault, isTrusted);\n }\n\n /// @notice Updates parameters of deposits.\n /// @param depositDustThreshold New value of the deposit dust threshold in\n /// satoshis. It is the minimal amount that can be requested to\n //// deposit. Value of this parameter must take into account the value\n /// of `depositTreasuryFeeDivisor` and `depositTxMaxFee` parameters\n /// in order to make requests that can incur the treasury and\n /// transaction fee and still satisfy the depositor.\n /// @param depositTreasuryFeeDivisor New value of the treasury fee divisor.\n /// It is the divisor used to compute the treasury fee taken from\n /// each deposit and transferred to the treasury upon sweep proof\n /// submission. That fee is computed as follows:\n /// `treasuryFee = depositedAmount / depositTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each deposit,\n /// the `depositTreasuryFeeDivisor` should be set to `50`\n /// because `1/50 = 0.02 = 2%`.\n /// @param depositTxMaxFee New value of the deposit tx max fee in satoshis.\n /// It is the maximum amount of BTC transaction fee that can\n /// be incurred by each swept deposit being part of the given sweep\n /// transaction. If the maximum BTC transaction fee is exceeded,\n /// such transaction is considered a fraud.\n /// @dev Requirements:\n /// - Deposit dust threshold must be greater than zero,\n /// - Deposit treasury fee divisor must be greater than zero,\n /// - Deposit transaction max fee must be greater than zero.\n function updateDepositParameters(\n uint64 depositDustThreshold,\n uint64 depositTreasuryFeeDivisor,\n uint64 depositTxMaxFee\n ) external onlyGovernance {\n self.updateDepositParameters(\n depositDustThreshold,\n depositTreasuryFeeDivisor,\n depositTxMaxFee\n );\n }\n\n /// @notice Updates parameters of redemptions.\n /// @param redemptionDustThreshold New value of the redemption dust\n /// threshold in satoshis. It is the minimal amount that can be\n /// requested for redemption. Value of this parameter must take into\n /// account the value of `redemptionTreasuryFeeDivisor` and\n /// `redemptionTxMaxFee` parameters in order to make requests that\n /// can incur the treasury and transaction fee and still satisfy the\n /// redeemer.\n /// @param redemptionTreasuryFeeDivisor New value of the redemption\n /// treasury fee divisor. It is the divisor used to compute the\n /// treasury fee taken from each redemption request and transferred\n /// to the treasury upon successful request finalization. That fee is\n /// computed as follows:\n /// `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each\n /// redemption request, the `redemptionTreasuryFeeDivisor` should\n /// be set to `50` because `1/50 = 0.02 = 2%`.\n /// @param redemptionTxMaxFee New value of the redemption transaction max\n /// fee in satoshis. It is the maximum amount of BTC transaction fee\n /// that can be incurred by each redemption request being part of the\n /// given redemption transaction. If the maximum BTC transaction fee\n /// is exceeded, such transaction is considered a fraud.\n /// This is a per-redemption output max fee for the redemption\n /// transaction.\n /// @param redemptionTimeout New value of the redemption timeout in seconds.\n /// It is the time after which the redemption request can be reported\n /// as timed out. It is counted from the moment when the redemption\n /// request was created via `requestRedemption` call. Reported timed\n /// out requests are cancelled and locked TBTC is returned to the\n /// redeemer in full amount.\n /// @param redemptionTimeoutSlashingAmount New value of the redemption\n /// timeout slashing amount in T, it is the amount slashed from each\n /// wallet member for redemption timeout.\n /// @param redemptionTimeoutNotifierRewardMultiplier New value of the\n /// redemption timeout notifier reward multiplier as percentage,\n /// it determines the percentage of the notifier reward from the\n /// staking contact the notifier of a redemption timeout receives.\n /// The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Redemption dust threshold must be greater than moving funds dust\n /// threshold,\n /// - Redemption treasury fee divisor must be greater than zero,\n /// - Redemption transaction max fee must be greater than zero,\n /// - Redemption timeout must be greater than zero,\n /// - Redemption timeout notifier reward multiplier must be in the\n /// range [0, 100].\n function updateRedemptionParameters(\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint256 redemptionTimeout,\n uint96 redemptionTimeoutSlashingAmount,\n uint256 redemptionTimeoutNotifierRewardMultiplier\n ) external onlyGovernance {\n self.updateRedemptionParameters(\n redemptionDustThreshold,\n redemptionTreasuryFeeDivisor,\n redemptionTxMaxFee,\n redemptionTimeout,\n redemptionTimeoutSlashingAmount,\n redemptionTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Updates parameters of moving funds.\n /// @param movingFundsTxMaxTotalFee New value of the moving funds transaction\n /// max total fee in satoshis. It is the maximum amount of the total\n /// BTC transaction fee that is acceptable in a single moving funds\n /// transaction. This is a _total_ max fee for the entire moving\n /// funds transaction.\n /// @param movingFundsDustThreshold New value of the moving funds dust\n /// threshold. It is the minimal satoshi amount that makes sense to\n /// be transferred during the moving funds process. Moving funds\n /// wallets having their BTC balance below that value can begin\n /// closing immediately as transferring such a low value may not be\n /// possible due to BTC network fees.\n /// @param movingFundsTimeoutResetDelay New value of the moving funds\n /// timeout reset delay in seconds. It is the time after which the\n /// moving funds timeout can be reset in case the target wallet\n /// commitment cannot be submitted due to a lack of live wallets\n /// in the system. It is counted from the moment when the wallet\n /// was requested to move their funds and switched to the MovingFunds\n /// state or from the moment the timeout was reset the last time.\n /// @param movingFundsTimeout New value of the moving funds timeout in\n /// seconds. It is the time after which the moving funds process can\n /// be reported as timed out. It is counted from the moment when the\n /// wallet was requested to move their funds and switched to the\n /// MovingFunds state.\n /// @param movingFundsTimeoutSlashingAmount New value of the moving funds\n /// timeout slashing amount in T, it is the amount slashed from each\n /// wallet member for moving funds timeout.\n /// @param movingFundsTimeoutNotifierRewardMultiplier New value of the\n /// moving funds timeout notifier reward multiplier as percentage,\n /// it determines the percentage of the notifier reward from the\n /// staking contact the notifier of a moving funds timeout receives.\n /// The value must be in the range [0, 100].\n /// @param movedFundsSweepTxMaxTotalFee New value of the moved funds sweep\n /// transaction max total fee in satoshis. It is the maximum amount\n /// of the total BTC transaction fee that is acceptable in a single\n /// moved funds sweep transaction. This is a _total_ max fee for the\n /// entire moved funds sweep transaction.\n /// @param movedFundsSweepTimeout New value of the moved funds sweep\n /// timeout in seconds. It is the time after which the moved funds\n /// sweep process can be reported as timed out. It is counted from\n /// the moment when the wallet was requested to sweep the received\n /// funds.\n /// @param movedFundsSweepTimeoutSlashingAmount New value of the moved\n /// funds sweep timeout slashing amount in T, it is the amount\n /// slashed from each wallet member for moved funds sweep timeout.\n /// @param movedFundsSweepTimeoutNotifierRewardMultiplier New value of\n /// the moved funds sweep timeout notifier reward multiplier as\n /// percentage, it determines the percentage of the notifier reward\n /// from the staking contact the notifier of a moved funds sweep\n /// timeout receives. The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Moving funds transaction max total fee must be greater than zero,\n /// - Moving funds dust threshold must be greater than zero and lower\n /// than the redemption dust threshold,\n /// - Moving funds timeout reset delay must be greater than zero,\n /// - Moving funds timeout must be greater than the moving funds\n /// timeout reset delay,\n /// - Moving funds timeout notifier reward multiplier must be in the\n /// range [0, 100],\n /// - Moved funds sweep transaction max total fee must be greater than zero,\n /// - Moved funds sweep timeout must be greater than zero,\n /// - Moved funds sweep timeout notifier reward multiplier must be in the\n /// range [0, 100].\n function updateMovingFundsParameters(\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeoutResetDelay,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint256 movingFundsTimeoutNotifierRewardMultiplier,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint256 movedFundsSweepTimeoutNotifierRewardMultiplier\n ) external onlyGovernance {\n self.updateMovingFundsParameters(\n movingFundsTxMaxTotalFee,\n movingFundsDustThreshold,\n movingFundsTimeoutResetDelay,\n movingFundsTimeout,\n movingFundsTimeoutSlashingAmount,\n movingFundsTimeoutNotifierRewardMultiplier,\n movedFundsSweepTxMaxTotalFee,\n movedFundsSweepTimeout,\n movedFundsSweepTimeoutSlashingAmount,\n movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Updates parameters of wallets.\n /// @param walletCreationPeriod New value of the wallet creation period in\n /// seconds, determines how frequently a new wallet creation can be\n /// requested.\n /// @param walletCreationMinBtcBalance New value of the wallet minimum BTC\n /// balance in satoshi, used to decide about wallet creation.\n /// @param walletCreationMaxBtcBalance New value of the wallet maximum BTC\n /// balance in satoshi, used to decide about wallet creation.\n /// @param walletClosureMinBtcBalance New value of the wallet minimum BTC\n /// balance in satoshi, used to decide about wallet closure.\n /// @param walletMaxAge New value of the wallet maximum age in seconds,\n /// indicates the maximum age of a wallet in seconds, after which\n /// the wallet moving funds process can be requested.\n /// @param walletMaxBtcTransfer New value of the wallet maximum BTC transfer\n /// in satoshi, determines the maximum amount that can be transferred\n // to a single target wallet during the moving funds process.\n /// @param walletClosingPeriod New value of the wallet closing period in\n /// seconds, determines the length of the wallet closing period,\n // i.e. the period when the wallet remains in the Closing state\n // and can be subject of deposit fraud challenges.\n /// @dev Requirements:\n /// - Wallet minimum BTC balance must be greater than zero,\n /// - Wallet maximum BTC balance must be greater than the wallet\n /// minimum BTC balance,\n /// - Wallet maximum BTC transfer must be greater than zero,\n /// - Wallet closing period must be greater than zero.\n function updateWalletParameters(\n uint32 walletCreationPeriod,\n uint64 walletCreationMinBtcBalance,\n uint64 walletCreationMaxBtcBalance,\n uint64 walletClosureMinBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n ) external onlyGovernance {\n self.updateWalletParameters(\n walletCreationPeriod,\n walletCreationMinBtcBalance,\n walletCreationMaxBtcBalance,\n walletClosureMinBtcBalance,\n walletMaxAge,\n walletMaxBtcTransfer,\n walletClosingPeriod\n );\n }\n\n /// @notice Updates parameters related to frauds.\n /// @param fraudChallengeDepositAmount New value of the fraud challenge\n /// deposit amount in wei, it is the amount of ETH the party\n /// challenging the wallet for fraud needs to deposit.\n /// @param fraudChallengeDefeatTimeout New value of the challenge defeat\n /// timeout in seconds, it is the amount of time the wallet has to\n /// defeat a fraud challenge. The value must be greater than zero.\n /// @param fraudSlashingAmount New value of the fraud slashing amount in T,\n /// it is the amount slashed from each wallet member for committing\n /// a fraud.\n /// @param fraudNotifierRewardMultiplier New value of the fraud notifier\n /// reward multiplier as percentage, it determines the percentage of\n /// the notifier reward from the staking contact the notifier of\n /// a fraud receives. The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Fraud challenge defeat timeout must be greater than 0,\n /// - Fraud notifier reward multiplier must be in the range [0, 100].\n function updateFraudParameters(\n uint256 fraudChallengeDepositAmount,\n uint256 fraudChallengeDefeatTimeout,\n uint96 fraudSlashingAmount,\n uint256 fraudNotifierRewardMultiplier\n ) external onlyGovernance {\n self.updateFraudParameters(\n fraudChallengeDepositAmount,\n fraudChallengeDefeatTimeout,\n fraudSlashingAmount,\n fraudNotifierRewardMultiplier\n );\n }\n\n /// @notice Collection of all revealed deposits indexed by\n /// keccak256(fundingTxHash | fundingOutputIndex).\n /// The fundingTxHash is bytes32 (ordered as in Bitcoin internally)\n /// and fundingOutputIndex an uint32. This mapping may contain valid\n /// and invalid deposits and the wallet is responsible for\n /// validating them before attempting to execute a sweep.\n function deposits(uint256 depositKey)\n external\n view\n returns (Deposit.DepositRequest memory)\n {\n return self.deposits[depositKey];\n }\n\n /// @notice Collection of all pending redemption requests indexed by\n /// redemption key built as\n /// keccak256(walletPubKeyHash | redeemerOutputScript). The\n /// walletPubKeyHash is the 20-byte wallet's public key hash\n /// (computed using Bitcoin HASH160 over the compressed ECDSA\n /// public key) and redeemerOutputScript is a Bitcoin script\n /// (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock\n /// redeemed BTC as requested by the redeemer. Requests are added\n /// to this mapping by the `requestRedemption` method (duplicates\n /// not allowed) and are removed by one of the following methods:\n /// - `submitRedemptionProof` in case the request was handled\n /// successfully,\n /// - `notifyRedemptionTimeout` in case the request was reported\n /// to be timed out.\n function pendingRedemptions(uint256 redemptionKey)\n external\n view\n returns (Redemption.RedemptionRequest memory)\n {\n return self.pendingRedemptions[redemptionKey];\n }\n\n /// @notice Collection of all timed out redemptions requests indexed by\n /// redemption key built as\n /// keccak256(walletPubKeyHash | redeemerOutputScript). The\n /// walletPubKeyHash is the 20-byte wallet's public key hash\n /// (computed using Bitcoin HASH160 over the compressed ECDSA\n /// public key) and redeemerOutputScript is the Bitcoin script\n /// (P2PKH, P2WPKH, P2SH or P2WSH) that is involved in the timed\n /// out request. Timed out requests are stored in this mapping to\n /// avoid slashing the wallets multiple times for the same timeout.\n /// Only one method can add to this mapping:\n /// - `notifyRedemptionTimeout` which puts the redemption key\n /// to this mapping basing on a timed out request stored\n /// previously in `pendingRedemptions` mapping.\n function timedOutRedemptions(uint256 redemptionKey)\n external\n view\n returns (Redemption.RedemptionRequest memory)\n {\n return self.timedOutRedemptions[redemptionKey];\n }\n\n /// @notice Collection of main UTXOs that are honestly spent indexed by\n /// keccak256(fundingTxHash | fundingOutputIndex). The fundingTxHash\n /// is bytes32 (ordered as in Bitcoin internally) and\n /// fundingOutputIndex an uint32. A main UTXO is considered honestly\n /// spent if it was used as an input of a transaction that have been\n /// proven in the Bridge.\n function spentMainUTXOs(uint256 utxoKey) external view returns (bool) {\n return self.spentMainUTXOs[utxoKey];\n }\n\n /// @notice Gets details about a registered wallet.\n /// @param walletPubKeyHash The 20-byte wallet public key hash (computed\n /// using Bitcoin HASH160 over the compressed ECDSA public key).\n /// @return Wallet details.\n function wallets(bytes20 walletPubKeyHash)\n external\n view\n returns (Wallets.Wallet memory)\n {\n return self.registeredWallets[walletPubKeyHash];\n }\n\n /// @notice Gets the public key hash of the active wallet.\n /// @return The 20-byte public key hash (computed using Bitcoin HASH160\n /// over the compressed ECDSA public key) of the active wallet.\n /// Returns bytes20(0) if there is no active wallet at the moment.\n function activeWalletPubKeyHash() external view returns (bytes20) {\n return self.activeWalletPubKeyHash;\n }\n\n /// @notice Gets the live wallets count.\n /// @return The current count of wallets being in the Live state.\n function liveWalletsCount() external view returns (uint32) {\n return self.liveWalletsCount;\n }\n\n /// @notice Returns the fraud challenge identified by the given key built\n /// as keccak256(walletPublicKey|sighash).\n function fraudChallenges(uint256 challengeKey)\n external\n view\n returns (Fraud.FraudChallenge memory)\n {\n return self.fraudChallenges[challengeKey];\n }\n\n /// @notice Collection of all moved funds sweep requests indexed by\n /// `keccak256(movingFundsTxHash | movingFundsOutputIndex)`.\n /// The `movingFundsTxHash` is `bytes32` (ordered as in Bitcoin\n /// internally) and `movingFundsOutputIndex` an `uint32`. Each entry\n /// is actually an UTXO representing the moved funds and is supposed\n /// to be swept with the current main UTXO of the recipient wallet.\n /// @param requestKey Request key built as\n /// `keccak256(movingFundsTxHash | movingFundsOutputIndex)`.\n /// @return Details of the moved funds sweep request.\n function movedFundsSweepRequests(uint256 requestKey)\n external\n view\n returns (MovingFunds.MovedFundsSweepRequest memory)\n {\n return self.movedFundsSweepRequests[requestKey];\n }\n\n /// @notice Indicates if the vault with the given address is trusted or not.\n /// Depositors can route their revealed deposits only to trusted\n /// vaults and have trusted vaults notified about new deposits as\n /// soon as these deposits get swept. Vaults not trusted by the\n /// Bridge can still be used by Bank balance owners on their own\n /// responsibility - anyone can approve their Bank balance to any\n /// address.\n function isVaultTrusted(address vault) external view returns (bool) {\n return self.isVaultTrusted[vault];\n }\n\n /// @notice Returns the current values of Bridge deposit parameters.\n /// @return depositDustThreshold The minimal amount that can be requested\n /// to deposit. Value of this parameter must take into account the\n /// value of `depositTreasuryFeeDivisor` and `depositTxMaxFee`\n /// parameters in order to make requests that can incur the\n /// treasury and transaction fee and still satisfy the depositor.\n /// @return depositTreasuryFeeDivisor Divisor used to compute the treasury\n /// fee taken from each deposit and transferred to the treasury upon\n /// sweep proof submission. That fee is computed as follows:\n /// `treasuryFee = depositedAmount / depositTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each deposit,\n /// the `depositTreasuryFeeDivisor` should be set to `50`\n /// because `1/50 = 0.02 = 2%`.\n /// @return depositTxMaxFee Maximum amount of BTC transaction fee that can\n /// be incurred by each swept deposit being part of the given sweep\n /// transaction. If the maximum BTC transaction fee is exceeded,\n /// such transaction is considered a fraud.\n function depositParameters()\n external\n view\n returns (\n uint64 depositDustThreshold,\n uint64 depositTreasuryFeeDivisor,\n uint64 depositTxMaxFee\n )\n {\n depositDustThreshold = self.depositDustThreshold;\n depositTreasuryFeeDivisor = self.depositTreasuryFeeDivisor;\n depositTxMaxFee = self.depositTxMaxFee;\n }\n\n /// @notice Returns the current values of Bridge redemption parameters.\n /// @return redemptionDustThreshold The minimal amount that can be requested\n /// for redemption. Value of this parameter must take into account\n /// the value of `redemptionTreasuryFeeDivisor` and `redemptionTxMaxFee`\n /// parameters in order to make requests that can incur the\n /// treasury and transaction fee and still satisfy the redeemer.\n /// @return redemptionTreasuryFeeDivisor Divisor used to compute the treasury\n /// fee taken from each redemption request and transferred to the\n /// treasury upon successful request finalization. That fee is\n /// computed as follows:\n /// `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each\n /// redemption request, the `redemptionTreasuryFeeDivisor` should\n /// be set to `50` because `1/50 = 0.02 = 2%`.\n /// @return redemptionTxMaxFee Maximum amount of BTC transaction fee that\n /// can be incurred by each redemption request being part of the\n /// given redemption transaction. If the maximum BTC transaction\n /// fee is exceeded, such transaction is considered a fraud.\n /// This is a per-redemption output max fee for the redemption\n /// transaction.\n /// @return redemptionTimeout Time after which the redemption request can be\n /// reported as timed out. It is counted from the moment when the\n /// redemption request was created via `requestRedemption` call.\n /// Reported timed out requests are cancelled and locked TBTC is\n /// returned to the redeemer in full amount.\n /// @return redemptionTimeoutSlashingAmount The amount of stake slashed\n /// from each member of a wallet for a redemption timeout.\n /// @return redemptionTimeoutNotifierRewardMultiplier The percentage of the\n /// notifier reward from the staking contract the notifier of a\n /// redemption timeout receives. The value is in the range [0, 100].\n function redemptionParameters()\n external\n view\n returns (\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint256 redemptionTimeout,\n uint96 redemptionTimeoutSlashingAmount,\n uint256 redemptionTimeoutNotifierRewardMultiplier\n )\n {\n redemptionDustThreshold = self.redemptionDustThreshold;\n redemptionTreasuryFeeDivisor = self.redemptionTreasuryFeeDivisor;\n redemptionTxMaxFee = self.redemptionTxMaxFee;\n redemptionTimeout = self.redemptionTimeout;\n redemptionTimeoutSlashingAmount = self.redemptionTimeoutSlashingAmount;\n redemptionTimeoutNotifierRewardMultiplier = self\n .redemptionTimeoutNotifierRewardMultiplier;\n }\n\n /// @notice Returns the current values of Bridge moving funds between\n /// wallets parameters.\n /// @return movingFundsTxMaxTotalFee Maximum amount of the total BTC\n /// transaction fee that is acceptable in a single moving funds\n /// transaction. This is a _total_ max fee for the entire moving\n /// funds transaction.\n /// @return movingFundsDustThreshold The minimal satoshi amount that makes\n /// sense to be transferred during the moving funds process. Moving\n /// funds wallets having their BTC balance below that value can\n /// begin closing immediately as transferring such a low value may\n /// not be possible due to BTC network fees.\n /// @return movingFundsTimeoutResetDelay Time after which the moving funds\n /// timeout can be reset in case the target wallet commitment\n /// cannot be submitted due to a lack of live wallets in the system.\n /// It is counted from the moment when the wallet was requested to\n /// move their funds and switched to the MovingFunds state or from\n /// the moment the timeout was reset the last time. Value in seconds\n /// This value should be lower than the value of the\n /// `movingFundsTimeout`.\n /// @return movingFundsTimeout Time after which the moving funds process\n /// can be reported as timed out. It is counted from the moment\n /// when the wallet was requested to move their funds and switched\n /// to the MovingFunds state. Value in seconds.\n /// @return movingFundsTimeoutSlashingAmount The amount of stake slashed\n /// from each member of a wallet for a moving funds timeout.\n /// @return movingFundsTimeoutNotifierRewardMultiplier The percentage of the\n /// notifier reward from the staking contract the notifier of a\n /// moving funds timeout receives. The value is in the range [0, 100].\n /// @return movedFundsSweepTxMaxTotalFee Maximum amount of the total BTC\n /// transaction fee that is acceptable in a single moved funds\n /// sweep transaction. This is a _total_ max fee for the entire\n /// moved funds sweep transaction.\n /// @return movedFundsSweepTimeout Time after which the moved funds sweep\n /// process can be reported as timed out. It is counted from the\n /// moment when the wallet was requested to sweep the received funds.\n /// Value in seconds.\n /// @return movedFundsSweepTimeoutSlashingAmount The amount of stake slashed\n /// from each member of a wallet for a moved funds sweep timeout.\n /// @return movedFundsSweepTimeoutNotifierRewardMultiplier The percentage\n /// of the notifier reward from the staking contract the notifier\n /// of a moved funds sweep timeout receives. The value is in the\n /// range [0, 100].\n function movingFundsParameters()\n external\n view\n returns (\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeoutResetDelay,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint256 movingFundsTimeoutNotifierRewardMultiplier,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint256 movedFundsSweepTimeoutNotifierRewardMultiplier\n )\n {\n movingFundsTxMaxTotalFee = self.movingFundsTxMaxTotalFee;\n movingFundsDustThreshold = self.movingFundsDustThreshold;\n movingFundsTimeoutResetDelay = self.movingFundsTimeoutResetDelay;\n movingFundsTimeout = self.movingFundsTimeout;\n movingFundsTimeoutSlashingAmount = self\n .movingFundsTimeoutSlashingAmount;\n movingFundsTimeoutNotifierRewardMultiplier = self\n .movingFundsTimeoutNotifierRewardMultiplier;\n movedFundsSweepTxMaxTotalFee = self.movedFundsSweepTxMaxTotalFee;\n movedFundsSweepTimeout = self.movedFundsSweepTimeout;\n movedFundsSweepTimeoutSlashingAmount = self\n .movedFundsSweepTimeoutSlashingAmount;\n movedFundsSweepTimeoutNotifierRewardMultiplier = self\n .movedFundsSweepTimeoutNotifierRewardMultiplier;\n }\n\n /// @return walletCreationPeriod Determines how frequently a new wallet\n /// creation can be requested. Value in seconds.\n /// @return walletCreationMinBtcBalance The minimum BTC threshold in satoshi\n /// that is used to decide about wallet creation.\n /// @return walletCreationMaxBtcBalance The maximum BTC threshold in satoshi\n /// that is used to decide about wallet creation.\n /// @return walletClosureMinBtcBalance The minimum BTC threshold in satoshi\n /// that is used to decide about wallet closure.\n /// @return walletMaxAge The maximum age of a wallet in seconds, after which\n /// the wallet moving funds process can be requested.\n /// @return walletMaxBtcTransfer The maximum BTC amount in satoshi than\n /// can be transferred to a single target wallet during the moving\n /// funds process.\n /// @return walletClosingPeriod Determines the length of the wallet closing\n /// period, i.e. the period when the wallet remains in the Closing\n /// state and can be subject of deposit fraud challenges. Value\n /// in seconds.\n function walletParameters()\n external\n view\n returns (\n uint32 walletCreationPeriod,\n uint64 walletCreationMinBtcBalance,\n uint64 walletCreationMaxBtcBalance,\n uint64 walletClosureMinBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n )\n {\n walletCreationPeriod = self.walletCreationPeriod;\n walletCreationMinBtcBalance = self.walletCreationMinBtcBalance;\n walletCreationMaxBtcBalance = self.walletCreationMaxBtcBalance;\n walletClosureMinBtcBalance = self.walletClosureMinBtcBalance;\n walletMaxAge = self.walletMaxAge;\n walletMaxBtcTransfer = self.walletMaxBtcTransfer;\n walletClosingPeriod = self.walletClosingPeriod;\n }\n\n /// @notice Returns the current values of Bridge fraud parameters.\n /// @return fraudChallengeDepositAmount The amount of ETH in wei the party\n /// challenging the wallet for fraud needs to deposit.\n /// @return fraudChallengeDefeatTimeout The amount of time the wallet has to\n /// defeat a fraud challenge.\n /// @return fraudSlashingAmount The amount slashed from each wallet member\n /// for committing a fraud.\n /// @return fraudNotifierRewardMultiplier The percentage of the notifier\n /// reward from the staking contract the notifier of a fraud\n /// receives. The value is in the range [0, 100].\n function fraudParameters()\n external\n view\n returns (\n uint256 fraudChallengeDepositAmount,\n uint256 fraudChallengeDefeatTimeout,\n uint96 fraudSlashingAmount,\n uint256 fraudNotifierRewardMultiplier\n )\n {\n fraudChallengeDepositAmount = self.fraudChallengeDepositAmount;\n fraudChallengeDefeatTimeout = self.fraudChallengeDefeatTimeout;\n fraudSlashingAmount = self.fraudSlashingAmount;\n fraudNotifierRewardMultiplier = self.fraudNotifierRewardMultiplier;\n }\n\n /// @notice Returns the addresses of contracts Bridge is interacting with.\n /// @return bank Address of the Bank the Bridge belongs to.\n /// @return relay Address of the Bitcoin relay providing the current Bitcoin\n /// network difficulty.\n /// @return ecdsaWalletRegistry Address of the ECDSA Wallet Registry.\n function contractReferences()\n external\n view\n returns (\n Bank bank,\n IRelay relay,\n EcdsaWalletRegistry ecdsaWalletRegistry\n )\n {\n bank = self.bank;\n relay = self.relay;\n ecdsaWalletRegistry = self.ecdsaWalletRegistry;\n }\n\n /// @notice Address where the deposit treasury fees will be sent to.\n /// Treasury takes part in the operators rewarding process.\n function treasury() external view returns (address) {\n return self.treasury;\n }\n\n /// @notice The number of confirmations on the Bitcoin chain required to\n /// successfully evaluate an SPV proof.\n function txProofDifficultyFactor() external view returns (uint256) {\n return self.txProofDifficultyFactor;\n }\n}\n"
253
+ "@openzeppelin/contracts/security/ReentrancyGuard.sol": {
254
+ "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n // Booleans are more expensive than uint256 or any type that takes up a full\n // word because each write operation emits an extra SLOAD to first read the\n // slot's contents, replace the bits taken up by the boolean, and then write\n // back. This is the compiler's defense against contract upgrades and\n // pointer aliasing, and it cannot be disabled.\n\n // The values being non-zero value makes deployment a bit more expensive,\n // but in exchange the refund on every call to nonReentrant will be lower in\n // amount. Since refunds are capped to a percentage of the total\n // transaction's gas, it is best to keep them low in cases like this one, to\n // increase the likelihood of the full refund coming into effect.\n uint256 private constant _NOT_ENTERED = 1;\n uint256 private constant _ENTERED = 2;\n\n uint256 private _status;\n\n constructor() {\n _status = _NOT_ENTERED;\n }\n\n /**\n * @dev Prevents a contract from calling itself, directly or indirectly.\n * Calling a `nonReentrant` function from another `nonReentrant`\n * function is not supported. It is possible to prevent this from happening\n * by making the `nonReentrant` function external, and making it call a\n * `private` function that does the actual work.\n */\n modifier nonReentrant() {\n // On the first call to nonReentrant, _notEntered will be true\n require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n // Any calls to nonReentrant after this point will fail\n _status = _ENTERED;\n\n _;\n\n // By storing the original value once again, a refund is triggered (see\n // https://eips.ethereum.org/EIPS/eip-2200)\n _status = _NOT_ENTERED;\n }\n}\n"
213
255
  },
214
- "@keep-network/ecdsa/contracts/api/IWalletOwner.sol": {
215
- "content": "// SPDX-License-Identifier: MIT\n//\n// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄\n// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓\n// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓\n// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀\n// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌\n// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓\n//\n// Trust math, not hardware.\n\npragma solidity ^0.8.9;\n\ninterface IWalletOwner {\n /// @notice Callback function executed once a new wallet is created.\n /// @dev Should be callable only by the Wallet Registry.\n /// @param walletID Wallet's unique identifier.\n /// @param publicKeyY Wallet's public key's X coordinate.\n /// @param publicKeyY Wallet's public key's Y coordinate.\n function __ecdsaWalletCreatedCallback(\n bytes32 walletID,\n bytes32 publicKeyX,\n bytes32 publicKeyY\n ) external;\n\n /// @notice Callback function executed once a wallet heartbeat failure\n /// is detected.\n /// @dev Should be callable only by the Wallet Registry.\n /// @param walletID Wallet's unique identifier.\n /// @param publicKeyY Wallet's public key's X coordinate.\n /// @param publicKeyY Wallet's public key's Y coordinate.\n function __ecdsaWalletHeartbeatFailedCallback(\n bytes32 walletID,\n bytes32 publicKeyX,\n bytes32 publicKeyY\n ) external;\n}\n"
256
+ "@keep-network/random-beacon/contracts/Reimbursable.sol": {
257
+ "content": "// SPDX-License-Identifier: MIT\n//\n// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄\n// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓\n// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓\n// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀\n// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌\n// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓\n//\n// Trust math, not hardware.\n\npragma solidity ^0.8.9;\n\nimport \"./ReimbursementPool.sol\";\n\nabstract contract Reimbursable {\n // The variable should be initialized by the implementing contract.\n // slither-disable-next-line uninitialized-state\n ReimbursementPool public reimbursementPool;\n\n // Reserved storage space in case we need to add more variables,\n // since there are upgradeable contracts that inherit from this one.\n // See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n // slither-disable-next-line unused-state\n uint256[49] private __gap;\n\n event ReimbursementPoolUpdated(address newReimbursementPool);\n\n modifier refundable(address receiver) {\n uint256 gasStart = gasleft();\n _;\n reimbursementPool.refund(gasStart - gasleft(), receiver);\n }\n\n modifier onlyReimbursableAdmin() virtual {\n _;\n }\n\n function updateReimbursementPool(ReimbursementPool _reimbursementPool)\n external\n onlyReimbursableAdmin\n {\n emit ReimbursementPoolUpdated(address(_reimbursementPool));\n\n reimbursementPool = _reimbursementPool;\n }\n}\n"
216
258
  },
217
- "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol": {
218
- "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../../utils/AddressUpgradeable.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n /**\n * @dev Indicates that the contract has been initialized.\n * @custom:oz-retyped-from bool\n */\n uint8 private _initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private _initializing;\n\n /**\n * @dev Triggered when the contract has been initialized or reinitialized.\n */\n event Initialized(uint8 version);\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`.\n */\n modifier initializer() {\n bool isTopLevelCall = _setInitializedVersion(1);\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original\n * initialization step. This is essential to configure modules that are added through upgrades and that require\n * initialization.\n *\n * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n * a contract, executing them in the right order is up to the developer or operator.\n */\n modifier reinitializer(uint8 version) {\n bool isTopLevelCall = _setInitializedVersion(version);\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(version);\n }\n }\n\n /**\n * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n * {initializer} and {reinitializer} modifiers, directly or indirectly.\n */\n modifier onlyInitializing() {\n require(_initializing, \"Initializable: contract is not initializing\");\n _;\n }\n\n /**\n * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n * through proxies.\n */\n function _disableInitializers() internal virtual {\n _setInitializedVersion(type(uint8).max);\n }\n\n function _setInitializedVersion(uint8 version) private returns (bool) {\n // If the contract is initializing we ignore whether _initialized is set in order to support multiple\n // inheritance patterns, but we only do this in the context of a constructor, and for the lowest level\n // of initializers, because in other contexts the contract may have been reentered.\n if (_initializing) {\n require(\n version == 1 && !AddressUpgradeable.isContract(address(this)),\n \"Initializable: contract is already initialized\"\n );\n return false;\n } else {\n require(_initialized < version, \"Initializable: contract is already initialized\");\n _initialized = version;\n return true;\n }\n }\n}\n"
259
+ "@threshold-network/solidity-contracts/contracts/staking/IApplication.sol": {
260
+ "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity 0.8.9;\n\n/// @title Application interface for Threshold Network applications\n/// @notice Generic interface for an application. Application is an external\n/// smart contract or a set of smart contracts utilizing functionalities\n/// offered by Threshold Network. Applications authorized for the given\n/// staking provider are eligible to slash the stake delegated to that\n/// staking provider.\ninterface IApplication {\n /// @dev Event emitted by `withdrawRewards` function.\n event RewardsWithdrawn(address indexed stakingProvider, uint96 amount);\n\n /// @notice Withdraws application rewards for the given staking provider.\n /// Rewards are withdrawn to the staking provider's beneficiary\n /// address set in the staking contract.\n /// @dev Emits `RewardsWithdrawn` event.\n function withdrawRewards(address stakingProvider) external;\n\n /// @notice Used by T staking contract to inform the application that the\n /// authorized amount for the given staking provider increased.\n /// The application may do any necessary housekeeping. The\n /// application must revert the transaction in case the\n /// authorization is below the minimum required.\n function authorizationIncreased(\n address stakingProvider,\n uint96 fromAmount,\n uint96 toAmount\n ) external;\n\n /// @notice Used by T staking contract to inform the application that the\n /// authorization decrease for the given staking provider has been\n /// requested. The application should mark the authorization as\n /// pending decrease and respond to the staking contract with\n /// `approveAuthorizationDecrease` at its discretion. It may\n /// happen right away but it also may happen several months later.\n function authorizationDecreaseRequested(\n address stakingProvider,\n uint96 fromAmount,\n uint96 toAmount\n ) external;\n\n /// @notice Used by T staking contract to inform the application the\n /// authorization has been decreased for the given staking provider\n /// involuntarily, as a result of slashing. Lets the application to\n /// do any housekeeping neccessary. Called with 250k gas limit and\n /// does not revert the transaction if\n /// `involuntaryAuthorizationDecrease` call failed.\n function involuntaryAuthorizationDecrease(\n address stakingProvider,\n uint96 fromAmount,\n uint96 toAmount\n ) external;\n\n /// @notice Returns the amount of application rewards available for\n /// withdrawal for the given staking provider.\n function availableRewards(address stakingProvider)\n external\n view\n returns (uint96);\n\n /// @notice The minimum authorization amount required for the staking\n /// provider so that they can participate in the application.\n function minimumAuthorization() external view returns (uint96);\n}\n"
219
261
  },
220
- "contracts/bridge/DepositSweep.sol": {
221
- "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\n\nimport \"./BitcoinTx.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Wallets.sol\";\n\nimport \"../bank/Bank.sol\";\n\n/// @title Bridge deposit sweep\n/// @notice The library handles the logic for sweeping transactions revealed to\n/// the Bridge\n/// @dev Bridge active wallet periodically signs a transaction that unlocks all\n/// of the valid, revealed deposits above the dust threshold, combines them\n/// into a single UTXO with the existing main wallet UTXO, and relocks\n/// those transactions without a 30-day refund clause to the same wallet.\n/// This has two main effects: it consolidates the UTXO set and it disables\n/// the refund. Balances of depositors in the Bank are increased when the\n/// SPV sweep proof is submitted to the Bridge.\nlibrary DepositSweep {\n using BridgeState for BridgeState.Storage;\n using BitcoinTx for BridgeState.Storage;\n\n using BTCUtils for bytes;\n\n /// @notice Represents temporary information needed during the processing\n /// of the deposit sweep Bitcoin transaction inputs. This structure\n /// is an internal one and should not be exported outside of the\n /// deposit sweep transaction processing code.\n /// @dev Allows to mitigate \"stack too deep\" errors on EVM.\n struct DepositSweepTxInputsProcessingInfo {\n // Input vector of the deposit sweep Bitcoin transaction. It is\n // assumed the vector's structure is valid so it must be validated\n // using e.g. `BTCUtils.validateVin` function before being used\n // during the processing. The validation is usually done as part\n // of the `BitcoinTx.validateProof` call that checks the SPV proof.\n bytes sweepTxInputVector;\n // Data of the wallet's main UTXO. If no main UTXO exists for the given\n // sweeping wallet, this parameter's fields should be zeroed to bypass\n // the main UTXO validation\n BitcoinTx.UTXO mainUtxo;\n // Address of the vault where all swept deposits should be routed to.\n // It is used to validate whether all swept deposits have been revealed\n // with the same `vault` parameter. It is an optional parameter.\n // Set to zero address if deposits are not routed to a vault.\n address vault;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's memory argument.\n }\n\n /// @notice Represents an outcome of the sweep Bitcoin transaction\n /// inputs processing.\n struct DepositSweepTxInputsInfo {\n // Sum of all inputs values i.e. all deposits and main UTXO value,\n // if present.\n uint256 inputsTotalValue;\n // Addresses of depositors who performed processed deposits. Ordered in\n // the same order as deposits inputs in the input vector. Size of this\n // array is either equal to the number of inputs (main UTXO doesn't\n // exist) or less by one (main UTXO exists and is pointed by one of\n // the inputs).\n address[] depositors;\n // Amounts of deposits corresponding to processed deposits. Ordered in\n // the same order as deposits inputs in the input vector. Size of this\n // array is either equal to the number of inputs (main UTXO doesn't\n // exist) or less by one (main UTXO exists and is pointed by one of\n // the inputs).\n uint256[] depositedAmounts;\n // Values of the treasury fee corresponding to processed deposits.\n // Ordered in the same order as deposits inputs in the input vector.\n // Size of this array is either equal to the number of inputs (main\n // UTXO doesn't exist) or less by one (main UTXO exists and is pointed\n // by one of the inputs).\n uint256[] treasuryFees;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's memory argument.\n }\n\n event DepositsSwept(bytes20 walletPubKeyHash, bytes32 sweepTxHash);\n\n /// @notice Used by the wallet to prove the BTC deposit sweep transaction\n /// and to update Bank balances accordingly. Sweep is only accepted\n /// if it satisfies SPV proof.\n ///\n /// The function is performing Bank balance updates by first\n /// computing the Bitcoin fee for the sweep transaction. The fee is\n /// divided evenly between all swept deposits. Each depositor\n /// receives a balance in the bank equal to the amount inferred\n /// during the reveal transaction, minus their fee share.\n ///\n /// It is possible to prove the given sweep only one time.\n /// @param sweepTx Bitcoin sweep transaction data.\n /// @param sweepProof Bitcoin sweep proof data.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain. If no main UTXO exists for the given wallet,\n /// this parameter is ignored.\n /// @param vault Optional address of the vault where all swept deposits\n /// should be routed to. All deposits swept as part of the transaction\n /// must have their `vault` parameters set to the same address.\n /// If this parameter is set to an address of a trusted vault, swept\n /// deposits are routed to that vault.\n /// If this parameter is set to the zero address or to an address\n /// of a non-trusted vault, swept deposits are not routed to a\n /// vault but depositors' balances are increased in the Bank\n /// individually.\n /// @dev Requirements:\n /// - `sweepTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash,\n /// - The `sweepTx` should represent a Bitcoin transaction with 1..n\n /// inputs. If the wallet has no main UTXO, all n inputs should\n /// correspond to P2(W)SH revealed deposits UTXOs. If the wallet has\n /// an existing main UTXO, one of the n inputs must point to that\n /// main UTXO and remaining n-1 inputs should correspond to P2(W)SH\n /// revealed deposits UTXOs. That transaction must have only\n /// one P2(W)PKH output locking funds on the 20-byte wallet public\n /// key hash,\n /// - All revealed deposits that are swept by `sweepTx` must have\n /// their `vault` parameters set to the same address as the address\n /// passed in the `vault` function parameter,\n /// - `sweepProof` components must match the expected structure. See\n /// `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// If there is no main UTXO, this parameter is ignored.\n function submitDepositSweepProof(\n BridgeState.Storage storage self,\n BitcoinTx.Info calldata sweepTx,\n BitcoinTx.Proof calldata sweepProof,\n BitcoinTx.UTXO calldata mainUtxo,\n address vault\n ) external {\n // The actual transaction proof is performed here. After that point, we\n // can assume the transaction happened on Bitcoin chain and has\n // a sufficient number of confirmations as determined by\n // `txProofDifficultyFactor` constant.\n bytes32 sweepTxHash = self.validateProof(sweepTx, sweepProof);\n\n // Process sweep transaction output and extract its target wallet\n // public key hash and value.\n (\n bytes20 walletPubKeyHash,\n uint64 sweepTxOutputValue\n ) = processDepositSweepTxOutput(self, sweepTx.outputVector);\n\n (\n Wallets.Wallet storage wallet,\n BitcoinTx.UTXO memory resolvedMainUtxo\n ) = resolveDepositSweepingWallet(self, walletPubKeyHash, mainUtxo);\n\n // Process sweep transaction inputs and extract all information needed\n // to perform deposit bookkeeping.\n DepositSweepTxInputsInfo\n memory inputsInfo = processDepositSweepTxInputs(\n self,\n DepositSweepTxInputsProcessingInfo(\n sweepTx.inputVector,\n resolvedMainUtxo,\n vault\n )\n );\n\n // Helper variable that will hold the sum of treasury fees paid by\n // all deposits.\n uint256 totalTreasuryFee = 0;\n\n // Determine the transaction fee that should be incurred by each deposit\n // and the indivisible remainder that should be additionally incurred\n // by the last deposit.\n (\n uint256 depositTxFee,\n uint256 depositTxFeeRemainder\n ) = depositSweepTxFeeDistribution(\n inputsInfo.inputsTotalValue,\n sweepTxOutputValue,\n inputsInfo.depositedAmounts.length\n );\n\n // Make sure the highest value of the deposit transaction fee does not\n // exceed the maximum value limited by the governable parameter.\n require(\n depositTxFee + depositTxFeeRemainder <= self.depositTxMaxFee,\n \"Transaction fee is too high\"\n );\n\n // Reduce each deposit amount by treasury fee and transaction fee.\n for (uint256 i = 0; i < inputsInfo.depositedAmounts.length; i++) {\n // The last deposit should incur the deposit transaction fee\n // remainder.\n uint256 depositTxFeeIncurred = i ==\n inputsInfo.depositedAmounts.length - 1\n ? depositTxFee + depositTxFeeRemainder\n : depositTxFee;\n\n // There is no need to check whether\n // `inputsInfo.depositedAmounts[i] - inputsInfo.treasuryFees[i] - txFee > 0`\n // since the `depositDustThreshold` should force that condition\n // to be always true.\n inputsInfo.depositedAmounts[i] =\n inputsInfo.depositedAmounts[i] -\n inputsInfo.treasuryFees[i] -\n depositTxFeeIncurred;\n totalTreasuryFee += inputsInfo.treasuryFees[i];\n }\n\n // Record this sweep data and assign them to the wallet public key hash\n // as new main UTXO. Transaction output index is always 0 as sweep\n // transaction always contains only one output.\n wallet.mainUtxoHash = keccak256(\n abi.encodePacked(sweepTxHash, uint32(0), sweepTxOutputValue)\n );\n\n // slither-disable-next-line reentrancy-events\n emit DepositsSwept(walletPubKeyHash, sweepTxHash);\n\n if (vault != address(0) && self.isVaultTrusted[vault]) {\n // If the `vault` address is not zero and belongs to a trusted\n // vault, route the deposits to that vault.\n self.bank.increaseBalanceAndCall(\n vault,\n inputsInfo.depositors,\n inputsInfo.depositedAmounts\n );\n } else {\n // If the `vault` address is zero or belongs to a non-trusted\n // vault, increase balances in the Bank individually for each\n // depositor.\n self.bank.increaseBalances(\n inputsInfo.depositors,\n inputsInfo.depositedAmounts\n );\n }\n\n // Pass the treasury fee to the treasury address.\n self.bank.increaseBalance(self.treasury, totalTreasuryFee);\n }\n\n /// @notice Resolves sweeping wallet based on the provided wallet public key\n /// hash. Validates the wallet state and current main UTXO, as\n /// currently known on the Ethereum chain.\n /// @param walletPubKeyHash public key hash of the wallet proving the sweep\n /// Bitcoin transaction.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain. If no main UTXO exists for the given wallet,\n /// this parameter is ignored.\n /// @return wallet Data of the sweeping wallet.\n /// @return resolvedMainUtxo The actual main UTXO of the sweeping wallet\n /// resolved by cross-checking the `mainUtxo` parameter with\n /// the chain state. If the validation went well, this is the\n /// plain-text main UTXO corresponding to the `wallet.mainUtxoHash`.\n /// @dev Requirements:\n /// - Sweeping wallet must be either in Live or MovingFunds state,\n /// - If the main UTXO of the sweeping wallet exists in the storage,\n /// the passed `mainUTXO` parameter must be equal to the stored one.\n function resolveDepositSweepingWallet(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata mainUtxo\n )\n internal\n view\n returns (\n Wallets.Wallet storage wallet,\n BitcoinTx.UTXO memory resolvedMainUtxo\n )\n {\n wallet = self.registeredWallets[walletPubKeyHash];\n\n Wallets.WalletState walletState = wallet.state;\n require(\n walletState == Wallets.WalletState.Live ||\n walletState == Wallets.WalletState.MovingFunds,\n \"Wallet must be in Live or MovingFunds state\"\n );\n\n // Check if the main UTXO for given wallet exists. If so, validate\n // passed main UTXO data against the stored hash and use them for\n // further processing. If no main UTXO exists, use empty data.\n resolvedMainUtxo = BitcoinTx.UTXO(bytes32(0), 0, 0);\n bytes32 mainUtxoHash = wallet.mainUtxoHash;\n if (mainUtxoHash != bytes32(0)) {\n require(\n keccak256(\n abi.encodePacked(\n mainUtxo.txHash,\n mainUtxo.txOutputIndex,\n mainUtxo.txOutputValue\n )\n ) == mainUtxoHash,\n \"Invalid main UTXO data\"\n );\n resolvedMainUtxo = mainUtxo;\n }\n }\n\n /// @notice Processes the Bitcoin sweep transaction output vector by\n /// extracting the single output and using it to gain additional\n /// information required for further processing (e.g. value and\n /// wallet public key hash).\n /// @param sweepTxOutputVector Bitcoin sweep transaction output vector.\n /// This function assumes vector's structure is valid so it must be\n /// validated using e.g. `BTCUtils.validateVout` function before\n /// it is passed here.\n /// @return walletPubKeyHash 20-byte wallet public key hash.\n /// @return value 8-byte sweep transaction output value.\n function processDepositSweepTxOutput(\n BridgeState.Storage storage self,\n bytes memory sweepTxOutputVector\n ) internal view returns (bytes20 walletPubKeyHash, uint64 value) {\n // To determine the total number of sweep transaction outputs, we need to\n // parse the compactSize uint (VarInt) the output vector is prepended by.\n // That compactSize uint encodes the number of vector elements using the\n // format presented in:\n // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers\n // We don't need asserting the compactSize uint is parseable since it\n // was already checked during `validateVout` validation.\n // See `BitcoinTx.outputVector` docs for more details.\n (, uint256 outputsCount) = sweepTxOutputVector.parseVarInt();\n require(\n outputsCount == 1,\n \"Sweep transaction must have a single output\"\n );\n\n bytes memory output = sweepTxOutputVector.extractOutputAtIndex(0);\n walletPubKeyHash = self.extractPubKeyHash(output);\n value = output.extractValue();\n\n return (walletPubKeyHash, value);\n }\n\n /// @notice Processes the Bitcoin sweep transaction input vector. It\n /// extracts each input and tries to obtain associated deposit or\n /// main UTXO data, depending on the input type. Reverts\n /// if one of the inputs cannot be recognized as a pointer to a\n /// revealed deposit or expected main UTXO.\n /// This function also marks each processed deposit as swept.\n /// @return resultInfo Outcomes of the processing.\n function processDepositSweepTxInputs(\n BridgeState.Storage storage self,\n DepositSweepTxInputsProcessingInfo memory processInfo\n ) internal returns (DepositSweepTxInputsInfo memory resultInfo) {\n // If the passed `mainUtxo` parameter's values are zeroed, the main UTXO\n // for the given wallet doesn't exist and it is not expected to be\n // included in the sweep transaction input vector.\n bool mainUtxoExpected = processInfo.mainUtxo.txHash != bytes32(0);\n bool mainUtxoFound = false;\n\n // Determining the total number of sweep transaction inputs in the same\n // way as for number of outputs. See `BitcoinTx.inputVector` docs for\n // more details.\n (uint256 inputsCompactSizeUintLength, uint256 inputsCount) = processInfo\n .sweepTxInputVector\n .parseVarInt();\n\n // To determine the first input starting index, we must jump over\n // the compactSize uint which prepends the input vector. One byte\n // must be added because `BtcUtils.parseVarInt` does not include\n // compactSize uint tag in the returned length.\n //\n // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`\n // returns `0`, so we jump over one byte of compactSize uint.\n //\n // For >= 253 && <= 0xffff there is `0xfd` tag,\n // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no\n // tag byte included) so we need to jump over 1+2 bytes of\n // compactSize uint.\n //\n // Please refer `BTCUtils` library and compactSize uint\n // docs in `BitcoinTx` library for more details.\n uint256 inputStartingIndex = 1 + inputsCompactSizeUintLength;\n\n // Determine the swept deposits count. If main UTXO is NOT expected,\n // all inputs should be deposits. If main UTXO is expected, one input\n // should point to that main UTXO.\n resultInfo.depositors = new address[](\n !mainUtxoExpected ? inputsCount : inputsCount - 1\n );\n resultInfo.depositedAmounts = new uint256[](\n resultInfo.depositors.length\n );\n resultInfo.treasuryFees = new uint256[](resultInfo.depositors.length);\n\n // Initialize helper variables.\n uint256 processedDepositsCount = 0;\n\n // Inputs processing loop.\n for (uint256 i = 0; i < inputsCount; i++) {\n (\n bytes32 outpointTxHash,\n uint32 outpointIndex,\n uint256 inputLength\n ) = parseDepositSweepTxInputAt(\n processInfo.sweepTxInputVector,\n inputStartingIndex\n );\n\n Deposit.DepositRequest storage deposit = self.deposits[\n uint256(\n keccak256(abi.encodePacked(outpointTxHash, outpointIndex))\n )\n ];\n\n if (deposit.revealedAt != 0) {\n // If we entered here, that means the input was identified as\n // a revealed deposit.\n require(deposit.sweptAt == 0, \"Deposit already swept\");\n\n require(\n deposit.vault == processInfo.vault,\n \"Deposit should be routed to another vault\"\n );\n\n if (processedDepositsCount == resultInfo.depositors.length) {\n // If this condition is true, that means a deposit input\n // took place of an expected main UTXO input.\n // In other words, there is no expected main UTXO\n // input and all inputs come from valid, revealed deposits.\n revert(\n \"Expected main UTXO not present in sweep transaction inputs\"\n );\n }\n\n /* solhint-disable-next-line not-rely-on-time */\n deposit.sweptAt = uint32(block.timestamp);\n\n resultInfo.depositors[processedDepositsCount] = deposit\n .depositor;\n resultInfo.depositedAmounts[processedDepositsCount] = deposit\n .amount;\n resultInfo.inputsTotalValue += resultInfo.depositedAmounts[\n processedDepositsCount\n ];\n resultInfo.treasuryFees[processedDepositsCount] = deposit\n .treasuryFee;\n\n processedDepositsCount++;\n } else if (\n mainUtxoExpected != mainUtxoFound &&\n processInfo.mainUtxo.txHash == outpointTxHash &&\n processInfo.mainUtxo.txOutputIndex == outpointIndex\n ) {\n // If we entered here, that means the input was identified as\n // the expected main UTXO.\n resultInfo.inputsTotalValue += processInfo\n .mainUtxo\n .txOutputValue;\n mainUtxoFound = true;\n\n // Main UTXO used as an input, mark it as spent.\n self.spentMainUTXOs[\n uint256(\n keccak256(\n abi.encodePacked(outpointTxHash, outpointIndex)\n )\n )\n ] = true;\n } else {\n revert(\"Unknown input type\");\n }\n\n // Make the `inputStartingIndex` pointing to the next input by\n // increasing it by current input's length.\n inputStartingIndex += inputLength;\n }\n\n // Construction of the input processing loop guarantees that:\n // `processedDepositsCount == resultInfo.depositors.length == resultInfo.depositedAmounts.length`\n // is always true at this point. We just use the first variable\n // to assert the total count of swept deposit is bigger than zero.\n require(\n processedDepositsCount > 0,\n \"Sweep transaction must process at least one deposit\"\n );\n\n // Assert the main UTXO was used as one of current sweep's inputs if\n // it was actually expected.\n require(\n mainUtxoExpected == mainUtxoFound,\n \"Expected main UTXO not present in sweep transaction inputs\"\n );\n\n return resultInfo;\n }\n\n /// @notice Parses a Bitcoin transaction input starting at the given index.\n /// @param inputVector Bitcoin transaction input vector.\n /// @param inputStartingIndex Index the given input starts at.\n /// @return outpointTxHash 32-byte hash of the Bitcoin transaction which is\n /// pointed in the given input's outpoint.\n /// @return outpointIndex 4-byte index of the Bitcoin transaction output\n /// which is pointed in the given input's outpoint.\n /// @return inputLength Byte length of the given input.\n /// @dev This function assumes vector's structure is valid so it must be\n /// validated using e.g. `BTCUtils.validateVin` function before it\n /// is passed here.\n function parseDepositSweepTxInputAt(\n bytes memory inputVector,\n uint256 inputStartingIndex\n )\n internal\n pure\n returns (\n bytes32 outpointTxHash,\n uint32 outpointIndex,\n uint256 inputLength\n )\n {\n outpointTxHash = inputVector.extractInputTxIdLeAt(inputStartingIndex);\n\n outpointIndex = BTCUtils.reverseUint32(\n uint32(inputVector.extractTxIndexLeAt(inputStartingIndex))\n );\n\n inputLength = inputVector.determineInputLengthAt(inputStartingIndex);\n\n return (outpointTxHash, outpointIndex, inputLength);\n }\n\n /// @notice Determines the distribution of the sweep transaction fee\n /// over swept deposits.\n /// @param sweepTxInputsTotalValue Total value of all sweep transaction inputs.\n /// @param sweepTxOutputValue Value of the sweep transaction output.\n /// @param depositsCount Count of the deposits swept by the sweep transaction.\n /// @return depositTxFee Transaction fee per deposit determined by evenly\n /// spreading the divisible part of the sweep transaction fee\n /// over all deposits.\n /// @return depositTxFeeRemainder The indivisible part of the sweep\n /// transaction fee than cannot be distributed over all deposits.\n /// @dev It is up to the caller to decide how the remainder should be\n /// counted in. This function only computes its value.\n function depositSweepTxFeeDistribution(\n uint256 sweepTxInputsTotalValue,\n uint256 sweepTxOutputValue,\n uint256 depositsCount\n )\n internal\n pure\n returns (uint256 depositTxFee, uint256 depositTxFeeRemainder)\n {\n // The sweep transaction fee is just the difference between inputs\n // amounts sum and the output amount.\n uint256 sweepTxFee = sweepTxInputsTotalValue - sweepTxOutputValue;\n // Compute the indivisible remainder that remains after dividing the\n // sweep transaction fee over all deposits evenly.\n depositTxFeeRemainder = sweepTxFee % depositsCount;\n // Compute the transaction fee per deposit by dividing the sweep\n // transaction fee (reduced by the remainder) by the number of deposits.\n depositTxFee = (sweepTxFee - depositTxFeeRemainder) / depositsCount;\n\n return (depositTxFee, depositTxFeeRemainder);\n }\n}\n"
262
+ "@keep-network/random-beacon/contracts/api/IRandomBeaconConsumer.sol": {
263
+ "content": "// SPDX-License-Identifier: MIT\n//\n// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄\n// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓\n// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓\n// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀\n// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌\n// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓\n//\n// Trust math, not hardware.\n\npragma solidity ^0.8.9;\n\ninterface IRandomBeaconConsumer {\n /// @notice Receives relay entry produced by Keep Random Beacon. This function\n /// should be called only by Keep Random Beacon.\n ///\n /// @param relayEntry Relay entry (random number) produced by Keep Random\n /// Beacon.\n /// @param blockNumber Block number at which the relay entry was submitted\n /// to the chain.\n function __beaconCallback(uint256 relayEntry, uint256 blockNumber) external;\n}\n"
222
264
  },
223
- "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol": {
224
- "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary AddressUpgradeable {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
265
+ "@keep-network/random-beacon/contracts/api/IRandomBeacon.sol": {
266
+ "content": "// SPDX-License-Identifier: MIT\n//\n// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄\n// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓\n// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓\n// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀\n// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌\n// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓\n//\n// Trust math, not hardware.\n\npragma solidity ^0.8.9;\n\nimport \"./IRandomBeaconConsumer.sol\";\n\n/// @title Random Beacon interface\ninterface IRandomBeacon {\n /// @notice Creates a request to generate a new relay entry. Requires a\n /// request fee denominated in T token.\n /// @param callbackContract Beacon consumer callback contract.\n function requestRelayEntry(IRandomBeaconConsumer callbackContract) external;\n}\n"
225
267
  },
226
- "contracts/test/TestRelay.sol": {
227
- "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.9;\n\nimport \"../bridge/Bridge.sol\";\n\ncontract TestRelay is IRelay {\n uint256 private currentEpochDifficulty;\n uint256 private prevEpochDifficulty;\n\n function setCurrentEpochDifficulty(uint256 _difficulty) external {\n currentEpochDifficulty = _difficulty;\n }\n\n function setPrevEpochDifficulty(uint256 _difficulty) external {\n prevEpochDifficulty = _difficulty;\n }\n\n function getCurrentEpochDifficulty()\n external\n view\n override\n returns (uint256)\n {\n return currentEpochDifficulty;\n }\n\n function getPrevEpochDifficulty() external view override returns (uint256) {\n return prevEpochDifficulty;\n }\n}\n"
268
+ "contracts/hardhat-dependency-compiler/@keep-network/ecdsa/contracts/WalletRegistry.sol": {
269
+ "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >0.0.0;\nimport '@keep-network/ecdsa/contracts/WalletRegistry.sol';\n"
228
270
  },
229
- "contracts/test/HeartbeatStub.sol": {
230
- "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.9;\n\nimport \"../bridge/Heartbeat.sol\";\n\n/// @dev This is a contract implemented to test Heartbeat library directly.\ncontract HeartbeatStub {\n function isValidHeartbeatMessage(bytes calldata message)\n public\n pure\n returns (bool)\n {\n return Heartbeat.isValidHeartbeatMessage(message);\n }\n}\n"
231
- },
232
- "contracts/test/TestEcdsaLib.sol": {
233
- "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.9;\n\nimport \"../bridge/EcdsaLib.sol\";\n\n// TODO: Rename to EcdsLibStub\n/// @dev This is a contract implemented to test EcdsaLib library directly.\ncontract TestEcdsaLib {\n function compressPublicKey(bytes32 x, bytes32 y)\n public\n pure\n returns (bytes memory)\n {\n return EcdsaLib.compressPublicKey(x, y);\n }\n}\n"
271
+ "@keep-network/ecdsa/contracts/WalletRegistry.sol": {
272
+ "content": "// SPDX-License-Identifier: MIT\n//\n// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄\n// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓\n// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓\n// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀\n// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌\n// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓\n//\n// Trust math, not hardware.\n\npragma solidity ^0.8.9;\n\nimport \"./api/IWalletRegistry.sol\";\nimport \"./api/IWalletOwner.sol\";\nimport \"./libraries/Wallets.sol\";\nimport {EcdsaAuthorization as Authorization} from \"./libraries/EcdsaAuthorization.sol\";\nimport {EcdsaDkg as DKG} from \"./libraries/EcdsaDkg.sol\";\nimport {EcdsaInactivity as Inactivity} from \"./libraries/EcdsaInactivity.sol\";\nimport {EcdsaDkgValidator as DKGValidator} from \"./EcdsaDkgValidator.sol\";\n\nimport \"@keep-network/sortition-pools/contracts/SortitionPool.sol\";\nimport \"@keep-network/random-beacon/contracts/api/IRandomBeacon.sol\";\nimport \"@keep-network/random-beacon/contracts/api/IRandomBeaconConsumer.sol\";\nimport \"@keep-network/random-beacon/contracts/Reimbursable.sol\";\nimport \"@keep-network/random-beacon/contracts/ReimbursementPool.sol\";\nimport \"@keep-network/random-beacon/contracts/Governable.sol\";\n\nimport \"@threshold-network/solidity-contracts/contracts/staking/IApplication.sol\";\nimport \"@threshold-network/solidity-contracts/contracts/staking/IStaking.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\ncontract WalletRegistry is\n IWalletRegistry,\n IRandomBeaconConsumer,\n IApplication,\n Governable,\n Reimbursable,\n Initializable\n{\n using Authorization for Authorization.Data;\n using DKG for DKG.Data;\n using Wallets for Wallets.Data;\n\n // Libraries data storages\n Authorization.Data internal authorization;\n DKG.Data internal dkg;\n Wallets.Data internal wallets;\n\n /// @notice Slashing amount for submitting a malicious DKG result. Every\n /// DKG result submitted can be challenged for the time of\n /// `dkg.resultChallengePeriodLength`. If the DKG result submitted\n /// is challenged and proven to be malicious, the operator who\n /// submitted the malicious result is slashed for\n /// `_maliciousDkgResultSlashingAmount`.\n uint96 internal _maliciousDkgResultSlashingAmount;\n\n /// @notice Percentage of the staking contract malicious behavior\n /// notification reward which will be transferred to the notifier\n /// reporting about a malicious DKG result. Notifiers are rewarded\n /// from a notifiers treasury pool. For example, if\n /// notification reward is 1000 and the value of the multiplier is\n /// 5, the notifier will receive: 5% of 1000 = 50 per each\n /// operator affected.\n uint256 internal _maliciousDkgResultNotificationRewardMultiplier;\n\n /// @notice Duration of the sortition pool rewards ban imposed on operators\n /// who missed their turn for DKG result submission or who failed\n /// a heartbeat.\n uint256 internal _sortitionPoolRewardsBanDuration;\n\n /// @notice Calculated max gas cost for submitting a DKG result. This will\n /// be refunded as part of the DKG approval process. It is in the\n /// submitter's interest to not skip his priority turn on the approval,\n /// otherwise the refund of the DKG submission will be refunded to\n /// another group member that will call the DKG approve function.\n uint256 internal _dkgResultSubmissionGas;\n\n /// @notice Gas that is meant to balance the DKG result approval's overall\n /// cost. It can be updated by the governance based on the current\n /// market conditions.\n uint256 internal _dkgResultApprovalGasOffset;\n\n /// @notice Gas that is meant to balance the notification of an operator\n /// inactivity. It can be updated by the governance based on the\n /// current market conditions.\n uint256 internal _notifyOperatorInactivityGasOffset;\n\n /// @notice Gas that is meant to balance the notification of a seed for DKG\n /// delivery timeout. It can be updated by the governance based on the\n /// current market conditions.\n uint256 internal _notifySeedTimeoutGasOffset;\n\n /// @notice Gas that is meant to balance the notification of a DKG protocol\n /// execution timeout. It can be updated by the governance based on the\n /// current market conditions.\n /// @dev The value is subtracted for the refundable gas calculation, as the\n /// DKG timeout notification transaction recovers some gas when cleaning\n /// up the storage.\n uint256 internal _notifyDkgTimeoutNegativeGasOffset;\n\n /// @notice Stores current operator inactivity claim nonce for the given\n /// wallet signing group. Each claim is made with a unique nonce\n /// which protects against claim replay.\n mapping(bytes32 => uint256) public inactivityClaimNonce; // walletID -> nonce\n\n // Address that is set as owner of all wallets. Only this address can request\n // new wallets creation and manage their state.\n IWalletOwner public walletOwner;\n\n // External dependencies\n\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n SortitionPool public immutable sortitionPool;\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n IStaking public immutable staking;\n IRandomBeacon public randomBeacon;\n\n // Events\n event DkgStarted(uint256 indexed seed);\n\n event DkgResultSubmitted(\n bytes32 indexed resultHash,\n uint256 indexed seed,\n DKG.Result result\n );\n\n event DkgTimedOut();\n\n event DkgResultApproved(\n bytes32 indexed resultHash,\n address indexed approver\n );\n\n event DkgResultChallenged(\n bytes32 indexed resultHash,\n address indexed challenger,\n string reason\n );\n\n event DkgStateLocked();\n\n event DkgSeedTimedOut();\n\n event WalletCreated(\n bytes32 indexed walletID,\n bytes32 indexed dkgResultHash\n );\n\n event WalletClosed(bytes32 indexed walletID);\n\n event DkgMaliciousResultSlashed(\n bytes32 indexed resultHash,\n uint256 slashingAmount,\n address maliciousSubmitter\n );\n\n event DkgMaliciousResultSlashingFailed(\n bytes32 indexed resultHash,\n uint256 slashingAmount,\n address maliciousSubmitter\n );\n\n event AuthorizationParametersUpdated(\n uint96 minimumAuthorization,\n uint64 authorizationDecreaseDelay,\n uint64 authorizationDecreaseChangePeriod\n );\n\n event RewardParametersUpdated(\n uint256 maliciousDkgResultNotificationRewardMultiplier,\n uint256 sortitionPoolRewardsBanDuration\n );\n\n event SlashingParametersUpdated(uint256 maliciousDkgResultSlashingAmount);\n\n event DkgParametersUpdated(\n uint256 seedTimeout,\n uint256 resultChallengePeriodLength,\n uint256 resultSubmissionTimeout,\n uint256 resultSubmitterPrecedencePeriodLength\n );\n\n event GasParametersUpdated(\n uint256 dkgResultSubmissionGas,\n uint256 dkgResultApprovalGasOffset,\n uint256 notifyOperatorInactivityGasOffset,\n uint256 notifySeedTimeoutGasOffset,\n uint256 notifyDkgTimeoutNegativeGasOffset\n );\n\n event RandomBeaconUpgraded(address randomBeacon);\n\n event WalletOwnerUpdated(address walletOwner);\n\n event OperatorRegistered(\n address indexed stakingProvider,\n address indexed operator\n );\n\n event AuthorizationIncreased(\n address indexed stakingProvider,\n address indexed operator,\n uint96 fromAmount,\n uint96 toAmount\n );\n\n event AuthorizationDecreaseRequested(\n address indexed stakingProvider,\n address indexed operator,\n uint96 fromAmount,\n uint96 toAmount,\n uint64 decreasingAt\n );\n\n event AuthorizationDecreaseApproved(address indexed stakingProvider);\n\n event InvoluntaryAuthorizationDecreaseFailed(\n address indexed stakingProvider,\n address indexed operator,\n uint96 fromAmount,\n uint96 toAmount\n );\n\n event OperatorJoinedSortitionPool(\n address indexed stakingProvider,\n address indexed operator\n );\n\n event OperatorStatusUpdated(\n address indexed stakingProvider,\n address indexed operator\n );\n\n event InactivityClaimed(\n bytes32 indexed walletID,\n uint256 nonce,\n address notifier\n );\n\n modifier onlyStakingContract() {\n require(\n msg.sender == address(staking),\n \"Caller is not the staking contract\"\n );\n _;\n }\n\n /// @notice Reverts if called not by the Wallet Owner.\n modifier onlyWalletOwner() {\n require(\n msg.sender == address(walletOwner),\n \"Caller is not the Wallet Owner\"\n );\n _;\n }\n\n modifier onlyReimbursableAdmin() override {\n require(governance == msg.sender, \"Caller is not the governance\");\n _;\n }\n\n /// @dev Used to initialize immutable variables only, use `initialize` function\n /// for upgradable contract initialization on deployment.\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(SortitionPool _sortitionPool, IStaking _staking) {\n sortitionPool = _sortitionPool;\n staking = _staking;\n\n _disableInitializers();\n }\n\n /// @dev Initializes upgradable contract on deployment.\n function initialize(\n DKGValidator _ecdsaDkgValidator,\n IRandomBeacon _randomBeacon,\n ReimbursementPool _reimbursementPool\n ) external initializer {\n randomBeacon = _randomBeacon;\n reimbursementPool = _reimbursementPool;\n\n _transferGovernance(msg.sender);\n\n //\n // All parameters set in the constructor are initial ones, used at the\n // moment contracts were deployed for the first time. Parameters are\n // governable and values assigned in the constructor do not need to\n // reflect the current ones.\n //\n\n // Minimum authorization is 40k T.\n //\n // Authorization decrease delay is 45 days.\n //\n // Authorization decrease change period is 45 days. It means pending\n // authorization decrease can be overwriten all the time.\n authorization.setMinimumAuthorization(40_000e18);\n authorization.setAuthorizationDecreaseDelay(3_888_000);\n authorization.setAuthorizationDecreaseChangePeriod(3_888_000);\n\n // Malicious DKG result slashing amount is set initially to 1% of the\n // minimum authorization (400 T). This values needs to be increased\n // significantly once the system is fully launched.\n //\n // Notifier of a malicious DKG result receives 100% of the notifier\n // reward from the staking contract.\n //\n // Inactive operators are set as ineligible for rewards for 2 weeks.\n _maliciousDkgResultSlashingAmount = 400e18;\n _maliciousDkgResultNotificationRewardMultiplier = 100;\n _sortitionPoolRewardsBanDuration = 2 weeks;\n\n // DKG seed timeout is set to 48h assuming 15s block time. The same\n // value is used by the Random Beacon as a relay entry hard timeout.\n //\n // DKG result challenge period length is set to 48h as well, assuming\n // 15s block time.\n //\n // DKG result submission timeout, gives each member 20 blocks to submit\n // the result. Assuming 15s block time, it is ~8h to submit the result\n // in the pessimistic case.\n //\n // The original DKG result submitter has 20 blocks to approve it before\n // anyone else can do that.\n //\n // With these parameters, the happy path takes no more than 104 hours.\n // In practice, it should take about 48 hours (just the challenge time).\n dkg.init(sortitionPool, _ecdsaDkgValidator);\n dkg.setSeedTimeout(11_520);\n dkg.setResultChallengePeriodLength(11_520);\n dkg.setResultSubmissionTimeout(100 * 20);\n dkg.setSubmitterPrecedencePeriodLength(20);\n\n // Gas parameters were adjusted based on Ethereum state in April 2022.\n // If the cost of EVM opcodes change over time, these parameters will\n // have to be updated.\n _dkgResultSubmissionGas = 290_000;\n _dkgResultApprovalGasOffset = 72_000;\n _notifyOperatorInactivityGasOffset = 93_000;\n _notifySeedTimeoutGasOffset = 7_250;\n _notifyDkgTimeoutNegativeGasOffset = 2_300;\n }\n\n /// @notice Withdraws application rewards for the given staking provider.\n /// Rewards are withdrawn to the staking provider's beneficiary\n /// address set in the staking contract. Reverts if staking provider\n /// has not registered the operator address.\n /// @dev Emits `RewardsWithdrawn` event.\n function withdrawRewards(address stakingProvider) external {\n address operator = stakingProviderToOperator(stakingProvider);\n require(operator != address(0), \"Unknown operator\");\n (, address beneficiary, ) = staking.rolesOf(stakingProvider);\n uint96 amount = sortitionPool.withdrawRewards(operator, beneficiary);\n // slither-disable-next-line reentrancy-events\n emit RewardsWithdrawn(stakingProvider, amount);\n }\n\n /// @notice Withdraws rewards belonging to operators marked as ineligible\n /// for sortition pool rewards.\n /// @dev Can be called only by the contract guvnor, which should be the\n /// wallet registry governance contract.\n /// @param recipient Recipient of withdrawn rewards.\n function withdrawIneligibleRewards(address recipient)\n external\n onlyGovernance\n {\n sortitionPool.withdrawIneligible(recipient);\n }\n\n /// @notice Used by staking provider to set operator address that will\n /// operate ECDSA node. The given staking provider can set operator\n /// address only one time. The operator address can not be changed\n /// and must be unique. Reverts if the operator is already set for\n /// the staking provider or if the operator address is already in\n /// use. Reverts if there is a pending authorization decrease for\n /// the staking provider.\n function registerOperator(address operator) external {\n authorization.registerOperator(operator);\n }\n\n /// @notice Lets the operator join the sortition pool. The operator address\n /// must be known - before calling this function, it has to be\n /// appointed by the staking provider by calling `registerOperator`.\n /// Also, the operator must have the minimum authorization required\n /// by ECDSA. Function reverts if there is no minimum stake\n /// authorized or if the operator is not known. If there was an\n /// authorization decrease requested, it is activated by starting\n /// the authorization decrease delay.\n function joinSortitionPool() external {\n authorization.joinSortitionPool(staking, sortitionPool);\n }\n\n /// @notice Updates status of the operator in the sortition pool. If there\n /// was an authorization decrease requested, it is activated by\n /// starting the authorization decrease delay.\n /// Function reverts if the operator is not known.\n function updateOperatorStatus(address operator) external {\n authorization.updateOperatorStatus(staking, sortitionPool, operator);\n }\n\n /// @notice Used by T staking contract to inform the application that the\n /// authorized stake amount for the given staking provider increased.\n ///\n /// Reverts if the authorization amount is below the minimum.\n ///\n /// The function is not updating the sortition pool. Sortition pool\n /// state needs to be updated by the operator with a call to\n /// `joinSortitionPool` or `updateOperatorStatus`.\n ///\n /// @dev Can only be called by T staking contract.\n function authorizationIncreased(\n address stakingProvider,\n uint96 fromAmount,\n uint96 toAmount\n ) external onlyStakingContract {\n authorization.authorizationIncreased(\n stakingProvider,\n fromAmount,\n toAmount\n );\n }\n\n /// @notice Used by T staking contract to inform the application that the\n /// authorization decrease for the given staking provider has been\n /// requested.\n ///\n /// Reverts if the amount after deauthorization would be non-zero\n /// and lower than the minimum authorization.\n ///\n /// If the operator is not known (`registerOperator` was not called)\n /// it lets to `approveAuthorizationDecrease` immediatelly. If the\n /// operator is known (`registerOperator` was called), the operator\n /// needs to update state of the sortition pool with a call to\n /// `joinSortitionPool` or `updateOperatorStatus`. After the\n /// sortition pool state is in sync, authorization decrease delay\n /// starts.\n ///\n /// After authorization decrease delay passes, authorization\n /// decrease request needs to be approved with a call to\n /// `approveAuthorizationDecrease` function.\n ///\n /// If there is a pending authorization decrease request, it is\n /// overwritten.\n ///\n /// @dev Can only be called by T staking contract.\n function authorizationDecreaseRequested(\n address stakingProvider,\n uint96 fromAmount,\n uint96 toAmount\n ) external onlyStakingContract {\n authorization.authorizationDecreaseRequested(\n stakingProvider,\n fromAmount,\n toAmount\n );\n }\n\n /// @notice Approves the previously registered authorization decrease\n /// request. Reverts if authorization decrease delay has not passed\n /// yet or if the authorization decrease was not requested for the\n /// given staking provider.\n function approveAuthorizationDecrease(address stakingProvider) external {\n authorization.approveAuthorizationDecrease(staking, stakingProvider);\n }\n\n /// @notice Used by T staking contract to inform the application the\n /// authorization has been decreased for the given staking provider\n /// involuntarily, as a result of slashing.\n ///\n /// If the operator is not known (`registerOperator` was not called)\n /// the function does nothing. The operator was never in a sortition\n /// pool so there is nothing to update.\n ///\n /// If the operator is known, sortition pool is unlocked, and the\n /// operator is in the sortition pool, the sortition pool state is\n /// updated. If the sortition pool is locked, update needs to be\n /// postponed. Every other staker is incentivized to call\n /// `updateOperatorStatus` for the problematic operator to increase\n /// their own rewards in the pool.\n function involuntaryAuthorizationDecrease(\n address stakingProvider,\n uint96 fromAmount,\n uint96 toAmount\n ) external onlyStakingContract {\n authorization.involuntaryAuthorizationDecrease(\n staking,\n sortitionPool,\n stakingProvider,\n fromAmount,\n toAmount\n );\n }\n\n /// @notice Updates address of the Random Beacon.\n /// @dev Can be called only by the contract guvnor, which should be the\n /// wallet registry governance contract. The caller is responsible for\n /// validating parameters.\n /// @param _randomBeacon Random Beacon address.\n function upgradeRandomBeacon(IRandomBeacon _randomBeacon)\n external\n onlyGovernance\n {\n randomBeacon = _randomBeacon;\n emit RandomBeaconUpgraded(address(_randomBeacon));\n }\n\n /// @notice Updates the wallet owner.\n /// @dev Can be called only by the contract guvnor, which should be the\n /// wallet registry governance contract. The caller is responsible for\n /// validating parameters. The wallet owner has to implement `IWalletOwner`\n /// interface.\n /// @param _walletOwner New wallet owner address.\n function updateWalletOwner(IWalletOwner _walletOwner)\n external\n onlyGovernance\n {\n walletOwner = _walletOwner;\n emit WalletOwnerUpdated(address(_walletOwner));\n }\n\n /// @notice Updates the values of authorization parameters.\n /// @dev Can be called only by the contract guvnor, which should be the\n /// wallet registry governance contract. The caller is responsible for\n /// validating parameters.\n /// @param _minimumAuthorization New minimum authorization amount\n /// @param _authorizationDecreaseDelay New authorization decrease delay in\n /// seconds\n /// @param _authorizationDecreaseChangePeriod New authorization decrease\n /// change period in seconds\n function updateAuthorizationParameters(\n uint96 _minimumAuthorization,\n uint64 _authorizationDecreaseDelay,\n uint64 _authorizationDecreaseChangePeriod\n ) external onlyGovernance {\n authorization.setMinimumAuthorization(_minimumAuthorization);\n authorization.setAuthorizationDecreaseDelay(\n _authorizationDecreaseDelay\n );\n authorization.setAuthorizationDecreaseChangePeriod(\n _authorizationDecreaseChangePeriod\n );\n\n emit AuthorizationParametersUpdated(\n _minimumAuthorization,\n _authorizationDecreaseDelay,\n _authorizationDecreaseChangePeriod\n );\n }\n\n /// @notice Updates the values of DKG parameters.\n /// @dev Can be called only by the contract guvnor, which should be the\n /// wallet registry governance contract. The caller is responsible for\n /// validating parameters.\n /// @param _seedTimeout New seed timeout.\n /// @param _resultChallengePeriodLength New DKG result challenge period\n /// length\n /// @param _resultSubmissionTimeout New DKG result submission timeout\n /// @param _submitterPrecedencePeriodLength New submitter precedence period\n /// length\n function updateDkgParameters(\n uint256 _seedTimeout,\n uint256 _resultChallengePeriodLength,\n uint256 _resultSubmissionTimeout,\n uint256 _submitterPrecedencePeriodLength\n ) external onlyGovernance {\n dkg.setSeedTimeout(_seedTimeout);\n dkg.setResultChallengePeriodLength(_resultChallengePeriodLength);\n dkg.setResultSubmissionTimeout(_resultSubmissionTimeout);\n dkg.setSubmitterPrecedencePeriodLength(\n _submitterPrecedencePeriodLength\n );\n\n // slither-disable-next-line reentrancy-events\n emit DkgParametersUpdated(\n _seedTimeout,\n _resultChallengePeriodLength,\n _resultSubmissionTimeout,\n _submitterPrecedencePeriodLength\n );\n }\n\n /// @notice Updates the values of reward parameters.\n /// @dev Can be called only by the contract guvnor, which should be the\n /// wallet registry governance contract. The caller is responsible for\n /// validating parameters.\n /// @param maliciousDkgResultNotificationRewardMultiplier New value of the\n /// DKG malicious result notification reward multiplier.\n /// @param sortitionPoolRewardsBanDuration New sortition pool rewards\n /// ban duration in seconds.\n function updateRewardParameters(\n uint256 maliciousDkgResultNotificationRewardMultiplier,\n uint256 sortitionPoolRewardsBanDuration\n ) external onlyGovernance {\n _maliciousDkgResultNotificationRewardMultiplier = maliciousDkgResultNotificationRewardMultiplier;\n _sortitionPoolRewardsBanDuration = sortitionPoolRewardsBanDuration;\n emit RewardParametersUpdated(\n maliciousDkgResultNotificationRewardMultiplier,\n sortitionPoolRewardsBanDuration\n );\n }\n\n /// @notice Updates the values of slashing parameters.\n /// @dev Can be called only by the contract guvnor, which should be the\n /// wallet registry governance contract. The caller is responsible for\n /// validating parameters.\n /// @param maliciousDkgResultSlashingAmount New malicious DKG result\n /// slashing amount\n function updateSlashingParameters(uint96 maliciousDkgResultSlashingAmount)\n external\n onlyGovernance\n {\n _maliciousDkgResultSlashingAmount = maliciousDkgResultSlashingAmount;\n emit SlashingParametersUpdated(maliciousDkgResultSlashingAmount);\n }\n\n /// @notice Updates the values of gas-related parameters.\n /// @dev Can be called only by the contract guvnor, which should be the\n /// wallet registry governance contract. The caller is responsible for\n /// validating parameters.\n /// @param dkgResultSubmissionGas New DKG result submission gas\n /// @param dkgResultApprovalGasOffset New DKG result approval gas offset\n /// @param notifyOperatorInactivityGasOffset New operator inactivity\n /// notification gas offset\n /// @param notifySeedTimeoutGasOffset New seed for DKG delivery timeout\n /// notification gas offset\n /// @param notifyDkgTimeoutNegativeGasOffset New DKG timeout notification gas\n /// offset\n function updateGasParameters(\n uint256 dkgResultSubmissionGas,\n uint256 dkgResultApprovalGasOffset,\n uint256 notifyOperatorInactivityGasOffset,\n uint256 notifySeedTimeoutGasOffset,\n uint256 notifyDkgTimeoutNegativeGasOffset\n ) external onlyGovernance {\n _dkgResultSubmissionGas = dkgResultSubmissionGas;\n _dkgResultApprovalGasOffset = dkgResultApprovalGasOffset;\n _notifyOperatorInactivityGasOffset = notifyOperatorInactivityGasOffset;\n _notifySeedTimeoutGasOffset = notifySeedTimeoutGasOffset;\n _notifyDkgTimeoutNegativeGasOffset = notifyDkgTimeoutNegativeGasOffset;\n\n emit GasParametersUpdated(\n dkgResultSubmissionGas,\n dkgResultApprovalGasOffset,\n notifyOperatorInactivityGasOffset,\n _notifySeedTimeoutGasOffset,\n _notifyDkgTimeoutNegativeGasOffset\n );\n }\n\n /// @notice Requests a new wallet creation.\n /// @dev Can be called only by the owner of wallets.\n /// It locks the DKG and request a new relay entry. It expects\n /// that the DKG process will be started once a new relay entry\n /// gets generated.\n function requestNewWallet() external onlyWalletOwner {\n dkg.lockState();\n\n randomBeacon.requestRelayEntry(this);\n }\n\n /// @notice Closes an existing wallet. Reverts if wallet with the given ID\n /// does not exist or if it has already been closed.\n /// @param walletID ID of the wallet.\n /// @dev Only a Wallet Owner can call this function.\n function closeWallet(bytes32 walletID) external onlyWalletOwner {\n wallets.deleteWallet(walletID);\n emit WalletClosed(walletID);\n }\n\n /// @notice A callback that is executed once a new relay entry gets\n /// generated. It starts the DKG process.\n /// @dev Can be called only by the random beacon contract.\n /// @param relayEntry Relay entry.\n function __beaconCallback(uint256 relayEntry, uint256) external {\n require(\n msg.sender == address(randomBeacon),\n \"Caller is not the Random Beacon\"\n );\n\n dkg.start(relayEntry);\n }\n\n /// @notice Submits result of DKG protocol.\n /// The DKG result consists of result submitting member index,\n /// calculated group public key, bytes array of misbehaved members,\n /// concatenation of signatures from group members, indices of members\n /// corresponding to each signature and the list of group members.\n /// The result is registered optimistically and waits for an approval.\n /// The result can be challenged when it is believed to be incorrect.\n /// The challenge verifies the registered result i.a. it checks if members\n /// list corresponds to the expected set of members determined\n /// by the sortition pool.\n /// @dev The message to be signed by each member is keccak256 hash of the\n /// calculated group public key, misbehaved members indices and DKG\n /// start block. The calculated hash should be prefixed with prefixed with\n /// `\\x19Ethereum signed message:\\n` before signing, so the message to\n /// sign is:\n /// `\\x19Ethereum signed message:\\n${keccak256(groupPubKey,misbehavedIndices,startBlock)}`\n /// @param dkgResult DKG result.\n function submitDkgResult(DKG.Result calldata dkgResult) external {\n dkg.submitResult(dkgResult);\n }\n\n /// @notice Approves DKG result. Can be called when the challenge period for\n /// the submitted result is finished. Considers the submitted result\n /// as valid, bans misbehaved group members from the sortition pool\n /// rewards, and completes the group creation by activating the\n /// candidate group. For the first `resultSubmissionTimeout` blocks\n /// after the end of the challenge period can be called only by the\n /// DKG result submitter. After that time, can be called by anyone.\n /// A new wallet based on the DKG result details.\n /// @param dkgResult Result to approve. Must match the submitted result\n /// stored during `submitDkgResult`.\n function approveDkgResult(DKG.Result calldata dkgResult) external {\n uint256 gasStart = gasleft();\n uint32[] memory misbehavedMembers = dkg.approveResult(dkgResult);\n\n (bytes32 walletID, bytes32 publicKeyX, bytes32 publicKeyY) = wallets\n .addWallet(dkgResult.membersHash, dkgResult.groupPubKey);\n\n emit WalletCreated(walletID, keccak256(abi.encode(dkgResult)));\n\n if (misbehavedMembers.length > 0) {\n sortitionPool.setRewardIneligibility(\n misbehavedMembers,\n // solhint-disable-next-line not-rely-on-time\n block.timestamp + _sortitionPoolRewardsBanDuration\n );\n }\n\n walletOwner.__ecdsaWalletCreatedCallback(\n walletID,\n publicKeyX,\n publicKeyY\n );\n\n dkg.complete();\n\n // Refund msg.sender's ETH for DKG result submission and result approval\n reimbursementPool.refund(\n _dkgResultSubmissionGas +\n (gasStart - gasleft()) +\n _dkgResultApprovalGasOffset,\n msg.sender\n );\n }\n\n /// @notice Notifies about seed for DKG delivery timeout. It is expected\n /// that a seed is delivered by the Random Beacon as a relay entry in a\n /// callback function.\n function notifySeedTimeout() external {\n uint256 gasStart = gasleft();\n\n dkg.notifySeedTimeout();\n\n reimbursementPool.refund(\n (gasStart - gasleft()) + _notifySeedTimeoutGasOffset,\n msg.sender\n );\n }\n\n /// @notice Notifies about DKG timeout.\n function notifyDkgTimeout() external {\n uint256 gasStart = gasleft();\n\n dkg.notifyDkgTimeout();\n\n // Note that the offset is subtracted as it is expected that the cleanup\n // performed on DKG timeout notification removes data from the storage\n // which is recovering gas for the transaction.\n reimbursementPool.refund(\n (gasStart - gasleft()) - _notifyDkgTimeoutNegativeGasOffset,\n msg.sender\n );\n }\n\n /// @notice Challenges DKG result. If the submitted result is proved to be\n /// invalid it reverts the DKG back to the result submission phase.\n /// @param dkgResult Result to challenge. Must match the submitted result\n /// stored during `submitDkgResult`.\n function challengeDkgResult(DKG.Result calldata dkgResult) external {\n (\n bytes32 maliciousDkgResultHash,\n uint32 maliciousDkgResultSubmitterId\n ) = dkg.challengeResult(dkgResult);\n\n address maliciousDkgResultSubmitterAddress = sortitionPool\n .getIDOperator(maliciousDkgResultSubmitterId);\n\n address[] memory operatorWrapper = new address[](1);\n operatorWrapper[0] = operatorToStakingProvider(\n maliciousDkgResultSubmitterAddress\n );\n\n try\n staking.seize(\n _maliciousDkgResultSlashingAmount,\n _maliciousDkgResultNotificationRewardMultiplier,\n msg.sender,\n operatorWrapper\n )\n {\n // slither-disable-next-line reentrancy-events\n emit DkgMaliciousResultSlashed(\n maliciousDkgResultHash,\n _maliciousDkgResultSlashingAmount,\n maliciousDkgResultSubmitterAddress\n );\n } catch {\n // Should never happen but we want to ensure a non-critical path\n // failure from an external contract does not stop the challenge\n // to complete.\n emit DkgMaliciousResultSlashingFailed(\n maliciousDkgResultHash,\n _maliciousDkgResultSlashingAmount,\n maliciousDkgResultSubmitterAddress\n );\n }\n }\n\n /// @notice Notifies about operators who are inactive. Using this function,\n /// a majority of the wallet signing group can decide about\n /// punishing specific group members who constantly fail doing their\n /// job. If the provided claim is proved to be valid and signed by\n /// sufficient number of group members, operators of members deemed\n /// as inactive are banned from sortition pool rewards for the\n /// duration specified by `sortitionPoolRewardsBanDuration` parameter.\n /// The function allows to signal about single operators being\n /// inactive as well as to signal wallet-wide heartbeat failures\n /// that are propagated to the wallet owner who should begin the\n /// procedure of moving responsibilities to another wallet given\n /// that the wallet who failed the heartbeat may soon be not able to\n /// function and provide new signatures.\n /// The sender of the claim must be one of the claim signers. This\n /// function can be called only for registered wallets\n /// @param claim Operator inactivity claim\n /// @param nonce Current inactivity claim nonce for the given wallet signing\n /// group. Must be the same as the stored one\n /// @param groupMembers Identifiers of the wallet signing group members\n function notifyOperatorInactivity(\n Inactivity.Claim calldata claim,\n uint256 nonce,\n uint32[] calldata groupMembers\n ) external {\n uint256 gasStart = gasleft();\n\n bytes32 walletID = claim.walletID;\n\n require(nonce == inactivityClaimNonce[walletID], \"Invalid nonce\");\n\n (bytes32 pubKeyX, bytes32 pubKeyY) = wallets\n .getWalletPublicKeyCoordinates(walletID);\n bytes32 memberIdsHash = wallets.getWalletMembersIdsHash(walletID);\n\n require(\n memberIdsHash == keccak256(abi.encode(groupMembers)),\n \"Invalid group members\"\n );\n\n uint32[] memory ineligibleOperators = Inactivity.verifyClaim(\n sortitionPool,\n claim,\n bytes.concat(pubKeyX, pubKeyY),\n nonce,\n groupMembers\n );\n\n inactivityClaimNonce[walletID]++;\n\n emit InactivityClaimed(walletID, nonce, msg.sender);\n\n sortitionPool.setRewardIneligibility(\n ineligibleOperators,\n // solhint-disable-next-line not-rely-on-time\n block.timestamp + _sortitionPoolRewardsBanDuration\n );\n\n if (claim.heartbeatFailed) {\n walletOwner.__ecdsaWalletHeartbeatFailedCallback(\n walletID,\n pubKeyX,\n pubKeyY\n );\n }\n\n reimbursementPool.refund(\n (gasStart - gasleft()) + _notifyOperatorInactivityGasOffset,\n msg.sender\n );\n }\n\n /// @notice Allows the wallet owner to add all signing group members of the\n /// wallet with the given ID to the slashing queue of the staking .\n /// contract. The notifier will receive reward per each group member\n /// from the staking contract notifiers treasury. The reward is\n /// scaled by the `rewardMultiplier` provided as a parameter.\n /// @param amount Amount of tokens to seize from each signing group member\n /// @param rewardMultiplier Fraction of the staking contract notifiers\n /// reward the notifier should receive; should be between [0, 100]\n /// @param notifier Address of the misbehavior notifier\n /// @param walletID ID of the wallet\n /// @param walletMembersIDs Identifiers of the wallet signing group members\n /// @dev Requirements:\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events.\n /// - `rewardMultiplier` must be between [0, 100].\n /// - This function does revert if staking contract call reverts.\n /// The calling code needs to handle the potential revert.\n function seize(\n uint96 amount,\n uint256 rewardMultiplier,\n address notifier,\n bytes32 walletID,\n uint32[] calldata walletMembersIDs\n ) external onlyWalletOwner {\n bytes32 memberIdsHash = wallets.getWalletMembersIdsHash(walletID);\n require(\n memberIdsHash == keccak256(abi.encode(walletMembersIDs)),\n \"Invalid wallet members identifiers\"\n );\n\n address[] memory groupMembersAddresses = sortitionPool.getIDOperators(\n walletMembersIDs\n );\n address[] memory stakingProvidersAddresses = new address[](\n walletMembersIDs.length\n );\n for (uint256 i = 0; i < groupMembersAddresses.length; i++) {\n stakingProvidersAddresses[i] = operatorToStakingProvider(\n groupMembersAddresses[i]\n );\n }\n\n staking.seize(\n amount,\n rewardMultiplier,\n notifier,\n stakingProvidersAddresses\n );\n }\n\n /// @notice Checks if DKG result is valid for the current DKG.\n /// @param result DKG result.\n /// @return True if the result is valid. If the result is invalid it returns\n /// false and an error message.\n function isDkgResultValid(DKG.Result calldata result)\n external\n view\n returns (bool, string memory)\n {\n return dkg.isResultValid(result);\n }\n\n /// @notice Check current wallet creation state.\n function getWalletCreationState() external view returns (DKG.State) {\n return dkg.currentState();\n }\n\n /// @notice Checks whether the given operator is a member of the given\n /// wallet signing group.\n /// @param walletID ID of the wallet\n /// @param walletMembersIDs Identifiers of the wallet signing group members\n /// @param operator Address of the checked operator\n /// @param walletMemberIndex Position of the operator in the wallet signing\n /// group members list\n /// @return True - if the operator is a member of the given wallet signing\n /// group. False - otherwise.\n /// @dev Requirements:\n /// - The `operator` parameter must be an actual sortition pool operator.\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events.\n /// - The `walletMemberIndex` must be in range [1, walletMembersIDs.length]\n function isWalletMember(\n bytes32 walletID,\n uint32[] calldata walletMembersIDs,\n address operator,\n uint256 walletMemberIndex\n ) external view returns (bool) {\n uint32 operatorID = sortitionPool.getOperatorID(operator);\n\n require(operatorID != 0, \"Not a sortition pool operator\");\n\n bytes32 memberIdsHash = wallets.getWalletMembersIdsHash(walletID);\n\n require(\n memberIdsHash == keccak256(abi.encode(walletMembersIDs)),\n \"Invalid wallet members identifiers\"\n );\n\n require(\n 1 <= walletMemberIndex &&\n walletMemberIndex <= walletMembersIDs.length,\n \"Wallet member index is out of range\"\n );\n\n return walletMembersIDs[walletMemberIndex - 1] == operatorID;\n }\n\n /// @notice Checks if awaiting seed timed out.\n /// @return True if awaiting seed timed out, false otherwise.\n function hasSeedTimedOut() external view returns (bool) {\n return dkg.hasSeedTimedOut();\n }\n\n /// @notice Checks if DKG timed out. The DKG timeout period includes time required\n /// for off-chain protocol execution and time for the result publication\n /// for all group members. After this time result cannot be submitted\n /// and DKG can be notified about the timeout.\n /// @return True if DKG timed out, false otherwise.\n function hasDkgTimedOut() external view returns (bool) {\n return dkg.hasDkgTimedOut();\n }\n\n function getWallet(bytes32 walletID)\n external\n view\n returns (Wallets.Wallet memory)\n {\n return wallets.registry[walletID];\n }\n\n /// @notice Gets public key of a wallet with a given wallet ID.\n /// The public key is returned in an uncompressed format as a 64-byte\n /// concatenation of X and Y coordinates.\n /// @param walletID ID of the wallet.\n /// @return Uncompressed public key of the wallet.\n function getWalletPublicKey(bytes32 walletID)\n external\n view\n returns (bytes memory)\n {\n return wallets.getWalletPublicKey(walletID);\n }\n\n /// @notice Checks if a wallet with the given ID is registered.\n /// @param walletID Wallet's ID.\n /// @return True if wallet is registered, false otherwise.\n function isWalletRegistered(bytes32 walletID) external view returns (bool) {\n return wallets.isWalletRegistered(walletID);\n }\n\n /// @notice The minimum authorization amount required so that operator can\n /// participate in ECDSA Wallet operations.\n function minimumAuthorization() external view returns (uint96) {\n return authorization.parameters.minimumAuthorization;\n }\n\n /// @notice Returns the current value of the staking provider's eligible\n /// stake. Eligible stake is defined as the currently authorized\n /// stake minus the pending authorization decrease. Eligible stake\n /// is what is used for operator's weight in the sortition pool.\n /// If the authorized stake minus the pending authorization decrease\n /// is below the minimum authorization, eligible stake is 0.\n function eligibleStake(address stakingProvider)\n external\n view\n returns (uint96)\n {\n return authorization.eligibleStake(staking, stakingProvider);\n }\n\n /// @notice Returns the amount of rewards available for withdrawal for the\n /// given staking provider. Reverts if staking provider has not\n /// registered the operator address.\n function availableRewards(address stakingProvider)\n external\n view\n returns (uint96)\n {\n address operator = stakingProviderToOperator(stakingProvider);\n require(operator != address(0), \"Unknown operator\");\n return sortitionPool.getAvailableRewards(operator);\n }\n\n /// @notice Returns the amount of stake that is pending authorization\n /// decrease for the given staking provider. If no authorization\n /// decrease has been requested, returns zero.\n function pendingAuthorizationDecrease(address stakingProvider)\n external\n view\n returns (uint96)\n {\n return authorization.pendingAuthorizationDecrease(stakingProvider);\n }\n\n /// @notice Returns the remaining time in seconds that needs to pass before\n /// the requested authorization decrease can be approved.\n /// If the sortition pool state was not updated yet by the operator\n /// after requesting the authorization decrease, returns\n /// `type(uint64).max`.\n function remainingAuthorizationDecreaseDelay(address stakingProvider)\n external\n view\n returns (uint64)\n {\n return\n authorization.remainingAuthorizationDecreaseDelay(stakingProvider);\n }\n\n /// @notice Returns operator registered for the given staking provider.\n function stakingProviderToOperator(address stakingProvider)\n public\n view\n returns (address)\n {\n return authorization.stakingProviderToOperator[stakingProvider];\n }\n\n /// @notice Returns staking provider of the given operator.\n function operatorToStakingProvider(address operator)\n public\n view\n returns (address)\n {\n return authorization.operatorToStakingProvider[operator];\n }\n\n /// @notice Checks if the operator's authorized stake is in sync with\n /// operator's weight in the sortition pool.\n /// If the operator is not in the sortition pool and their\n /// authorized stake is non-zero, function returns false.\n function isOperatorUpToDate(address operator) external view returns (bool) {\n return\n authorization.isOperatorUpToDate(staking, sortitionPool, operator);\n }\n\n /// @notice Returns true if the given operator is in the sortition pool.\n /// Otherwise, returns false.\n function isOperatorInPool(address operator) external view returns (bool) {\n return sortitionPool.isOperatorInPool(operator);\n }\n\n /// @notice Selects a new group of operators. Can only be called when DKG\n /// is in progress and the pool is locked.\n /// At least one operator has to be registered in the pool,\n /// otherwise the function fails reverting the transaction.\n /// @return IDs of selected group members.\n function selectGroup() external view returns (uint32[] memory) {\n return sortitionPool.selectGroup(DKG.groupSize, bytes32(dkg.seed));\n }\n\n /// @notice Retrieves dkg parameters that were set in DKG library.\n function dkgParameters() external view returns (DKG.Parameters memory) {\n return dkg.parameters;\n }\n\n /// @notice Returns authorization-related parameters.\n /// @dev The minimum authorization is also returned by `minimumAuthorization()`\n /// function, as a requirement of `IApplication` interface.\n /// @return minimumAuthorization The minimum authorization amount required\n /// so that operator can participate in the random beacon. This\n /// amount is required to execute slashing for providing a malicious\n /// DKG result or when a relay entry times out.\n /// @return authorizationDecreaseDelay Delay in seconds that needs to pass\n /// between the time authorization decrease is requested and the\n /// time that request gets approved. Protects against free-riders\n /// earning rewards and not being active in the network.\n /// @return authorizationDecreaseChangePeriod Authorization decrease change\n /// period in seconds. It is the time, before authorization decrease\n /// delay end, during which the pending authorization decrease\n /// request can be overwritten.\n /// If set to 0, pending authorization decrease request can not be\n /// overwritten until the endire `authorizationDecreaseDelay` ends.\n /// If set to value equal `authorizationDecreaseDelay`, request can\n /// always be overwritten.\n function authorizationParameters()\n external\n view\n returns (\n uint96 minimumAuthorization,\n uint64 authorizationDecreaseDelay,\n uint64 authorizationDecreaseChangePeriod\n )\n {\n return (\n authorization.parameters.minimumAuthorization,\n authorization.parameters.authorizationDecreaseDelay,\n authorization.parameters.authorizationDecreaseChangePeriod\n );\n }\n\n /// @notice Retrieves reward-related parameters.\n /// @return maliciousDkgResultNotificationRewardMultiplier Percentage of the\n /// staking contract malicious behavior notification reward which\n /// will be transferred to the notifier reporting about a malicious\n /// DKG result. Notifiers are rewarded from a notifiers treasury\n /// pool. For example, if notification reward is 1000 and the value\n /// of the multiplier is 5, the notifier will receive:\n /// 5% of 1000 = 50 per each operator affected.\n /// @return sortitionPoolRewardsBanDuration Duration of the sortition pool\n /// rewards ban imposed on operators who missed their turn for DKG\n /// result submission or who failed a heartbeat.\n function rewardParameters()\n external\n view\n returns (\n uint256 maliciousDkgResultNotificationRewardMultiplier,\n uint256 sortitionPoolRewardsBanDuration\n )\n {\n return (\n _maliciousDkgResultNotificationRewardMultiplier,\n _sortitionPoolRewardsBanDuration\n );\n }\n\n /// @notice Retrieves slashing-related parameters.\n /// @return maliciousDkgResultSlashingAmount Slashing amount for submitting\n /// a malicious DKG result. Every DKG result submitted can be\n /// challenged for the time of `dkg.resultChallengePeriodLength`.\n /// If the DKG result submitted is challenged and proven to be\n /// malicious, the operator who submitted the malicious result is\n /// slashed for `_maliciousDkgResultSlashingAmount`.\n function slashingParameters()\n external\n view\n returns (uint96 maliciousDkgResultSlashingAmount)\n {\n return _maliciousDkgResultSlashingAmount;\n }\n\n /// @notice Retrieves gas-related parameters.\n /// @return dkgResultSubmissionGas Calculated max gas cost for submitting\n /// a DKG result. This will be refunded as part of the DKG approval\n /// process. It is in the submitter's interest to not skip his\n /// priority turn on the approval, otherwise the refund of the DKG\n /// submission will be refunded to another group member that will\n /// call the DKG approve function.\n /// @return dkgResultApprovalGasOffset Gas that is meant to balance the DKG\n /// result approval's overall cost. It can be updated by the\n /// governace based on the current market conditions.\n /// @return notifyOperatorInactivityGasOffset Gas that is meant to balance\n /// the notification of an operator inactivity. It can be updated by\n /// the governance based on the current market conditions.\n /// @return notifySeedTimeoutGasOffset Gas that is meant to balance the\n /// notification of a seed for DKG delivery timeout. It can be updated\n /// by the governance based on the current market conditions.\n /// @return notifyDkgTimeoutNegativeGasOffset Gas that is meant to balance\n /// the notification of a DKG protocol execution timeout. It can be\n /// updated by the governance based on the current market conditions.\n function gasParameters()\n external\n view\n returns (\n uint256 dkgResultSubmissionGas,\n uint256 dkgResultApprovalGasOffset,\n uint256 notifyOperatorInactivityGasOffset,\n uint256 notifySeedTimeoutGasOffset,\n uint256 notifyDkgTimeoutNegativeGasOffset\n )\n {\n return (\n _dkgResultSubmissionGas,\n _dkgResultApprovalGasOffset,\n _notifyOperatorInactivityGasOffset,\n _notifySeedTimeoutGasOffset,\n _notifyDkgTimeoutNegativeGasOffset\n );\n }\n}\n"
234
273
  },
235
274
  "contracts/test/TestERC721.sol": {
236
275
  "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.9;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\n\ncontract TestERC721 is ERC721 {\n string public constant NAME = \"Test ERC721 Token\";\n string public constant SYMBOL = \"TT\";\n\n constructor() ERC721(NAME, SYMBOL) {}\n\n function mint(address to, uint256 tokenId) public {\n _mint(to, tokenId);\n }\n}\n"
237
276
  },
238
277
  "contracts/vault/DonationVault.sol": {
239
- "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport \"./IVault.sol\";\nimport \"../bank/Bank.sol\";\n\n/// @title BTC donation vault\n/// @notice Vault that allows making BTC donations to the system. Upon deposit,\n/// this vault does not increase depositors' balances and always\n/// decreases its own balance in the same transaction. The vault also\n/// allows making donations using existing Bank balances.\n///\n/// BEWARE: ALL BTC DEPOSITS TARGETING THIS VAULT ARE NOT REDEEMABLE\n/// AND THERE IS NO WAY TO RESTORE THE DONATED BALANCE.\n/// USE THIS VAULT ONLY WHEN YOU REALLY KNOW WHAT YOU ARE DOING!\ncontract DonationVault is IVault {\n Bank public bank;\n\n event DonationReceived(address donor, uint256 donatedAmount);\n\n modifier onlyBank() {\n require(msg.sender == address(bank), \"Caller is not the Bank\");\n _;\n }\n\n constructor(Bank _bank) {\n require(\n address(_bank) != address(0),\n \"Bank can not be the zero address\"\n );\n\n bank = _bank;\n }\n\n /// @notice Transfers the given `amount` of the Bank balance from the\n /// caller to the Donation Vault and immediately decreases the\n /// vault's balance in the Bank by the transferred `amount`.\n /// @param amount Amount of the Bank balance to donate.\n /// @dev Requirements:\n /// - The caller's balance in the Bank must be greater than or equal\n /// to the `amount`,\n /// - Donation Vault must have an allowance for caller's balance in\n /// the Bank for at least `amount`.\n function donate(uint256 amount) external {\n address donor = msg.sender;\n\n require(\n bank.balanceOf(donor) >= amount,\n \"Amount exceeds balance in the bank\"\n );\n\n emit DonationReceived(donor, amount);\n\n bank.transferBalanceFrom(donor, address(this), amount);\n bank.decreaseBalance(amount);\n }\n\n /// @notice Transfers the given `amount` of the Bank balance from the\n /// `owner` to the Donation Vault and immediately decreases the\n /// vault's balance in the Bank by the transferred `amount`.\n /// @param owner Address of the Bank balance owner who approved their\n /// balance to be used by the vault.\n /// @param amount The amount of the Bank balance approved by the owner\n /// to be used by the vault.\n /// @dev Requirements:\n /// - Can only be called by the Bank via `approveBalanceAndCall`,\n /// - The `owner` balance in the Bank must be greater than or equal\n /// to the `amount`.\n function receiveBalanceApproval(address owner, uint256 amount)\n external\n override\n onlyBank\n {\n require(\n bank.balanceOf(owner) >= amount,\n \"Amount exceeds balance in the bank\"\n );\n\n emit DonationReceived(owner, amount);\n\n bank.transferBalanceFrom(owner, address(this), amount);\n bank.decreaseBalance(amount);\n }\n\n /// @notice Ignores the deposited amounts and does not increase depositors'\n /// individual balances. The vault decreases its own tBTC balance\n /// in the Bank by the total deposited amount.\n /// @param depositors Addresses of depositors whose deposits have been swept.\n /// @param depositedAmounts Amounts deposited by individual depositors and\n /// swept.\n /// @dev Requirements:\n /// - Can only be called by the Bank after the Bridge swept deposits\n /// and Bank increased balance for the vault,\n /// - The `depositors` array must not be empty,\n /// - The `depositors` array length must be equal to the\n /// `depositedAmounts` array length.\n function receiveBalanceIncrease(\n address[] calldata depositors,\n uint256[] calldata depositedAmounts\n ) external override onlyBank {\n require(depositors.length != 0, \"No depositors specified\");\n\n uint256 totalAmount = 0;\n for (uint256 i = 0; i < depositors.length; i++) {\n totalAmount += depositedAmounts[i];\n emit DonationReceived(depositors[i], depositedAmounts[i]);\n }\n\n bank.decreaseBalance(totalAmount);\n }\n}\n"
278
+ "content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport \"./IVault.sol\";\nimport \"../bank/Bank.sol\";\n\n/// @title BTC donation vault\n/// @notice Vault that allows making BTC donations to the system. Upon deposit,\n/// this vault does not increase depositors' balances and always\n/// decreases its own balance in the same transaction. The vault also\n/// allows making donations using existing Bank balances.\n///\n/// BEWARE: ALL BTC DEPOSITS TARGETING THIS VAULT ARE NOT REDEEMABLE\n/// AND THERE IS NO WAY TO RESTORE THE DONATED BALANCE.\n/// USE THIS VAULT ONLY WHEN YOU REALLY KNOW WHAT YOU ARE DOING!\ncontract DonationVault is IVault {\n Bank public bank;\n\n event DonationReceived(address donor, uint256 donatedAmount);\n\n modifier onlyBank() {\n require(msg.sender == address(bank), \"Caller is not the Bank\");\n _;\n }\n\n constructor(Bank _bank) {\n require(\n address(_bank) != address(0),\n \"Bank can not be the zero address\"\n );\n\n bank = _bank;\n }\n\n /// @notice Transfers the given `amount` of the Bank balance from the\n /// caller to the Donation Vault and immediately decreases the\n /// vault's balance in the Bank by the transferred `amount`.\n /// @param amount Amount of the Bank balance to donate.\n /// @dev Requirements:\n /// - The caller's balance in the Bank must be greater than or equal\n /// to the `amount`,\n /// - Donation Vault must have an allowance for caller's balance in\n /// the Bank for at least `amount`.\n function donate(uint256 amount) external {\n address donor = msg.sender;\n\n require(\n bank.balanceOf(donor) >= amount,\n \"Amount exceeds balance in the bank\"\n );\n\n emit DonationReceived(donor, amount);\n\n bank.transferBalanceFrom(donor, address(this), amount);\n bank.decreaseBalance(amount);\n }\n\n /// @notice Transfers the given `amount` of the Bank balance from the\n /// `owner` to the Donation Vault and immediately decreases the\n /// vault's balance in the Bank by the transferred `amount`.\n /// @param owner Address of the Bank balance owner who approved their\n /// balance to be used by the vault.\n /// @param amount The amount of the Bank balance approved by the owner\n /// to be used by the vault.\n /// @dev Requirements:\n /// - Can only be called by the Bank via `approveBalanceAndCall`,\n /// - The `owner` balance in the Bank must be greater than or equal\n /// to the `amount`.\n function receiveBalanceApproval(\n address owner,\n uint256 amount,\n bytes memory\n ) external override onlyBank {\n require(\n bank.balanceOf(owner) >= amount,\n \"Amount exceeds balance in the bank\"\n );\n\n emit DonationReceived(owner, amount);\n\n bank.transferBalanceFrom(owner, address(this), amount);\n bank.decreaseBalance(amount);\n }\n\n /// @notice Ignores the deposited amounts and does not increase depositors'\n /// individual balances. The vault decreases its own tBTC balance\n /// in the Bank by the total deposited amount.\n /// @param depositors Addresses of depositors whose deposits have been swept.\n /// @param depositedAmounts Amounts deposited by individual depositors and\n /// swept.\n /// @dev Requirements:\n /// - Can only be called by the Bank after the Bridge swept deposits\n /// and Bank increased balance for the vault,\n /// - The `depositors` array must not be empty,\n /// - The `depositors` array length must be equal to the\n /// `depositedAmounts` array length.\n function receiveBalanceIncrease(\n address[] calldata depositors,\n uint256[] calldata depositedAmounts\n ) external override onlyBank {\n require(depositors.length != 0, \"No depositors specified\");\n\n uint256 totalAmount = 0;\n for (uint256 i = 0; i < depositors.length; i++) {\n totalAmount += depositedAmounts[i];\n emit DonationReceived(depositors[i], depositedAmounts[i]);\n }\n\n bank.decreaseBalance(totalAmount);\n }\n}\n"
240
279
  },
241
280
  "contracts/test/BankStub.sol": {
242
281
  "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.9;\n\nimport \"../bank/Bank.sol\";\n\ncontract BankStub is Bank {\n function setBalance(address addr, uint256 amount) external {\n balanceOf[addr] = amount;\n }\n}\n"