Skip to content

Commit

Permalink
use PublicKeyBytes instead of PublicKey
Browse files Browse the repository at this point in the history
  • Loading branch information
dknopik committed Jan 28, 2025
1 parent 5cc2376 commit a55717e
Show file tree
Hide file tree
Showing 14 changed files with 77 additions and 55 deletions.
4 changes: 2 additions & 2 deletions anchor/common/ssv_types/src/cluster.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::OperatorId;
use derive_more::{Deref, From};
use std::collections::HashSet;
use types::{Address, Graffiti, PublicKey};
use types::{Address, Graffiti, PublicKeyBytes};

/// Unique identifier for a cluster
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash, From, Deref)]
Expand Down Expand Up @@ -45,7 +45,7 @@ pub struct ValidatorIndex(pub usize);
#[derive(Debug, Clone)]
pub struct ValidatorMetadata {
/// Public key of the validator
pub public_key: PublicKey,
pub public_key: PublicKeyBytes,
/// The cluster that is responsible for this validator
pub cluster_id: ClusterId,
/// Index of the validator
Expand Down
6 changes: 3 additions & 3 deletions anchor/common/ssv_types/src/share.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
use crate::{ClusterId, OperatorId};
use types::PublicKey;
use types::PublicKeyBytes;

/// One of N shares of a split validator key.
#[derive(Debug, Clone)]
pub struct Share {
/// Public Key of the validator
pub validator_pubkey: PublicKey,
pub validator_pubkey: PublicKeyBytes,
/// Operator this share belongs to
pub operator_id: OperatorId,
/// Cluster the operator who owns this share belongs to
pub cluster_id: ClusterId,
/// The public key of this Share
pub share_pubkey: PublicKey,
pub share_pubkey: PublicKeyBytes,
/// The encrypted private key of the share
pub encrypted_private_key: [u8; 256],
}
8 changes: 4 additions & 4 deletions anchor/common/ssv_types/src/sql_conversions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use openssl::rsa::Rsa;
use rusqlite::{types::Type, Error as SqlError, Row};
use std::io::{Error, ErrorKind};
use std::str::FromStr;
use types::{Address, Graffiti, PublicKey, GRAFFITI_BYTES_LEN};
use types::{Address, Graffiti, PublicKeyBytes, GRAFFITI_BYTES_LEN};

// Helper for converting to Rustqlite Error
fn from_sql_error<E: std::error::Error + Send + Sync + 'static>(
Expand Down Expand Up @@ -107,7 +107,7 @@ impl TryFrom<&Row<'_>> for ValidatorMetadata {
fn try_from(row: &Row) -> Result<Self, Self::Error> {
// Get public key from column 0
let validator_pubkey_str = row.get::<_, String>(0)?;
let public_key = PublicKey::from_str(&validator_pubkey_str)
let public_key = PublicKeyBytes::from_str(&validator_pubkey_str)
.map_err(|e| from_sql_error(1, Type::Text, Error::new(ErrorKind::InvalidInput, e)))?;

// Get ClusterId from column 1
Expand All @@ -134,7 +134,7 @@ impl TryFrom<&Row<'_>> for Share {
fn try_from(row: &Row) -> Result<Self, Self::Error> {
// Get Share PublicKey from column 0
let share_pubkey_str = row.get::<_, String>(0)?;
let share_pubkey = PublicKey::from_str(&share_pubkey_str)
let share_pubkey = PublicKeyBytes::from_str(&share_pubkey_str)
.map_err(|e| from_sql_error(0, Type::Text, Error::new(ErrorKind::InvalidInput, e)))?;

// Get the encrypted private key from column 1
Expand All @@ -146,7 +146,7 @@ impl TryFrom<&Row<'_>> for Share {

// Get the Validator PublicKey from column 4
let validator_pubkey_str = row.get::<_, String>(4)?;
let validator_pubkey = PublicKey::from_str(&validator_pubkey_str)
let validator_pubkey = PublicKeyBytes::from_str(&validator_pubkey_str)
.map_err(|e| from_sql_error(4, Type::Text, Error::new(ErrorKind::InvalidInput, e)))?;

Ok(Share {
Expand Down
4 changes: 2 additions & 2 deletions anchor/database/src/cluster_operations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use super::{DatabaseError, NetworkDatabase, NonUniqueIndex, SqlStatement, Unique
use rusqlite::params;
use ssv_types::{Cluster, ClusterId, Share, ValidatorMetadata};
use std::sync::atomic::Ordering;
use types::{Address, PublicKey};
use types::{Address, PublicKeyBytes};

/// Implements all cluster related functionality on the database
impl NetworkDatabase {
Expand Down Expand Up @@ -105,7 +105,7 @@ impl NetworkDatabase {
/// Delete a validator from a cluster. This will cascade and remove all corresponding share
/// data for this validator. If this validator is the last one in the cluster, the cluster
/// and all corresponding cluster members will also be removed
pub fn delete_validator(&self, validator_pubkey: &PublicKey) -> Result<(), DatabaseError> {
pub fn delete_validator(&self, validator_pubkey: &PublicKeyBytes) -> Result<(), DatabaseError> {
// Remove from database
let conn = self.connection()?;
conn.prepare_cached(SQL[&SqlStatement::DeleteValidator])?
Expand Down
16 changes: 11 additions & 5 deletions anchor/database/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use std::path::Path;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::time::Duration;
use types::{Address, PublicKey};
use types::{Address, PublicKeyBytes};

pub use crate::error::DatabaseError;
pub use crate::multi_index::{MultiIndexMap, *};
Expand Down Expand Up @@ -38,19 +38,25 @@ type PoolConn = r2d2::PooledConnection<SqliteConnectionManager>;
/// Secondary: cluster id. corresponds to a list of shares
/// Tertiary: owner of the cluster. corresponds to a list of shares
pub(crate) type ShareMultiIndexMap =
MultiIndexMap<PublicKey, ClusterId, Address, Share, NonUniqueTag, NonUniqueTag>;
MultiIndexMap<PublicKeyBytes, ClusterId, Address, Share, NonUniqueTag, NonUniqueTag>;
/// Metadata for all validators in the network
/// Primary: public key of the validator. uniquely identifies the metadata
/// Secondary: cluster id. corresponds to list of metadata for all validators
/// Tertiary: owner of the cluster: corresponds to list of metadata for all validators
pub(crate) type MetadataMultiIndexMap =
MultiIndexMap<PublicKey, ClusterId, Address, ValidatorMetadata, NonUniqueTag, NonUniqueTag>;
pub(crate) type MetadataMultiIndexMap = MultiIndexMap<
PublicKeyBytes,
ClusterId,
Address,
ValidatorMetadata,
NonUniqueTag,
NonUniqueTag,
>;
/// All of the clusters in the network
/// Primary: cluster id. uniquely identifies a cluster
/// Secondary: public key of the validator. uniquely identifies a cluster
/// Tertiary: owner of the cluster. uniquely identifies a cluster
pub(crate) type ClusterMultiIndexMap =
MultiIndexMap<ClusterId, PublicKey, Address, Cluster, UniqueTag, UniqueTag>;
MultiIndexMap<ClusterId, PublicKeyBytes, Address, Cluster, UniqueTag, UniqueTag>;

// Information that needs to be accessed via multiple different indicies
#[derive(Debug)]
Expand Down
4 changes: 2 additions & 2 deletions anchor/database/src/share_operations.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
use super::{DatabaseError, NetworkDatabase, SqlStatement, SQL};
use rusqlite::{params, Transaction};
use ssv_types::Share;
use types::PublicKey;
use types::PublicKeyBytes;

/// Implements all Share related functionality on the database
impl NetworkDatabase {
pub(crate) fn insert_share(
&self,
tx: &Transaction<'_>,
share: &Share,
validator_pubkey: &PublicKey,
validator_pubkey: &PublicKeyBytes,
) -> Result<(), DatabaseError> {
tx.prepare_cached(SQL[&SqlStatement::InsertShare])?
.execute(params![
Expand Down
2 changes: 1 addition & 1 deletion anchor/database/src/tests/cluster_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ mod cluster_database_tests {
// cluster, cluster members, and shares are all cleaned up
fn test_delete_last_validator() {
let fixture = TestFixture::new();
let pubkey = fixture.validator.public_key.clone();
let pubkey = fixture.validator.public_key;
assert!(fixture.db.delete_validator(&pubkey).is_ok());

// Since there was only one validator in the cluster, everything should be removed
Expand Down
2 changes: 1 addition & 1 deletion anchor/database/src/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ pub mod test_prelude {
pub use crate::NetworkDatabase;
pub use ssv_types::*;
pub use tempfile::tempdir;
pub use types::{Address, Graffiti, PublicKey};
pub use types::{Address, Graffiti, PublicKeyBytes};
}

#[cfg(test)]
Expand Down
33 changes: 22 additions & 11 deletions anchor/database/src/tests/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,9 +157,13 @@ pub mod generators {
pub mod share {
use super::*;
// Generate a random keyshare
pub fn random(cluster_id: ClusterId, operator_id: OperatorId, pk: &PublicKey) -> Share {
pub fn random(
cluster_id: ClusterId,
operator_id: OperatorId,
pk: &PublicKeyBytes,
) -> Share {
Share {
validator_pubkey: pk.clone(),
validator_pubkey: *pk,
operator_id,
cluster_id,
share_pubkey: pubkey::random(),
Expand All @@ -170,6 +174,7 @@ pub mod generators {

pub mod pubkey {
use super::*;
use types::PublicKeyBytes;

// Generate a random RSA public key for operators
pub fn random_rsa() -> Rsa<Public> {
Expand All @@ -181,9 +186,9 @@ pub mod generators {
}

// Generate a random public key for validators
pub fn random() -> PublicKey {
pub fn random() -> PublicKeyBytes {
let rng = &mut XorShiftRng::from_seed(DEFAULT_SEED);
PublicKey::random_for_test(rng)
PublicKeyBytes::random_for_test(rng)
}
}

Expand All @@ -208,6 +213,7 @@ pub mod generators {
pub mod queries {
use super::*;
use std::str::FromStr;
use types::PublicKeyBytes;

// Single selection query statements
const GET_OPERATOR: &str =
Expand Down Expand Up @@ -247,23 +253,23 @@ pub mod queries {
}

// Get a share from the database
pub fn get_shares(db: &NetworkDatabase, pubkey: &PublicKey) -> Option<Vec<Share>> {
pub fn get_shares(db: &NetworkDatabase, pubkey: &PublicKeyBytes) -> Option<Vec<Share>> {
let conn = db.connection().unwrap();
let mut stmt = conn
.prepare(GET_SHARES)
.expect("Failed to prepare statement");
let shares: Result<Vec<_>, _> = stmt
.query_map(params![pubkey.to_string()], |row| {
let share_pubkey_str = row.get::<_, String>(0)?;
let share_pubkey = PublicKey::from_str(&share_pubkey_str).unwrap();
let share_pubkey = PublicKeyBytes::from_str(&share_pubkey_str).unwrap();
let encrypted_private_key: [u8; 256] = row.get(1)?;

// Get the OperatorId from column 6 and ClusterId from column 1
let cluster_id = ClusterId(row.get(2)?);
let operator_id = OperatorId(row.get(3)?);

Ok(Share {
validator_pubkey: pubkey.clone(),
validator_pubkey: *pubkey,
operator_id,
cluster_id,
share_pubkey,
Expand Down Expand Up @@ -458,6 +464,7 @@ pub mod assertions {
//
pub mod share {
use super::*;
use types::PublicKeyBytes;
fn data(s1: &Share, s2: &Share) {
assert_eq!(s1.cluster_id, s2.cluster_id);
assert_eq!(s1.encrypted_private_key, s2.encrypted_private_key);
Expand All @@ -466,7 +473,11 @@ pub mod assertions {
}

// Verifies that a share is in memory
pub fn exists_in_memory(db: &NetworkDatabase, validator_pubkey: &PublicKey, s: &Share) {
pub fn exists_in_memory(
db: &NetworkDatabase,
validator_pubkey: &PublicKeyBytes,
s: &Share,
) {
let stored_share = db
.shares()
.get_by(validator_pubkey)
Expand All @@ -475,13 +486,13 @@ pub mod assertions {
}

// Verifies that a share is not in memory
pub fn exists_not_in_memory(db: &NetworkDatabase, validator_pubkey: &PublicKey) {
pub fn exists_not_in_memory(db: &NetworkDatabase, validator_pubkey: &PublicKeyBytes) {
let stored_share = db.shares().get_by(validator_pubkey);
assert!(stored_share.is_none());
}

// Verifies that all of the shares for a validator are in the database
pub fn exists_in_db(db: &NetworkDatabase, validator_pubkey: &PublicKey, s: &[Share]) {
pub fn exists_in_db(db: &NetworkDatabase, validator_pubkey: &PublicKeyBytes, s: &[Share]) {
let db_shares =
queries::get_shares(db, validator_pubkey).expect("Shares should exist in db");
// have to pair them up since we dont know what order they will be returned from db in
Expand All @@ -496,7 +507,7 @@ pub mod assertions {
}

// Verifies that all of the shares for a validator are not in the database
pub fn exists_not_in_db(db: &NetworkDatabase, validator_pubkey: &PublicKey) {
pub fn exists_not_in_db(db: &NetworkDatabase, validator_pubkey: &PublicKeyBytes) {
let shares = queries::get_shares(db, validator_pubkey);
assert!(shares.is_none());
}
Expand Down
4 changes: 2 additions & 2 deletions anchor/database/src/validator_operations.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{multi_index::UniqueIndex, DatabaseError, NetworkDatabase, SqlStatement, SQL};
use rusqlite::params;
use types::{Address, Graffiti, PublicKey};
use types::{Address, Graffiti, PublicKeyBytes};

/// Implements all validator specific database functionality
impl NetworkDatabase {
Expand Down Expand Up @@ -31,7 +31,7 @@ impl NetworkDatabase {
/// Update the Graffiti for a Validator
pub fn update_graffiti(
&self,
validator_pubkey: &PublicKey,
validator_pubkey: &PublicKeyBytes,
graffiti: Graffiti,
) -> Result<(), DatabaseError> {
// Make sure this validator exists by getting the in memory entry
Expand Down
6 changes: 3 additions & 3 deletions anchor/eth/src/event_processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use std::collections::{HashMap, HashSet};
use std::str::FromStr;
use std::sync::Arc;
use tracing::{debug, error, info, instrument, trace, warn};
use types::PublicKey;
use types::PublicKeyBytes;

// Specific Handler for a log type
type EventHandler = fn(&EventProcessor, &Log) -> Result<(), ExecutionError>;
Expand Down Expand Up @@ -231,7 +231,7 @@ impl EventProcessor {
})?;

// Process data into a usable form
let validator_pubkey = PublicKey::from_str(&publicKey.to_string()).map_err(|e| {
let validator_pubkey = PublicKeyBytes::from_str(&publicKey.to_string()).map_err(|e| {
debug!(
validator_pubkey = %publicKey,
error = %e,
Expand Down Expand Up @@ -319,7 +319,7 @@ impl EventProcessor {
debug!(owner = ?owner, public_key = ?publicKey, "Processing Validator Removed");

// Parse the public key
let validator_pubkey = PublicKey::from_str(&publicKey.to_string()).map_err(|e| {
let validator_pubkey = PublicKeyBytes::from_str(&publicKey.to_string()).map_err(|e| {
debug!(
validator_pubkey = %publicKey,
error = %e,
Expand Down
10 changes: 5 additions & 5 deletions anchor/eth/src/network_actions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ use alloy::primitives::Address;
use alloy::{rpc::types::Log, sol_types::SolEvent};
use ssv_types::OperatorId;
use std::str::FromStr;
use types::PublicKey;
use types::PublicKeyBytes;

/// Actions that the network has to take in response to a event during the live sync
#[derive(Debug, PartialEq)]
pub enum NetworkAction {
StopValidator {
validator_pubkey: PublicKey,
validator_pubkey: PublicKeyBytes,
},
LiquidateCluster {
owner: Address,
Expand All @@ -27,7 +27,7 @@ pub enum NetworkAction {
recipient: Address,
},
ExitValidator {
validator_pubkey: PublicKey,
validator_pubkey: PublicKeyBytes,
},
NoOp,
}
Expand All @@ -42,7 +42,7 @@ impl TryFrom<&Log> for NetworkAction {
let SSVContract::ValidatorRemoved { publicKey, .. } =
SSVContract::ValidatorRemoved::decode_from_log(source)?;
let validator_pubkey =
PublicKey::from_str(&publicKey.to_string()).map_err(|e| {
PublicKeyBytes::from_str(&publicKey.to_string()).map_err(|e| {
ExecutionError::InvalidEvent(format!("Failed to create PublicKey: {e}"))
})?;
Ok(NetworkAction::StopValidator { validator_pubkey })
Expand Down Expand Up @@ -77,7 +77,7 @@ impl TryFrom<&Log> for NetworkAction {
let SSVContract::ValidatorExited { publicKey, .. } =
SSVContract::ValidatorExited::decode_from_log(source)?;
let validator_pubkey =
PublicKey::from_str(&publicKey.to_string()).map_err(|e| {
PublicKeyBytes::from_str(&publicKey.to_string()).map_err(|e| {
ExecutionError::InvalidEvent(format!("Failed to create PublicKey: {e}"))
})?;
Ok(NetworkAction::ExitValidator { validator_pubkey })
Expand Down
Loading

0 comments on commit a55717e

Please sign in to comment.