Verified contractExactGPL-3.0-only
L1BTCRedeemerWormhole
Address0x2f354daea4fd3365cda88a79e48248bf14c494ca
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.17
- Same code
1 more contract
Details
- Compiler
- solc 0.8.17+commit.8df45f5f
- Language
- solidity
- Optimization
- Yes, 1,000 runs
- License
- GPL-3.0-only
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 23,302,127
- Creation transaction
- 0x5a84665ac1…feabdc91a3
24 files
- contracts/cross-chain/wormhole/L1BTCRedeemerWormhole.solmain12.74 KB
- @keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol38.87 KB
- @keep-network/bitcoin-spv-sol/contracts/BytesLib.sol19.11 KB
- @keep-network/bitcoin-spv-sol/contracts/SafeMath.sol2.69 KB
- @keep-network/bitcoin-spv-sol/contracts/ValidateSPV.sol5.75 KB
- @keep-network/random-beacon/contracts/Reimbursable.sol3.02 KB
- @keep-network/random-beacon/contracts/ReimbursementPool.sol7.34 KB
- @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol3.15 KB
- @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol6.63 KB
- @openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol3.38 KB
- @openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol2.78 KB
- @openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-IERC20PermitUpgradeable.sol2.26 KB
- @openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol4.59 KB
- @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol8.28 KB
- @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol1.35 KB
- @openzeppelin/contracts/access/Ownable.sol2.62 KB
- @openzeppelin/contracts/security/ReentrancyGuard.sol2.84 KB
- @openzeppelin/contracts/utils/Context.sol844 B
- contracts/cross-chain/wormhole/Wormhole.sol6.72 KB
- contracts/integrator/AbstractBTCRedeemer.sol12.52 KB
- contracts/integrator/BitcoinTx.sol2 KB
- contracts/integrator/IBank.sol2.46 KB
- contracts/integrator/IBridge.sol4.2 KB
- contracts/integrator/ITBTCVault.sol1.64 KB
contracts/cross-chain/wormhole/L1BTCRedeemerWormhole.sol
// SPDX-License-Identifier: GPL-3.0-only
// ██████████████ ▐████▌ ██████████████
// ██████████████ ▐████▌ ██████████████
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ██████████████ ▐████▌ ██████████████
// ██████████████ ▐████▌ ██████████████
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
pragma solidity 0.8.17;
import "@keep-network/random-beacon/contracts/Reimbursable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "./Wormhole.sol";
import "../../integrator/AbstractBTCRedeemer.sol";
/// @title L1BTCRedeemerWormhole
/// @notice This contract is part of the direct bridging mechanism allowing
/// users to redeem ERC20 tBTC from a supported chain (L2) back to
/// Bitcoin, without the need to interact directly with the L1 tBTC
/// ledger chain where the redemption is processed.
///
/// `L1BTCRedeemerWormhole` is deployed on the L1 chain and interacts with
/// its destination chain counterpart (e.g., `L2BTCRedeemer` on an L2 chain).
/// Each `L1BTCRedeemerWormhole` & `L2BTCRedeemer` (or equivalent)
/// pair is responsible for a specific L2 chain.
///
/// The outline of the direct redemption mechanism is as follows:
/// 1. An L2 user initiates a redemption request on the L2 chain, specifying
/// the amount of tBTC to redeem and their Bitcoin destination address.
/// 2. The L2 contract sends this request (via a cross-chain message via Wormhole VAA)
/// to the `L1BTCRedeemerWormhole` on L1.
/// 3. The `L1BTCRedeemerWormhole` receives the tBTC from the L2 (via the token bridge)
/// and then calls the tBTC `Bridge` contract on L1 to request the redemption,
/// providing the user's Bitcoin address.
/// 4. The tBTC `Bridge` handles the redemption process, and the user eventually
/// receives Bitcoin in their specified address.
/// 5. Relayers (or other authorized entities) might be involved in facilitating
/// the cross-chain communication and L1 transaction submissions, potentially
/// eligible for gas reimbursement.
contract L1BTCRedeemerWormhole is
AbstractBTCRedeemer,
Reimbursable,
ReentrancyGuardUpgradeable
{
// Custom errors
error CallerNotOwner();
error SourceAddressNotAuthorized();
error WormholeTokenBridgeAlreadySet();
/// @notice Reference to the Wormhole Token Bridge contract.
IWormholeTokenBridge public wormholeTokenBridge;
/// @notice Gas that is meant to balance the overall cost of processing a redemption request via L1.
/// Can be updated by the owner based on the current market conditions.
uint256 public requestRedemptionGasOffset;
/// @notice Set of addresses that are authorized to receive gas reimbursements
/// for relaying redemption requests. The authorization is
/// granted by the contract owner.
mapping(address => bool) public reimbursementAuthorizations;
/// @notice Maps sender addresses to their authorization status. Only messages
/// from authorized senders will be accepted. The addresses are stored
/// in Wormhole format (bytes32).
mapping(bytes32 => bool) public allowedSenders;
event RedemptionRequested(
uint256 indexed redemptionKey,
bytes20 indexed walletPubKeyHash,
BitcoinTx.UTXO mainUtxo,
bytes indexed redemptionOutputScript,
uint256 amount
);
event GasOffsetParametersUpdated(uint256 requestRedemptionGasOffset);
event ReimbursementAuthorizationUpdated(
address indexed _address,
bool authorization
);
event AllowedSenderUpdated(bytes32 indexed sender, bool allowed);
/// @dev This modifier comes from the `Reimbursable` base contract and
/// must be overridden to protect the `updateReimbursementPool` call.
modifier onlyReimbursableAdmin() override {
if (msg.sender != owner()) revert CallerNotOwner();
_;
}
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
function initialize(
address _thresholdBridge,
address _wormholeTokenBridge,
address _tbtcToken,
address _bank,
address _tbtcVault
) external initializer {
__AbstractBTCRedeemer_initialize(
_thresholdBridge,
_tbtcToken,
_bank,
_tbtcVault
);
__Ownable_init();
if (address(wormholeTokenBridge) != address(0)) {
revert WormholeTokenBridgeAlreadySet();
}
if (_wormholeTokenBridge == address(0)) {
revert ZeroAddress();
}
wormholeTokenBridge = IWormholeTokenBridge(_wormholeTokenBridge);
requestRedemptionGasOffset = 60_000;
}
/// @notice Updates the values of gas offset parameters for redemption processing.
/// @dev Can be called only by the contract owner. The caller is responsible
/// for validating parameters.
/// @param _requestRedemptionGasOffset New redemption gas offset.
function updateGasOffsetParameters(uint256 _requestRedemptionGasOffset)
external
onlyOwner
{
requestRedemptionGasOffset = _requestRedemptionGasOffset;
emit GasOffsetParametersUpdated(_requestRedemptionGasOffset);
}
/// @notice Updates the reimbursement authorization for the given address.
/// @param _address Address to update the authorization for.
/// @param authorization New authorization status.
/// @dev Requirements:
/// - Can be called only by the contract owner.
function updateReimbursementAuthorization(
address _address,
bool authorization
) external onlyOwner {
emit ReimbursementAuthorizationUpdated(_address, authorization);
reimbursementAuthorizations[_address] = authorization;
}
/// @notice Updates the allowed sender status for a given Wormhole sender address.
/// @param _sender The Wormhole sender address (in bytes32 format).
/// @param _allowed New allowed status.
/// @dev Requirements:
/// - Can be called only by the contract owner.
function updateAllowedSender(bytes32 _sender, bool _allowed)
external
onlyOwner
{
allowedSenders[_sender] = _allowed;
emit AllowedSenderUpdated(_sender, _allowed);
}
/// @notice Initiates a redemption on L1 using tBTC received from another chain (e.g., L2)
/// via a Wormhole VAA. The tBTC is then used to request a Bitcoin redemption
/// from the main tBTC Bridge.
/// @param walletPubKeyHash The 20-byte wallet public key hash of the tBTC wallet
/// that will process this redemption on the Bitcoin network.
/// This needs to be chosen carefully, usually an active wallet provided by the system.
/// @param mainUtxo The main UTXO of the `walletPubKeyHash`. This information is critical
/// for the Bridge to identify the correct wallet and its state.
/// @param encodedVm A byte array containing a Wormhole VAA. This VAA should represent
/// a transfer of tBTC from an L2 (or other chain) to this L1 contract address,
/// with the payload containing the user's destination Bitcoin output script.
/// @dev Requirements:
/// - The Wormhole VAA must be valid and correctly transfer tBTC to this contract.
/// - The VAA must originate from an allowed sender address.
/// - The payload of the VAA must be the user's Bitcoin `redemptionOutputScript`.
/// - `walletPubKeyHash` and `mainUtxo` must correspond to a live, funded tBTC wallet.
/// - All requirements of tBTC `Bridge.requestRedemption` must be met.
/// - Callers (typically relayers) might be eligible for gas reimbursement if authorized
/// and the reimbursement pool is funded.
///
/// The Wormhole Token Bridge contract has protection against redeeming
/// the same VAA again. When a Token Bridge VAA is redeemed, its
/// message body hash is stored in a map. This map is used to check
/// whether the hash has already been set in this map. For this reason,
/// this function does not have to be nonReentrant in theory. However,
/// to make this function non-dependent on Wormhole Bridge implementation,
/// we are making it nonReentrant anyway.
function requestRedemption(
bytes20 walletPubKeyHash,
BitcoinTx.UTXO calldata mainUtxo,
bytes calldata encodedVm
) external nonReentrant {
uint256 gasStart = gasleft();
// WormholeTokenBridge.completeTransferWithPayload completes a contract-controlled
// transfer of an ERC20 token. Calling this function is not enough to
// ensure L2WormholeGateway received Wormhole tBTC representation.
// Instead of going too deep into the WormholeTokenBridge implementation,
// asserting who is the receiver of the token, and which token it is,
// we check the balance before the WormholeTokenBridge call and the balance
// after ITokenBridge call. This way, we are sure this contract received
// Wormhole tBTC token in the given amount. This is transparent to
// all potential upgrades of ITokenBridge implementation and no other
// validations are needed.
uint256 balanceBefore = tbtcToken.balanceOf(address(this));
bytes memory encoded = wormholeTokenBridge.completeTransferWithPayload(
encodedVm
);
uint256 balanceAfter = tbtcToken.balanceOf(address(this));
uint256 amount = balanceAfter - balanceBefore;
// Parse the full transfer data to validate the source
IWormholeTokenBridge.TransferWithPayload
memory transfer = wormholeTokenBridge.parseTransferWithPayload(
encoded
);
// Validate that the message came from an authorized sender
bytes32 sender = transfer.fromAddress;
if (!allowedSenders[sender]) revert SourceAddressNotAuthorized();
bytes memory redemptionOutputScript = transfer.payload;
// Input parameters do not have to be validated in any way.
// The tBTC Bridge is responsible for validating whether the provided
// redemption data is correct.
(uint256 redemptionKey, ) = _requestRedemption(
walletPubKeyHash,
mainUtxo,
redemptionOutputScript,
amount
);
// The function is non-reentrant.
// slither-disable-next-line reentrancy-events
emit RedemptionRequested(
redemptionKey,
walletPubKeyHash,
mainUtxo,
redemptionOutputScript,
amount
);
// Record a deferred gas reimbursement if the reimbursement pool is
// attached and the caller is authorized to receive reimbursements.
// `ReimbursementPool` calls the untrusted receiver address using a
// low-level call. Reentrancy risk is mitigated by making sure that
// `ReimbursementPool.refund` is a non-reentrant function and executing
// reimbursements as part of this redemption processing step.
if (
address(reimbursementPool) != address(0) &&
reimbursementAuthorizations[msg.sender]
) {
reimbursementPool.refund(
(gasStart - gasleft()) + requestRedemptionGasOffset,
msg.sender
);
}
}
}
@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol
pragma solidity ^0.8.4;
/** @title BitcoinSPV */
/** @author Summa (https://summa.one) */
import {BytesLib} from "./BytesLib.sol";
import {SafeMath} from "./SafeMath.sol";
library BTCUtils {
using BytesLib for bytes;
using SafeMath for uint256;
// The target at minimum Difficulty. Also the target of the genesis block
uint256 public constant DIFF1_TARGET = 0xffff0000000000000000000000000000000000000000000000000000;
uint256 public constant RETARGET_PERIOD = 2 * 7 * 24 * 60 * 60; // 2 weeks in seconds
uint256 public constant RETARGET_PERIOD_BLOCKS = 2016; // 2 weeks in blocks
uint256 public constant ERR_BAD_ARG = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
/* ***** */
/* UTILS */
/* ***** */
/// @notice Determines the length of a VarInt in bytes
/// @dev A VarInt of >1 byte is prefixed with a flag indicating its length
/// @param _flag The first byte of a VarInt
/// @return The number of non-flag bytes in the VarInt
function determineVarIntDataLength(bytes memory _flag) internal pure returns (uint8) {
return determineVarIntDataLengthAt(_flag, 0);
}
/// @notice Determines the length of a VarInt in bytes
/// @dev A VarInt of >1 byte is prefixed with a flag indicating its length
/// @param _b The byte array containing a VarInt
/// @param _at The position of the VarInt in the array
/// @return The number of non-flag bytes in the VarInt
function determineVarIntDataLengthAt(bytes memory _b, uint256 _at) internal pure returns (uint8) {
if (uint8(_b[_at]) == 0xff) {
return 8; // one-byte flag, 8 bytes data
}
if (uint8(_b[_at]) == 0xfe) {
return 4; // one-byte flag, 4 bytes data
}
if (uint8(_b[_at]) == 0xfd) {
return 2; // one-byte flag, 2 bytes data
}
return 0; // flag is data
}
/// @notice Parse a VarInt into its data length and the number it represents
/// @dev Useful for Parsing Vins and Vouts. Returns ERR_BAD_ARG if insufficient bytes.
/// Caller SHOULD explicitly handle this case (or bubble it up)
/// @param _b A byte-string starting with a VarInt
/// @return number of bytes in the encoding (not counting the tag), the encoded int
function parseVarInt(bytes memory _b) internal pure returns (uint256, uint256) {
return parseVarIntAt(_b, 0);
}
/// @notice Parse a VarInt into its data length and the number it represents
/// @dev Useful for Parsing Vins and Vouts. Returns ERR_BAD_ARG if insufficient bytes.
/// Caller SHOULD explicitly handle this case (or bubble it up)
/// @param _b A byte-string containing a VarInt
/// @param _at The position of the VarInt
/// @return number of bytes in the encoding (not counting the tag), the encoded int
function parseVarIntAt(bytes memory _b, uint256 _at) internal pure returns (uint256, uint256) {
uint8 _dataLen = determineVarIntDataLengthAt(_b, _at);
if (_dataLen == 0) {
return (0, uint8(_b[_at]));
}
if (_b.length < 1 + _dataLen + _at) {
return (ERR_BAD_ARG, 0);
}
uint256 _number;
if (_dataLen == 2) {
_number = reverseUint16(uint16(_b.slice2(1 + _at)));
} else if (_dataLen == 4) {
_number = reverseUint32(uint32(_b.slice4(1 + _at)));
} else if (_dataLen == 8) {
_number = reverseUint64(uint64(_b.slice8(1 + _at)));
}
return (_dataLen, _number);
}
/// @notice Changes the endianness of a byte array
/// @dev Returns a new, backwards, bytes
/// @param _b The bytes to reverse
/// @return The reversed bytes
function reverseEndianness(bytes memory _b) internal pure returns (bytes memory) {
bytes memory _newValue = new bytes(_b.length);
for (uint i = 0; i < _b.length; i++) {
_newValue[_b.length - i - 1] = _b[i];
}
return _newValue;
}
/// @notice Changes the endianness of a uint256
/// @dev https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel
/// @param _b The unsigned integer to reverse
/// @return v The reversed value
function reverseUint256(uint256 _b) internal pure returns (uint256 v) {
v = _b;
// swap bytes
v = ((v >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) |
((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8);
// swap 2-byte long pairs
v = ((v >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) |
((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16);
// swap 4-byte long pairs
v = ((v >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) |
((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32);
// swap 8-byte long pairs
v = ((v >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) |
((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64);
// swap 16-byte long pairs
v = (v >> 128) | (v << 128);
}
/// @notice Changes the endianness of a uint64
/// @param _b The unsigned integer to reverse
/// @return v The reversed value
function reverseUint64(uint64 _b) internal pure returns (uint64 v) {
v = _b;
// swap bytes
v = ((v >> 8) & 0x00FF00FF00FF00FF) |
((v & 0x00FF00FF00FF00FF) << 8);
// swap 2-byte long pairs
v = ((v >> 16) & 0x0000FFFF0000FFFF) |
((v & 0x0000FFFF0000FFFF) << 16);
// swap 4-byte long pairs
v = (v >> 32) | (v << 32);
}
/// @notice Changes the endianness of a uint32
/// @param _b The unsigned integer to reverse
/// @return v The reversed value
function reverseUint32(uint32 _b) internal pure returns (uint32 v) {
v = _b;
// swap bytes
v = ((v >> 8) & 0x00FF00FF) |
((v & 0x00FF00FF) << 8);
// swap 2-byte long pairs
v = (v >> 16) | (v << 16);
}
/// @notice Changes the endianness of a uint24
/// @param _b The unsigned integer to reverse
/// @return v The reversed value
function reverseUint24(uint24 _b) internal pure returns (uint24 v) {
v = (_b << 16) | (_b & 0x00FF00) | (_b >> 16);
}
/// @notice Changes the endianness of a uint16
/// @param _b The unsigned integer to reverse
/// @return v The reversed value
function reverseUint16(uint16 _b) internal pure returns (uint16 v) {
v = (_b << 8) | (_b >> 8);
}
/// @notice Converts big-endian bytes to a uint
/// @dev Traverses the byte array and sums the bytes
/// @param _b The big-endian bytes-encoded integer
/// @return The integer representation
function bytesToUint(bytes memory _b) internal pure returns (uint256) {
uint256 _number;
for (uint i = 0; i < _b.length; i++) {
_number = _number + uint8(_b[i]) * (2 ** (8 * (_b.length - (i + 1))));
}
return _number;
}
/// @notice Get the last _num bytes from a byte array
/// @param _b The byte array to slice
/// @param _num The number of bytes to extract from the end
/// @return The last _num bytes of _b
function lastBytes(bytes memory _b, uint256 _num) internal pure returns (bytes memory) {
uint256 _start = _b.length.sub(_num);
return _b.slice(_start, _num);
}
/// @notice Implements bitcoin's hash160 (rmd160(sha2()))
/// @dev abi.encodePacked changes the return to bytes instead of bytes32
/// @param _b The pre-image
/// @return The digest
function hash160(bytes memory _b) internal pure returns (bytes memory) {
return abi.encodePacked(ripemd160(abi.encodePacked(sha256(_b))));
}
/// @notice Implements bitcoin's hash160 (sha2 + ripemd160)
/// @dev sha2 precompile at address(2), ripemd160 at address(3)
/// @param _b The pre-image
/// @return res The digest
function hash160View(bytes memory _b) internal view returns (bytes20 res) {
// solium-disable-next-line security/no-inline-assembly
assembly {
pop(staticcall(gas(), 2, add(_b, 32), mload(_b), 0x00, 32))
pop(staticcall(gas(), 3, 0x00, 32, 0x00, 32))
// read from position 12 = 0c
res := mload(0x0c)
}
}
/// @notice Implements bitcoin's hash256 (double sha2)
/// @dev abi.encodePacked changes the return to bytes instead of bytes32
/// @param _b The pre-image
/// @return The digest
function hash256(bytes memory _b) internal pure returns (bytes32) {
return sha256(abi.encodePacked(sha256(_b)));
}
/// @notice Implements bitcoin's hash256 (double sha2)
/// @dev sha2 is precompiled smart contract located at address(2)
/// @param _b The pre-image
/// @return res The digest
function hash256View(bytes memory _b) internal view returns (bytes32 res) {
// solium-disable-next-line security/no-inline-assembly
assembly {
pop(staticcall(gas(), 2, add(_b, 32), mload(_b), 0x00, 32))
pop(staticcall(gas(), 2, 0x00, 32, 0x00, 32))
res := mload(0x00)
}
}
/// @notice Implements bitcoin's hash256 on a pair of bytes32
/// @dev sha2 is precompiled smart contract located at address(2)
/// @param _a The first bytes32 of the pre-image
/// @param _b The second bytes32 of the pre-image
/// @return res The digest
function hash256Pair(bytes32 _a, bytes32 _b) internal view returns (bytes32 res) {
// solium-disable-next-line security/no-inline-assembly
assembly {
mstore(0x00, _a)
mstore(0x20, _b)
pop(staticcall(gas(), 2, 0x00, 64, 0x00, 32))
pop(staticcall(gas(), 2, 0x00, 32, 0x00, 32))
res := mload(0x00)
}
}
/// @notice Implements bitcoin's hash256 (double sha2)
/// @dev sha2 is precompiled smart contract located at address(2)
/// @param _b The array containing the pre-image
/// @param at The start of the pre-image
/// @param len The length of the pre-image
/// @return res The digest
function hash256Slice(
bytes memory _b,
uint256 at,
uint256 len
) internal view returns (bytes32 res) {
// solium-disable-next-line security/no-inline-assembly
assembly {
pop(staticcall(gas(), 2, add(_b, add(32, at)), len, 0x00, 32))
pop(staticcall(gas(), 2, 0x00, 32, 0x00, 32))
res := mload(0x00)
}
}
/* ************ */
/* Legacy Input */
/* ************ */
/// @notice Extracts the nth input from the vin (0-indexed)
/// @dev Iterates over the vin. If you need to extract several, write a custom function
/// @param _vin The vin as a tightly-packed byte array
/// @param _index The 0-indexed location of the input to extract
/// @return The input as a byte array
function extractInputAtIndex(bytes memory _vin, uint256 _index) internal pure returns (bytes memory) {
uint256 _varIntDataLen;
uint256 _nIns;
(_varIntDataLen, _nIns) = parseVarInt(_vin);
require(_varIntDataLen != ERR_BAD_ARG, "Read overrun during VarInt parsing");
require(_index < _nIns, "Vin read overrun");
uint256 _len = 0;
uint256 _offset = 1 + _varIntDataLen;
for (uint256 _i = 0; _i < _index; _i ++) {
_len = determineInputLengthAt(_vin, _offset);
require(_len != ERR_BAD_ARG, "Bad VarInt in scriptSig");
_offset = _offset + _len;
}
_len = determineInputLengthAt(_vin, _offset);
require(_len != ERR_BAD_ARG, "Bad VarInt in scriptSig");
return _vin.slice(_offset, _len);
}
/// @notice Determines whether an input is legacy
/// @dev False if no scriptSig, otherwise True
/// @param _input The input
/// @return True for legacy, False for witness
function isLegacyInput(bytes memory _input) internal pure returns (bool) {
return _input[36] != hex"00";
}
/// @notice Determines the length of a scriptSig in an input
/// @dev Will return 0 if passed a witness input.
/// @param _input The LEGACY input
/// @return The length of the script sig
function extractScriptSigLen(bytes memory _input) internal pure returns (uint256, uint256) {
return extractScriptSigLenAt(_input, 0);
}
/// @notice Determines the length of a scriptSig in an input
/// starting at the specified position
/// @dev Will return 0 if passed a witness input.
/// @param _input The byte array containing the LEGACY input
/// @param _at The position of the input in the array
/// @return The length of the script sig
function extractScriptSigLenAt(bytes memory _input, uint256 _at) internal pure returns (uint256, uint256) {
if (_input.length < 37 + _at) {
return (ERR_BAD_ARG, 0);
}
uint256 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = parseVarIntAt(_input, _at + 36);
return (_varIntDataLen, _scriptSigLen);
}
/// @notice Determines the length of an input from its scriptSig
/// @dev 36 for outpoint, 1 for scriptSig length, 4 for sequence
/// @param _input The input
/// @return The length of the input in bytes
function determineInputLength(bytes memory _input) internal pure returns (uint256) {
return determineInputLengthAt(_input, 0);
}
/// @notice Determines the length of an input from its scriptSig,
/// starting at the specified position
/// @dev 36 for outpoint, 1 for scriptSig length, 4 for sequence
/// @param _input The byte array containing the input
/// @param _at The position of the input in the array
/// @return The length of the input in bytes
function determineInputLengthAt(bytes memory _input, uint256 _at) internal pure returns (uint256) {
uint256 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = extractScriptSigLenAt(_input, _at);
if (_varIntDataLen == ERR_BAD_ARG) {
return ERR_BAD_ARG;
}
return 36 + 1 + _varIntDataLen + _scriptSigLen + 4;
}
/// @notice Extracts the LE sequence bytes from an input
/// @dev Sequence is used for relative time locks
/// @param _input The LEGACY input
/// @return The sequence bytes (LE uint)
function extractSequenceLELegacy(bytes memory _input) internal pure returns (bytes4) {
uint256 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input);
require(_varIntDataLen != ERR_BAD_ARG, "Bad VarInt in scriptSig");
return _input.slice4(36 + 1 + _varIntDataLen + _scriptSigLen);
}
/// @notice Extracts the sequence from the input
/// @dev Sequence is a 4-byte little-endian number
/// @param _input The LEGACY input
/// @return The sequence number (big-endian uint)
function extractSequenceLegacy(bytes memory _input) internal pure returns (uint32) {
uint32 _leSeqence = uint32(extractSequenceLELegacy(_input));
uint32 _beSequence = reverseUint32(_leSeqence);
return _beSequence;
}
/// @notice Extracts the VarInt-prepended scriptSig from the input in a tx
/// @dev Will return hex"00" if passed a witness input
/// @param _input The LEGACY input
/// @return The length-prepended scriptSig
function extractScriptSig(bytes memory _input) internal pure returns (bytes memory) {
uint256 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input);
require(_varIntDataLen != ERR_BAD_ARG, "Bad VarInt in scriptSig");
return _input.slice(36, 1 + _varIntDataLen + _scriptSigLen);
}
/* ************* */
/* Witness Input */
/* ************* */
/// @notice Extracts the LE sequence bytes from an input
/// @dev Sequence is used for relative time locks
/// @param _input The WITNESS input
/// @return The sequence bytes (LE uint)
function extractSequenceLEWitness(bytes memory _input) internal pure returns (bytes4) {
return _input.slice4(37);
}
/// @notice Extracts the sequence from the input in a tx
/// @dev Sequence is a 4-byte little-endian number
/// @param _input The WITNESS input
/// @return The sequence number (big-endian uint)
function extractSequenceWitness(bytes memory _input) internal pure returns (uint32) {
uint32 _leSeqence = uint32(extractSequenceLEWitness(_input));
uint32 _inputeSequence = reverseUint32(_leSeqence);
return _inputeSequence;
}
/// @notice Extracts the outpoint from the input in a tx
/// @dev 32-byte tx id with 4-byte index
/// @param _input The input
/// @return The outpoint (LE bytes of prev tx hash + LE bytes of prev tx index)
function extractOutpoint(bytes memory _input) internal pure returns (bytes memory) {
return _input.slice(0, 36);
}
/// @notice Extracts the outpoint tx id from an input
/// @dev 32-byte tx id
/// @param _input The input
/// @return The tx id (little-endian bytes)
function extractInputTxIdLE(bytes memory _input) internal pure returns (bytes32) {
return _input.slice32(0);
}
/// @notice Extracts the outpoint tx id from an input
/// starting at the specified position
/// @dev 32-byte tx id
/// @param _input The byte array containing the input
/// @param _at The position of the input
/// @return The tx id (little-endian bytes)
function extractInputTxIdLeAt(bytes memory _input, uint256 _at) internal pure returns (bytes32) {
return _input.slice32(_at);
}
/// @notice Extracts the LE tx input index from the input in a tx
/// @dev 4-byte tx index
/// @param _input The input
/// @return The tx index (little-endian bytes)
function extractTxIndexLE(bytes memory _input) internal pure returns (bytes4) {
return _input.slice4(32);
}
/// @notice Extracts the LE tx input index from the input in a tx
/// starting at the specified position
/// @dev 4-byte tx index
/// @param _input The byte array containing the input
/// @param _at The position of the input
/// @return The tx index (little-endian bytes)
function extractTxIndexLeAt(bytes memory _input, uint256 _at) internal pure returns (bytes4) {
return _input.slice4(32 + _at);
}
/* ****** */
/* Output */
/* ****** */
/// @notice Determines the length of an output
/// @dev Works with any properly formatted output
/// @param _output The output
/// @return The length indicated by the prefix, error if invalid length
function determineOutputLength(bytes memory _output) internal pure returns (uint256) {
return determineOutputLengthAt(_output, 0);
}
/// @notice Determines the length of an output
/// starting at the specified position
/// @dev Works with any properly formatted output
/// @param _output The byte array containing the output
/// @param _at The position of the output
/// @return The length indicated by the prefix, error if invalid length
function determineOutputLengthAt(bytes memory _output, uint256 _at) internal pure returns (uint256) {
if (_output.length < 9 + _at) {
return ERR_BAD_ARG;
}
uint256 _varIntDataLen;
uint256 _scriptPubkeyLength;
(_varIntDataLen, _scriptPubkeyLength) = parseVarIntAt(_output, 8 + _at);
if (_varIntDataLen == ERR_BAD_ARG) {
return ERR_BAD_ARG;
}
// 8-byte value, 1-byte for tag itself
return 8 + 1 + _varIntDataLen + _scriptPubkeyLength;
}
/// @notice Extracts the output at a given index in the TxOuts vector
/// @dev Iterates over the vout. If you need to extract multiple, write a custom function
/// @param _vout The _vout to extract from
/// @param _index The 0-indexed location of the output to extract
/// @return The specified output
function extractOutputAtIndex(bytes memory _vout, uint256 _index) internal pure returns (bytes memory) {
uint256 _varIntDataLen;
uint256 _nOuts;
(_varIntDataLen, _nOuts) = parseVarInt(_vout);
require(_varIntDataLen != ERR_BAD_ARG, "Read overrun during VarInt parsing");
require(_index < _nOuts, "Vout read overrun");
uint256 _len = 0;
uint256 _offset = 1 + _varIntDataLen;
for (uint256 _i = 0; _i < _index; _i ++) {
_len = determineOutputLengthAt(_vout, _offset);
require(_len != ERR_BAD_ARG, "Bad VarInt in scriptPubkey");
_offset += _len;
}
_len = determineOutputLengthAt(_vout, _offset);
require(_len != ERR_BAD_ARG, "Bad VarInt in scriptPubkey");
return _vout.slice(_offset, _len);
}
/// @notice Extracts the value bytes from the output in a tx
/// @dev Value is an 8-byte little-endian number
/// @param _output The output
/// @return The output value as LE bytes
function extractValueLE(bytes memory _output) internal pure returns (bytes8) {
return _output.slice8(0);
}
/// @notice Extracts the value from the output in a tx
/// @dev Value is an 8-byte little-endian number
/// @param _output The output
/// @return The output value
function extractValue(bytes memory _output) internal pure returns (uint64) {
uint64 _leValue = uint64(extractValueLE(_output));
uint64 _beValue = reverseUint64(_leValue);
return _beValue;
}
/// @notice Extracts the value from the output in a tx
/// @dev Value is an 8-byte little-endian number
/// @param _output The byte array containing the output
/// @param _at The starting index of the output in the array
/// @return The output value
function extractValueAt(bytes memory _output, uint256 _at) internal pure returns (uint64) {
uint64 _leValue = uint64(_output.slice8(_at));
uint64 _beValue = reverseUint64(_leValue);
return _beValue;
}
/// @notice Extracts the data from an op return output
/// @dev Returns hex"" if no data or not an op return
/// @param _output The output
/// @return Any data contained in the opreturn output, null if not an op return
function extractOpReturnData(bytes memory _output) internal pure returns (bytes memory) {
if (_output[9] != hex"6a") {
return hex"";
}
bytes1 _dataLen = _output[10];
return _output.slice(11, uint256(uint8(_dataLen)));
}
/// @notice Extracts the hash from the output script
/// @dev Determines type by the length prefix and validates format
/// @param _output The output
/// @return The hash committed to by the pk_script, or null for errors
function extractHash(bytes memory _output) internal pure returns (bytes memory) {
return extractHashAt(_output, 8, _output.length - 8);
}
/// @notice Extracts the hash from the output script
/// @dev Determines type by the length prefix and validates format
/// @param _output The byte array containing the output
/// @param _at The starting index of the output script in the array
/// (output start + 8)
/// @param _len The length of the output script
/// (output length - 8)
/// @return The hash committed to by the pk_script, or null for errors
function extractHashAt(
bytes memory _output,
uint256 _at,
uint256 _len
) internal pure returns (bytes memory) {
uint8 _scriptLen = uint8(_output[_at]);
// don't have to worry about overflow here.
// if _scriptLen + 1 overflows, then output length would have to be < 1
// for this check to pass. if it's < 1, then we errored when assigning
// _scriptLen
if (_scriptLen + 1 != _len) {
return hex"";
}
if (uint8(_output[_at + 1]) == 0) {
if (_scriptLen < 2) {
return hex"";
}
uint256 _payloadLen = uint8(_output[_at + 2]);
// Check for maliciously formatted witness outputs.
// No need to worry about underflow as long b/c of the `< 2` check
if (_payloadLen != _scriptLen - 2 || (_payloadLen != 0x20 && _payloadLen != 0x14)) {
return hex"";
}
return _output.slice(_at + 3, _payloadLen);
} else {
bytes3 _tag = _output.slice3(_at);
// p2pkh
if (_tag == hex"1976a9") {
// Check for maliciously formatted p2pkh
// No need to worry about underflow, b/c of _scriptLen check
if (uint8(_output[_at + 3]) != 0x14 ||
_output.slice2(_at + _len - 2) != hex"88ac") {
return hex"";
}
return _output.slice(_at + 4, 20);
//p2sh
} else if (_tag == hex"17a914") {
// Check for maliciously formatted p2sh
// No need to worry about underflow, b/c of _scriptLen check
if (uint8(_output[_at + _len - 1]) != 0x87) {
return hex"";
}
return _output.slice(_at + 3, 20);
}
}
return hex""; /* NB: will trigger on OPRETURN and any non-standard that doesn't overrun */
}
/* ********** */
/* Witness TX */
/* ********** */
/// @notice Checks that the vin passed up is properly formatted
/// @dev Consider a vin with a valid vout in its scriptsig
/// @param _vin Raw bytes length-prefixed input vector
/// @return True if it represents a validly formatted vin
function validateVin(bytes memory _vin) internal pure returns (bool) {
uint256 _varIntDataLen;
uint256 _nIns;
(_varIntDataLen, _nIns) = parseVarInt(_vin);
// Not valid if it says there are too many or no inputs
if (_nIns == 0 || _varIntDataLen == ERR_BAD_ARG) {
return false;
}
uint256 _offset = 1 + _varIntDataLen;
for (uint256 i = 0; i < _nIns; i++) {
// If we're at the end, but still expect more
if (_offset >= _vin.length) {
return false;
}
// Grab the next input and determine its length.
uint256 _nextLen = determineInputLengthAt(_vin, _offset);
if (_nextLen == ERR_BAD_ARG) {
return false;
}
// Increase the offset by that much
_offset += _nextLen;
}
// Returns false if we're not exactly at the end
return _offset == _vin.length;
}
/// @notice Checks that the vout passed up is properly formatted
/// @dev Consider a vout with a valid scriptpubkey
/// @param _vout Raw bytes length-prefixed output vector
/// @return True if it represents a validly formatted vout
function validateVout(bytes memory _vout) internal pure returns (bool) {
uint256 _varIntDataLen;
uint256 _nOuts;
(_varIntDataLen, _nOuts) = parseVarInt(_vout);
// Not valid if it says there are too many or no outputs
if (_nOuts == 0 || _varIntDataLen == ERR_BAD_ARG) {
return false;
}
uint256 _offset = 1 + _varIntDataLen;
for (uint256 i = 0; i < _nOuts; i++) {
// If we're at the end, but still expect more
if (_offset >= _vout.length) {
return false;
}
// Grab the next output and determine its length.
// Increase the offset by that much
uint256 _nextLen = determineOutputLengthAt(_vout, _offset);
if (_nextLen == ERR_BAD_ARG) {
return false;
}
_offset += _nextLen;
}
// Returns false if we're not exactly at the end
return _offset == _vout.length;
}
/* ************ */
/* Block Header */
/* ************ */
/// @notice Extracts the transaction merkle root from a block header
/// @dev Use verifyHash256Merkle to verify proofs with this root
/// @param _header The header
/// @return The merkle root (little-endian)
function extractMerkleRootLE(bytes memory _header) internal pure returns (bytes32) {
return _header.slice32(36);
}
/// @notice Extracts the target from a block header
/// @dev Target is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent
/// @param _header The header
/// @return The target threshold
function extractTarget(bytes memory _header) internal pure returns (uint256) {
return extractTargetAt(_header, 0);
}
/// @notice Extracts the target from a block header
/// @dev Target is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent
/// @param _header The array containing the header
/// @param at The start of the header
/// @return The target threshold
function extractTargetAt(bytes memory _header, uint256 at) internal pure returns (uint256) {
uint24 _m = uint24(_header.slice3(72 + at));
uint8 _e = uint8(_header[75 + at]);
uint256 _mantissa = uint256(reverseUint24(_m));
uint _exponent = _e - 3;
return _mantissa * (256 ** _exponent);
}
/// @notice Calculate difficulty from the difficulty 1 target and current target
/// @dev Difficulty 1 is 0x1d00ffff on mainnet and testnet
/// @dev Difficulty 1 is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent
/// @param _target The current target
/// @return The block difficulty (bdiff)
function calculateDifficulty(uint256 _target) internal pure returns (uint256) {
// Difficulty 1 calculated from 0x1d00ffff
return DIFF1_TARGET.div(_target);
}
/// @notice Extracts the previous block's hash from a block header
/// @dev Block headers do NOT include block number :(
/// @param _header The header
/// @return The previous block's hash (little-endian)
function extractPrevBlockLE(bytes memory _header) internal pure returns (bytes32) {
return _header.slice32(4);
}
/// @notice Extracts the previous block's hash from a block header
/// @dev Block headers do NOT include block number :(
/// @param _header The array containing the header
/// @param at The start of the header
/// @return The previous block's hash (little-endian)
function extractPrevBlockLEAt(
bytes memory _header,
uint256 at
) internal pure returns (bytes32) {
return _header.slice32(4 + at);
}
/// @notice Extracts the timestamp from a block header
/// @dev Time is not 100% reliable
/// @param _header The header
/// @return The timestamp (little-endian bytes)
function extractTimestampLE(bytes memory _header) internal pure returns (bytes4) {
return _header.slice4(68);
}
/// @notice Extracts the timestamp from a block header
/// @dev Time is not 100% reliable
/// @param _header The header
/// @return The timestamp (uint)
function extractTimestamp(bytes memory _header) internal pure returns (uint32) {
return reverseUint32(uint32(extractTimestampLE(_header)));
}
/// @notice Extracts the expected difficulty from a block header
/// @dev Does NOT verify the work
/// @param _header The header
/// @return The difficulty as an integer
function extractDifficulty(bytes memory _header) internal pure returns (uint256) {
return calculateDifficulty(extractTarget(_header));
}
/// @notice Concatenates and hashes two inputs for merkle proving
/// @param _a The first hash
/// @param _b The second hash
/// @return The double-sha256 of the concatenated hashes
function _hash256MerkleStep(bytes memory _a, bytes memory _b) internal view returns (bytes32) {
return hash256View(abi.encodePacked(_a, _b));
}
/// @notice Concatenates and hashes two inputs for merkle proving
/// @param _a The first hash
/// @param _b The second hash
/// @return The double-sha256 of the concatenated hashes
function _hash256MerkleStep(bytes32 _a, bytes32 _b) internal view returns (bytes32) {
return hash256Pair(_a, _b);
}
/// @notice Verifies a Bitcoin-style merkle tree
/// @dev Leaves are 0-indexed. Inefficient version.
/// @param _proof The proof. Tightly packed LE sha256 hashes. The last hash is the root
/// @param _index The index of the leaf
/// @return true if the proof is valid, else false
function verifyHash256Merkle(bytes memory _proof, uint _index) internal view returns (bool) {
// Not an even number of hashes
if (_proof.length % 32 != 0) {
return false;
}
// Special case for coinbase-only blocks
if (_proof.length == 32) {
return true;
}
// Should never occur
if (_proof.length == 64) {
return false;
}
bytes32 _root = _proof.slice32(_proof.length - 32);
bytes32 _current = _proof.slice32(0);
bytes memory _tree = _proof.slice(32, _proof.length - 64);
return verifyHash256Merkle(_current, _tree, _root, _index);
}
/// @notice Verifies a Bitcoin-style merkle tree
/// @dev Leaves are 0-indexed. Efficient version.
/// @param _leaf The leaf of the proof. LE sha256 hash.
/// @param _tree The intermediate nodes in the proof.
/// Tightly packed LE sha256 hashes.
/// @param _root The root of the proof. LE sha256 hash.
/// @param _index The index of the leaf
/// @return true if the proof is valid, else false
function verifyHash256Merkle(
bytes32 _leaf,
bytes memory _tree,
bytes32 _root,
uint _index
) internal view returns (bool) {
// Not an even number of hashes
if (_tree.length % 32 != 0) {
return false;
}
// Should never occur
if (_tree.length == 0) {
return false;
}
uint _idx = _index;
bytes32 _current = _leaf;
// i moves in increments of 32
for (uint i = 0; i < _tree.length; i += 32) {
if (_idx % 2 == 1) {
_current = _hash256MerkleStep(_tree.slice32(i), _current);
} else {
_current = _hash256MerkleStep(_current, _tree.slice32(i));
}
_idx = _idx >> 1;
}
return _current == _root;
}
/*
NB: https://github.com/bitcoin/bitcoin/blob/78dae8caccd82cfbfd76557f1fb7d7557c7b5edb/src/pow.cpp#L49-L72
NB: We get a full-bitlength target from this. For comparison with
header-encoded targets we need to mask it with the header target
e.g. (full & truncated) == truncated
*/
/// @notice performs the bitcoin difficulty retarget
/// @dev implements the Bitcoin algorithm precisely
/// @param _previousTarget the target of the previous period
/// @param _firstTimestamp the timestamp of the first block in the difficulty period
/// @param _secondTimestamp the timestamp of the last block in the difficulty period
/// @return the new period's target threshold
function retargetAlgorithm(
uint256 _previousTarget,
uint256 _firstTimestamp,
uint256 _secondTimestamp
) internal pure returns (uint256) {
uint256 _elapsedTime = _secondTimestamp.sub(_firstTimestamp);
// Normalize ratio to factor of 4 if very long or very short
if (_elapsedTime < RETARGET_PERIOD.div(4)) {
_elapsedTime = RETARGET_PERIOD.div(4);
}
if (_elapsedTime > RETARGET_PERIOD.mul(4)) {
_elapsedTime = RETARGET_PERIOD.mul(4);
}
/*
NB: high targets e.g. ffff0020 can cause overflows here
so we divide it by 256**2, then multiply by 256**2 later
we know the target is evenly divisible by 256**2, so this isn't an issue
*/
uint256 _adjusted = _previousTarget.div(65536).mul(_elapsedTime);
return _adjusted.div(RETARGET_PERIOD).mul(65536);
}
}
@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol
pragma solidity ^0.8.4;
/*
https://github.com/GNSPS/solidity-bytes-utils/
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <https://unlicense.org>
*/
/** @title BytesLib **/
/** @author https://github.com/GNSPS **/
library BytesLib {
function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) {
bytes memory tempBytes;
assembly {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// Store the length of the first bytes array at the beginning of
// the memory for tempBytes.
let length := mload(_preBytes)
mstore(tempBytes, length)
// Maintain a memory counter for the current write location in the
// temp bytes array by adding the 32 bytes for the array length to
// the starting location.
let mc := add(tempBytes, 0x20)
// Stop copying when the memory counter reaches the length of the
// first bytes array.
let end := add(mc, length)
for {
// Initialize a copy counter to the start of the _preBytes data,
// 32 bytes into its memory.
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
// Increase both counters by 32 bytes each iteration.
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// Write the _preBytes data into the tempBytes memory 32 bytes
// at a time.
mstore(mc, mload(cc))
}
// Add the length of _postBytes to the current length of tempBytes
// and store it as the new length in the first 32 bytes of the
// tempBytes memory.
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
// Move the memory counter back from a multiple of 0x20 to the
// actual end of the _preBytes data.
mc := end
// Stop copying when the memory counter reaches the new combined
// length of the arrays.
end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
// Update the free-memory pointer by padding our last write location
// to 32 bytes: add 31 bytes to the end of tempBytes to move to the
// next 32 byte block, then round down to the nearest multiple of
// 32. If the sum of the length of the two arrays is zero then add
// one before rounding down to leave a blank 32 bytes (the length block with 0).
mstore(0x40, and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31) // Round down to the nearest 32 bytes.
))
}
return tempBytes;
}
function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {
assembly {
// Read the first 32 bytes of _preBytes storage, which is the length
// of the array. (We don't need to use the offset into the slot
// because arrays use the entire slot.)
let fslot := sload(_preBytes.slot)
// Arrays of 31 bytes or less have an even value in their slot,
// while longer arrays have an odd value. The actual length is
// the slot divided by two for odd values, and the lowest order
// byte divided by two for even values.
// If the slot is even, bitwise and the slot with 255 and divide by
// two to get the length. If the slot is odd, bitwise and the slot
// with -1 and divide by two.
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
let newlength := add(slength, mlength)
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
switch add(lt(slength, 32), lt(newlength, 32))
case 2 {
// Since the new array still fits in the slot, we just need to
// update the contents of the slot.
// uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
sstore(
_preBytes.slot,
// all the modifications to the slot are inside this
// next block
add(
// we can just add to the slot contents because the
// bytes we want to change are the LSBs
fslot,
add(
mul(
div(
// load the bytes from memory
mload(add(_postBytes, 0x20)),
// zero all bytes to the right
exp(0x100, sub(32, mlength))
),
// and now shift left the number of bytes to
// leave space for the length in the slot
exp(0x100, sub(32, newlength))
),
// increase length by the double of the memory
// bytes length
mul(mlength, 2)
)
)
)
}
case 1 {
// The stored value fits in the slot, but the combined value
// will exceed it.
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes.slot)
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes.slot, add(mul(newlength, 2), 1))
// The contents of the _postBytes array start 32 bytes into
// the structure. Our first read should obtain the `submod`
// bytes that can fit into the unused space in the last word
// of the stored array. To get this, we read 32 bytes starting
// from `submod`, so the data we read overlaps with the array
// contents by `submod` bytes. Masking the lowest-order
// `submod` bytes allows us to add that value directly to the
// stored value.
let submod := sub(32, slength)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(
sc,
add(
and(
fslot,
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
),
and(mload(mc), mask)
)
)
for {
mc := add(mc, 0x20)
sc := add(sc, 1)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
default {
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes.slot)
// Start copying to the last used word of the stored array.
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes.slot, add(mul(newlength, 2), 1))
// Copy over the first `submod` bytes of the new data as in
// case 1 above.
let slengthmod := mod(slength, 32)
let mlengthmod := mod(mlength, 32)
let submod := sub(32, slengthmod)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(sc, add(sload(sc), and(mload(mc), mask)))
for {
sc := add(sc, 1)
mc := add(mc, 0x20)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
}
}
function slice(bytes memory _bytes, uint _start, uint _length) internal pure returns (bytes memory res) {
if (_length == 0) {
return hex"";
}
uint _end = _start + _length;
require(_end > _start && _bytes.length >= _end, "Slice out of bounds");
assembly {
// Alloc bytes array with additional 32 bytes afterspace and assign it's size
res := mload(0x40)
mstore(0x40, add(add(res, 64), _length))
mstore(res, _length)
// Compute distance between source and destination pointers
let diff := sub(res, add(_bytes, _start))
for {
let src := add(add(_bytes, 32), _start)
let end := add(src, _length)
} lt(src, end) {
src := add(src, 32)
} {
mstore(add(src, diff), mload(src))
}
}
}
/// @notice Take a slice of the byte array, overwriting the destination.
/// The length of the slice will equal the length of the destination array.
/// @dev Make sure the destination array has afterspace if required.
/// @param _bytes The source array
/// @param _dest The destination array.
/// @param _start The location to start in the source array.
function sliceInPlace(
bytes memory _bytes,
bytes memory _dest,
uint _start
) internal pure {
uint _length = _dest.length;
uint _end = _start + _length;
require(_end > _start && _bytes.length >= _end, "Slice out of bounds");
assembly {
for {
let src := add(add(_bytes, 32), _start)
let res := add(_dest, 32)
let end := add(src, _length)
} lt(src, end) {
src := add(src, 32)
res := add(res, 32)
} {
mstore(res, mload(src))
}
}
}
// Static slice functions, no bounds checking
/// @notice take a 32-byte slice from the specified position
function slice32(bytes memory _bytes, uint _start) internal pure returns (bytes32 res) {
assembly {
res := mload(add(add(_bytes, 32), _start))
}
}
/// @notice take a 20-byte slice from the specified position
function slice20(bytes memory _bytes, uint _start) internal pure returns (bytes20) {
return bytes20(slice32(_bytes, _start));
}
/// @notice take a 8-byte slice from the specified position
function slice8(bytes memory _bytes, uint _start) internal pure returns (bytes8) {
return bytes8(slice32(_bytes, _start));
}
/// @notice take a 4-byte slice from the specified position
function slice4(bytes memory _bytes, uint _start) internal pure returns (bytes4) {
return bytes4(slice32(_bytes, _start));
}
/// @notice take a 3-byte slice from the specified position
function slice3(bytes memory _bytes, uint _start) internal pure returns (bytes3) {
return bytes3(slice32(_bytes, _start));
}
/// @notice take a 2-byte slice from the specified position
function slice2(bytes memory _bytes, uint _start) internal pure returns (bytes2) {
return bytes2(slice32(_bytes, _start));
}
function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) {
uint _totalLen = _start + 20;
require(_totalLen > _start && _bytes.length >= _totalLen, "Address conversion out of bounds.");
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) {
uint _totalLen = _start + 32;
require(_totalLen > _start && _bytes.length >= _totalLen, "Uint conversion out of bounds.");
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {
bool success = true;
assembly {
let length := mload(_preBytes)
// if lengths don't match the arrays are not equal
switch eq(length, mload(_postBytes))
case 1 {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
let mc := add(_preBytes, 0x20)
let end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
} eq(add(lt(mc, end), cb), 2) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// if any of these checks fails then arrays are not equal
if iszero(eq(mload(mc), mload(cc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) {
bool success = true;
assembly {
// we know _preBytes_offset is 0
let fslot := sload(_preBytes.slot)
// Decode the length of the stored array like in concatStorage().
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
// if lengths don't match the arrays are not equal
switch eq(slength, mlength)
case 1 {
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
if iszero(iszero(slength)) {
switch lt(slength, 32)
case 1 {
// blank the last byte which is the length
fslot := mul(div(fslot, 0x100), 0x100)
if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
// unsuccess:
success := 0
}
}
default {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes.slot)
let sc := keccak256(0x0, 0x20)
let mc := add(_postBytes, 0x20)
let end := add(mc, mlength)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
for {} eq(add(lt(mc, end), cb), 2) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
if iszero(eq(sload(sc), mload(mc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
function toBytes32(bytes memory _source) pure internal returns (bytes32 result) {
if (_source.length == 0) {
return 0x0;
}
assembly {
result := mload(add(_source, 32))
}
}
function keccak256Slice(bytes memory _bytes, uint _start, uint _length) pure internal returns (bytes32 result) {
uint _end = _start + _length;
require(_end > _start && _bytes.length >= _end, "Slice out of bounds");
assembly {
result := keccak256(add(add(_bytes, 32), _start), _length)
}
}
}
@keep-network/bitcoin-spv-sol/contracts/SafeMath.sol
pragma solidity ^0.8.4;
/*
The MIT License (MIT)
Copyright (c) 2016 Smart Contract Solutions, Inc.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
require(c / _a == _b, "Overflow during multiplication.");
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a, "Underflow during subtraction.");
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
require(c >= _a, "Overflow during addition.");
return c;
}
}
@keep-network/bitcoin-spv-sol/contracts/ValidateSPV.sol
pragma solidity ^0.8.4;
/** @title ValidateSPV*/
/** @author Summa (https://summa.one) */
import {BytesLib} from "./BytesLib.sol";
import {SafeMath} from "./SafeMath.sol";
import {BTCUtils} from "./BTCUtils.sol";
library ValidateSPV {
using BTCUtils for bytes;
using BTCUtils for uint256;
using BytesLib for bytes;
using SafeMath for uint256;
enum InputTypes { NONE, LEGACY, COMPATIBILITY, WITNESS }
enum OutputTypes { NONE, WPKH, WSH, OP_RETURN, PKH, SH, NONSTANDARD }
uint256 constant ERR_BAD_LENGTH = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
uint256 constant ERR_INVALID_CHAIN = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe;
uint256 constant ERR_LOW_WORK = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd;
function getErrBadLength() internal pure returns (uint256) {
return ERR_BAD_LENGTH;
}
function getErrInvalidChain() internal pure returns (uint256) {
return ERR_INVALID_CHAIN;
}
function getErrLowWork() internal pure returns (uint256) {
return ERR_LOW_WORK;
}
/// @notice Validates a tx inclusion in the block
/// @dev `index` is not a reliable indicator of location within a block
/// @param _txid The txid (LE)
/// @param _merkleRoot The merkle root (as in the block header)
/// @param _intermediateNodes The proof's intermediate nodes (digests between leaf and root)
/// @param _index The leaf's index in the tree (0-indexed)
/// @return true if fully valid, false otherwise
function prove(
bytes32 _txid,
bytes32 _merkleRoot,
bytes memory _intermediateNodes,
uint _index
) internal view returns (bool) {
// Shortcut the empty-block case
if (_txid == _merkleRoot && _index == 0 && _intermediateNodes.length == 0) {
return true;
}
// If the Merkle proof failed, bubble up error
return BTCUtils.verifyHash256Merkle(
_txid,
_intermediateNodes,
_merkleRoot,
_index
);
}
/// @notice Hashes transaction to get txid
/// @dev Supports Legacy and Witness
/// @param _version 4-bytes version
/// @param _vin Raw bytes length-prefixed input vector
/// @param _vout Raw bytes length-prefixed output vector
/// @param _locktime 4-byte tx locktime
/// @return 32-byte transaction id, little endian
function calculateTxId(
bytes4 _version,
bytes memory _vin,
bytes memory _vout,
bytes4 _locktime
) internal view returns (bytes32) {
// Get transaction hash double-Sha256(version + nIns + inputs + nOuts + outputs + locktime)
return abi.encodePacked(_version, _vin, _vout, _locktime).hash256View();
}
/// @notice Checks validity of header chain
/// @notice Compares the hash of each header to the prevHash in the next header
/// @param headers Raw byte array of header chain
/// @return totalDifficulty The total accumulated difficulty of the header chain, or an error code
function validateHeaderChain(
bytes memory headers
) internal view returns (uint256 totalDifficulty) {
// Check header chain length
if (headers.length % 80 != 0) {return ERR_BAD_LENGTH;}
// Initialize header start index
bytes32 digest;
totalDifficulty = 0;
for (uint256 start = 0; start < headers.length; start += 80) {
// After the first header, check that headers are in a chain
if (start != 0) {
if (!validateHeaderPrevHash(headers, start, digest)) {return ERR_INVALID_CHAIN;}
}
// ith header target
uint256 target = headers.extractTargetAt(start);
// Require that the header has sufficient work
digest = headers.hash256Slice(start, 80);
if(uint256(digest).reverseUint256() > target) {
return ERR_LOW_WORK;
}
// Add ith header difficulty to difficulty sum
totalDifficulty = totalDifficulty + target.calculateDifficulty();
}
}
/// @notice Checks validity of header work
/// @param digest Header digest
/// @param target The target threshold
/// @return true if header work is valid, false otherwise
function validateHeaderWork(
bytes32 digest,
uint256 target
) internal pure returns (bool) {
if (digest == bytes32(0)) {return false;}
return (uint256(digest).reverseUint256() < target);
}
/// @notice Checks validity of header chain
/// @dev Compares current header prevHash to previous header's digest
/// @param headers The raw bytes array containing the header
/// @param at The position of the header
/// @param prevHeaderDigest The previous header's digest
/// @return true if the connect is valid, false otherwise
function validateHeaderPrevHash(
bytes memory headers,
uint256 at,
bytes32 prevHeaderDigest
) internal pure returns (bool) {
// Extract prevHash of current header
bytes32 prevHash = headers.extractPrevBlockLEAt(at);
// Compare prevHash of current header to previous header's digest
if (prevHash != prevHeaderDigest) {return false;}
return true;
}
}
@keep-network/random-beacon/contracts/Reimbursable.sol
// SPDX-License-Identifier: GPL-3.0-only
//
// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
//
// Trust math, not hardware.
pragma solidity 0.8.17;
import "./ReimbursementPool.sol";
abstract contract Reimbursable {
// The variable should be initialized by the implementing contract.
// slither-disable-next-line uninitialized-state
ReimbursementPool public reimbursementPool;
// Reserved storage space in case we need to add more variables,
// since there are upgradeable contracts that inherit from this one.
// See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
// slither-disable-next-line unused-state
uint256[49] private __gap;
event ReimbursementPoolUpdated(address newReimbursementPool);
modifier refundable(address receiver) {
uint256 gasStart = gasleft();
_;
reimbursementPool.refund(gasStart - gasleft(), receiver);
}
modifier onlyReimbursableAdmin() virtual {
_;
}
function updateReimbursementPool(ReimbursementPool _reimbursementPool)
external
onlyReimbursableAdmin
{
emit ReimbursementPoolUpdated(address(_reimbursementPool));
reimbursementPool = _reimbursementPool;
}
}
@keep-network/random-beacon/contracts/ReimbursementPool.sol
// SPDX-License-Identifier: GPL-3.0-only
//
// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
//
// Trust math, not hardware.
pragma solidity 0.8.17;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
contract ReimbursementPool is Ownable, ReentrancyGuard {
/// @notice Authorized contracts that can interact with the reimbursment pool.
/// Authorization can be granted and removed by the owner.
mapping(address => bool) public isAuthorized;
/// @notice Static gas includes:
/// - cost of the refund function
/// - base transaction cost
uint256 public staticGas;
/// @notice Max gas price used to reimburse a transaction submitter. Protects
/// against malicious operator-miners.
uint256 public maxGasPrice;
event StaticGasUpdated(uint256 newStaticGas);
event MaxGasPriceUpdated(uint256 newMaxGasPrice);
event SendingEtherFailed(uint256 refundAmount, address receiver);
event AuthorizedContract(address thirdPartyContract);
event UnauthorizedContract(address thirdPartyContract);
event FundsWithdrawn(uint256 withdrawnAmount, address receiver);
constructor(uint256 _staticGas, uint256 _maxGasPrice) {
staticGas = _staticGas;
maxGasPrice = _maxGasPrice;
}
/// @notice Receive ETH
receive() external payable {}
/// @notice Refunds ETH to a spender for executing specific transactions.
/// @dev Ignoring the result of sending ETH to a receiver is made on purpose.
/// For EOA receiving ETH should always work. If a receiver is a smart
/// contract, then we do not want to fail a transaction, because in some
/// cases the refund is done at the very end of multiple calls where all
/// the previous calls were already paid off. It is a receiver's smart
/// contract resposibility to make sure it can receive ETH.
/// @dev Only authorized contracts are allowed calling this function.
/// @param gasSpent Gas spent on a transaction that needs to be reimbursed.
/// @param receiver Address where the reimbursment is sent.
function refund(uint256 gasSpent, address receiver) external nonReentrant {
require(
isAuthorized[msg.sender],
"Contract is not authorized for a refund"
);
require(receiver != address(0), "Receiver's address cannot be zero");
uint256 gasPrice = tx.gasprice < maxGasPrice
? tx.gasprice
: maxGasPrice;
uint256 refundAmount = (gasSpent + staticGas) * gasPrice;
/* solhint-disable avoid-low-level-calls */
// slither-disable-next-line low-level-calls,unchecked-lowlevel
(bool sent, ) = receiver.call{value: refundAmount}("");
/* solhint-enable avoid-low-level-calls */
if (!sent) {
// slither-disable-next-line reentrancy-events
emit SendingEtherFailed(refundAmount, receiver);
}
}
/// @notice Authorize a contract that can interact with this reimbursment pool.
/// Can be authorized by the owner only.
/// @param _contract Authorized contract.
function authorize(address _contract) external onlyOwner {
isAuthorized[_contract] = true;
emit AuthorizedContract(_contract);
}
/// @notice Unauthorize a contract that was previously authorized to interact
/// with this reimbursment pool. Can be unauthorized by the
/// owner only.
/// @param _contract Authorized contract.
function unauthorize(address _contract) external onlyOwner {
delete isAuthorized[_contract];
emit UnauthorizedContract(_contract);
}
/// @notice Setting a static gas cost for executing a transaction. Can be set
/// by the owner only.
/// @param _staticGas Static gas cost.
function setStaticGas(uint256 _staticGas) external onlyOwner {
staticGas = _staticGas;
emit StaticGasUpdated(_staticGas);
}
/// @notice Setting a max gas price for transactions. Can be set by the
/// owner only.
/// @param _maxGasPrice Max gas price used to reimburse tx submitters.
function setMaxGasPrice(uint256 _maxGasPrice) external onlyOwner {
maxGasPrice = _maxGasPrice;
emit MaxGasPriceUpdated(_maxGasPrice);
}
/// @notice Withdraws all ETH from this pool which are sent to a given
/// address. Can be set by the owner only.
/// @param receiver An address where ETH is sent.
function withdrawAll(address receiver) external onlyOwner {
withdraw(address(this).balance, receiver);
}
/// @notice Withdraws ETH amount from this pool which are sent to a given
/// address. Can be set by the owner only.
/// @param amount Amount to withdraw from the pool.
/// @param receiver An address where ETH is sent.
function withdraw(uint256 amount, address receiver) public onlyOwner {
require(
address(this).balance >= amount,
"Insufficient contract balance"
);
require(receiver != address(0), "Receiver's address cannot be zero");
emit FundsWithdrawn(amount, receiver);
/* solhint-disable avoid-low-level-calls */
// slither-disable-next-line low-level-calls,arbitrary-send
(bool sent, ) = receiver.call{value: amount}("");
/* solhint-enable avoid-low-level-calls */
require(sent, "Failed to send Ether");
}
}
@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.1) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
"Initializable: contract is already initialized"
);
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: setting the version to 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_initialized = version;
_initializing = true;
_;
_initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
require(!_initializing, "Initializable: contract is initializing");
if (_initialized < type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint8) {
return _initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}
@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
}
@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-IERC20PermitUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20PermitUpgradeable {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../extensions/draft-IERC20PermitUpgradeable.sol";
import "../../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using AddressUpgradeable for address;
function safeTransfer(
IERC20Upgradeable token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20Upgradeable token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
function safePermit(
IERC20PermitUpgradeable token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
@openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
@openzeppelin/contracts/security/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
contracts/cross-chain/wormhole/Wormhole.sol
// SPDX-License-Identifier: GPL-3.0-only
// ██████████████ ▐████▌ ██████████████
// ██████████████ ▐████▌ ██████████████
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ██████████████ ▐████▌ ██████████████
// ██████████████ ▐████▌ ██████████████
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
pragma solidity 0.8.17;
/// @title WormholeTypes
/// @notice Namespace which groups all types relevant to Wormhole interfaces.
library WormholeTypes {
/// @dev See: https://github.com/wormhole-foundation/wormhole-solidity-sdk/blob/2b7db51f99b49eda99b44f4a044e751cb0b2e8ea/src/interfaces/IWormholeRelayer.sol#L22
struct VaaKey {
uint16 chainId;
bytes32 emitterAddress;
uint64 sequence;
}
}
/// @title IWormholeGateway
/// @notice Interface to the `L2WormholeGateway` contract.
interface IWormholeGateway {
/// @dev See ./L2WormholeGateway.sol#receiveTbtc
function receiveTbtc(bytes memory vaa) external;
}
/// @title IWormhole
/// @notice Wormhole interface.
/// @dev See: https://github.com/wormhole-foundation/wormhole-solidity-sdk/blob/2b7db51f99b49eda99b44f4a044e751cb0b2e8ea/src/interfaces/IWormhole.sol#L6
interface IWormhole {
/// @dev See: https://github.com/wormhole-foundation/wormhole-solidity-sdk/blob/2b7db51f99b49eda99b44f4a044e751cb0b2e8ea/src/interfaces/IWormhole.sol#L109
function chainId() external view returns (uint16);
/// @dev See: https://github.com/wormhole-foundation/wormhole-solidity-sdk/blob/2b7db51f99b49eda99b44f4a044e751cb0b2e8ea/src/interfaces/IWormhole.sol#L117
function messageFee() external view returns (uint256);
}
/// @title IWormholeRelayer
/// @notice Wormhole Relayer interface.
/// @dev See: https://github.com/wormhole-foundation/wormhole-solidity-sdk/blob/2b7db51f99b49eda99b44f4a044e751cb0b2e8ea/src/interfaces/IWormholeRelayer.sol#L74
interface IWormholeRelayer {
/// @dev See: https://github.com/wormhole-foundation/wormhole-solidity-sdk/blob/2b7db51f99b49eda99b44f4a044e751cb0b2e8ea/src/interfaces/IWormholeRelayer.sol#L442
function quoteEVMDeliveryPrice(
uint16 targetChain,
uint256 receiverValue,
uint256 gasLimit
)
external
view
returns (
uint256 nativePriceQuote,
uint256 targetChainRefundPerGasUnused
);
/// @dev See: https://github.com/wormhole-foundation/wormhole-solidity-sdk/blob/2b7db51f99b49eda99b44f4a044e751cb0b2e8ea/src/interfaces/IWormholeRelayer.sol#L182
function sendVaasToEvm(
uint16 targetChain,
address targetAddress,
bytes memory payload,
uint256 receiverValue,
uint256 gasLimit,
WormholeTypes.VaaKey[] memory vaaKeys,
uint16 refundChain,
address refundAddress
) external payable returns (uint64 sequence);
}
/// @title IWormholeReceiver
/// @notice Wormhole Receiver interface.
/// @dev See: https://github.com/wormhole-foundation/wormhole-solidity-sdk/blob/2b7db51f99b49eda99b44f4a044e751cb0b2e8ea/src/interfaces/IWormholeReceiver.sol#L8
interface IWormholeReceiver {
/// @dev See: https://github.com/wormhole-foundation/wormhole-solidity-sdk/blob/2b7db51f99b49eda99b44f4a044e751cb0b2e8ea/src/interfaces/IWormholeReceiver.sol#L44
function receiveWormholeMessages(
bytes memory payload,
bytes[] memory additionalVaas,
bytes32 sourceAddress,
uint16 sourceChain,
bytes32 deliveryHash
) external payable;
}
/// @title IWormholeTokenBridge
/// @notice Wormhole Token Bridge interface.
/// @dev See: https://github.com/wormhole-foundation/wormhole-solidity-sdk/blob/2b7db51f99b49eda99b44f4a044e751cb0b2e8ea/src/interfaces/ITokenBridge.sol#L9
interface IWormholeTokenBridge {
function completeTransferWithPayload(bytes memory encodedVm)
external
returns (bytes memory);
function parseTransferWithPayload(bytes memory encoded)
external
pure
returns (TransferWithPayload memory transfer);
function transferTokens(
address token,
uint256 amount,
uint16 recipientChain,
bytes32 recipient,
uint256 arbiterFee,
uint32 nonce
) external payable returns (uint64 sequence);
function transferTokensWithPayload(
address token,
uint256 amount,
uint16 recipientChain,
bytes32 recipient,
uint32 nonce,
bytes memory payload
) external payable returns (uint64 sequence);
struct TransferWithPayload {
uint8 payloadID;
uint256 amount;
bytes32 tokenAddress;
uint16 tokenChain;
bytes32 to;
uint16 toChain;
bytes32 fromAddress;
bytes payload;
}
}
/// @title WormholeUtils
/// @notice Library for Wormhole utilities.
library WormholeUtils {
/// @notice Converts Ethereum address into Wormhole format.
/// @param _address The address to convert.
function toWormholeAddress(address _address)
internal
pure
returns (bytes32)
{
return bytes32(uint256(uint160(_address)));
}
/// @notice Converts Wormhole address into Ethereum format.
/// @param _address The address to convert.
function fromWormholeAddress(bytes32 _address)
internal
pure
returns (address)
{
return address(uint160(uint256(_address)));
}
/// @dev Eliminates the dust that cannot be bridged with Wormhole
/// due to the decimal shift in the Wormhole Bridge contract.
/// See https://github.com/wormhole-foundation/wormhole/blob/96682bdbeb7c87bfa110eade0554b3d8cbf788d2/ethereum/contracts/bridge/Bridge.sol#L276-L288
function normalize(uint256 amount) internal pure returns (uint256) {
// slither-disable-next-line divide-before-multiply
amount /= 10**10;
amount *= 10**10;
return amount;
}
}
contracts/integrator/AbstractBTCRedeemer.sol
// SPDX-License-Identifier: GPL-3.0-only
// ██████████████ ▐████▌ ██████████████
// ██████████████ ▐████▌ ██████████████
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ██████████████ ▐████▌ ██████████████
// ██████████████ ▐████▌ ██████████████
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
pragma solidity 0.8.17;
import {BTCUtils} from "@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "./IBridge.sol";
import "./IBank.sol";
import "./BitcoinTx.sol";
import "./ITBTCVault.sol";
/// @title Abstract AbstractBTCRedeemer contract.
/// @notice This abstract contract is meant to facilitate integration of protocols
/// aiming to use tBTC as an underlying Bitcoin bridge for redemptions.
///
/// Such an integrator is supposed to:
/// - Create a child contract inheriting from this abstract contract
/// - Call the `__AbstractBTCRedeemer_initialize` initializer function
/// - Use the `_requestRedemption` as part of their
/// business logic in order to request and track redemptions.
///
/// @dev Example usage:
/// ```
/// // Example upgradeable integrator contract.
/// contract ExampleBTCIntegrator is AbstractBTCRedeemer, Initializable {
/// /// @custom:oz-upgrades-unsafe-allow constructor
/// constructor() {
/// // Prevents the contract from being initialized again.
/// _disableInitializers();
/// }
///
/// function initialize(
/// address _bridge,
/// address _tbtcToken
/// ) external initializer {
/// __AbstractBTCRedeemer_initialize(_bridge, _tbtcToken);
/// }
///
/// function startRedemptionProcess(
/// bytes20 walletPubKeyHash,
/// BitcoinTx.UTXO memory mainUtxo,
/// bytes calldata redemptionOutputScript,
/// uint64 amount
/// ) external {
/// (uint256 redemptionKey, uint256 tbtcAmount) = _requestRedemption(
/// walletPubKeyHash,
/// mainUtxo,
/// redemptionOutputScript,
/// amount
/// );
///
/// // Use the redemptionKey to track the process.
/// // Use tbtcAmount to know the expected Bitcoin amount to be received.
/// }
/// }
abstract contract AbstractBTCRedeemer is OwnableUpgradeable {
using SafeERC20Upgradeable for IERC20Upgradeable;
using BTCUtils for bytes;
// Custom errors
error AlreadyInitialized();
error ZeroAddress();
error InsufficientBalance();
/// @notice Emitted when tBTC tokens are rescued from the contract.
/// @param recipient The address that received the rescued tBTC tokens.
/// @param amount The amount of tBTC rescued.
event TbtcRescued(address indexed recipient, uint256 amount);
/// @notice Multiplier to convert satoshi to TBTC token units.
uint256 public constant SATOSHI_MULTIPLIER = 10**10;
/// @notice Bridge contract address.
IBridge public thresholdBridge;
/// @notice TBTC token contract address.
IERC20Upgradeable public tbtcToken;
/// @notice Bank contract address.
IBank public bank;
/// @notice TBTC vault contract address.
ITBTCVault public tbtcVault;
// Reserved storage space that allows adding more variables without affecting
// the storage layout of the child contracts. The convention from OpenZeppelin
// suggests the storage space should add up to 50 slots. If more variables are
// added in the upcoming versions one needs to reduce the array size accordingly.
// See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
// slither-disable-next-line unused-state
uint256[46] private __gap;
/// @notice Initializes the contract. MUST BE CALLED from the child
/// contract initializer.
// slither-disable-next-line dead-code
function __AbstractBTCRedeemer_initialize(
address _thresholdBridge,
address _tbtcToken,
address _bank,
address _tbtcVault
) internal {
if (
address(thresholdBridge) != address(0) ||
address(tbtcToken) != address(0) ||
address(bank) != address(0)
) {
revert AlreadyInitialized();
}
if (_thresholdBridge == address(0)) revert ZeroAddress();
if (_tbtcToken == address(0)) revert ZeroAddress();
if (_bank == address(0)) revert ZeroAddress();
if (_tbtcVault == address(0)) revert ZeroAddress();
thresholdBridge = IBridge(_thresholdBridge);
tbtcToken = IERC20Upgradeable(_tbtcToken);
bank = IBank(_bank);
tbtcVault = ITBTCVault(_tbtcVault);
}
/// @notice Requests a redemption from the Bridge.
/// @param walletPubKeyHash The 20-byte wallet public key hash to redeem from.
/// @param mainUtxo The main UTXO of the specified wallet.
/// @param redemptionOutputScript The Bitcoin output script where the BTC should be sent.
/// @param amount The amount of tBTC (in satoshi equivalent) to redeem.
/// @return redemptionKey Redemption key computed as
/// `keccak256(keccak256(redemptionOutputScript) | walletPubKeyHash)`. This
/// key can be used to refer to the redemption in the Bridge.
/// @return tbtcAmount The net amount of Bitcoin (in tBTC token decimals precision)
/// expected to be received by the redeemer after fees.
/// @dev Requirements:
/// - This contract (AbstractBTCRedeemer instance) must have `amount` in its Bank balance.
/// - This contract must have approved the `thresholdBridge` to spend `amount` of its Bank balance.
/// - All requirements from {Bridge#requestRedemption} must be met.
// slither-disable-next-line dead-code
function _requestRedemption(
bytes20 walletPubKeyHash,
BitcoinTx.UTXO memory mainUtxo,
bytes memory redemptionOutputScript,
uint256 amount
) internal returns (uint256 redemptionKey, uint256 tbtcAmount) {
// Reset approval to 0 and approve the TBTC vault to pull tBTC tokens from
// this contract to proceed with unminting.
tbtcToken.safeApprove(address(tbtcVault), 0);
tbtcToken.safeApprove(address(tbtcVault), amount);
// Unmint tBTC tokens. This burns the ERC-20 tokens and credits this
// contract's balance in the Bank with the corresponding value in satoshis.
tbtcVault.unmint(amount);
// Convert the tBTC token amount (1e18 precision) to satoshis
// (1e8 precision) for Bridge operations.
uint64 amountInSatoshis = uint64(amount / SATOSHI_MULTIPLIER);
// This contract (as balanceOwner) approves the Bridge to spend its Bank balance.
// The amount for Bank allowance is in satoshi units (which is what `amount` already is).
bank.increaseBalanceAllowance(
address(thresholdBridge),
amountInSatoshis
);
// This contract calls the Bridge. The Bridge will see `msg.sender` (this contract) as the `balanceOwner`.
// The Bridge's internal Redemption logic will then call `bank.transferBalanceFrom(address(this), address(bridge_or_redemption_contract), amount)`.
// The actual `balanceOwner` parameter for Bridge.requestRedemption might be `address(this)` if the Bridge function signature supports it,
// or it might be implicitly msg.sender for the Bridge. Assuming msg.sender is balanceOwner for the Bridge call.
thresholdBridge.requestRedemption(
walletPubKeyHash,
mainUtxo,
redemptionOutputScript,
amountInSatoshis
);
redemptionKey = _getRedemptionKey(
walletPubKeyHash,
redemptionOutputScript
);
IBridgeTypes.RedemptionRequest memory redemption = thresholdBridge
.pendingRedemptions(redemptionKey);
tbtcAmount = _calculateTbtcAmount(
redemption.requestedAmount,
redemption.treasuryFee
);
}
/// @notice Calculates the net amount of Bitcoin the redeemer will receive.
/// @param redemptionAmountSat Requested redemption amount in satoshi (1e8 precision).
/// This is the gross amount of tBTC the user wants to convert to BTC.
/// @param redemptionTreasuryFeeSat Redemption treasury fee in satoshi (1e8 precision).
/// This is an accurate value of the treasury fee that was actually
/// charged for the redemption request.
/// @return tbtcAmount Net amount of Bitcoin (in tBTC token decimals precision)
/// expected to be sent to the redeemer's Bitcoin address.
/// @dev This function calculates the expected Bitcoin amount by subtracting
/// the treasury fee and the maximum Bitcoin transaction fee from the
/// requested redemption amount. The actual Bitcoin transaction fee might
/// be lower, but using the maximum ensures the user is aware of the
/// minimum BTC they will receive.
// slither-disable-next-line dead-code
function _calculateTbtcAmount(
uint64 redemptionAmountSat,
uint64 redemptionTreasuryFeeSat
) internal view virtual returns (uint256) {
// Both redemption amount and treasury fee are in the 1e8 satoshi precision.
// We need to convert them to the 1e18 TBTC precision.
uint256 amountSubTreasury = (redemptionAmountSat -
redemptionTreasuryFeeSat) * SATOSHI_MULTIPLIER;
(, , uint64 redemptionTxMaxFee, , , , ) = thresholdBridge
.redemptionParameters();
uint256 txMaxFee = redemptionTxMaxFee * SATOSHI_MULTIPLIER;
return amountSubTreasury - txMaxFee;
}
/// @notice Calculate redemption key without allocations.
/// @param walletPubKeyHash the pubkey hash of the wallet.
/// @param script the output script of the redemption.
/// @return The key = keccak256(keccak256(script) | walletPubKeyHash).
function _getRedemptionKey(bytes20 walletPubKeyHash, bytes memory script)
internal
pure
returns (uint256)
{
bytes32 scriptHash = keccak256(script);
uint256 key;
/* solhint-disable-next-line no-inline-assembly */
assembly {
mstore(0, scriptHash)
mstore(32, walletPubKeyHash)
key := keccak256(0, 52)
}
return key;
}
/// @notice Allows the contract owner to recover tBTC tokens that may
/// remain stuck in this contract. This could happen if a redemption
/// fails or is canceled, leaving some tBTC behind.
/// @param recipient The address that will receive the rescued tBTC tokens.
/// @param amount The amount of tBTC (in 18 decimal precision) to transfer.
function rescueTbtc(address recipient, uint256 amount) external onlyOwner {
if (recipient == address(0)) revert ZeroAddress();
if (tbtcToken.balanceOf(address(this)) < amount) {
revert InsufficientBalance();
}
tbtcToken.safeTransfer(recipient, amount);
// slither-disable-next-line reentrancy-events
emit TbtcRescued(recipient, amount);
}
}
contracts/integrator/BitcoinTx.sol
// SPDX-License-Identifier: GPL-3.0-only
// ██████████████ ▐████▌ ██████████████
// ██████████████ ▐████▌ ██████████████
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ██████████████ ▐████▌ ██████████████
// ██████████████ ▐████▌ ██████████████
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
pragma solidity 0.8.17;
import {ValidateSPV} from "@keep-network/bitcoin-spv-sol/contracts/ValidateSPV.sol";
/// @title Bitcoin transaction
/// @notice Allows to reference Bitcoin raw transaction in Solidity.
/// @dev See https://developer.bitcoin.org/reference/transactions.html#raw-transaction-format
// slither-disable-next-line name-reused
library BitcoinTx {
using ValidateSPV for bytes32;
/// @notice Represents info about an unspent transaction output.
struct UTXO {
/// @notice Hash of the transaction the output belongs to.
/// @dev Byte order corresponds to the Bitcoin internal byte order.
bytes32 txHash;
/// @notice Index of the transaction output (0-indexed).
uint32 txOutputIndex;
/// @notice Value of the transaction output.
uint64 txOutputValue;
// This struct doesn't contain `__gap` property as the structure is not
// stored, it is used as a function's calldata argument.
}
}
contracts/integrator/IBank.sol
// SPDX-License-Identifier: GPL-3.0-only
// ██████████████ ▐████▌ ██████████████
// ██████████████ ▐████▌ ██████████████
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ██████████████ ▐████▌ ██████████████
// ██████████████ ▐████▌ ██████████████
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
pragma solidity ^0.8.0;
/// @notice Interface of the Bank contract.
/// @dev See bank/Bank.sol
interface IBank {
/// @notice Emitted when an approval for `spender` to transfer `value`
/// tokens from `owner` is set.
event BalanceApproval(
address indexed owner,
address indexed spender,
uint256 value
);
/// @notice Emitted when `value` tokens are transferred from `from` to `to`.
event TransferBalance(
address indexed from,
address indexed to,
uint256 value
);
/// @notice Increase the allowance of the spender address.
/// @param spender Address of the spender.
/// @param amount Amount of the allowance to increase.
function increaseBalanceAllowance(address spender, uint256 amount) external;
/// @notice Returns the amount of tokens owned by `account`.
function balanceAvailable(address account) external view returns (uint256);
/// @notice Transfers `amount` tokens from `sender` to `recipient` using
/// the allowance mechanism.
/// @param sender Address of the sender.
/// @param recipient Address of the recipient.
/// @param amount Amount of tokens to transfer.
/// @return A boolean value indicating whether the operation succeeded.
function transferBalanceFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
}
contracts/integrator/IBridge.sol
// SPDX-License-Identifier: GPL-3.0-only
// ██████████████ ▐████▌ ██████████████
// ██████████████ ▐████▌ ██████████████
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ██████████████ ▐████▌ ██████████████
// ██████████████ ▐████▌ ██████████████
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
pragma solidity ^0.8.0;
import "./BitcoinTx.sol";
/// @notice Namespace which groups all types relevant to the IBridge interface.
/// @dev This is a mirror of the real types used in the Bridge contract.
/// This way, the `integrator` subpackage does not need to import
/// anything from the `bridge` subpackage and explicitly depend on it.
/// This simplifies the dependency graph for integrators.
library IBridgeTypes {
/// @dev See bridge/BitcoinTx.sol#Info
struct BitcoinTxInfo {
bytes4 version;
bytes inputVector;
bytes outputVector;
bytes4 locktime;
}
/// @dev See bridge/Deposit.sol#DepositRevealInfo
struct DepositRevealInfo {
uint32 fundingOutputIndex;
bytes8 blindingFactor;
bytes20 walletPubKeyHash;
bytes20 refundPubKeyHash;
bytes4 refundLocktime;
address vault;
}
/// @dev See bridge/Deposit.sol#DepositRequest
struct DepositRequest {
address depositor;
uint64 amount;
uint32 revealedAt;
address vault;
uint64 treasuryFee;
uint32 sweptAt;
bytes32 extraData;
}
/// @dev See bridge/Redemption.sol#RedemptionRequest
struct RedemptionRequest {
address redeemer;
uint64 requestedAmount;
uint64 treasuryFee;
uint64 txMaxFee;
uint32 requestedAt;
}
}
/// @notice Interface of the Bridge contract.
/// @dev See bridge/Bridge.sol
interface IBridge {
/// @dev See {Bridge#revealDepositWithExtraData}
function revealDepositWithExtraData(
IBridgeTypes.BitcoinTxInfo calldata fundingTx,
IBridgeTypes.DepositRevealInfo calldata reveal,
bytes32 extraData
) external;
/// @dev See {Bridge#deposits}
function deposits(uint256 depositKey)
external
view
returns (IBridgeTypes.DepositRequest memory);
/// @dev See {Bridge#depositParameters}
function depositParameters()
external
view
returns (
uint64 depositDustThreshold,
uint64 depositTreasuryFeeDivisor,
uint64 depositTxMaxFee,
uint32 depositRevealAheadPeriod
);
/// @dev See {Bridge#requestRedemption}
function requestRedemption(
bytes20 walletPubKeyHash,
BitcoinTx.UTXO calldata mainUtxo,
bytes calldata redeemerOutputScript,
uint64 amount
) external;
/// @dev See {Bridge#pendingRedemptions}
function pendingRedemptions(uint256 redemptionKey)
external
view
returns (IBridgeTypes.RedemptionRequest memory);
/// @dev See {Bridge#redemptionParameters}
function redemptionParameters()
external
view
returns (
uint64 redemptionDustThreshold,
uint64 redemptionTreasuryFeeDivisor,
uint64 redemptionTxMaxFee,
uint64 redemptionTxMaxTotalFee,
uint32 redemptionTimeout,
uint96 redemptionTimeoutSlashingAmount,
uint32 redemptionTimeoutNotifierRewardMultiplier
);
}
contracts/integrator/ITBTCVault.sol
// SPDX-License-Identifier: GPL-3.0-only
// ██████████████ ▐████▌ ██████████████
// ██████████████ ▐████▌ ██████████████
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ██████████████ ▐████▌ ██████████████
// ██████████████ ▐████▌ ██████████████
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
// ▐████▌ ▐████▌
pragma solidity ^0.8.0;
/// @notice Interface of the TBTCVault contract.
/// @dev See vault/TBTCVault.sol
interface ITBTCVault {
/// @dev See {TBTCVault#optimisticMintingRequests}
function optimisticMintingRequests(uint256 depositKey)
external
returns (uint64 requestedAt, uint64 finalizedAt);
/// @dev See {TBTCVault#optimisticMintingFeeDivisor}
function optimisticMintingFeeDivisor() external view returns (uint32);
/// @dev See {TBTCVault#tbtcToken}
function tbtcToken() external view returns (address);
/// @dev See {TBTCVault#unmint}
function unmint(uint256 amount) external;
}
Compiler settingsShow
{
"metadata": {
"useLiteralContent": true
},
"optimizer": {
"runs": 1000,
"enabled": true
}
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.