Verified contractExactMIT
ScribeOffboarder
Address0x967a51a9628285b94e5cef437bfd2a6bef1a0d2d
- Balance
0 ETH
- Transactions
20
- Compiler
solc 0.8.16
- Same code
Only this contract
Details
- Compiler
- solc 0.8.16+commit.07a7930e
- Language
- solidity
- Optimization
- Yes, 10,000 runs
- EVM version
- london
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 24,934,463
- Creation transaction
- 0x76785d1301…20d6b005e8
6 files
- script/offboard/ScribeOffboarder.solmain7.66 KB
- lib/chronicle-std/src/IChronicle.sol1.45 KB
- lib/chronicle-std/src/auth/Auth.sol4.66 KB
- lib/chronicle-std/src/auth/IAuth.sol1.75 KB
- src/IScribe.sol10.61 KB
- src/libs/LibSecp256k1.sol13.52 KB
script/offboard/ScribeOffboarder.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;
import {Auth} from "chronicle-std/auth/Auth.sol";
import {IAuth} from "chronicle-std/auth/IAuth.sol";
import {IScribe} from "../../src/IScribe.sol";
import {LibSecp256k1} from "../../src/libs/LibSecp256k1.sol";
/**
* @title ScribeOffboarder
*
* @notice Permanently disables a `Scribe` oracle in a single transaction.
* The contract must be granted `auth` on the target scribe.
*
* `offboard(scribe)` enumerates every currently-lifted feed, drops
* them, sets bar = 1, lifts the hardcoded offboarder feed, pokes
* val = 0, drops the offboarder feed, and raises bar = 255.
*
* @dev Security note: the offboarder feed's private key is hardcoded as a
* `constant` in the bytecode and is therefore publicly readable. This
* is intentional; the feed is only lifted inside an offboarder call
* and dropped again before the transaction returns, so any signatures
* craftable from the leaked key require the attacker to already hold
* `auth` on the scribe and re-lift the feed (at which point they could
* poke arbitrary values directly anyway).
*/
contract ScribeOffboarder is Auth {
// -----------------------------------------------------------------------------
// Hardcoded Offboarder Feed
//
// All four values below are derived from a single string seed:
//
// SEED = "Chronicle.ScribeOffboarder.v1"
// FEED_PRIV_KEY = uint(keccak256(SEED)) mod Q
// pubKey = vm.createWallet(FEED_PRIV_KEY).{publicKeyX, publicKeyY}
// ECDSA(v,r,s) = vm.sign(FEED_PRIV_KEY, FEED_REGISTRATION_MESSAGE)
//
// where Q is the order of secp256k1 and
//
// FEED_REGISTRATION_MESSAGE =
// keccak256(
// "\x19Ethereum Signed Message:\n32" ‖
// keccak256("Chronicle Feed Registration")
// )
//
// FEED_REGISTRATION_MESSAGE is a Scribe protocol constant (see
// `Scribe.feedRegistrationMessage`), so the ECDSA signature below is
// valid against every Scribe deployment.
/// @dev `keccak256("Chronicle.ScribeOffboarder.v1") mod Q`.
uint private constant FEED_PRIV_KEY =
0xf067ac0350b6ab5e39cf9138ae16508404c05af8b58676e07ae14e9a510a600e;
uint private constant FEED_PUBKEY_X =
0xc2f3bfebb984817bbcaaf2b8e185259b09493f6db4b2c30d7b4feca89f7a64b2;
uint private constant FEED_PUBKEY_Y =
0x53a0dc54c1d22a62fbb1b3724737486c7e61c26080a44817eef7f5992a521a40;
/// @notice Feed id is the highest-order byte of the ethereum address
/// derived from the offboarder feed's public key
/// (= 0x03da1Db2b7875106395548682B068a7C7b296902 => id = 0x03).
uint8 private constant FEED_ID = 0x03;
// ECDSA signature over FEED_REGISTRATION_MESSAGE by FEED_PRIV_KEY.
uint8 private constant LIFT_V = 28;
bytes32 private constant LIFT_R =
0xc9988947c96dd6899cc097e3979b1e4d9228e09b4bc7cf53a9e0fe2ff395a77c;
bytes32 private constant LIFT_S =
0x76ec989c8765878f18daceb7893ea2c24b1a87401c847e240a1301c3565f8dd7;
// -----------------------------------------------------------------------------
// secp256k1 Constants
/// @dev x-coordinate of the secp256k1 generator G.
uint private constant G_X =
0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798;
/// @dev Order of the secp256k1 group.
uint private constant Q =
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141;
/// @dev `v` value corresponding to G (G_y is even, so parity = 0).
uint8 private constant G_V = 27;
// -----------------------------------------------------------------------------
// Events
event Offboarded(address indexed caller, address indexed scribe);
// -----------------------------------------------------------------------------
// Constructor
constructor(address initialAuthed) Auth(initialAuthed) {}
// -----------------------------------------------------------------------------
// Offboard
/// @notice Offboards `scribe` in a single transaction: enumerates the
/// currently-lifted feeds, drops them, sets bar = 1, lifts the
/// hardcoded offboarder feed, pokes val = 0, drops the
/// offboarder feed, and raises bar = 255.
function offboard(address scribe) external auth {
require(IAuth(scribe).authed(address(this)));
IScribe target = IScribe(scribe);
// Drop every currently-lifted feed.
address[] memory currentFeeds = target.feeds();
if (currentFeeds.length != 0) {
uint8[] memory ids = new uint8[](currentFeeds.length);
for (uint i; i < currentFeeds.length; i++) {
ids[i] = uint8(uint(uint160(currentFeeds[i])) >> 152);
}
target.drop(ids);
}
// Set bar to one and lift the offboarder feed.
target.setBar(1);
target.lift(
LibSecp256k1.Point({x: FEED_PUBKEY_X, y: FEED_PUBKEY_Y}),
IScribe.ECDSAData({v: LIFT_V, r: LIFT_R, s: LIFT_S})
);
// Poke val = 0 via the offboarder feed's 1-of-1 Schnorr signature.
uint32 pokeAge = uint32(block.timestamp);
bytes32 message = target.constructPokeMessage(
IScribe.PokeData({val: 0, age: pokeAge})
);
(bytes32 signature, address commitment) = _signSchnorr(message);
target.poke(
IScribe.PokeData({val: 0, age: pokeAge}),
IScribe.SchnorrData({
signature: signature,
commitment: commitment,
feedIds: abi.encodePacked(FEED_ID)
})
);
target.drop(FEED_ID);
// Set bar to max.
target.setBar(type(uint8).max);
// Deny offboarder.
IAuth(scribe).deny(address(this));
emit Offboarded(msg.sender, scribe);
}
// -----------------------------------------------------------------------------
// Internal — Schnorr signing
/// @dev Produces a 1-of-1 Schnorr signature over `message` using the
/// hardcoded offboarder feed.
///
/// The ethereum address `R_e = address(k·G)` is computed via the
/// ecrecover precompile trick rather than a full secp256k1 scalar
/// multiplication: with `h = 0`, `r = G_x`, `v = G_v`,
/// `s = k·G_x mod Q`, ecrecover returns exactly `address(k·G)` —
/// which is all the signing scheme needs as the commitment.
///
/// See the scribe repo's `docs/Schnorr.md` for the scheme this
/// implements.
function _signSchnorr(bytes32 message)
internal
pure
returns (bytes32 signature, address commitment)
{
// k = H(privKey ‖ m) mod Q
uint nonce =
uint(keccak256(abi.encodePacked(FEED_PRIV_KEY, message))) % Q;
// R_e = address(k·G) via the ecrecover trick.
commitment = ecrecover(
bytes32(0), G_V, bytes32(G_X), bytes32(mulmod(nonce, G_X, Q))
);
require(commitment != address(0), "ScribeOffboarder: bad commitment");
// e = H(Pₓ ‖ Pₚ ‖ m ‖ R_e) mod Q
uint challenge = uint(
keccak256(
abi.encodePacked(
FEED_PUBKEY_X, uint8(FEED_PUBKEY_Y & 1), message, commitment
)
)
) % Q;
// s = k + e·x mod Q
signature =
bytes32(addmod(nonce, mulmod(challenge, FEED_PRIV_KEY, Q), Q));
}
}
lib/chronicle-std/src/IChronicle.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;
/**
* @title IChronicle
*
* @notice Interface for Chronicle Protocol's oracle products
*/
interface IChronicle {
/// @notice Returns the oracle's identifier.
/// @return wat The oracle's identifier.
function wat() external view returns (bytes32 wat);
/// @notice Returns the oracle's current value.
/// @dev Reverts if no value set.
/// @return value The oracle's current value.
function read() external view returns (uint value);
/// @notice Returns the oracle's current value and its age.
/// @dev Reverts if no value set.
/// @return value The oracle's current value.
/// @return age The value's age.
function readWithAge() external view returns (uint value, uint age);
/// @notice Returns the oracle's current value.
/// @return isValid True if value exists, false otherwise.
/// @return value The oracle's current value if it exists, zero otherwise.
function tryRead() external view returns (bool isValid, uint value);
/// @notice Returns the oracle's current value and its age.
/// @return isValid True if value exists, false otherwise.
/// @return value The oracle's current value if it exists, zero otherwise.
/// @return age The value's age if value exists, zero otherwise.
function tryReadWithAge()
external
view
returns (bool isValid, uint value, uint age);
}
lib/chronicle-std/src/auth/Auth.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;
import {IAuth} from "./IAuth.sol";
/**
* @title Auth Module
*
* @dev The `Auth` contract module provides a basic access control mechanism,
* where a set of addresses are granted access to protected functions.
* These addresses are said to be _auth'ed_.
*
* Initially, the address given as constructor argument is the only address
* auth'ed. Through the `rely(address)` and `deny(address)` functions,
* auth'ed callers are able to grant/renounce auth to/from addresses.
*
* This module is used through inheritance. It will make available the
* modifier `auth`, which can be applied to functions to restrict their
* use to only auth'ed callers.
*/
abstract contract Auth is IAuth {
/// @dev Mapping storing whether address is auth'ed.
/// @custom:invariant Image of mapping is {0, 1}.
/// ∀x ∊ Address: _wards[x] ∊ {0, 1}
/// @custom:invariant Only address given as constructor argument is authenticated after deployment.
/// deploy(initialAuthed) → (∀x ∊ Address: _wards[x] == 1 → x == initialAuthed)
/// @custom:invariant Only functions `rely` and `deny` may mutate the mapping's state.
/// ∀x ∊ Address: preTx(_wards[x]) != postTx(_wards[x])
/// → (msg.sig == "rely" ∨ msg.sig == "deny")
/// @custom:invariant Mapping's state may only be mutated by authenticated caller.
/// ∀x ∊ Address: preTx(_wards[x]) != postTx(_wards[x]) → _wards[msg.sender] = 1
mapping(address => uint) private _wards;
/// @dev List of addresses possibly being auth'ed.
/// @dev May contain duplicates.
/// @dev May contain addresses not being auth'ed anymore.
/// @custom:invariant Every address being auth'ed once is element of the list.
/// ∀x ∊ Address: authed(x) -> x ∊ _wardsTouched
address[] private _wardsTouched;
/// @dev Ensures caller is auth'ed.
modifier auth() {
assembly ("memory-safe") {
// Compute slot of _wards[msg.sender].
mstore(0x00, caller())
mstore(0x20, _wards.slot)
let slot := keccak256(0x00, 0x40)
// Revert if caller not auth'ed.
let isAuthed := sload(slot)
if iszero(isAuthed) {
// Store selector of `NotAuthorized(address)`.
mstore(0x00, 0x4a0bfec1)
// Store msg.sender.
mstore(0x20, caller())
// Revert with (offset, size).
revert(0x1c, 0x24)
}
}
_;
}
constructor(address initialAuthed) {
_wards[initialAuthed] = 1;
_wardsTouched.push(initialAuthed);
// Note to use address(0) as caller to indicate address was auth'ed
// during deployment.
emit AuthGranted(address(0), initialAuthed);
}
/// @inheritdoc IAuth
function rely(address who) external auth {
if (_wards[who] == 1) return;
_wards[who] = 1;
_wardsTouched.push(who);
emit AuthGranted(msg.sender, who);
}
/// @inheritdoc IAuth
function deny(address who) external auth {
if (_wards[who] == 0) return;
_wards[who] = 0;
emit AuthRenounced(msg.sender, who);
}
/// @inheritdoc IAuth
function authed(address who) public view returns (bool) {
return _wards[who] == 1;
}
/// @inheritdoc IAuth
/// @custom:invariant Only contains auth'ed addresses.
/// ∀x ∊ authed(): _wards[x] == 1
/// @custom:invariant Contains all auth'ed addresses.
/// ∀x ∊ Address: _wards[x] == 1 → x ∊ authed()
function authed() public view returns (address[] memory) {
// Initiate array with upper limit length.
address[] memory wardsList = new address[](_wardsTouched.length);
// Iterate through all possible auth'ed addresses.
uint ctr;
for (uint i; i < wardsList.length; i++) {
// Add address only if still auth'ed.
if (_wards[_wardsTouched[i]] == 1) {
wardsList[ctr++] = _wardsTouched[i];
}
}
// Set length of array to number of auth'ed addresses actually included.
assembly ("memory-safe") {
mstore(wardsList, ctr)
}
return wardsList;
}
/// @inheritdoc IAuth
function wards(address who) public view returns (uint) {
return _wards[who];
}
}
lib/chronicle-std/src/auth/IAuth.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;
interface IAuth {
/// @notice Thrown by protected function if caller not auth'ed.
/// @param caller The caller's address.
error NotAuthorized(address caller);
/// @notice Emitted when auth granted to address.
/// @param caller The caller's address.
/// @param who The address auth got granted to.
event AuthGranted(address indexed caller, address indexed who);
/// @notice Emitted when auth renounced from address.
/// @param caller The caller's address.
/// @param who The address auth got renounced from.
event AuthRenounced(address indexed caller, address indexed who);
/// @notice Grants address `who` auth.
/// @dev Only callable by auth'ed address.
/// @param who The address to grant auth.
function rely(address who) external;
/// @notice Renounces address `who`'s auth.
/// @dev Only callable by auth'ed address.
/// @param who The address to renounce auth.
function deny(address who) external;
/// @notice Returns whether address `who` is auth'ed.
/// @param who The address to check.
/// @return True if `who` is auth'ed, false otherwise.
function authed(address who) external view returns (bool);
/// @notice Returns full list of addresses granted auth.
/// @dev May contain duplicates.
/// @return List of addresses granted auth.
function authed() external view returns (address[] memory);
/// @notice Returns whether address `who` is auth'ed.
/// @custom:deprecated Use `authed(address)(bool)` instead.
/// @param who The address to check.
/// @return 1 if `who` is auth'ed, 0 otherwise.
function wards(address who) external view returns (uint);
}
src/IScribe.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;
// forgefmt: disable-start
import {IChronicle} from "chronicle-std/IChronicle.sol";
import {LibSecp256k1} from "./libs/LibSecp256k1.sol";
interface IScribe is IChronicle {
/// @dev PokeData encapsulates a value and its age.
struct PokeData {
uint128 val;
uint32 age;
}
/// @dev SchnorrData encapsulates a (aggregated) Schnorr signature.
/// Schnorr signatures are used to prove a PokeData's integrity.
struct SchnorrData {
bytes32 signature;
address commitment;
bytes feedIds;
}
/// @dev ECDSAData encapsulates an ECDSA signature.
struct ECDSAData {
uint8 v;
bytes32 r;
bytes32 s;
}
/// @notice Thrown if a poked value's age is not greater than the oracle's
/// current value's age.
/// @param givenAge The poked value's age.
/// @param currentAge The oracle's current value's age.
error StaleMessage(uint32 givenAge, uint32 currentAge);
/// @notice Thrown if a poked value's age is greater than the current
/// time.
/// @param givenAge The poked value's age.
/// @param currentTimestamp The current time.
error FutureMessage(uint32 givenAge, uint32 currentTimestamp);
/// @notice Thrown if Schnorr signature not signed by exactly bar many
/// signers.
/// @param numberSigners The number of signers for given Schnorr signature.
/// @param bar The bar security parameter.
error BarNotReached(uint8 numberSigners, uint8 bar);
/// @notice Thrown if given feed id invalid.
/// @param feedId The invalid feed id.
error InvalidFeedId(uint8 feedId);
/// @notice Thrown if double signing attempted.
/// @param feedId The id of the feed attempting to double sign.
error DoubleSigningAttempted(uint8 feedId);
/// @notice Thrown if Schnorr signature verification failed.
error SchnorrSignatureInvalid();
/// @notice Emitted when oracle was successfully poked.
/// @param caller The caller's address.
/// @param val The value poked.
/// @param age The age of the value poked.
event Poked(address indexed caller, uint128 val, uint32 age);
/// @notice Emitted when new feed lifted.
/// @param caller The caller's address.
/// @param feed The feed address lifted.
event FeedLifted(address indexed caller, address indexed feed);
/// @notice Emitted when feed dropped.
/// @param caller The caller's address.
/// @param feed The feed address dropped.
event FeedDropped(address indexed caller, address indexed feed);
/// @notice Emitted when bar updated.
/// @param caller The caller's address.
/// @param oldBar The old bar's value.
/// @param newBar The new bar's value.
event BarUpdated(address indexed caller, uint8 oldBar, uint8 newBar);
/// @notice Returns the feed registration message.
/// @dev This message must be signed by a feed in order to be lifted.
/// @return feedRegistrationMessage Chronicle Protocol's feed registration
/// message.
function feedRegistrationMessage()
external
view
returns (bytes32 feedRegistrationMessage);
/// @notice Returns the bar security parameter.
/// @return bar The bar security parameter.
function bar() external view returns (uint8 bar);
/// @notice Returns the number of decimals of the oracle's value.
/// @dev Provides partial compatibility with Chainlink's
/// IAggregatorV3Interface.
/// @return decimals The oracle value's number of decimals.
function decimals() external view returns (uint8 decimals);
/// @notice Returns the oracle's latest value.
/// @dev Provides partial compatibility with Chainlink's
/// IAggregatorV3Interface.
/// @return roundId 1.
/// @return answer The oracle's latest value.
/// @return startedAt 0.
/// @return updatedAt The timestamp of oracle's latest update.
/// @return answeredInRound 1.
function latestRoundData()
external
view
returns (
uint80 roundId,
int answer,
uint startedAt,
uint updatedAt,
uint80 answeredInRound
);
/// @notice Returns the oracle's latest value.
/// @dev Provides partial compatibility with Chainlink's
/// IAggregatorV3Interface.
/// @custom:deprecated See https://docs.chain.link/data-feeds/api-reference/#latestanswer.
/// @return answer The oracle's latest value.
function latestAnswer() external view returns (int);
/// @notice Pokes the oracle.
/// @dev Expects `pokeData`'s age to be greater than the timestamp of the
/// last successful poke.
/// @dev Expects `pokeData`'s age to not be greater than the current time.
/// @dev Expects `schnorrData` to prove `pokeData`'s integrity.
/// See `isAcceptableSchnorrSignatureNow(bytes32,SchnorrData)(bool)`.
/// @param pokeData The PokeData being poked.
/// @param schnorrData The SchnorrData proving the `pokeData`'s
/// integrity.
function poke(PokeData calldata pokeData, SchnorrData calldata schnorrData)
external;
/// @notice Returns whether the Schnorr signature `schnorrData` is
/// currently acceptable for message `message`.
/// @dev Note that a valid Schnorr signature is only acceptable if the
/// signature was signed by exactly bar many feeds.
/// For more info, see `bar()(uint8)` and `feeds()(address[])`.
/// @dev Note that bar and feeds are configurable, meaning a once acceptable
/// Schnorr signature may become unacceptable in the future.
/// @param message The message expected to be signed via `schnorrData`.
/// @param schnorrData The SchnorrData to verify whether it proves
/// the `message`'s integrity.
/// @return ok True if Schnorr signature is acceptable, false otherwise.
function isAcceptableSchnorrSignatureNow(
bytes32 message,
SchnorrData calldata schnorrData
) external view returns (bool ok);
/// @notice Returns the message expected to be signed via Schnorr for
/// `pokeData`.
/// @dev The message is defined as:
/// H(tag ‖ H(wat ‖ pokeData)), where H() is the keccak256 function.
/// @param pokeData The pokeData to create the message for.
/// @return pokeMessage Message for `pokeData`.
function constructPokeMessage(PokeData calldata pokeData)
external
view
returns (bytes32 pokeMessage);
/// @notice Returns whether address `who` is a feed.
/// @param who The address to check.
/// @return isFeed True if `who` is feed, false otherwise.
function feeds(address who) external view returns (bool isFeed);
/// @notice Returns whether feed id `feedId` is a feed and, if so, the
/// feed's address.
/// @param feedId The feed id to check.
/// @return isFeed True if `feedId` is a feed, false otherwise.
/// @return feed Address of the feed with id `feedId` if `feedId` is a feed,
/// zero-address otherwise.
function feeds(uint8 feedId)
external
view
returns (bool isFeed, address feed);
/// @notice Returns list of feed addresses.
/// @dev Note that this function has a high gas consumption and is not
/// intended to be called onchain.
/// @return feeds List of feed addresses.
function feeds() external view returns (address[] memory feeds);
/// @notice Lifts public key `pubKey` to being a feed.
/// @dev Only callable by auth'ed address.
/// @dev The message expected to be signed by `ecdsaData` is defined via
/// `feedRegistrationMessage()(bytes32)`.
/// @custom:security The lift function's proof of possession is vulnerable
/// to rogue-key attacks. Additional verification MUST be
/// performed before lifting to ensure a feed's public key
/// validity.
/// @param pubKey The public key of the feed.
/// @param ecdsaData ECDSA signed message by the feed's public key.
/// @return feedId The id of the newly lifted feed.
function lift(LibSecp256k1.Point memory pubKey, ECDSAData memory ecdsaData)
external
returns (uint8 feedId);
/// @notice Lifts public keys `pubKeys` to being feeds.
/// @dev Only callable by auth'ed address.
/// @dev The message expected to be signed by `ecdsaDatas` is defined via
/// `feedRegistrationMessage()(bytes32)`.
/// @custom:security The lift function's proof of possession is vulnerable
/// to rogue-key attacks. Additional verification MUST be
/// performed before lifting to ensure a feed's public key
/// validity.
/// @param pubKeys The public keys of the feeds.
/// @param ecdsaDatas ECDSA signed message by the feeds' public keys.
/// @return List of feed ids of the newly lifted feeds.
function lift(
LibSecp256k1.Point[] memory pubKeys,
ECDSAData[] memory ecdsaDatas
) external returns (uint8[] memory);
/// @notice Drops feed with id `feedId`.
/// @dev Only callable by auth'ed address.
/// @param feedId The feed id to drop.
function drop(uint8 feedId) external;
/// @notice Drops feeds with ids' `feedIds`.
/// @dev Only callable by auth'ed address.
/// @param feedIds The feed ids to drop.
function drop(uint8[] memory feedIds) external;
/// @notice Updates the bar security parameters to `bar`.
/// @dev Only callable by auth'ed address.
/// @dev Reverts if `bar` is zero.
/// @param bar The value to update bar to.
function setBar(uint8 bar) external;
/// @notice Returns the oracle's current value.
/// @custom:deprecated Use `tryRead()(bool,uint)` instead.
/// @return value The oracle's current value if it exists, zero otherwise.
/// @return isValid True if value exists, false otherwise.
function peek() external view returns (uint value, bool isValid);
/// @notice Returns the oracle's current value.
/// @custom:deprecated Use `tryRead()(bool,uint)` instead.
/// @return value The oracle's current value if it exists, zero otherwise.
/// @return isValid True if value exists, false otherwise.
function peep() external view returns (uint value, bool isValid);
}
// forgefmt: disable-end
src/libs/LibSecp256k1.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;
// forgefmt: disable-start
/**
* @title LibSecp256k1
*
* @notice Library for secp256k1 elliptic curve computations
*
* @dev This library was developed to efficiently compute aggregated public
* keys for Schnorr signatures based on secp256k1, i.e. it is _not_ a
* general purpose elliptic curve library!
*
* References to the Ethereum Yellow Paper are based on the following
* version: "BERLIN VERSION beacfbd – 2022-10-24".
*/
library LibSecp256k1 {
using LibSecp256k1 for LibSecp256k1.Point;
using LibSecp256k1 for LibSecp256k1.JacobianPoint;
uint private constant ADDRESS_MASK =
0x000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
// -- Secp256k1 Constants --
//
// Taken from https://www.secg.org/sec2-v2.pdf.
// See section 2.4.1 "Recommended Parameters secp256k1".
uint private constant _A = 0;
uint private constant _B = 7;
uint private constant _P =
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
/// @dev Returns the order of the group.
function Q() internal pure returns (uint) {
return
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141;
}
/// @dev Returns the generator G.
/// Note that the generator is also called base point.
function G() internal pure returns (Point memory) {
return Point({
x: 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798,
y: 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8
});
}
/// @dev Returns the zero point.
function ZERO_POINT() internal pure returns (Point memory) {
return Point({x: 0, y: 0});
}
// -- (Affine) Point --
/// @dev Point encapsulates a secp256k1 point in Affine coordinates.
struct Point {
uint x;
uint y;
}
/// @dev Returns the Ethereum address of `self`.
///
/// @dev An Ethereum address is defined as the rightmost 160 bits of the
/// keccak256 hash of the concatenation of the hex-encoded x and y
/// coordinates of the corresponding ECDSA public key.
/// See "Appendix F: Signing Transactions" §134 in the Yellow Paper.
function toAddress(Point memory self) internal pure returns (address) {
address addr;
// Functionally equivalent Solidity code:
// addr = address(uint160(uint(keccak256(abi.encode(self.x, self.y)))));
assembly ("memory-safe") {
addr := and(keccak256(self, 0x40), ADDRESS_MASK)
}
return addr;
}
/// @dev Returns Affine point `self` in Jacobian coordinates.
function toJacobian(Point memory self)
internal
pure
returns (JacobianPoint memory)
{
return JacobianPoint({x: self.x, y: self.y, z: 1});
}
/// @dev Returns whether `self` is the zero point.
function isZeroPoint(Point memory self) internal pure returns (bool) {
return (self.x | self.y) == 0;
}
/// @dev Returns whether `self` is a point on the curve.
///
/// @dev The secp256k1 curve is specified as y² ≡ x³ + ax + b (mod P)
/// where:
/// a = 0
/// b = 7
function isOnCurve(Point memory self) internal pure returns (bool) {
uint left = mulmod(self.y, self.y, _P);
// Note that adding a * x can be waived as ∀x: a * x = 0.
uint right =
addmod(mulmod(self.x, mulmod(self.x, self.x, _P), _P), _B, _P);
return left == right;
}
/// @dev Returns the parity of `self`'s y coordinate.
///
/// @dev The value 0 represents an even y value and 1 represents an odd y
/// value.
/// See "Appendix F: Signing Transactions" in the Yellow Paper.
function yParity(Point memory self) internal pure returns (uint) {
return self.y & 1;
}
// -- Jacobian Point --
/// @dev JacobianPoint encapsulates a secp256k1 point in Jacobian
/// coordinates.
struct JacobianPoint {
uint x;
uint y;
uint z;
}
/// @dev Returns Jacobian point `self` in Affine coordinates.
///
/// @custom:invariant Reverts iff out of gas.
/// @custom:invariant Does not run into an infinite loop.
function toAffine(JacobianPoint memory self)
internal
pure
returns (Point memory)
{
Point memory result;
// Compute z⁻¹, i.e. the modular inverse of self.z.
uint zInv = _invMod(self.z);
// Compute (z⁻¹)² (mod P)
uint zInv_2 = mulmod(zInv, zInv, _P);
// Compute self.x * (z⁻¹)² (mod P), i.e. the x coordinate of given
// Jacobian point in Affine representation.
result.x = mulmod(self.x, zInv_2, _P);
// Compute self.y * (z⁻¹)³ (mod P), i.e. the y coordinate of given
// Jacobian point in Affine representation.
result.y = mulmod(self.y, mulmod(zInv, zInv_2, _P), _P);
return result;
}
/// @dev Adds Affine point `p` to Jacobian point `self`.
///
/// It is the caller's responsibility to ensure given points are on the
/// curve!
///
/// Computation based on: https://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#addition-madd-2007-bl.
///
/// Note that the formula assumes z2 = 1, which always holds if z2's
/// point is given in Affine coordinates.
///
/// Note that eventhough the function is marked as pure, to be
/// understood as only being dependent on the input arguments, it
/// nevertheless has side effects by writing the result into the
/// `self` memory variable.
///
/// @custom:invariant Only mutates `self` memory variable.
/// @custom:invariant Reverts iff out of gas.
/// @custom:invariant Uses constant amount of gas.
function addAffinePoint(JacobianPoint memory self, Point memory p)
internal
pure
{
// Addition formula:
// x = r² - j - (2 * v) (mod P)
// y = (r * (v - x)) - (2 * y1 * j) (mod P)
// z = (z1 + h)² - z1² - h² (mod P)
//
// where:
// r = 2 * (s - y1) (mod P)
// j = h * i (mod P)
// v = x1 * i (mod P)
// h = u - x1 (mod P)
// s = y2 * z1³ (mod P) Called s2 in reference
// i = 4 * h² (mod P)
// u = x2 * z1² (mod P) Called u2 in reference
//
// and:
// x1 = self.x
// y1 = self.y
// z1 = self.z
// x2 = p.x
// y2 = p.y
//
// Note that in order to save memory allocations the result is stored
// in the self variable, i.e. the following holds true after the
// functions execution:
// x = self.x
// y = self.y
// z = self.z
// Cache self's coordinates on stack.
uint x1 = self.x;
uint y1 = self.y;
uint z1 = self.z;
// Compute z1_2 = z1² (mod P)
// = z1 * z1 (mod P)
uint z1_2 = mulmod(z1, z1, _P);
// Compute h = u - x1 (mod P)
// = u + (P - x1) (mod P)
// = x2 * z1² + (P - x1) (mod P)
//
// Unchecked because the only protected operation performed is P - x1
// where x1 is guaranteed by the caller to be an x coordinate belonging
// to a point on the curve, i.e. being less than P.
uint h;
unchecked {
h = addmod(mulmod(p.x, z1_2, _P), _P - x1, _P);
}
// Compute h_2 = h² (mod P)
// = h * h (mod P)
uint h_2 = mulmod(h, h, _P);
// Compute i = 4 * h² (mod P)
uint i = mulmod(4, h_2, _P);
// Compute z = (z1 + h)² - z1² - h² (mod P)
// = (z1 + h)² - z1² + (P - h²) (mod P)
// = (z1 + h)² + (P - z1²) + (P - h²) (mod P)
// ╰───────╯ ╰───────╯ ╰──────╯
// left mid right
//
// Unchecked because the only protected operations performed are
// subtractions from P where the subtrahend is the result of a (mod P)
// computation, i.e. the subtrahend being guaranteed to be less than P.
unchecked {
uint left = mulmod(addmod(z1, h, _P), addmod(z1, h, _P), _P);
uint mid = _P - z1_2;
uint right = _P - h_2;
self.z = addmod(left, addmod(mid, right, _P), _P);
}
// Compute v = x1 * i (mod P)
uint v = mulmod(x1, i, _P);
// Compute j = h * i (mod P)
uint j = mulmod(h, i, _P);
// Compute r = 2 * (s - y1) (mod P)
// = 2 * (s + (P - y1)) (mod P)
// = 2 * ((y2 * z1³) + (P - y1)) (mod P)
// = 2 * ((y2 * z1² * z1) + (P - y1)) (mod P)
//
// Unchecked because the only protected operation performed is P - y1
// where y1 is guaranteed by the caller to be an y coordinate belonging
// to a point on the curve, i.e. being less than P.
uint r;
unchecked {
r = mulmod(
2,
addmod(mulmod(p.y, mulmod(z1_2, z1, _P), _P), _P - y1, _P),
_P
);
}
// Compute x = r² - j - (2 * v) (mod P)
// = r² - j + (P - (2 * v)) (mod P)
// = r² + (P - j) + (P - (2 * v)) (mod P)
// ╰─────╯ ╰───────────╯
// mid right
//
// Unchecked because the only protected operations performed are
// subtractions from P where the subtrahend is the result of a (mod P)
// computation, i.e. the subtrahend being guaranteed to be less than P.
unchecked {
uint r_2 = mulmod(r, r, _P);
uint mid = _P - j;
uint right = _P - mulmod(2, v, _P);
self.x = addmod(r_2, addmod(mid, right, _P), _P);
}
// Compute y = (r * (v - x)) - (2 * y1 * j) (mod P)
// = (r * (v - x)) + (P - (2 * y1 * j)) (mod P)
// = (r * (v + (P - x))) + (P - (2 * y1 * j)) (mod P)
// ╰─────────────────╯ ╰────────────────╯
// left right
//
// Unchecked because the only protected operations performed are
// subtractions from P where the subtrahend is the result of a (mod P)
// computation, i.e. the subtrahend being guaranteed to be less than P.
unchecked {
uint left = mulmod(r, addmod(v, _P - self.x, _P), _P);
uint right = _P - mulmod(2, mulmod(y1, j, _P), _P);
self.y = addmod(left, right, _P);
}
}
// -- Private Helpers --
/// @dev Returns the modular inverse of `x` for modulo `_P`.
///
/// It is the caller's responsibility to ensure `x` is less than `_P`!
///
/// The modular inverse of `x` is x⁻¹ such that x * x⁻¹ ≡ 1 (mod P).
///
/// @dev Modified from Jordi Baylina's [ecsol](https://github.com/jbaylina/ecsol/blob/c2256afad126b7500e6f879a9369b100e47d435d/ec.sol#L51-L67).
///
/// @custom:invariant Reverts iff out of gas.
/// @custom:invariant Does not run into an infinite loop.
function _invMod(uint x) private pure returns (uint) {
uint t;
uint q;
uint newT = 1;
uint r = _P;
assembly ("memory-safe") {
// Implemented in assembly to circumvent division-by-zero
// and over-/underflow protection.
//
// Functionally equivalent Solidity code:
// while (x != 0) {
// q = r / x;
// (t, newT) = (newT, addmod(t, (_P - mulmod(q, newT, _P)), _P));
// (r, x) = (x, r - (q * x));
// }
//
// For the division r / x, x is guaranteed to not be zero via the
// loop condition.
//
// The subtraction of form P - mulmod(_, _, P) is guaranteed to not
// underflow due to the subtrahend being a (mod P) result,
// i.e. the subtrahend being guaranteed to be less than P.
//
// The subterm q * x is guaranteed to not overflow because
// q * x ≤ r due to q = ⎣r / x⎦.
//
// The term r - (q * x) is guaranteed to not underflow because
// q * x ≤ r and therefore r - (q * x) ≥ 0.
for {} x {} {
q := div(r, x)
let tmp := t
t := newT
newT := addmod(tmp, sub(_P, mulmod(q, newT, _P)), _P)
tmp := r
r := x
x := sub(tmp, mul(q, x))
}
}
return t;
}
}
// forgefmt: disable-end
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 10000,
"enabled": true
},
"evmVersion": "london",
"remappings": [
"ds-test/=lib/forge-std/lib/ds-test/src/",
"forge-std/=lib/forge-std/src/",
"chronicle-std/=lib/chronicle-std/src/",
"lib/chronicle-std:src/=lib/chronicle-std/src/",
"lib/chronicle-std:ds-test/=lib/chronicle-std/lib/forge-std/lib/ds-test/src/",
"lib/chronicle-std:forge-std/=lib/chronicle-std/lib/forge-std/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.