Verified contractExactMIT
Ibc
Address0x6dec5ad62b6faa830a17e8ef08ae94a19eb18b77
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.28
- Same code
Only this contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- No
- EVM version
- paris
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,427,171
- Creation transaction
- 0xcb202b284d…3e082cf7ce
7 files
- contracts/bridge/Ibc.solmain19.36 KB
- @openzeppelin/contracts/access/Ownable.sol3.1 KB
- @openzeppelin/contracts/utils/Address.sol6 KB
- @openzeppelin/contracts/utils/Context.sol963 B
- @openzeppelin/contracts/utils/Errors.sol896 B
- @openzeppelin/contracts/utils/ReentrancyGuard.sol3.38 KB
- contracts/utils/AcurastP256.sol3.74 KB
contracts/bridge/Ibc.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import {AcurastP256} from "../utils/AcurastP256.sol";
contract Ibc is Ownable, ReentrancyGuard {
/*
A constant that represents this chain as a recipient. It's the enum index of this Acurast enum:
pub enum Subject<AccountId, Contract> {
Acurast(Layer<AccountId, Contract>) = 0,
AlephZero(Layer<AccountId32, Contract>) = 1,
Vara(Layer<AccountId32, Contract>) = 2,
Ethereum(Layer<AccountId20, AccountId20>) = 3,
Solana(Layer<AccountId32, AccountId32>) = 4
}
*/
uint8 public constant ACURAST_INDEX = 0;
uint8 public constant ETHEREUM_INDEX = 3;
Config public config;
mapping(bytes32 => OutgoingMessageWithMeta) public outgoing;
mapping(bytes32 => IncomingMessageWithMeta) public incoming;
// The message counter is not read in the contract but very helpful for clients/indexers to know which new messages to index. Works around the limitation that solidity mappings cannot be iterated from clients.
uint256 public messageCounter;
// Whitelisted oracle P-256 (secp256r1) keys: the 33-byte compressed key `0x02|0x03 || x`, exactly as
// published on Acurast. P-256 has no ecrecover, so each signature carries its key and is checked against
// this set.
mapping(bytes => bool) public oracles;
// _owner: who may add oracles and configure; Ownable rejects the zero address.
constructor(address _owner) Ownable(_owner) {
// Fail the deployment instead of deploying a contract that can never accept a signature.
require(AcurastP256.isPrecompileAvailable(), "P256VERIFY unavailable");
config = Config({
minDeliverySignatures: 3,
minReceiptSignatures: 3,
minTTL: 20,
maxTTL: 200,
incomingTTL: 30
});
}
// An oracle's signature over a message digest: raw P-256 ECDSA (r, s), not low-s normalized, with the
// signer's uncompressed public key (x, y).
//
// The digest, signed as a raw prehash, is keccak256(abi.encodePacked(block.chainid, address(this), <message>)).
// Chain id and contract address bind it to this deployment, so signatures cannot be replayed against another
// Ibc instance, e.g. a redeployment whose `incoming` index starts empty or an Ibc paired with another Acurast
// network. Both are fixed-length and <message> has a single dynamic field, so the packed encoding stays
// unambiguous; its first byte (ETHEREUM_INDEX vs ACURAST_INDEX) tells deliveries from receipts.
struct OracleSignature {
bytes32 r;
bytes32 s;
bytes32 x;
bytes32 y;
}
struct Config {
uint8 minDeliverySignatures;
uint8 minReceiptSignatures;
uint256 minTTL;
uint256 maxTTL;
uint256 incomingTTL;
}
struct OutgoingMessage {
bytes32 id;
// uint8 senderIndex; <- since we know senderIndex is always ETHEREUM_INDEX it's redundant to store
address sender;
bytes32 nonce;
uint8 recipientIndex;
bytes32 recipient;
bytes payload;
}
struct IncomingMessage {
bytes32 id;
uint8 senderIndex;
bytes32 sender;
bytes32 nonce;
// uint8 recipientIndex; <- since we know recipientIndex is always ETHEREUM_INDEX it's redundant to store
address recipient;
bytes payload;
}
struct OutgoingMessageWithMeta {
OutgoingMessage message;
uint256 currentBlock;
uint256 ttlBlock;
uint256 fee;
}
struct IncomingMessageWithMeta {
IncomingMessage message;
uint256 currentBlock;
// The relayer denotes the trustless service that issues transactions to relay (=transport) messages from sender to recipient chain. It can do so only with the signatures it requests form oracles.
// These oracles are in turn trusted and run as Acurast Processors inheriting all the security properties the Acurast protocol provides.
// These separation achieves that the oracles do not need to issue any transaction on chains and therefore do not need funds, avoiding cumbersome management of their balances and loosing funds on oracles no longer responding.
// (they cannot be claimed back since the processors private key only lives in TPM module)
//
// -> The relayer is stored solely to avoid front-running from other relayers and claiming the reward at the source chain.
// It is part of the oracle-signed digest in receiveMessage, so only the relayer the oracles signed for can be recorded.
bytes32 relayer;
}
// `publicKey` is the 33-byte compressed key as published on Acurast (assignment.pubKeys[].SECP256r1).
event OracleAdded(bytes publicKey);
event OracleRemoved(bytes publicKey);
event MessageReadyToSend(OutgoingMessage message);
event MessageDelivered(bytes32 id);
event MessageProcessed(bytes32 id);
event MessageProcessedWithErrors(
uint8 senderIndex,
bytes32 sender,
// uint8 recipientIndex; <- since we know recipientIndex is always ETHEREUM_INDEX it's redundant to emit in event
address recipient,
bytes payload,
string reason
);
// Emitted when the orphaned fee of an expired message is returned, either while that
// message slot is being overwritten by a new sendMessage with the same nonce (e.g. a
// retry) or when the sender claims it explicitly via refundStaleFee. `recipient` is
// where the fee went, which is the message's sender unless it nominated another
// account when claiming.
event FeeRefunded(
bytes32 indexed id,
address indexed recipient,
uint256 amount
);
function configure(
uint8 minDeliverySignatures,
uint8 minReceiptSignatures,
uint256 minTTL,
uint256 maxTTL,
uint256 incomingTTL
) public onlyOwner {
// Zero would accept messages without any oracle signature.
require(
minDeliverySignatures > 0 && minReceiptSignatures > 0,
"Min signatures must be positive"
);
config.minDeliverySignatures = minDeliverySignatures;
config.minReceiptSignatures = minReceiptSignatures;
config.minTTL = minTTL;
config.maxTTL = maxTTL;
config.incomingTTL = incomingTTL;
}
// Takes the 33-byte compressed P-256 key exactly as published on Acurast, so it can be compared byte for
// byte with the oracle processor's job assignment. Whether it is a point on the curve is not checked here:
// a key that is not can never produce a valid signature.
function addOracle(bytes calldata publicKey) external onlyOwner {
require(
publicKey.length == 33 && (publicKey[0] == 0x02 || publicKey[0] == 0x03),
"Invalid public key"
);
require(!oracles[publicKey], "Oracle already added");
oracles[publicKey] = true;
emit OracleAdded(publicKey);
}
function removeOracle(bytes calldata publicKey) external onlyOwner {
require(oracles[publicKey], "Oracle not found");
delete oracles[publicKey];
emit OracleRemoved(publicKey);
}
function sendMessage(
bytes32 nonce,
bytes32 recipient,
bytes memory payload,
uint256 ttl
) public payable nonReentrant returns (bool) {
require(ttl >= config.minTTL, "TTL too small");
require(ttl <= config.maxTTL, "TTL too large");
bytes32 id = keccak256(abi.encodePacked(msg.sender, nonce));
uint256 staleFee = 0;
// Solidity returns default value for maps if key does not exist, so check for non-zero value
if (outgoing[id].ttlBlock != 0) {
// potential duplicate found: check for ttl
if (outgoing[id].ttlBlock >= block.number) {
revert("Message with same nonce pending");
}
// The prior message expired and is about to be overwritten. Capture its
// orphaned relayer fee so it is returned instead of being lost. Since `id`
// binds to msg.sender, the previous sender is always the current caller.
// Only the ETH relayer fee is ever refunded here — never the bridged asset,
// which is not held by this contract.
staleFee = outgoing[id].fee;
// continue below and overwrite message
}
outgoing[id] = OutgoingMessageWithMeta({
message: OutgoingMessage({
id: id,
sender: msg.sender,
nonce: nonce,
recipientIndex: ACURAST_INDEX,
recipient: recipient,
payload: payload
}),
currentBlock: block.number,
ttlBlock: block.number + ttl,
// make sure the exact value payed to this contract at the moment of sendMessage is stored for later payout to the relayer
fee: msg.value
});
messageCounter++;
emit MessageReadyToSend(outgoing[id].message);
// Interaction last (checks-effects-interactions). The new message state is
// already committed above, so refunding the previous fee cannot orphan it.
if (staleFee > 0) {
// sendValue, not transfer: a 2300 gas stipend cannot pay a recipient whose
// receive() does real work. Reentrancy is covered by nonReentrant.
Address.sendValue(payable(msg.sender), staleFee);
emit FeeRefunded(id, msg.sender, staleFee);
}
return true;
}
// Returns the orphaned relayer fee of an expired outgoing message, without requiring a
// new sendMessage under the same nonce. Only the ETH fee, never the bridged asset.
//
// `id` binds to msg.sender, so only the message's sender can claim, and only once.
// `recipient` just says where that sender wants its own money, which lets a contract
// that sent on a user's behalf (e.g. HyperdriveTokenBridge) pay the user directly
// instead of custodying the fee. It does not widen who may claim.
function refundStaleFee(
bytes32 nonce,
address recipient
) external nonReentrant returns (uint256) {
require(recipient != address(0), "Invalid recipient");
bytes32 id = keccak256(abi.encodePacked(msg.sender, nonce));
// Solidity returns default value for maps if key does not exist, so check for non-zero value
require(outgoing[id].ttlBlock != 0, "Message not found");
require(
outgoing[id].ttlBlock < block.number,
"Message with same nonce pending"
);
uint256 staleFee = outgoing[id].fee;
// Effects before interaction (checks-effects-interactions): dropping the expired
// message makes the claim non-repeatable and frees the nonce for a fresh send.
delete outgoing[id];
if (staleFee > 0) {
// sendValue, not transfer: a 2300 gas stipend cannot pay a recipient whose
// receive() does real work. Guarded by nonReentrant plus the delete above.
Address.sendValue(payable(recipient), staleFee);
emit FeeRefunded(id, recipient, staleFee);
}
return staleFee;
}
function confirmMessageDelivery(
bytes32 id,
OracleSignature[] calldata signatures
) external {
require(outgoing[id].message.id != 0, "Message not found"); // Ensure message exists
require(
outgoing[id].ttlBlock >= block.number,
"Delivery confirmation overdue"
);
// since id is hash of sender + nonce, it's not necessary to be part of signed payload
bytes32 messageHash = keccak256(
abi.encodePacked(
block.chainid,
address(this),
ETHEREUM_INDEX,
outgoing[id].message.sender,
outgoing[id].message.nonce,
outgoing[id].message.recipientIndex,
outgoing[id].message.recipient,
outgoing[id].message.payload,
msg.sender // ensures no front-running of competing relayer trying to get fee
)
);
checkSignatures(messageHash, signatures, config.minDeliverySignatures); // Ensure valid signature
// SECURITY FIX: Follow checks-effects-interactions pattern
// Store fee amount and payer before deleting state
uint256 feeAmount = outgoing[id].fee;
address payable feeReceiver = payable(msg.sender);
// Update state before external call
delete outgoing[id];
// sendValue, not transfer: a 2300 gas stipend cannot pay a recipient whose
// receive() does real work.
//
// Deliberately the one full-gas payout here without nonReentrant, because it runs on
// every delivery and the guard would tax that permanently. Reentry is harmless: the
// fee is deleted above, so this id cannot pay twice, and any other id needs oracle
// signatures naming the re-entrant caller as relayer -- which it could have used
// directly. Keep the delete before the send; that ordering is what makes this safe.
Address.sendValue(feeReceiver, feeAmount);
emit MessageDelivered(id);
}
function receiveMessage(
bytes32 acurastSender,
bytes32 nonce,
uint8 recipientIndex,
address recipient,
bytes memory payload,
bytes32 relayer,
OracleSignature[] calldata signatures
) external nonReentrant {
// since id is hash of acurastSender + nonce, it's not necessary for the id to be part of signed payload.
// `relayer` is signed so a front-runner copying this tx from the mempool cannot swap in its own id:
// the Acurast pallet only pays the delivery fee to the relayer recorded here, so a swapped one would
// revert the honest tx and strand the fee.
bytes32 messageHash = keccak256(
abi.encodePacked(
block.chainid,
address(this),
ACURAST_INDEX,
acurastSender,
nonce,
recipientIndex,
recipient,
payload,
relayer
)
);
require(
recipientIndex == ETHEREUM_INDEX,
"Message recipientIndex invalid"
);
checkSignatures(messageHash, signatures, config.minReceiptSignatures); // Ensure valid signature
bytes32 id = keccak256(abi.encodePacked(acurastSender, nonce));
require(incoming[id].message.id == 0, "Message already received");
incoming[id] = IncomingMessageWithMeta({
message: IncomingMessage({
id: id,
senderIndex: ACURAST_INDEX,
sender: acurastSender,
nonce: nonce,
// uint8 recipientIndex <- since we know recipientIndex is always ETHEREUM_INDEX it's redundant to store
recipient: recipient,
payload: payload
}),
currentBlock: block.number,
relayer: relayer
});
require(recipient.code.length > 0, "Recipient is not a contract");
(bool success, bytes memory returnData) = recipient.call(
abi.encodeWithSignature(
"processMessage(bytes32,bytes)",
acurastSender,
payload
)
);
if (!success) {
string memory errorMessage = _getRevertReason(returnData);
emit MessageProcessedWithErrors(
ACURAST_INDEX,
acurastSender,
recipient,
payload,
errorMessage
);
return;
}
emit MessageProcessed(id);
}
function _getRevertReason(
bytes memory returnData
) private pure returns (string memory) {
if (returnData.length < 68) return "Unknown failure";
assembly {
returnData := add(returnData, 0x04) // Skip function selector
}
return abi.decode(returnData, (string));
}
function checkSignatures(
bytes32 messageHash,
OracleSignature[] calldata signatures,
uint8 min_signatures
) internal view {
require(signatures.length >= min_signatures, "Not enough signatures");
bytes32[] memory seenOracles = new bytes32[](min_signatures);
uint256 validSignatures = 0;
// Stops as soon as enough unique valid signatures are found. Invalid, stray and duplicate
// signatures are skipped rather than failing the batch, as long as enough valid ones remain.
for (
uint256 i = 0;
i < signatures.length && validSignatures < min_signatures;
i++
) {
OracleSignature calldata sig = signatures[i];
// The signer's compressed key: y's parity picks the prefix. For a given x only one point has that
// parity, so a y that does not match the registered key fails P256VERIFY below.
bytes memory publicKey = abi.encodePacked(
bytes1(uint8(2 + (uint256(sig.y) & 1))),
sig.x
);
// Skip keys that are not authorized oracles. Checked first because it is cheaper than the
// precompile.
if (!oracles[publicKey]) {
continue;
}
bytes32 id = keccak256(publicKey);
// Skip duplicates - only count each oracle once. Only verified signatures are in seenOracles, so an
// invalid signature placed first cannot shadow a valid one by the same oracle.
bool duplicate = false;
for (uint256 j = 0; j < validSignatures; j++) {
if (seenOracles[j] == id) {
duplicate = true;
break;
}
}
if (duplicate) {
continue;
}
// Returns false (never reverts) on any invalid signature, including high-s twins of other
// signatures, which is fine since uniqueness is by oracle key, not by signature bytes.
if (!AcurastP256.verify(messageHash, sig.r, sig.s, sig.x, sig.y)) {
continue;
}
seenOracles[validSignatures] = id;
validSignatures++;
}
// Ensure we have enough unique valid signatures
require(
validSignatures >= min_signatures,
"Not enough unique valid signatures"
);
}
function cleanIncomingIndex(bytes32[] calldata clean) external onlyOwner {
for (uint256 i = 0; i < clean.length; i++) {
if (
incoming[clean[i]].currentBlock + config.incomingTTL <
block.number
) {
delete incoming[clean[i]];
}
}
}
}
@openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
@openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @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://consensys.net/diligence/blog/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.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
(bool success, bytes memory returndata) = recipient.call{value: amount}("");
if (!success) {
_revert(returndata);
}
}
/**
* @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 or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* 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.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @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`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
*/
function _revert(bytes memory returndata) 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
assembly ("memory-safe") {
revert(add(returndata, 0x20), mload(returndata))
}
} else {
revert Errors.FailedCall();
}
}
}
@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
@openzeppelin/contracts/utils/Errors.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}
@openzeppelin/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
contracts/utils/AcurastP256.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @title AcurastP256
/// @notice Verifies Acurast processor P-256 (secp256r1) ECDSA signatures with the EIP-7951 `P256VERIFY`
/// precompile at address 0x100.
///
/// @dev Taken from eth-p256-sign-poc (`src/AcurastP256.sol`), reduced to {verify} on the uncompressed key and
/// extended by {isPrecompileAvailable} for a deployment-time probe.
///
/// Acurast format: the device signs its 32-byte input as a raw ECDSA prehash (no prefix, no second hash)
/// and emits raw `r || s` (64 bytes, not low-s normalized). Its public key is published on the Acurast
/// chain as a 33-byte compressed point `0x02|0x03 || X`; callers pass the uncompressed `(x, y)`, which maps
/// directly onto the precompile input `digest || r || s || x || y`.
///
/// The precompile never fails the call: any invalid input (r or s outside (0, n), coordinates >= p, point
/// not on the curve or at infinity, mismatch) returns empty data. Invalid signatures therefore yield
/// `false`, and verification fails closed on chains where 0x100 is an empty account. A precompile call
/// that itself fails can only be out of gas, and is surfaced as a revert so that `false` always means
/// "invalid signature".
///
/// @custom:security Signatures are malleable: `(r, s)` and `(r, n - s)` both verify, so never use signature
/// bytes as a nonce or identifier. A digest of 0 or n is rejected: for h ≡ 0 (mod n) ECDSA
/// admits a universal forgery (any key, no private key needed). Prefer hashing the message
/// on-chain over accepting a caller-supplied digest, and bind messages to chain id, verifying
/// contract and a nonce.
library AcurastP256 {
/// @dev Group order n.
uint256 internal constant N = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551;
/// @notice Verify a signature over `digest` against the uncompressed public key `(x, y)`. ~7.1k gas.
function verify(bytes32 digest, bytes32 r, bytes32 s, bytes32 x, bytes32 y) internal view returns (bool ok) {
if (digest == 0 || digest == bytes32(N)) return false; // h ≡ 0 (mod n): universal forgery
assembly ("memory-safe") {
let ptr := mload(0x40) // scratch above the free pointer; nothing allocates before we read it
mstore(ptr, digest)
mstore(add(ptr, 0x20), r)
mstore(add(ptr, 0x40), s)
mstore(add(ptr, 0x60), x)
mstore(add(ptr, 0x80), y)
if iszero(staticcall(gas(), 0x100, ptr, 0xa0, ptr, 0x20)) { revert(0, 0) } // out of gas
// On empty return `mload(ptr)` still holds `digest`, so the size check is required.
ok := and(eq(returndatasize(), 0x20), eq(mload(ptr), 1))
}
}
/// @notice True iff a conforming P256VERIFY is live on this chain: a known-good Acurast SDK vector must
/// verify with both its low-s and high-s form, and must fail for a tampered digest.
function isPrecompileAvailable() internal view returns (bool) {
bytes32 d = 0xbb67a3ba9ac64fb89ab480f634755f0d92c263f980b8705dbb24b3010a3b1e69;
bytes32 r = 0xe0fdb186b140de795f73c30ed8c269a2a71ba4c062502c8befe85d38044fd9ec;
bytes32 s = 0x4a3246b6ba7fb06045a2d121e4f6c8e2aa90be01b5a96502e8e53407bbb13bc2;
bytes32 x = 0x97e0c76ca850349cfb7684121c5fc7516f7ff3300bf047631cc8e6b155b56758;
bytes32 y = 0x117b227d500ba6791571a2d09206063d243ffe36d26c85e85bf8e86409d7ce6f;
return verify(d, r, s, x, y) && verify(d, r, bytes32(N - uint256(s)), x, y)
&& !verify(d ^ bytes32(uint256(1)), r, s, x, y);
}
}
Compiler settingsShow
{
"optimizer": {
"runs": 200,
"enabled": false
},
"evmVersion": "paris"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.