Fix clippy, update old dependencies

This commit is contained in:
Luke Parker
2025-08-25 09:17:29 -04:00
parent c24b694fb2
commit 9dddfd91c8
93 changed files with 637 additions and 663 deletions

View File

@@ -4,9 +4,9 @@ use zeroize::{Zeroize, Zeroizing};
use ciphersuite::{
group::{ff::PrimeField, GroupEncoding},
Ciphersuite, Ristretto,
Ciphersuite,
};
use dkg::evrf::EvrfCurve;
use dkg::{Curves, Ristretto};
use serai_client::validator_sets::primitives::Session;
@@ -100,8 +100,8 @@ fn key_gen<K: KeyGenParams>() -> KeyGen<K> {
res
}
KeyGen::new(
read_key_from_env::<<Ristretto as EvrfCurve>::EmbeddedCurve>("SUBSTRATE_EVRF_KEY"),
read_key_from_env::<<K::ExternalNetworkCiphersuite as EvrfCurve>::EmbeddedCurve>(
read_key_from_env::<<Ristretto as Curves>::EmbeddedCurve>("SUBSTRATE_EVRF_KEY"),
read_key_from_env::<<K::ExternalNetworkCiphersuite as Curves>::EmbeddedCurve>(
"NETWORK_EVRF_KEY",
),
)
@@ -170,11 +170,13 @@ impl Hooks for () {
pub async fn main_loop<
H: Hooks,
S: ScannerFeed,
K: KeyGenParams<ExternalNetworkCiphersuite: Ciphersuite<G = KeyFor<S>>>,
K: KeyGenParams<ExternalNetworkCiphersuite: Curves<ToweringCurve: Ciphersuite<G = KeyFor<S>>>>,
Sch: Clone
+ Scheduler<
S,
SignableTransaction: SignableTransaction<Ciphersuite = K::ExternalNetworkCiphersuite>,
SignableTransaction: SignableTransaction<
Ciphersuite = <K::ExternalNetworkCiphersuite as Curves>::ToweringCurve,
>,
>,
>(
mut db: Db,

View File

@@ -25,6 +25,7 @@ scale = { package = "parity-scale-codec", version = "3", default-features = fals
borsh = { version = "1", default-features = false, features = ["std", "derive", "de_strict_order"] }
ciphersuite = { path = "../../crypto/ciphersuite", default-features = false, features = ["std"] }
ciphersuite-kp256 = { path = "../../crypto/ciphersuite/kp256", default-features = false, features = ["std"] }
dkg = { package = "dkg-evrf", path = "../../crypto/dkg/evrf", default-features = false, features = ["std", "secp256k1"] }
frost = { package = "modular-frost", path = "../../crypto/frost", default-features = false }

View File

@@ -1,5 +1,5 @@
use ciphersuite::{group::GroupEncoding, Ciphersuite, Secp256k1};
use frost::ThresholdKeys;
use ciphersuite::{group::GroupEncoding, Ciphersuite};
use dkg::{ThresholdKeys, Curves, Secp256k1};
use crate::{primitives::x_coord_to_even_point, scan::scanner};
@@ -9,20 +9,26 @@ impl key_gen::KeyGenParams for KeyGenParams {
type ExternalNetworkCiphersuite = Secp256k1;
fn tweak_keys(keys: &mut ThresholdKeys<Self::ExternalNetworkCiphersuite>) {
*keys = bitcoin_serai::wallet::tweak_keys(keys);
fn tweak_keys(
keys: &mut ThresholdKeys<<Self::ExternalNetworkCiphersuite as Curves>::ToweringCurve>,
) {
*keys = bitcoin_serai::wallet::tweak_keys(keys.clone());
// Also create a scanner to assert these keys, and all expected paths, are usable
scanner(keys.group_key());
}
fn encode_key(key: <Self::ExternalNetworkCiphersuite as Ciphersuite>::G) -> Vec<u8> {
fn encode_key(
key: <<Self::ExternalNetworkCiphersuite as Curves>::ToweringCurve as Ciphersuite>::G,
) -> Vec<u8> {
let key = key.to_bytes();
let key: &[u8] = key.as_ref();
// Skip the parity encoding as we know this key is even
key[1 ..].to_vec()
}
fn decode_key(key: &[u8]) -> Option<<Self::ExternalNetworkCiphersuite as Ciphersuite>::G> {
fn decode_key(
key: &[u8],
) -> Option<<<Self::ExternalNetworkCiphersuite as Curves>::ToweringCurve as Ciphersuite>::G> {
x_coord_to_even_point(key)
}
}

View File

@@ -1,7 +1,8 @@
use core::fmt;
use std::collections::HashMap;
use ciphersuite::{Ciphersuite, Secp256k1};
use ciphersuite::Ciphersuite;
use ciphersuite_kp256::Secp256k1;
use bitcoin_serai::bitcoin::block::{Header, Block as BBlock};

View File

@@ -1,4 +1,5 @@
use ciphersuite::{Ciphersuite, Secp256k1};
use ciphersuite::Ciphersuite;
use ciphersuite_kp256::Secp256k1;
use bitcoin_serai::bitcoin::key::{Parity, XOnlyPublicKey};

View File

@@ -1,6 +1,7 @@
use std::io;
use ciphersuite::{Ciphersuite, Secp256k1};
use ciphersuite::Ciphersuite;
use ciphersuite_kp256::Secp256k1;
use bitcoin_serai::{
bitcoin::{

View File

@@ -2,7 +2,7 @@ use std::io;
use rand_core::{RngCore, CryptoRng};
use ciphersuite::Secp256k1;
use ciphersuite_kp256::Secp256k1;
use frost::{dkg::ThresholdKeys, sign::PreprocessMachine};
use bitcoin_serai::{

View File

@@ -1,6 +1,7 @@
use std::{sync::LazyLock, collections::HashMap};
use ciphersuite::{Ciphersuite, Secp256k1};
use ciphersuite::Ciphersuite;
use ciphersuite_kp256::Secp256k1;
use bitcoin_serai::{
bitcoin::{

View File

@@ -1,6 +1,7 @@
use core::future::Future;
use ciphersuite::{Ciphersuite, Secp256k1};
use ciphersuite::Ciphersuite;
use ciphersuite_kp256::Secp256k1;
use bitcoin_serai::{
bitcoin::ScriptBuf,

View File

@@ -26,6 +26,7 @@ scale = { package = "parity-scale-codec", version = "3", default-features = fals
borsh = { version = "1", default-features = false, features = ["std", "derive", "de_strict_order"] }
ciphersuite = { path = "../../crypto/ciphersuite", default-features = false, features = ["std"] }
ciphersuite-kp256 = { path = "../../crypto/ciphersuite/kp256", default-features = false, features = ["std"] }
dkg = { package = "dkg-evrf", path = "../../crypto/dkg/evrf", default-features = false, features = ["std", "secp256k1"] }
frost = { package = "modular-frost", path = "../../crypto/frost", default-features = false, features = ["secp256k1"] }
@@ -34,11 +35,11 @@ k256 = { version = "^0.13.1", default-features = false, features = ["std"] }
alloy-core = { version = "1", default-features = false }
alloy-rlp = { version = "0.3", default-features = false }
alloy-rpc-types-eth = { version = "0.14", default-features = false }
alloy-transport = { version = "0.14", default-features = false }
alloy-rpc-types-eth = { version = "1", default-features = false }
alloy-transport = { version = "1", default-features = false }
alloy-simple-request-transport = { path = "../../networks/ethereum/alloy-simple-request-transport", default-features = false }
alloy-rpc-client = { version = "0.14", default-features = false }
alloy-provider = { version = "0.14", default-features = false }
alloy-rpc-client = { version = "1", default-features = false }
alloy-provider = { version = "1", default-features = false }
serai-client = { path = "../../substrate/client", default-features = false, features = ["ethereum"] }

View File

@@ -1,164 +0,0 @@
TODO
async fn publish_completion(
&self,
completion: &<Self::Eventuality as EventualityTrait>::Completion,
) -> Result<(), NetworkError> {
// Publish this to the dedicated TX server for a solver to actually publish
#[cfg(not(test))]
{
}
// Publish this using a dummy account we fund with magic RPC commands
#[cfg(test)]
{
let router = self.router().await;
let router = router.as_ref().unwrap();
let mut tx = match completion.command() {
RouterCommand::UpdateSeraiKey { key, .. } => {
router.update_serai_key(key, completion.signature())
}
RouterCommand::Execute { outs, .. } => router.execute(
&outs.iter().cloned().map(Into::into).collect::<Vec<_>>(),
completion.signature(),
),
};
tx.gas_limit = 1_000_000u64.into();
tx.gas_price = 1_000_000_000u64.into();
let tx = ethereum_serai::crypto::deterministically_sign(tx);
if self.provider.get_transaction_by_hash(*tx.hash()).await.unwrap().is_none() {
self
.provider
.raw_request::<_, ()>(
"anvil_setBalance".into(),
[
tx.recover_signer().unwrap().to_string(),
(U256::from(tx.tx().gas_limit) * U256::from(tx.tx().gas_price)).to_string(),
],
)
.await
.unwrap();
let (tx, sig, _) = tx.into_parts();
let mut bytes = vec![];
tx.encode_with_signature_fields(&sig, &mut bytes);
let pending_tx = self.provider.send_raw_transaction(&bytes).await.unwrap();
self.mine_block().await;
assert!(pending_tx.get_receipt().await.unwrap().status());
}
Ok(())
}
}
#[cfg(test)]
async fn get_transaction_by_eventuality(
&self,
block: usize,
eventuality: &Self::Eventuality,
) -> Self::Transaction {
// We mine 96 blocks to ensure the 32 blocks relevant are finalized
// Back-check the prior two epochs in response to this
// TODO: Review why this is sub(3) and not sub(2)
for block in block.saturating_sub(3) ..= block {
match eventuality.1 {
RouterCommand::UpdateSeraiKey { nonce, .. } | RouterCommand::Execute { nonce, .. } => {
let router = self.router().await;
let router = router.as_ref().unwrap();
let block = u64::try_from(block).unwrap();
let filter = router
.key_updated_filter()
.from_block(block * 32)
.to_block(((block + 1) * 32) - 1)
.topic1(nonce);
let logs = self.provider.get_logs(&filter).await.unwrap();
if let Some(log) = logs.first() {
return self
.provider
.get_transaction_by_hash(log.clone().transaction_hash.unwrap())
.await
.unwrap()
.unwrap();
};
let filter = router
.executed_filter()
.from_block(block * 32)
.to_block(((block + 1) * 32) - 1)
.topic1(nonce);
let logs = self.provider.get_logs(&filter).await.unwrap();
if logs.is_empty() {
continue;
}
return self
.provider
.get_transaction_by_hash(logs[0].transaction_hash.unwrap())
.await
.unwrap()
.unwrap();
}
}
}
panic!("couldn't find completion in any three of checked blocks");
}
#[cfg(test)]
async fn mine_block(&self) {
self.provider.raw_request::<_, ()>("anvil_mine".into(), [96]).await.unwrap();
}
#[cfg(test)]
async fn test_send(&self, send_to: Self::Address) -> Self::Block {
use rand_core::OsRng;
use ciphersuite::group::ff::Field;
use ethereum_serai::alloy::sol_types::SolCall;
let key = <Secp256k1 as Ciphersuite>::F::random(&mut OsRng);
let address = ethereum_serai::crypto::address(&(Secp256k1::generator() * key));
// Set a 1.1 ETH balance
self
.provider
.raw_request::<_, ()>(
"anvil_setBalance".into(),
[Address(address).to_string(), "1100000000000000000".into()],
)
.await
.unwrap();
let value = U256::from_str_radix("1000000000000000000", 10).unwrap();
let tx = ethereum_serai::alloy::consensus::TxLegacy {
chain_id: None,
nonce: 0,
gas_price: 1_000_000_000u128,
gas_limit: 200_000u128,
to: ethereum_serai::alloy::primitives::TxKind::Call(send_to.0.into()),
// 1 ETH
value,
input: ethereum_serai::router::abi::inInstructionCall::new((
[0; 20].into(),
value,
vec![].into(),
))
.abi_encode()
.into(),
};
use ethereum_serai::alloy::{primitives::Signature, consensus::SignableTransaction};
let sig = k256::ecdsa::SigningKey::from(k256::elliptic_curve::NonZeroScalar::new(key).unwrap())
.sign_prehash_recoverable(tx.signature_hash().as_ref())
.unwrap();
let mut bytes = vec![];
tx.encode_with_signature_fields(&Signature::from(sig), &mut bytes);
let pending_tx = self.provider.send_raw_transaction(&bytes).await.ok().unwrap();
// Mine an epoch containing this TX
self.mine_block().await;
assert!(pending_tx.get_receipt().await.unwrap().status());
// Yield the freshly mined block
self.get_block(self.get_latest_block_number().await.unwrap()).await.unwrap()
}

View File

@@ -1,31 +0,0 @@
// TODO
use rand_core::OsRng;
use group::ff::{Field, PrimeField};
use k256::{
ecdsa::{
self, hazmat::SignPrimitive, signature::hazmat::PrehashVerifier, SigningKey, VerifyingKey,
},
Scalar, ProjectivePoint,
};
use frost::{
curve::{Ciphersuite, Secp256k1},
algorithm::{Hram, IetfSchnorr},
tests::{algorithm_machines, sign},
};
use crate::{crypto::*, tests::key_gen};
// Run the sign test with the EthereumHram
#[test]
fn test_signing() {
let (keys, _) = key_gen();
const MESSAGE: &[u8] = b"Hello, World!";
let algo = IetfSchnorr::<Secp256k1, EthereumHram>::ietf();
let _sig =
sign(&mut OsRng, &algo, keys.clone(), algorithm_machines(&mut OsRng, &algo, &keys), MESSAGE);
}

View File

@@ -1,45 +0,0 @@
// TODO
use std::{sync::Arc, collections::HashMap};
use rand_core::OsRng;
use k256::{Scalar, ProjectivePoint};
use frost::{curve::Secp256k1, Participant, ThresholdKeys, tests::key_gen as frost_key_gen};
use alloy_core::{
primitives::{Address, U256, Bytes, Signature, TxKind},
hex::FromHex,
};
use alloy_consensus::{SignableTransaction, TxLegacy};
use alloy_rpc_types_eth::TransactionReceipt;
use alloy_simple_request_transport::SimpleRequest;
use alloy_provider::{Provider, RootProvider};
use crate::crypto::{address, deterministically_sign, PublicKey};
#[cfg(test)]
mod crypto;
#[cfg(test)]
use contracts::tests as abi;
#[cfg(test)]
mod router;
pub fn key_gen() -> (HashMap<Participant, ThresholdKeys<Secp256k1>>, PublicKey) {
let mut keys = frost_key_gen::<_, Secp256k1>(&mut OsRng);
let mut group_key = keys[&Participant::new(1).unwrap()].group_key();
let mut offset = Scalar::ZERO;
while PublicKey::new(group_key).is_none() {
offset += Scalar::ONE;
group_key += ProjectivePoint::GENERATOR;
}
for keys in keys.values_mut() {
*keys = keys.offset(offset);
}
let public_key = PublicKey::new(group_key).unwrap();
(keys, public_key)
}

View File

@@ -22,11 +22,11 @@ alloy-core = { version = "1", default-features = false }
alloy-sol-types = { version = "1", default-features = false }
alloy-sol-macro = { version = "1", default-features = false }
alloy-consensus = { version = "0.14", default-features = false }
alloy-consensus = { version = "1", default-features = false }
alloy-rpc-types-eth = { version = "0.14", default-features = false }
alloy-transport = { version = "0.14", default-features = false }
alloy-provider = { version = "0.14", default-features = false }
alloy-rpc-types-eth = { version = "1", default-features = false }
alloy-transport = { version = "1", default-features = false }
alloy-provider = { version = "1", default-features = false }
ethereum-primitives = { package = "serai-processor-ethereum-primitives", path = "../primitives", default-features = false }
@@ -35,9 +35,9 @@ build-solidity-contracts = { path = "../../../networks/ethereum/build-contracts"
[dev-dependencies]
alloy-simple-request-transport = { path = "../../../networks/ethereum/alloy-simple-request-transport", default-features = false }
alloy-rpc-client = { version = "0.14", default-features = false }
alloy-node-bindings = { version = "0.14", default-features = false }
alloy-rpc-client = { version = "1", default-features = false }
alloy-node-bindings = { version = "1", default-features = false }
tokio = { version = "1.0", default-features = false, features = ["rt-multi-thread", "macros"] }
tokio = { version = "1", default-features = false, features = ["rt-multi-thread", "macros"] }
ethereum-test-primitives = { package = "serai-ethereum-test-primitives", path = "../test-primitives" }

View File

@@ -22,9 +22,9 @@ alloy-core = { version = "1", default-features = false }
alloy-sol-types = { version = "1", default-features = false }
alloy-sol-macro = { version = "1", default-features = false }
alloy-rpc-types-eth = { version = "0.14", default-features = false }
alloy-transport = { version = "0.14", default-features = false }
alloy-provider = { version = "0.14", default-features = false }
alloy-rpc-types-eth = { version = "1", default-features = false }
alloy-transport = { version = "1", default-features = false }
alloy-provider = { version = "1", default-features = false }
ethereum-primitives = { package = "serai-processor-ethereum-primitives", path = "../primitives", default-features = false }

View File

@@ -23,4 +23,4 @@ group = { version = "0.13", default-features = false }
k256 = { version = "^0.13.1", default-features = false, features = ["std", "arithmetic"] }
alloy-primitives = { version = "1", default-features = false }
alloy-consensus = { version = "0.14", default-features = false, features = ["k256"] }
alloy-consensus = { version = "1", default-features = false, features = ["k256"] }

View File

@@ -27,13 +27,13 @@ alloy-core = { version = "1", default-features = false }
alloy-sol-types = { version = "1", default-features = false }
alloy-sol-macro = { version = "1", default-features = false }
alloy-consensus = { version = "0.14", default-features = false }
alloy-consensus = { version = "1", default-features = false }
alloy-rpc-types-eth = { version = "0.14", default-features = false }
alloy-transport = { version = "0.14", default-features = false }
alloy-provider = { version = "0.14", default-features = false }
alloy-rpc-types-eth = { version = "1", default-features = false }
alloy-transport = { version = "1", default-features = false }
alloy-provider = { version = "1", default-features = false }
revm = { version = "22", default-features = false, features = ["std"] }
revm = { version = "29", default-features = false, features = ["std"] }
ethereum-schnorr = { package = "ethereum-schnorr-contract", path = "../../../networks/ethereum/schnorr", default-features = false }
@@ -61,10 +61,10 @@ rand_core = { version = "0.6", default-features = false, features = ["std"] }
k256 = { version = "0.13", default-features = false, features = ["std"] }
alloy-simple-request-transport = { path = "../../../networks/ethereum/alloy-simple-request-transport", default-features = false }
alloy-provider = { version = "0.14", default-features = false, features = ["debug-api", "trace-api"] }
alloy-rpc-client = { version = "0.14", default-features = false }
alloy-node-bindings = { version = "0.14", default-features = false }
alloy-provider = { version = "1", default-features = false, features = ["debug-api", "trace-api"] }
alloy-rpc-client = { version = "1", default-features = false }
alloy-node-bindings = { version = "1", default-features = false }
tokio = { version = "1.0", default-features = false, features = ["rt-multi-thread", "macros"] }
tokio = { version = "1", default-features = false, features = ["rt-multi-thread", "macros"] }
ethereum-test-primitives = { package = "serai-ethereum-test-primitives", path = "../test-primitives" }

View File

@@ -21,8 +21,8 @@ use revm::{
},
context::{
result::{EVMError, InvalidTransaction, ExecutionResult},
evm::{EvmData, Evm},
context::Context,
evm::Evm,
*,
},
inspector::{Inspector, InspectorHandler},
@@ -124,6 +124,7 @@ pub(crate) type GasEstimator = Evm<
WorstCaseCallInspector,
EthInstructions<EthInterpreter, RevmContext>,
EthPrecompiles,
EthFrame,
>;
impl Router {
@@ -218,26 +219,24 @@ impl Router {
db
};
Evm {
data: EvmData {
ctx: RevmContext::new(db, SPEC_ID)
.modify_cfg_chained(|cfg| {
cfg.chain_id = CHAIN_ID.try_into().unwrap();
})
.modify_tx_chained(|tx: &mut TxEnv| {
tx.gas_limit = u64::MAX;
tx.kind = self.address.into();
}),
inspector: WorstCaseCallInspector {
erc20,
call_depth: 0,
unused_gas: 0,
override_immediate_call_return_value: false,
},
Evm::new_with_inspector(
RevmContext::new(db, SPEC_ID)
.modify_cfg_chained(|cfg| {
cfg.chain_id = CHAIN_ID.try_into().unwrap();
})
.modify_tx_chained(|tx: &mut TxEnv| {
tx.gas_limit = u64::MAX;
tx.kind = self.address.into();
}),
WorstCaseCallInspector {
erc20,
call_depth: 0,
unused_gas: 0,
override_immediate_call_return_value: false,
},
instruction: EthInstructions::default(),
precompiles: precompiles(),
}
EthInstructions::default(),
precompiles(),
)
}
/// The worst-case gas cost for a legacy transaction which executes this batch.
@@ -262,7 +261,7 @@ impl Router {
let fee = if fee_per_gas == U256::ZERO { U256::ZERO } else { U256::ONE };
// Set a balance of the amount sent out to ensure we don't error on that premise
gas_estimator.data.ctx.modify_db(|db| {
gas_estimator.ctx.modify_db(|db| {
let account = db.load_account(self.address).unwrap();
account.info.balance = fee + outs.0.iter().map(|out| out.amount).sum::<U256>();
});
@@ -290,7 +289,7 @@ impl Router {
consistent use of nonce #1 shows storage read/writes aren't being persisted. They're solely
returned upon execution in a `state` field we ignore.
*/
gas_estimator.data.ctx.modify_tx(|tx| {
gas_estimator.ctx.modify_tx(|tx| {
tx.caller = Address::from({
/*
We assume the transaction sender is not the destination of any `OutInstruction`, making
@@ -317,21 +316,17 @@ impl Router {
});
// Execute the transaction
let mut gas = match MainnetHandler::<
_,
EVMError<Infallible, InvalidTransaction>,
EthFrame<_, _, _>,
>::default()
.inspect_run(&mut gas_estimator)
.unwrap()
.result
{
ExecutionResult::Success { gas_used, gas_refunded, .. } => {
assert_eq!(gas_refunded, 0);
gas_used
}
res => panic!("estimated execute transaction failed: {res:?}"),
};
let mut gas =
match MainnetHandler::<_, EVMError<Infallible, InvalidTransaction>, EthFrame<_>>::default()
.inspect_run(&mut gas_estimator)
.unwrap()
{
ExecutionResult::Success { gas_used, gas_refunded, .. } => {
assert_eq!(gas_refunded, 0);
gas_used
}
res => panic!("estimated execute transaction failed: {res:?}"),
};
gas += gas_estimator.into_inspector().unused_gas;
/*

View File

@@ -1,5 +1,5 @@
use ciphersuite::{Ciphersuite, Secp256k1};
use dkg::ThresholdKeys;
use ciphersuite::Ciphersuite;
use dkg::{ThresholdKeys, Curves, Secp256k1};
use ethereum_schnorr::PublicKey;
@@ -9,17 +9,23 @@ impl key_gen::KeyGenParams for KeyGenParams {
type ExternalNetworkCiphersuite = Secp256k1;
fn tweak_keys(keys: &mut ThresholdKeys<Self::ExternalNetworkCiphersuite>) {
fn tweak_keys(
keys: &mut ThresholdKeys<<Self::ExternalNetworkCiphersuite as Curves>::ToweringCurve>,
) {
while PublicKey::new(keys.group_key()).is_none() {
*keys = keys.offset(<Secp256k1 as Ciphersuite>::F::ONE);
*keys = keys.clone().offset(<<Secp256k1 as Curves>::ToweringCurve as Ciphersuite>::F::ONE);
}
}
fn encode_key(key: <Self::ExternalNetworkCiphersuite as Ciphersuite>::G) -> Vec<u8> {
fn encode_key(
key: <<Self::ExternalNetworkCiphersuite as Curves>::ToweringCurve as Ciphersuite>::G,
) -> Vec<u8> {
PublicKey::new(key).unwrap().eth_repr().to_vec()
}
fn decode_key(key: &[u8]) -> Option<<Self::ExternalNetworkCiphersuite as Ciphersuite>::G> {
fn decode_key(
key: &[u8],
) -> Option<<<Self::ExternalNetworkCiphersuite as Curves>::ToweringCurve as Ciphersuite>::G> {
PublicKey::from_eth_repr(key.try_into().ok()?).map(|key| key.point())
}
}

View File

@@ -1,6 +1,7 @@
use std::collections::HashMap;
use ciphersuite::{Ciphersuite, Secp256k1};
use ciphersuite::Ciphersuite;
use ciphersuite_kp256::Secp256k1;
use serai_client::networks::ethereum::Address;

View File

@@ -2,7 +2,8 @@ use std::{io, collections::HashMap};
use rand_core::{RngCore, CryptoRng};
use ciphersuite::{Ciphersuite, Secp256k1};
use ciphersuite::Ciphersuite;
use ciphersuite_kp256::Secp256k1;
use frost::{
dkg::{Participant, ThresholdKeys},
FrostError,

View File

@@ -1,6 +1,7 @@
use std::io;
use ciphersuite::{group::GroupEncoding, Ciphersuite, Secp256k1};
use ciphersuite::{group::GroupEncoding, Ciphersuite};
use ciphersuite_kp256::Secp256k1;
use alloy_core::primitives::U256;

View File

@@ -1,6 +1,6 @@
use std::io;
use ciphersuite::Secp256k1;
use ciphersuite_kp256::Secp256k1;
use frost::dkg::ThresholdKeys;
use alloy_core::primitives::{U256, Address as EthereumAddress};

View File

@@ -20,9 +20,9 @@ workspace = true
k256 = { version = "0.13", default-features = false, features = ["std"] }
alloy-core = { version = "1", default-features = false }
alloy-consensus = { version = "0.14", default-features = false, features = ["std"] }
alloy-consensus = { version = "1", default-features = false, features = ["std"] }
alloy-rpc-types-eth = { version = "0.14", default-features = false }
alloy-provider = { version = "0.14", default-features = false }
alloy-rpc-types-eth = { version = "1", default-features = false }
alloy-provider = { version = "1", default-features = false }
ethereum-primitives = { package = "serai-processor-ethereum-primitives", path = "../primitives", default-features = false }

View File

@@ -31,9 +31,7 @@ rand_chacha = { version = "0.3", default-features = false, features = ["std"] }
# Cryptography
blake2 = { version = "0.10", default-features = false, features = ["std"] }
transcript = { package = "flexible-transcript", path = "../../crypto/transcript", default-features = false, features = ["std"] }
ec-divisors = { git = "https://github.com/kayabaNerve/monero-oxide", rev = "54da48f27a05fa8656014942919da1dfbab4d8e3", default-features = false }
ciphersuite = { path = "../../crypto/ciphersuite", default-features = false, features = ["std"] }
dalek-ff-group = { path = "../../crypto/dalek-ff-group", default-features = false, features = ["std"] }
dkg = { package = "dkg-evrf", path = "../../crypto/dkg/evrf", default-features = false, features = ["std", "ristretto"] }
# Substrate

View File

@@ -3,8 +3,8 @@ use std::collections::HashMap;
use zeroize::Zeroizing;
use ciphersuite::{group::GroupEncoding, Ciphersuite, Ristretto};
use dkg::{Participant, ThresholdCore, ThresholdKeys, evrf::EvrfCurve};
use ciphersuite::{group::GroupEncoding, Ciphersuite};
use dkg::*;
use serai_validator_sets_primitives::Session;
@@ -17,9 +17,9 @@ pub(crate) struct Params<P: KeyGenParams> {
pub(crate) t: u16,
pub(crate) n: u16,
pub(crate) substrate_evrf_public_keys:
Vec<<<Ristretto as EvrfCurve>::EmbeddedCurve as Ciphersuite>::G>,
Vec<<<Ristretto as Curves>::EmbeddedCurve as Ciphersuite>::G>,
pub(crate) network_evrf_public_keys:
Vec<<<P::ExternalNetworkCiphersuite as EvrfCurve>::EmbeddedCurve as Ciphersuite>::G>,
Vec<<<P::ExternalNetworkCiphersuite as Curves>::EmbeddedCurve as Ciphersuite>::G>,
}
#[derive(BorshSerialize, BorshDeserialize)]
@@ -85,7 +85,7 @@ impl<P: KeyGenParams> KeyGenDb<P> {
.substrate_evrf_public_keys
.into_iter()
.map(|key| {
<<Ristretto as EvrfCurve>::EmbeddedCurve as Ciphersuite>::read_G(&mut key.as_slice())
<<Ristretto as Curves>::EmbeddedCurve as Ciphersuite>::read_G(&mut key.as_slice())
.unwrap()
})
.collect(),
@@ -93,7 +93,7 @@ impl<P: KeyGenParams> KeyGenDb<P> {
.network_evrf_public_keys
.into_iter()
.map(|key| {
<<P::ExternalNetworkCiphersuite as EvrfCurve>::EmbeddedCurve as Ciphersuite>::read_G::<
<<P::ExternalNetworkCiphersuite as Curves>::EmbeddedCurve as Ciphersuite>::read_G::<
&[u8],
>(&mut key.as_ref())
.unwrap()
@@ -117,8 +117,8 @@ impl<P: KeyGenParams> KeyGenDb<P> {
pub(crate) fn set_key_shares(
txn: &mut impl DbTxn,
session: Session,
substrate_keys: &[ThresholdKeys<Ristretto>],
network_keys: &[ThresholdKeys<P::ExternalNetworkCiphersuite>],
substrate_keys: &[ThresholdKeys<<Ristretto as Curves>::ToweringCurve>],
network_keys: &[ThresholdKeys<<P::ExternalNetworkCiphersuite as Curves>::ToweringCurve>],
) {
assert_eq!(substrate_keys.len(), network_keys.len());
@@ -134,16 +134,18 @@ impl<P: KeyGenParams> KeyGenDb<P> {
pub(crate) fn key_shares(
getter: &impl Get,
session: Session,
) -> Option<(Vec<ThresholdKeys<Ristretto>>, Vec<ThresholdKeys<P::ExternalNetworkCiphersuite>>)>
{
) -> Option<(
Vec<ThresholdKeys<<Ristretto as Curves>::ToweringCurve>>,
Vec<ThresholdKeys<<P::ExternalNetworkCiphersuite as Curves>::ToweringCurve>>,
)> {
let keys = _db::KeyShares::get(getter, &session)?;
let mut keys: &[u8] = keys.as_ref();
let mut substrate_keys = vec![];
let mut network_keys = vec![];
while !keys.is_empty() {
substrate_keys.push(ThresholdKeys::new(ThresholdCore::read(&mut keys).unwrap()));
let mut these_network_keys = ThresholdKeys::new(ThresholdCore::read(&mut keys).unwrap());
substrate_keys.push(ThresholdKeys::read(&mut keys).unwrap());
let mut these_network_keys = ThresholdKeys::read(&mut keys).unwrap();
P::tweak_keys(&mut these_network_keys);
network_keys.push(these_network_keys);
}

View File

@@ -4,7 +4,7 @@ use std::{
collections::HashMap,
};
use dkg::evrf::*;
use dkg::*;
use serai_validator_sets_primitives::MAX_KEY_SHARES_PER_SET;
@@ -21,14 +21,14 @@ use serai_validator_sets_primitives::MAX_KEY_SHARES_PER_SET;
static GENERATORS: LazyLock<Mutex<HashMap<TypeId, &'static (dyn Send + Sync + Any)>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
pub(crate) fn generators<C: EvrfCurve>() -> &'static EvrfGenerators<C> {
pub(crate) fn generators<C: 'static + Curves>() -> &'static Generators<C> {
GENERATORS
.lock()
.unwrap()
.entry(TypeId::of::<C>())
.or_insert_with(|| {
// If we haven't prior needed generators for this Ciphersuite, generate new ones
Box::leak(Box::new(EvrfGenerators::<C>::new(
Box::leak(Box::new(Generators::<C>::new(
(MAX_KEY_SHARES_PER_SET * 2 / 3) + 1,
MAX_KEY_SHARES_PER_SET,
)))

View File

@@ -13,9 +13,9 @@ use blake2::{Digest, Blake2s256};
use transcript::{Transcript, RecommendedTranscript};
use ciphersuite::{
group::{Group, GroupEncoding},
Ciphersuite, Ristretto,
Ciphersuite,
};
use dkg::{Participant, ThresholdKeys, evrf::*};
use dkg::*;
use serai_validator_sets_primitives::Session;
use messages::key_gen::*;
@@ -34,33 +34,36 @@ pub trait KeyGenParams {
const ID: &'static str;
/// The curve used for the external network.
type ExternalNetworkCiphersuite: EvrfCurve<
EmbeddedCurve: Ciphersuite<
G: ec_divisors::DivisorCurve<
FieldElement = <Self::ExternalNetworkCiphersuite as Ciphersuite>::F,
>,
>,
>;
type ExternalNetworkCiphersuite: 'static + Curves;
/// Tweaks keys as necessary/beneficial.
///
/// A default implementation which doesn't perform any tweaking is provided.
fn tweak_keys(keys: &mut ThresholdKeys<Self::ExternalNetworkCiphersuite>) {
fn tweak_keys(
keys: &mut ThresholdKeys<<Self::ExternalNetworkCiphersuite as Curves>::ToweringCurve>,
) {
let _ = keys;
}
/// Encode keys as optimal.
///
/// A default implementation is provided which calls the traditional `to_bytes`.
fn encode_key(key: <Self::ExternalNetworkCiphersuite as Ciphersuite>::G) -> Vec<u8> {
fn encode_key(
key: <<Self::ExternalNetworkCiphersuite as Curves>::ToweringCurve as Ciphersuite>::G,
) -> Vec<u8> {
key.to_bytes().as_ref().to_vec()
}
/// Decode keys from their optimal encoding.
///
/// A default implementation is provided which calls the traditional `from_bytes`.
fn decode_key(mut key: &[u8]) -> Option<<Self::ExternalNetworkCiphersuite as Ciphersuite>::G> {
let res = <Self::ExternalNetworkCiphersuite as Ciphersuite>::read_G(&mut key).ok()?;
fn decode_key(
mut key: &[u8],
) -> Option<<<Self::ExternalNetworkCiphersuite as Curves>::ToweringCurve as Ciphersuite>::G> {
let res = <<Self::ExternalNetworkCiphersuite as Curves>::ToweringCurve as Ciphersuite>::read_G(
&mut key,
)
.ok()?;
if !key.is_empty() {
None?;
}
@@ -96,10 +99,10 @@ pub trait KeyGenParams {
Returns the coerced keys and faulty participants.
*/
fn coerce_keys<C: EvrfCurve>(
fn coerce_keys<C: 'static + Curves>(
key_bytes: &[impl AsRef<[u8]>],
) -> (Vec<<C::EmbeddedCurve as Ciphersuite>::G>, Vec<Participant>) {
fn evrf_key<C: EvrfCurve>(key: &[u8]) -> Option<<C::EmbeddedCurve as Ciphersuite>::G> {
fn evrf_key<C: 'static + Curves>(key: &[u8]) -> Option<<C::EmbeddedCurve as Ciphersuite>::G> {
let mut repr = <<C::EmbeddedCurve as Ciphersuite>::G as GroupEncoding>::Repr::default();
if repr.as_ref().len() != key.len() {
None?;
@@ -146,21 +149,18 @@ fn coerce_keys<C: EvrfCurve>(
/// An instance of the Serai key generation protocol.
#[derive(Debug)]
pub struct KeyGen<P: KeyGenParams> {
substrate_evrf_private_key:
Zeroizing<<<Ristretto as EvrfCurve>::EmbeddedCurve as Ciphersuite>::F>,
substrate_evrf_private_key: Zeroizing<<<Ristretto as Curves>::EmbeddedCurve as Ciphersuite>::F>,
network_evrf_private_key:
Zeroizing<<<P::ExternalNetworkCiphersuite as EvrfCurve>::EmbeddedCurve as Ciphersuite>::F>,
Zeroizing<<<P::ExternalNetworkCiphersuite as Curves>::EmbeddedCurve as Ciphersuite>::F>,
}
impl<P: KeyGenParams> KeyGen<P> {
/// Create a new key generation instance.
#[allow(clippy::new_ret_no_self)]
pub fn new(
substrate_evrf_private_key: Zeroizing<
<<Ristretto as EvrfCurve>::EmbeddedCurve as Ciphersuite>::F,
>,
substrate_evrf_private_key: Zeroizing<<<Ristretto as Curves>::EmbeddedCurve as Ciphersuite>::F>,
network_evrf_private_key: Zeroizing<
<<P::ExternalNetworkCiphersuite as EvrfCurve>::EmbeddedCurve as Ciphersuite>::F,
<<P::ExternalNetworkCiphersuite as Curves>::EmbeddedCurve as Ciphersuite>::F,
>,
) -> KeyGen<P> {
KeyGen { substrate_evrf_private_key, network_evrf_private_key }
@@ -171,8 +171,10 @@ impl<P: KeyGenParams> KeyGen<P> {
pub fn key_shares(
getter: &impl Get,
session: Session,
) -> Option<(Vec<ThresholdKeys<Ristretto>>, Vec<ThresholdKeys<P::ExternalNetworkCiphersuite>>)>
{
) -> Option<(
Vec<ThresholdKeys<<Ristretto as Curves>::ToweringCurve>>,
Vec<ThresholdKeys<<P::ExternalNetworkCiphersuite as Curves>::ToweringCurve>>,
)> {
// This is safe, despite not having a txn, since it's a static value
// It doesn't change over time/in relation to other operations
// It is solely set or unset
@@ -209,14 +211,14 @@ impl<P: KeyGenParams> KeyGen<P> {
faulty.extend(additional_faulty);
// Participate for both Substrate and the network
fn participate<C: EvrfCurve>(
fn participate<C: 'static + Curves>(
context: [u8; 32],
threshold: u16,
evrf_public_keys: &[<C::EmbeddedCurve as Ciphersuite>::G],
evrf_private_key: &Zeroizing<<C::EmbeddedCurve as Ciphersuite>::F>,
output: &mut impl io::Write,
) {
let participation = EvrfDkg::<C>::participate(
let participation = Dkg::<C>::participate(
&mut OsRng,
generators(),
context,
@@ -270,7 +272,7 @@ impl<P: KeyGenParams> KeyGen<P> {
}
CoordinatorMessage::Participation { session, participant, participation } => {
log::debug!("received participation from {:?} for {:?}", participant, session);
log::debug!("received participation from {participant:?} for {session:?}");
let Params { t: threshold, n, substrate_evrf_public_keys, network_evrf_public_keys } =
KeyGenDb::<P>::params(txn, session).unwrap();
@@ -305,9 +307,9 @@ impl<P: KeyGenParams> KeyGen<P> {
// participations and continue. We solely have to verify them, as to identify malicious
// participants and prevent DoSs, before returning
if Self::key_shares(txn, session).is_some() {
log::debug!("already finished generating a key for {:?}", session);
log::debug!("already finished generating a key for {session:?}");
match EvrfDkg::<Ristretto>::verify(
match Dkg::<Ristretto>::verify(
&mut OsRng,
generators(),
context::<P>(session, SUBSTRATE_KEY_CONTEXT),
@@ -324,7 +326,7 @@ impl<P: KeyGenParams> KeyGen<P> {
}
}
match EvrfDkg::<P::ExternalNetworkCiphersuite>::verify(
match Dkg::<P::ExternalNetworkCiphersuite>::verify(
&mut OsRng,
generators(),
context::<P>(session, NETWORK_KEY_CONTEXT),
@@ -404,7 +406,7 @@ impl<P: KeyGenParams> KeyGen<P> {
}
// If we now have the threshold participating, verify their `Participation`s
fn verify_dkg<P: KeyGenParams, C: EvrfCurve>(
fn verify_dkg<P: KeyGenParams, C: 'static + Curves>(
txn: &mut impl DbTxn,
session: Session,
true_if_substrate_false_if_network: bool,
@@ -412,7 +414,7 @@ impl<P: KeyGenParams> KeyGen<P> {
evrf_public_keys: &[<C::EmbeddedCurve as Ciphersuite>::G],
substrate_participations: &mut HashMap<Participant, Vec<u8>>,
network_participations: &mut HashMap<Participant, Vec<u8>>,
) -> Result<EvrfDkg<C>, Vec<ProcessorMessage>> {
) -> Result<Dkg<C>, Vec<ProcessorMessage>> {
// Parse the `Participation`s
let participations = (if true_if_substrate_false_if_network {
&*substrate_participations
@@ -433,7 +435,7 @@ impl<P: KeyGenParams> KeyGen<P> {
.collect();
// Actually call verify on the DKG
match EvrfDkg::<C>::verify(
match Dkg::<C>::verify(
&mut OsRng,
generators(),
context::<P>(

View File

@@ -25,8 +25,8 @@ zeroize = { version = "1", default-features = false, features = ["std"] }
scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["std"] }
borsh = { version = "1", default-features = false, features = ["std", "derive", "de_strict_order"] }
dalek-ff-group = { path = "../../crypto/dalek-ff-group", default-features = false, features = ["std"] }
ciphersuite = { path = "../../crypto/ciphersuite", default-features = false, features = ["std"] }
dalek-ff-group = { path = "../../crypto/dalek-ff-group", default-features = false, features = ["std"] }
dkg = { package = "dkg-evrf", path = "../../crypto/dkg/evrf", default-features = false, features = ["std", "ed25519"] }
frost = { package = "modular-frost", path = "../../crypto/frost", default-features = false }

View File

@@ -1,4 +1,4 @@
use ciphersuite::Ed25519;
use dkg::Ed25519;
pub(crate) struct KeyGenParams;
impl key_gen::KeyGenParams for KeyGenParams {

View File

@@ -1,6 +1,7 @@
use std::collections::HashMap;
use ciphersuite::{Ciphersuite, Ed25519};
use ciphersuite::Ciphersuite;
use dalek_ff_group::Ed25519;
use monero_wallet::{
block::Block as MBlock, rpc::ScannableBlock as MScannableBlock, ScanError, GuaranteedScanner,

View File

@@ -1,6 +1,7 @@
use zeroize::Zeroizing;
use ciphersuite::{Ciphersuite, Ed25519};
use ciphersuite::Ciphersuite;
use dalek_ff_group::Ed25519;
use monero_wallet::{address::SubaddressIndex, ViewPairError, GuaranteedViewPair};

View File

@@ -1,6 +1,7 @@
use std::io;
use ciphersuite::{group::Group, Ciphersuite, Ed25519};
use ciphersuite::{group::Group, Ciphersuite};
use dalek_ff_group::Ed25519;
use monero_wallet::WalletOutput;

View File

@@ -2,7 +2,7 @@ use std::io;
use rand_core::{RngCore, CryptoRng};
use ciphersuite::Ed25519;
use dalek_ff_group::Ed25519;
use frost::{dkg::ThresholdKeys, sign::PreprocessMachine};
use monero_wallet::{

View File

@@ -4,7 +4,8 @@ use zeroize::Zeroizing;
use rand_core::SeedableRng;
use rand_chacha::ChaCha20Rng;
use ciphersuite::{Ciphersuite, Ed25519};
use ciphersuite::Ciphersuite;
use dalek_ff_group::Ed25519;
use monero_wallet::rpc::{FeeRate, RpcError};
@@ -200,6 +201,9 @@ impl TransactionPlanner<Rpc, ()> for Planner {
Err(SendError::TooLargeTransaction) => {
panic!("too large transaction despite MAX_INPUTS/MAX_OUTPUTS")
}
Err(SendError::AmountsUnrepresentable { .. }) => {
panic!("monero-wallet AmountsUnrepresentable")
}
Err(
SendError::WrongPrivateKey |
SendError::MaliciousSerialization |
@@ -255,6 +259,9 @@ impl TransactionPlanner<Rpc, ()> for Planner {
Err(SendError::TooLargeTransaction) => {
panic!("too large transaction despite MAX_INPUTS/MAX_OUTPUTS")
}
Err(SendError::AmountsUnrepresentable { .. }) => {
panic!("monero-wallet AmountsUnrepresentable")
}
Err(
SendError::WrongPrivateKey |
SendError::MaliciousSerialization |

View File

@@ -70,12 +70,13 @@ impl<D: Db, S: ScannerFeed> ContinuallyRan for IndexTask<D, S> {
Err(e) => Err(format!("couldn't fetch the latest finalized block number: {e:?}"))?,
};
#[allow(clippy::uninlined_format_args)]
if latest_finalized < our_latest_finalized {
// Explicitly log this as an error as returned ephemeral errors are logged with debug
// This doesn't panic as the node should sync along our indexed chain, and if it doesn't,
// we'll panic at that point in time
log::error!(
"node is out of sync, latest finalized {} is behind our indexed {}",
"node is out of sync, latest finalized ({}) is behind our indexed ({})",
latest_finalized,
our_latest_finalized
);

View File

@@ -26,6 +26,7 @@ zeroize = { version = "1", default-features = false, features = ["std"] }
blake2 = { version = "0.10", default-features = false, features = ["std"] }
ciphersuite = { path = "../../crypto/ciphersuite", default-features = false, features = ["std"] }
dalek-ff-group = { path = "../../crypto/dalek-ff-group", default-features = false, features = ["std"] }
frost = { package = "modular-frost", path = "../../crypto/frost", default-features = false }
frost-schnorrkel = { path = "../../crypto/schnorrkel", default-features = false }

View File

@@ -2,7 +2,8 @@ use core::future::Future;
use std::collections::HashSet;
use blake2::{digest::typenum::U32, Digest, Blake2b};
use ciphersuite::{group::GroupEncoding, Ristretto};
use ciphersuite::group::GroupEncoding;
use dalek_ff_group::Ristretto;
use frost::dkg::ThresholdKeys;
use scale::Encode;

View File

@@ -1,6 +1,6 @@
use core::future::Future;
use ciphersuite::Ristretto;
use dalek_ff_group::Ristretto;
use frost::dkg::ThresholdKeys;
use scale::Encode;

View File

@@ -7,8 +7,9 @@ use std::collections::HashMap;
use zeroize::Zeroizing;
use ciphersuite::{group::GroupEncoding, Ciphersuite, Ristretto};
use frost::dkg::{ThresholdCore, ThresholdKeys};
use ciphersuite::{group::GroupEncoding, Ciphersuite};
use dalek_ff_group::Ristretto;
use frost::dkg::ThresholdKeys;
use serai_primitives::Signature;
use serai_validator_sets_primitives::{Session, SlashReport};
@@ -262,11 +263,8 @@ impl<
let mut substrate_keys = vec![];
let mut external_keys = vec![];
while !buf.is_empty() {
substrate_keys
.push(ThresholdKeys::from(ThresholdCore::<Ristretto>::read(&mut buf).unwrap()));
external_keys.push(ThresholdKeys::from(
ThresholdCore::<CiphersuiteFor<S, Sch>>::read(&mut buf).unwrap(),
));
substrate_keys.push(ThresholdKeys::<Ristretto>::read(&mut buf).unwrap());
external_keys.push(ThresholdKeys::<CiphersuiteFor<S, Sch>>::read(&mut buf).unwrap());
}
tasks.insert(

View File

@@ -1,6 +1,6 @@
use core::{marker::PhantomData, future::Future};
use ciphersuite::Ristretto;
use dalek_ff_group::Ristretto;
use frost::dkg::ThresholdKeys;
use serai_primitives::Signature;

View File

@@ -5,7 +5,7 @@ use std::{
use rand_core::{RngCore, CryptoRng};
use ciphersuite::Ristretto;
use dalek_ff_group::Ristretto;
use frost::{
dkg::{Participant, ThresholdKeys},
FrostError,