mirror of
https://github.com/serai-dex/serai.git
synced 2025-01-01 08:29:54 +00:00
0f0db14f05
* Clean up Ethereum * Consistent contract address for deployed contracts * Flesh out Router a bit * Add a Deployer for DoS-less deployment * Implement Router-finding * Use CREATE2 helper present in ethers * Move from CREATE2 to CREATE Bit more streamlined for our use case. * Document ethereum-serai * Tidy tests a bit * Test updateSeraiKey * Use encodePacked for updateSeraiKey * Take in the block hash to read state during * Add a Sandbox contract to the Ethereum integration * Add retrieval of transfers from Ethereum * Add inInstruction function to the Router * Augment our handling of InInstructions events with a check the transfer event also exists * Have the Deployer error upon failed deployments * Add --via-ir * Make get_transaction test-only We only used it to get transactions to confirm the resolution of Eventualities. Eventualities need to be modularized. By introducing the dedicated confirm_completion function, we remove the need for a non-test get_transaction AND begin this modularization (by no longer explicitly grabbing a transaction to check with). * Modularize Eventuality Almost fully-deprecates the Transaction trait for Completion. Replaces Transaction ID with Claim. * Modularize the Scheduler behind a trait * Add an extremely basic account Scheduler * Add nonce uses, key rotation to the account scheduler * Only report the account Scheduler empty after transferring keys Also ban payments to the branch/change/forward addresses. * Make fns reliant on state test-only * Start of an Ethereum integration for the processor * Add a session to the Router to prevent updateSeraiKey replaying This would only happen if an old key was rotated to again, which would require n-of-n collusion (already ridiculous and a valid fault attributable event). It just clarifies the formal arguments. * Add a RouterCommand + SignMachine for producing it to coins/ethereum * Ethereum which compiles * Have branch/change/forward return an option Also defines a UtxoNetwork extension trait for MAX_INPUTS. * Make external_address exclusively a test fn * Move the "account" scheduler to "smart contract" * Remove ABI artifact * Move refund/forward Plan creation into the Processor We create forward Plans in the scan path, and need to know their exact fees in the scan path. This requires adding a somewhat wonky shim_forward_plan method so we can obtain a Plan equivalent to the actual forward Plan for fee reasons, yet don't expect it to be the actual forward Plan (which may be distinct if the Plan pulls from the global state, such as with a nonce). Also properly types a Scheduler addendum such that the SC scheduler isn't cramming the nonce to use into the N::Output type. * Flesh out the Ethereum integration more * Two commits ago, into the **Scheduler, not Processor * Remove misc TODOs in SC Scheduler * Add constructor to RouterCommandMachine * RouterCommand read, pairing with the prior added write * Further add serialization methods * Have the Router's key included with the InInstruction This does not use the key at the time of the event. This uses the key at the end of the block for the event. Its much simpler than getting the full event streams for each, checking when they interlace. This does not read the state. Every block, this makes a request for every single key update and simply chooses the last one. This allows pruning state, only keeping the event tree. Ideally, we'd also introduce a cache to reduce the cost of the filter (small in events yielded, long in blocks searched). Since Serai doesn't have any forwarding TXs, nor Branches, nor change, all of our Plans should solely have payments out, and there's no expectation of a Plan being made under one key broken by it being received by another key. * Add read/write to InInstruction * Abstract the ABI for Call/OutInstruction in ethereum-serai * Fill out signable_transaction for Ethereum * Move ethereum-serai to alloy Resolves #331. * Use the opaque sol macro instead of generated files * Move the processor over to the now-alloy-based ethereum-serai * Use the ecrecover provided by alloy * Have the SC use nonce for rotation, not session (an independent nonce which wasn't synchronized) * Always use the latest keys for SC scheduled plans * get_eventuality_completions for Ethereum * Finish fleshing out the processor Ethereum integration as needed for serai-processor tests This doesn't not support any actual deployments, not even the ones simulated by serai-processor-docker-tests. * Add alloy-simple-request-transport to the GH workflows * cargo update * Clarify a few comments and make one check more robust * Use a string for 27.0 in .github * Remove optional from no-longer-optional dependencies in processor * Add alloy to git deny exception * Fix no longer optional specification in processor's binaries feature * Use a version of foundry from 2024 * Correct fetching Bitcoin TXs in the processor docker tests * Update rustls to resolve RUSTSEC warnings * Use the monthly nightly foundry, not the deleted daily nightly
185 lines
5.4 KiB
Rust
185 lines
5.4 KiB
Rust
use group::ff::PrimeField;
|
|
use k256::{
|
|
elliptic_curve::{ops::Reduce, point::AffineCoordinates, sec1::ToEncodedPoint},
|
|
ProjectivePoint, Scalar, U256 as KU256,
|
|
};
|
|
#[cfg(test)]
|
|
use k256::{elliptic_curve::point::DecompressPoint, AffinePoint};
|
|
|
|
use frost::{
|
|
algorithm::{Hram, SchnorrSignature},
|
|
curve::{Ciphersuite, Secp256k1},
|
|
};
|
|
|
|
use alloy_core::primitives::{Parity, Signature as AlloySignature};
|
|
use alloy_consensus::{SignableTransaction, Signed, TxLegacy};
|
|
|
|
use crate::abi::router::{Signature as AbiSignature};
|
|
|
|
pub(crate) fn keccak256(data: &[u8]) -> [u8; 32] {
|
|
alloy_core::primitives::keccak256(data).into()
|
|
}
|
|
|
|
pub(crate) fn hash_to_scalar(data: &[u8]) -> Scalar {
|
|
<Scalar as Reduce<KU256>>::reduce_bytes(&keccak256(data).into())
|
|
}
|
|
|
|
pub fn address(point: &ProjectivePoint) -> [u8; 20] {
|
|
let encoded_point = point.to_encoded_point(false);
|
|
// Last 20 bytes of the hash of the concatenated x and y coordinates
|
|
// We obtain the concatenated x and y coordinates via the uncompressed encoding of the point
|
|
keccak256(&encoded_point.as_ref()[1 .. 65])[12 ..].try_into().unwrap()
|
|
}
|
|
|
|
pub(crate) fn deterministically_sign(tx: &TxLegacy) -> Signed<TxLegacy> {
|
|
assert!(
|
|
tx.chain_id.is_none(),
|
|
"chain ID was Some when deterministically signing a TX (causing a non-deterministic signer)"
|
|
);
|
|
|
|
let sig_hash = tx.signature_hash().0;
|
|
let mut r = hash_to_scalar(&[sig_hash.as_slice(), b"r"].concat());
|
|
let mut s = hash_to_scalar(&[sig_hash.as_slice(), b"s"].concat());
|
|
loop {
|
|
let r_bytes: [u8; 32] = r.to_repr().into();
|
|
let s_bytes: [u8; 32] = s.to_repr().into();
|
|
let v = Parity::NonEip155(false);
|
|
let signature =
|
|
AlloySignature::from_scalars_and_parity(r_bytes.into(), s_bytes.into(), v).unwrap();
|
|
let tx = tx.clone().into_signed(signature);
|
|
if tx.recover_signer().is_ok() {
|
|
return tx;
|
|
}
|
|
|
|
// Re-hash until valid
|
|
r = hash_to_scalar(r_bytes.as_ref());
|
|
s = hash_to_scalar(s_bytes.as_ref());
|
|
}
|
|
}
|
|
|
|
/// The public key for a Schnorr-signing account.
|
|
#[allow(non_snake_case)]
|
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
|
pub struct PublicKey {
|
|
pub(crate) A: ProjectivePoint,
|
|
pub(crate) px: Scalar,
|
|
}
|
|
|
|
impl PublicKey {
|
|
/// Construct a new `PublicKey`.
|
|
///
|
|
/// This will return None if the provided point isn't eligible to be a public key (due to
|
|
/// bounds such as parity).
|
|
#[allow(non_snake_case)]
|
|
pub fn new(A: ProjectivePoint) -> Option<PublicKey> {
|
|
let affine = A.to_affine();
|
|
// Only allow even keys to save a word within Ethereum
|
|
let is_odd = bool::from(affine.y_is_odd());
|
|
if is_odd {
|
|
None?;
|
|
}
|
|
|
|
let x_coord = affine.x();
|
|
let x_coord_scalar = <Scalar as Reduce<KU256>>::reduce_bytes(&x_coord);
|
|
// Return None if a reduction would occur
|
|
// Reductions would be incredibly unlikely and shouldn't be an issue, yet it's one less
|
|
// headache/concern to have
|
|
// This does ban a trivial amoount of public keys
|
|
if x_coord_scalar.to_repr() != x_coord {
|
|
None?;
|
|
}
|
|
|
|
Some(PublicKey { A, px: x_coord_scalar })
|
|
}
|
|
|
|
pub fn point(&self) -> ProjectivePoint {
|
|
self.A
|
|
}
|
|
|
|
pub(crate) fn eth_repr(&self) -> [u8; 32] {
|
|
self.px.to_repr().into()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
pub(crate) fn from_eth_repr(repr: [u8; 32]) -> Option<Self> {
|
|
#[allow(non_snake_case)]
|
|
let A = Option::<AffinePoint>::from(AffinePoint::decompress(&repr.into(), 0.into()))?.into();
|
|
Option::from(Scalar::from_repr(repr.into())).map(|px| PublicKey { A, px })
|
|
}
|
|
}
|
|
|
|
/// The HRAm to use for the Schnorr contract.
|
|
#[derive(Clone, Default)]
|
|
pub struct EthereumHram {}
|
|
impl Hram<Secp256k1> for EthereumHram {
|
|
#[allow(non_snake_case)]
|
|
fn hram(R: &ProjectivePoint, A: &ProjectivePoint, m: &[u8]) -> Scalar {
|
|
let x_coord = A.to_affine().x();
|
|
|
|
let mut data = address(R).to_vec();
|
|
data.extend(x_coord.as_slice());
|
|
data.extend(m);
|
|
|
|
<Scalar as Reduce<KU256>>::reduce_bytes(&keccak256(&data).into())
|
|
}
|
|
}
|
|
|
|
/// A signature for the Schnorr contract.
|
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
|
pub struct Signature {
|
|
pub(crate) c: Scalar,
|
|
pub(crate) s: Scalar,
|
|
}
|
|
impl Signature {
|
|
pub fn verify(&self, public_key: &PublicKey, message: &[u8]) -> bool {
|
|
#[allow(non_snake_case)]
|
|
let R = (Secp256k1::generator() * self.s) - (public_key.A * self.c);
|
|
EthereumHram::hram(&R, &public_key.A, message) == self.c
|
|
}
|
|
|
|
/// Construct a new `Signature`.
|
|
///
|
|
/// This will return None if the signature is invalid.
|
|
pub fn new(
|
|
public_key: &PublicKey,
|
|
message: &[u8],
|
|
signature: SchnorrSignature<Secp256k1>,
|
|
) -> Option<Signature> {
|
|
let c = EthereumHram::hram(&signature.R, &public_key.A, message);
|
|
if !signature.verify(public_key.A, c) {
|
|
None?;
|
|
}
|
|
|
|
let res = Signature { c, s: signature.s };
|
|
assert!(res.verify(public_key, message));
|
|
Some(res)
|
|
}
|
|
|
|
pub fn c(&self) -> Scalar {
|
|
self.c
|
|
}
|
|
pub fn s(&self) -> Scalar {
|
|
self.s
|
|
}
|
|
|
|
pub fn to_bytes(&self) -> [u8; 64] {
|
|
let mut res = [0; 64];
|
|
res[.. 32].copy_from_slice(self.c.to_repr().as_ref());
|
|
res[32 ..].copy_from_slice(self.s.to_repr().as_ref());
|
|
res
|
|
}
|
|
|
|
pub fn from_bytes(bytes: [u8; 64]) -> std::io::Result<Self> {
|
|
let mut reader = bytes.as_slice();
|
|
let c = Secp256k1::read_F(&mut reader)?;
|
|
let s = Secp256k1::read_F(&mut reader)?;
|
|
Ok(Signature { c, s })
|
|
}
|
|
}
|
|
impl From<&Signature> for AbiSignature {
|
|
fn from(sig: &Signature) -> AbiSignature {
|
|
let c: [u8; 32] = sig.c.to_repr().into();
|
|
let s: [u8; 32] = sig.s.to_repr().into();
|
|
AbiSignature { c: c.into(), s: s.into() }
|
|
}
|
|
}
|