2024-09-05 14:42:06 -04:00
|
|
|
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
|
|
|
|
#![doc = include_str!("../README.md")]
|
|
|
|
|
#![deny(missing_docs)]
|
|
|
|
|
|
2024-09-07 03:33:26 -04:00
|
|
|
use core::{fmt::Debug, marker::PhantomData};
|
2024-09-08 00:30:55 -04:00
|
|
|
use std::collections::HashMap;
|
2024-09-06 03:20:38 -04:00
|
|
|
|
2024-09-07 03:33:26 -04:00
|
|
|
use zeroize::Zeroizing;
|
2024-09-06 03:20:38 -04:00
|
|
|
|
2024-09-08 22:13:42 -04:00
|
|
|
use ciphersuite::{group::GroupEncoding, Ciphersuite, Ristretto};
|
2024-09-07 03:33:26 -04:00
|
|
|
use frost::dkg::{ThresholdCore, ThresholdKeys};
|
|
|
|
|
|
2024-09-08 22:13:42 -04:00
|
|
|
use serai_validator_sets_primitives::Session;
|
2024-09-09 01:01:29 -04:00
|
|
|
use serai_in_instructions_primitives::SignedBatch;
|
2024-09-08 22:13:42 -04:00
|
|
|
|
2024-09-07 03:33:26 -04:00
|
|
|
use serai_db::{DbTxn, Db};
|
|
|
|
|
|
2024-09-08 22:13:42 -04:00
|
|
|
use messages::sign::{VariantSignId, ProcessorMessage, CoordinatorMessage};
|
|
|
|
|
|
|
|
|
|
use primitives::task::{Task, TaskHandle, ContinuallyRan};
|
|
|
|
|
use scheduler::{Transaction, SignableTransaction, TransactionFor};
|
2024-09-06 03:20:38 -04:00
|
|
|
|
2024-09-09 01:01:29 -04:00
|
|
|
mod wrapped_schnorrkel;
|
|
|
|
|
pub(crate) use wrapped_schnorrkel::WrappedSchnorrkelMachine;
|
|
|
|
|
|
2024-09-06 03:20:38 -04:00
|
|
|
pub(crate) mod db;
|
|
|
|
|
|
2024-09-08 22:13:42 -04:00
|
|
|
mod coordinator;
|
|
|
|
|
use coordinator::CoordinatorTask;
|
|
|
|
|
|
2024-09-09 01:01:29 -04:00
|
|
|
mod batch;
|
|
|
|
|
use batch::BatchSignerTask;
|
|
|
|
|
|
2024-09-05 14:42:06 -04:00
|
|
|
mod transaction;
|
2024-09-09 01:01:29 -04:00
|
|
|
use transaction::TransactionSignerTask;
|
2024-09-08 22:13:42 -04:00
|
|
|
|
|
|
|
|
/// A connection to the Coordinator which messages can be published with.
|
|
|
|
|
#[async_trait::async_trait]
|
|
|
|
|
pub trait Coordinator: 'static + Send + Sync {
|
2024-09-09 01:01:29 -04:00
|
|
|
/// An error encountered when interacting with a coordinator.
|
2024-09-08 22:13:42 -04:00
|
|
|
///
|
2024-09-09 01:01:29 -04:00
|
|
|
/// This MUST be an ephemeral error. Retrying an interaction MUST eventually resolve without
|
2024-09-08 22:13:42 -04:00
|
|
|
/// manual intervention/changing the arguments.
|
|
|
|
|
type EphemeralError: Debug;
|
|
|
|
|
|
|
|
|
|
/// Send a `messages::sign::ProcessorMessage`.
|
|
|
|
|
async fn send(&mut self, message: ProcessorMessage) -> Result<(), Self::EphemeralError>;
|
2024-09-09 01:01:29 -04:00
|
|
|
|
2024-09-09 03:06:37 -04:00
|
|
|
/// Publish a `Batch`.
|
|
|
|
|
async fn publish_batch(&mut self, batch: Batch) -> Result<(), Self::EphemeralError>;
|
|
|
|
|
|
2024-09-09 01:01:29 -04:00
|
|
|
/// Publish a `SignedBatch`.
|
2024-09-09 03:06:37 -04:00
|
|
|
async fn publish_signed_batch(&mut self, batch: SignedBatch) -> Result<(), Self::EphemeralError>;
|
2024-09-08 22:13:42 -04:00
|
|
|
}
|
2024-09-05 14:42:06 -04:00
|
|
|
|
2024-09-06 03:20:38 -04:00
|
|
|
/// An object capable of publishing a transaction.
|
|
|
|
|
#[async_trait::async_trait]
|
2024-09-08 22:13:42 -04:00
|
|
|
pub trait TransactionPublisher<T: Transaction>: 'static + Send + Sync + Clone {
|
2024-09-06 03:20:38 -04:00
|
|
|
/// An error encountered when publishing a transaction.
|
|
|
|
|
///
|
|
|
|
|
/// This MUST be an ephemeral error. Retrying publication MUST eventually resolve without manual
|
|
|
|
|
/// intervention/changing the arguments.
|
|
|
|
|
type EphemeralError: Debug;
|
|
|
|
|
|
|
|
|
|
/// Publish a transaction.
|
|
|
|
|
///
|
|
|
|
|
/// This will be called multiple times, with the same transaction, until the transaction is
|
|
|
|
|
/// confirmed on-chain.
|
2024-09-06 04:15:02 -04:00
|
|
|
///
|
|
|
|
|
/// The transaction already being present in the mempool/on-chain MUST NOT be considered an
|
|
|
|
|
/// error.
|
2024-09-07 03:33:26 -04:00
|
|
|
async fn publish(&self, tx: T) -> Result<(), Self::EphemeralError>;
|
|
|
|
|
}
|
|
|
|
|
|
2024-09-08 22:13:42 -04:00
|
|
|
struct Tasks {
|
|
|
|
|
cosigner: TaskHandle,
|
|
|
|
|
batch: TaskHandle,
|
|
|
|
|
slash_report: TaskHandle,
|
|
|
|
|
transaction: TaskHandle,
|
|
|
|
|
}
|
|
|
|
|
|
2024-09-07 03:33:26 -04:00
|
|
|
/// The signers used by a processor.
|
2024-09-08 22:13:42 -04:00
|
|
|
#[allow(non_snake_case)]
|
2024-09-08 00:30:55 -04:00
|
|
|
pub struct Signers<ST: SignableTransaction> {
|
2024-09-08 22:13:42 -04:00
|
|
|
coordinator_handle: TaskHandle,
|
|
|
|
|
tasks: HashMap<Session, Tasks>,
|
2024-09-08 00:30:55 -04:00
|
|
|
_ST: PhantomData<ST>,
|
|
|
|
|
}
|
2024-09-07 03:33:26 -04:00
|
|
|
|
|
|
|
|
/*
|
|
|
|
|
This is completely outside of consensus, so the worst that can happen is:
|
|
|
|
|
|
|
|
|
|
1) Leakage of a private key, hence the usage of frost-attempt-manager which has an API to ensure
|
|
|
|
|
that doesn't happen
|
|
|
|
|
2) The database isn't perfectly cleaned up (leaving some bytes on disk wasted)
|
|
|
|
|
3) The state isn't perfectly cleaned up (leaving some bytes in RAM wasted)
|
|
|
|
|
|
|
|
|
|
The last two are notably possible via a series of race conditions. For example, if an Eventuality
|
|
|
|
|
completion comes in *before* we registered a key, the signer will hold the signing protocol in
|
|
|
|
|
memory until the session is retired entirely.
|
|
|
|
|
*/
|
|
|
|
|
impl<ST: SignableTransaction> Signers<ST> {
|
|
|
|
|
/// Initialize the signers.
|
|
|
|
|
///
|
|
|
|
|
/// This will spawn tasks for any historically registered keys.
|
2024-09-08 22:13:42 -04:00
|
|
|
pub fn new(
|
|
|
|
|
mut db: impl Db,
|
|
|
|
|
coordinator: impl Coordinator,
|
|
|
|
|
publisher: &impl TransactionPublisher<TransactionFor<ST>>,
|
|
|
|
|
) -> Self {
|
|
|
|
|
/*
|
|
|
|
|
On boot, perform any database cleanup which was queued.
|
|
|
|
|
|
|
|
|
|
We don't do this cleanup at time of dropping the task as we'd need to wait an unbounded
|
|
|
|
|
amount of time for the task to stop (requiring an async task), then we'd have to drain the
|
|
|
|
|
channels (which would be on a distinct DB transaction and risk not occurring if we rebooted
|
|
|
|
|
while waiting for the task to stop). This is the easiest way to handle this.
|
|
|
|
|
*/
|
|
|
|
|
{
|
|
|
|
|
let mut txn = db.txn();
|
|
|
|
|
for (session, external_key_bytes) in db::ToCleanup::get(&txn).unwrap_or(vec![]) {
|
|
|
|
|
let mut external_key_bytes = external_key_bytes.as_slice();
|
|
|
|
|
let external_key =
|
|
|
|
|
<ST::Ciphersuite as Ciphersuite>::read_G(&mut external_key_bytes).unwrap();
|
|
|
|
|
assert!(external_key_bytes.is_empty());
|
|
|
|
|
|
2024-09-09 01:01:29 -04:00
|
|
|
// Drain the Batches to sign
|
|
|
|
|
// This will be fully populated by the scanner before retiry occurs, making this perfect
|
|
|
|
|
// in not leaving any pending blobs behind
|
|
|
|
|
while scanner::BatchesToSign::try_recv(&mut txn, &external_key).is_some() {}
|
|
|
|
|
// Drain the acknowledged batches to no longer sign
|
|
|
|
|
while scanner::AcknowledgedBatches::try_recv(&mut txn, &external_key).is_some() {}
|
|
|
|
|
|
2024-09-08 22:13:42 -04:00
|
|
|
// Drain the transactions to sign
|
2024-09-09 01:01:29 -04:00
|
|
|
// This will be fully populated by the scheduler before retiry
|
2024-09-08 22:13:42 -04:00
|
|
|
while scheduler::TransactionsToSign::<ST>::try_recv(&mut txn, &external_key).is_some() {}
|
|
|
|
|
|
|
|
|
|
// Drain the completed Eventualities
|
|
|
|
|
while scanner::CompletedEventualities::try_recv(&mut txn, &external_key).is_some() {}
|
|
|
|
|
|
|
|
|
|
// Drain our DB channels
|
|
|
|
|
while db::CoordinatorToCosignerMessages::try_recv(&mut txn, session).is_some() {}
|
|
|
|
|
while db::CosignerToCoordinatorMessages::try_recv(&mut txn, session).is_some() {}
|
|
|
|
|
while db::CoordinatorToBatchSignerMessages::try_recv(&mut txn, session).is_some() {}
|
|
|
|
|
while db::BatchSignerToCoordinatorMessages::try_recv(&mut txn, session).is_some() {}
|
|
|
|
|
while db::CoordinatorToSlashReportSignerMessages::try_recv(&mut txn, session).is_some() {}
|
|
|
|
|
while db::SlashReportSignerToCoordinatorMessages::try_recv(&mut txn, session).is_some() {}
|
|
|
|
|
while db::CoordinatorToTransactionSignerMessages::try_recv(&mut txn, session).is_some() {}
|
|
|
|
|
while db::TransactionSignerToCoordinatorMessages::try_recv(&mut txn, session).is_some() {}
|
|
|
|
|
}
|
|
|
|
|
db::ToCleanup::del(&mut txn);
|
|
|
|
|
txn.commit();
|
|
|
|
|
}
|
|
|
|
|
|
2024-09-08 00:30:55 -04:00
|
|
|
let mut tasks = HashMap::new();
|
|
|
|
|
|
2024-09-08 22:13:42 -04:00
|
|
|
let (coordinator_task, coordinator_handle) = Task::new();
|
|
|
|
|
tokio::spawn(
|
|
|
|
|
CoordinatorTask::new(db.clone(), coordinator).continually_run(coordinator_task, vec![]),
|
|
|
|
|
);
|
|
|
|
|
|
2024-09-07 03:33:26 -04:00
|
|
|
for session in db::RegisteredKeys::get(&db).unwrap_or(vec![]) {
|
|
|
|
|
let buf = db::SerializedKeys::get(&db, session).unwrap();
|
|
|
|
|
let mut buf = buf.as_slice();
|
|
|
|
|
|
|
|
|
|
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::<ST::Ciphersuite>::read(&mut buf).unwrap()));
|
|
|
|
|
}
|
|
|
|
|
|
2024-09-09 01:15:56 -04:00
|
|
|
// TODO: Cosigner and slash report signers
|
2024-09-08 22:13:42 -04:00
|
|
|
|
2024-09-09 01:01:29 -04:00
|
|
|
let (batch_task, batch_handle) = Task::new();
|
|
|
|
|
tokio::spawn(
|
|
|
|
|
BatchSignerTask::new(
|
|
|
|
|
db.clone(),
|
|
|
|
|
session,
|
|
|
|
|
external_keys[0].group_key(),
|
|
|
|
|
substrate_keys.clone(),
|
|
|
|
|
)
|
|
|
|
|
.continually_run(batch_task, vec![coordinator_handle.clone()]),
|
|
|
|
|
);
|
|
|
|
|
|
2024-09-08 22:13:42 -04:00
|
|
|
let (transaction_task, transaction_handle) = Task::new();
|
|
|
|
|
tokio::spawn(
|
2024-09-09 01:01:29 -04:00
|
|
|
TransactionSignerTask::<_, ST, _>::new(
|
|
|
|
|
db.clone(),
|
|
|
|
|
publisher.clone(),
|
|
|
|
|
session,
|
|
|
|
|
external_keys,
|
|
|
|
|
)
|
|
|
|
|
.continually_run(transaction_task, vec![coordinator_handle.clone()]),
|
2024-09-08 22:13:42 -04:00
|
|
|
);
|
|
|
|
|
|
2024-09-09 01:01:29 -04:00
|
|
|
tasks.insert(
|
|
|
|
|
session,
|
|
|
|
|
Tasks {
|
|
|
|
|
cosigner: todo!("TODO"),
|
|
|
|
|
batch: batch_handle,
|
|
|
|
|
slash_report: todo!("TODO"),
|
|
|
|
|
transaction: transaction_handle,
|
|
|
|
|
},
|
|
|
|
|
);
|
2024-09-07 03:33:26 -04:00
|
|
|
}
|
|
|
|
|
|
2024-09-08 22:13:42 -04:00
|
|
|
Self { coordinator_handle, tasks, _ST: PhantomData }
|
2024-09-07 03:33:26 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Register a set of keys to sign with.
|
|
|
|
|
///
|
|
|
|
|
/// If this session (or a session after it) has already been retired, this is a NOP.
|
|
|
|
|
pub fn register_keys(
|
|
|
|
|
&mut self,
|
|
|
|
|
txn: &mut impl DbTxn,
|
|
|
|
|
session: Session,
|
|
|
|
|
substrate_keys: Vec<ThresholdKeys<Ristretto>>,
|
|
|
|
|
network_keys: Vec<ThresholdKeys<ST::Ciphersuite>>,
|
|
|
|
|
) {
|
2024-09-08 00:30:55 -04:00
|
|
|
// Don't register already retired keys
|
2024-09-07 03:33:26 -04:00
|
|
|
if Some(session.0) <= db::LatestRetiredSession::get(txn).map(|session| session.0) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
{
|
|
|
|
|
let mut sessions = db::RegisteredKeys::get(txn).unwrap_or_else(|| Vec::with_capacity(1));
|
|
|
|
|
sessions.push(session);
|
|
|
|
|
db::RegisteredKeys::set(txn, &sessions);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
{
|
|
|
|
|
let mut buf = Zeroizing::new(Vec::with_capacity(2 * substrate_keys.len() * 128));
|
|
|
|
|
for (substrate_keys, network_keys) in substrate_keys.into_iter().zip(network_keys) {
|
|
|
|
|
buf.extend(&*substrate_keys.serialize());
|
|
|
|
|
buf.extend(&*network_keys.serialize());
|
|
|
|
|
}
|
|
|
|
|
db::SerializedKeys::set(txn, session, &buf);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Retire the signers for a session.
|
|
|
|
|
///
|
|
|
|
|
/// This MUST be called in order, for every session (even if we didn't register keys for this
|
|
|
|
|
/// session).
|
|
|
|
|
pub fn retire_session(
|
|
|
|
|
&mut self,
|
|
|
|
|
txn: &mut impl DbTxn,
|
|
|
|
|
session: Session,
|
|
|
|
|
external_key: &impl GroupEncoding,
|
|
|
|
|
) {
|
|
|
|
|
// Update the latest retired session
|
|
|
|
|
{
|
|
|
|
|
let next_to_retire =
|
|
|
|
|
db::LatestRetiredSession::get(txn).map_or(Session(0), |session| Session(session.0 + 1));
|
|
|
|
|
assert_eq!(session, next_to_retire);
|
|
|
|
|
db::LatestRetiredSession::set(txn, &session);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Update RegisteredKeys/SerializedKeys
|
|
|
|
|
if let Some(registered) = db::RegisteredKeys::get(txn) {
|
|
|
|
|
db::RegisteredKeys::set(
|
|
|
|
|
txn,
|
|
|
|
|
®istered.into_iter().filter(|session_i| *session_i != session).collect(),
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
db::SerializedKeys::del(txn, session);
|
|
|
|
|
|
2024-09-08 00:30:55 -04:00
|
|
|
// Queue the session for clean up
|
|
|
|
|
let mut to_cleanup = db::ToCleanup::get(txn).unwrap_or(vec![]);
|
|
|
|
|
to_cleanup.push((session, external_key.to_bytes().as_ref().to_vec()));
|
|
|
|
|
db::ToCleanup::set(txn, &to_cleanup);
|
2024-09-08 22:13:42 -04:00
|
|
|
}
|
2024-09-08 00:30:55 -04:00
|
|
|
|
2024-09-08 22:13:42 -04:00
|
|
|
/// Queue handling a message.
|
|
|
|
|
///
|
|
|
|
|
/// This is a cheap call and able to be done inline with a higher-level loop.
|
|
|
|
|
pub fn queue_message(&mut self, txn: &mut impl DbTxn, message: &CoordinatorMessage) {
|
|
|
|
|
let sign_id = message.sign_id();
|
|
|
|
|
let tasks = self.tasks.get(&sign_id.session);
|
|
|
|
|
match sign_id.id {
|
|
|
|
|
VariantSignId::Cosign(_) => {
|
|
|
|
|
db::CoordinatorToCosignerMessages::send(txn, sign_id.session, message);
|
2024-09-09 01:01:29 -04:00
|
|
|
if let Some(tasks) = tasks {
|
|
|
|
|
tasks.cosigner.run_now();
|
|
|
|
|
}
|
2024-09-08 22:13:42 -04:00
|
|
|
}
|
|
|
|
|
VariantSignId::Batch(_) => {
|
|
|
|
|
db::CoordinatorToBatchSignerMessages::send(txn, sign_id.session, message);
|
2024-09-09 01:01:29 -04:00
|
|
|
if let Some(tasks) = tasks {
|
|
|
|
|
tasks.batch.run_now();
|
|
|
|
|
}
|
2024-09-08 22:13:42 -04:00
|
|
|
}
|
|
|
|
|
VariantSignId::SlashReport(_) => {
|
|
|
|
|
db::CoordinatorToSlashReportSignerMessages::send(txn, sign_id.session, message);
|
2024-09-09 01:01:29 -04:00
|
|
|
if let Some(tasks) = tasks {
|
|
|
|
|
tasks.slash_report.run_now();
|
|
|
|
|
}
|
2024-09-08 22:13:42 -04:00
|
|
|
}
|
|
|
|
|
VariantSignId::Transaction(_) => {
|
|
|
|
|
db::CoordinatorToTransactionSignerMessages::send(txn, sign_id.session, message);
|
2024-09-09 01:01:29 -04:00
|
|
|
if let Some(tasks) = tasks {
|
|
|
|
|
tasks.transaction.run_now();
|
|
|
|
|
}
|
2024-09-08 00:30:55 -04:00
|
|
|
}
|
|
|
|
|
}
|
2024-09-07 03:33:26 -04:00
|
|
|
}
|
2024-09-06 03:20:38 -04:00
|
|
|
}
|