Outline the Ethereum processor

This was only half-finished to begin with, unfortunately...
This commit is contained in:
Luke Parker
2024-09-14 07:54:18 -04:00
parent 72a18bf8bb
commit 7761798a78
19 changed files with 810 additions and 524 deletions

View File

@@ -0,0 +1,71 @@
use std::collections::HashMap;
use ciphersuite::{Ciphersuite, Secp256k1};
use serai_client::networks::ethereum::Address;
use primitives::{ReceivedOutput, EventualityTracker};
use crate::{output::Output, transaction::Eventuality};
// We interpret 32-block Epochs as singular blocks.
// There's no reason for further accuracy when these will all finalize at the same time.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) struct Epoch {
// The hash of the block which ended the prior Epoch.
pub(crate) prior_end_hash: [u8; 32],
// The first block number within this Epoch.
pub(crate) start: u64,
// The hash of the last block within this Epoch.
pub(crate) end_hash: [u8; 32],
// The monotonic time for this Epoch.
pub(crate) time: u64,
}
impl Epoch {
// The block number of the last block within this epoch.
fn end(&self) -> u64 {
self.start + 31
}
}
impl primitives::BlockHeader for Epoch {
fn id(&self) -> [u8; 32] {
self.end_hash
}
fn parent(&self) -> [u8; 32] {
self.prior_end_hash
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) struct FullEpoch {
epoch: Epoch,
}
impl primitives::Block for FullEpoch {
type Header = Epoch;
type Key = <Secp256k1 as Ciphersuite>::G;
type Address = Address;
type Output = Output;
type Eventuality = Eventuality;
fn id(&self) -> [u8; 32] {
self.epoch.end_hash
}
fn scan_for_outputs_unordered(&self, key: Self::Key) -> Vec<Self::Output> {
todo!("TODO")
}
#[allow(clippy::type_complexity)]
fn check_for_eventuality_resolutions(
&self,
eventualities: &mut EventualityTracker<Self::Eventuality>,
) -> HashMap<
<Self::Output as ReceivedOutput<Self::Key, Self::Address>>::TransactionId,
Self::Eventuality,
> {
todo!("TODO")
}
}

View File

@@ -0,0 +1,3 @@
pub(crate) mod output;
pub(crate) mod transaction;
pub(crate) mod block;

View File

@@ -0,0 +1,123 @@
use std::io;
use ciphersuite::{Ciphersuite, Secp256k1};
use ethereum_serai::{
alloy::primitives::U256,
router::{Coin as EthereumCoin, InInstruction as EthereumInInstruction},
};
use scale::{Encode, Decode};
use borsh::{BorshSerialize, BorshDeserialize};
use serai_client::{
primitives::{NetworkId, Coin, Amount, Balance},
networks::ethereum::Address,
};
use primitives::{OutputType, ReceivedOutput};
#[cfg(not(test))]
const DAI: [u8; 20] =
match const_hex::const_decode_to_array(b"0x6B175474E89094C44Da98b954EedeAC495271d0F") {
Ok(res) => res,
Err(_) => panic!("invalid non-test DAI hex address"),
};
#[cfg(test)] // TODO
const DAI: [u8; 20] =
match const_hex::const_decode_to_array(b"0000000000000000000000000000000000000000") {
Ok(res) => res,
Err(_) => panic!("invalid test DAI hex address"),
};
fn coin_to_serai_coin(coin: &EthereumCoin) -> Option<Coin> {
match coin {
EthereumCoin::Ether => Some(Coin::Ether),
EthereumCoin::Erc20(token) => {
if *token == DAI {
return Some(Coin::Dai);
}
None
}
}
}
fn amount_to_serai_amount(coin: Coin, amount: U256) -> Amount {
assert_eq!(coin.network(), NetworkId::Ethereum);
assert_eq!(coin.decimals(), 8);
// Remove 10 decimals so we go from 18 decimals to 8 decimals
let divisor = U256::from(10_000_000_000u64);
// This is valid up to 184b, which is assumed for the coins allowed
Amount(u64::try_from(amount / divisor).unwrap())
}
#[derive(
Clone, Copy, PartialEq, Eq, Hash, Debug, Encode, Decode, BorshSerialize, BorshDeserialize,
)]
pub(crate) struct OutputId(pub(crate) [u8; 40]);
impl Default for OutputId {
fn default() -> Self {
Self([0; 40])
}
}
impl AsRef<[u8]> for OutputId {
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
impl AsMut<[u8]> for OutputId {
fn as_mut(&mut self) -> &mut [u8] {
self.0.as_mut()
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub(crate) struct Output(pub(crate) EthereumInInstruction);
impl ReceivedOutput<<Secp256k1 as Ciphersuite>::G, Address> for Output {
type Id = OutputId;
type TransactionId = [u8; 32];
// We only scan external outputs as we don't have branch/change/forwards
fn kind(&self) -> OutputType {
OutputType::External
}
fn id(&self) -> Self::Id {
let mut id = [0; 40];
id[.. 32].copy_from_slice(&self.0.id.0);
id[32 ..].copy_from_slice(&self.0.id.1.to_le_bytes());
OutputId(id)
}
fn transaction_id(&self) -> Self::TransactionId {
self.0.id.0
}
fn key(&self) -> <Secp256k1 as Ciphersuite>::G {
self.0.key_at_end_of_block
}
fn presumed_origin(&self) -> Option<Address> {
Some(Address::from(self.0.from))
}
fn balance(&self) -> Balance {
let coin = coin_to_serai_coin(&self.0.coin).unwrap_or_else(|| {
panic!(
"mapping coin from an EthereumInInstruction with coin {}, which we don't handle.",
"this never should have been yielded"
)
});
Balance { coin, amount: amount_to_serai_amount(coin, self.0.amount) }
}
fn data(&self) -> &[u8] {
&self.0.data
}
fn write<W: io::Write>(&self, writer: &mut W) -> io::Result<()> {
self.0.write(writer)
}
fn read<R: io::Read>(reader: &mut R) -> io::Result<Self> {
EthereumInInstruction::read(reader).map(Self)
}
}

View File

@@ -0,0 +1,117 @@
use std::io;
use rand_core::{RngCore, CryptoRng};
use ciphersuite::{group::GroupEncoding, Ciphersuite, Secp256k1};
use frost::{dkg::ThresholdKeys, sign::PreprocessMachine};
use ethereum_serai::{crypto::PublicKey, machine::*};
use crate::output::OutputId;
#[derive(Clone, Debug)]
pub(crate) struct Transaction(pub(crate) SignedRouterCommand);
impl From<SignedRouterCommand> for Transaction {
fn from(signed_router_command: SignedRouterCommand) -> Self {
Self(signed_router_command)
}
}
impl scheduler::Transaction for Transaction {
fn read(reader: &mut impl io::Read) -> io::Result<Self> {
SignedRouterCommand::read(reader).map(Self)
}
fn write(&self, writer: &mut impl io::Write) -> io::Result<()> {
self.0.write(writer)
}
}
#[derive(Clone, Debug)]
pub(crate) struct SignableTransaction(pub(crate) RouterCommand);
#[derive(Clone)]
pub(crate) struct ClonableTransctionMachine(RouterCommand, ThresholdKeys<Secp256k1>);
impl PreprocessMachine for ClonableTransctionMachine {
type Preprocess = <RouterCommandMachine as PreprocessMachine>::Preprocess;
type Signature = <RouterCommandMachine as PreprocessMachine>::Signature;
type SignMachine = <RouterCommandMachine as PreprocessMachine>::SignMachine;
fn preprocess<R: RngCore + CryptoRng>(
self,
rng: &mut R,
) -> (Self::SignMachine, Self::Preprocess) {
// TODO: Use a proper error here, not an Option
RouterCommandMachine::new(self.1.clone(), self.0.clone()).unwrap().preprocess(rng)
}
}
impl scheduler::SignableTransaction for SignableTransaction {
type Transaction = Transaction;
type Ciphersuite = Secp256k1;
type PreprocessMachine = ClonableTransctionMachine;
fn read(reader: &mut impl io::Read) -> io::Result<Self> {
RouterCommand::read(reader).map(Self)
}
fn write(&self, writer: &mut impl io::Write) -> io::Result<()> {
self.0.write(writer)
}
fn id(&self) -> [u8; 32] {
let mut res = [0; 32];
// TODO: Add getter for the nonce
match self.0 {
RouterCommand::UpdateSeraiKey { nonce, .. } | RouterCommand::Execute { nonce, .. } => {
res[.. 8].copy_from_slice(&nonce.as_le_bytes());
}
}
res
}
fn sign(self, keys: ThresholdKeys<Self::Ciphersuite>) -> Self::PreprocessMachine {
ClonableTransctionMachine(self.0, keys)
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub(crate) struct Eventuality(pub(crate) PublicKey, pub(crate) RouterCommand);
impl primitives::Eventuality for Eventuality {
type OutputId = OutputId;
fn id(&self) -> [u8; 32] {
let mut res = [0; 32];
match self.1 {
RouterCommand::UpdateSeraiKey { nonce, .. } | RouterCommand::Execute { nonce, .. } => {
res[.. 8].copy_from_slice(&nonce.as_le_bytes());
}
}
res
}
fn lookup(&self) -> Vec<u8> {
match self.1 {
RouterCommand::UpdateSeraiKey { nonce, .. } | RouterCommand::Execute { nonce, .. } => {
nonce.as_le_bytes().to_vec()
}
}
}
fn singular_spent_output(&self) -> Option<Self::OutputId> {
None
}
fn read(reader: &mut impl io::Read) -> io::Result<Self> {
let point = Secp256k1::read_G(reader)?;
let command = RouterCommand::read(reader)?;
Ok(Eventuality(
PublicKey::new(point).ok_or(io::Error::other("unusable key within Eventuality"))?,
command,
))
}
fn write(&self, writer: &mut impl io::Write) -> io::Result<()> {
writer.write_all(self.0.point().to_bytes().as_slice())?;
self.1.write(writer)
}
}