Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: make encryption per partition instead of per message #107

Merged
merged 14 commits into from
Jan 22, 2025
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions chain-signatures/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions chain-signatures/keys/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ crate-type = ["cdylib", "lib"]

[dependencies]
borsh = "1.5.3"
hex = "0.4.3"
hpke = { version = "0.11", features = ["serde_impls", "std"] }
serde = { version = "1", features = ["derive"] }
rand = { version = "0.8" }
Expand Down
17 changes: 16 additions & 1 deletion chain-signatures/keys/src/hpke.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::io;
use std::{fmt, io};

use borsh::{self, BorshDeserialize, BorshSerialize};
use hpke::{
Expand All @@ -19,6 +19,7 @@ const INFO_ENTROPY: &[u8] = b"mpc-key-v1";
pub type Kem = X25519HkdfSha256;
pub type Aead = ChaCha20Poly1305;
pub type Kdf = HkdfSha384;
pub type Error = hpke::HpkeError;

#[derive(Serialize, Deserialize)]
pub struct Ciphered {
Expand All @@ -37,6 +38,16 @@ pub struct PublicKey(<Kem as hpke::Kem>::PublicKey);
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SecretKey(<Kem as hpke::Kem>::PrivateKey);

impl fmt::Debug for SecretKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let key = hex::encode(self.to_bytes());
let debug_key = format!("{}[..]", &key[..key.len() - 4]);
f.debug_struct("SecretKey")
.field("key", &debug_key)
.finish()
}
}

#[derive(Clone, Serialize, Deserialize)]
pub struct EncappedKey(<Kem as hpke::Kem>::EncappedKey);

Expand Down Expand Up @@ -101,6 +112,10 @@ impl SecretKey {
hpke::Serializable::to_bytes(&self.0).into()
}

pub fn from_bytes(bytes: &[u8]) -> Self {
Self(hpke::Deserializable::from_bytes(bytes).expect("invalid bytes"))
}

pub fn try_from_bytes(bytes: &[u8]) -> Result<Self, hpke::HpkeError> {
Ok(Self(hpke::Deserializable::from_bytes(bytes)?))
}
Expand Down
2 changes: 2 additions & 0 deletions chain-signatures/node/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ borsh = "1.5.3"
cait-sith = { git = "https://github.com/LIT-Protocol/cait-sith.git", features = [
"k256",
], rev = "8ad2316" }
ciborium = "0.2.2"
clap = { version = "4.2", features = ["derive", "env"] }
chrono = "0.4.24"
google-datastore1 = "=5.0.4"
Expand All @@ -36,6 +37,7 @@ semver = "1.0.23"
sha2 = "0.10.8"
sha3 = "0.10.8"
serde = { version = "1", features = ["derive"] }
serde_bytes = "0.11.15"
serde_json = "1"
thiserror = "1"
tokio = { version = "1.28", features = ["full"] }
Expand Down
35 changes: 11 additions & 24 deletions chain-signatures/node/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,7 @@ pub fn run(cmd: Cli) -> anyhow::Result<()> {
let config = Arc::new(RwLock::new(Config::new(LocalConfig {
over: override_config.unwrap_or_else(Default::default),
network: NetworkConfig {
cipher_sk: hpke::SecretKey::try_from_bytes(&hex::decode(cipher_sk)?)?,
cipher_pk: hpke::PublicKey::try_from_bytes(&hex::decode(cipher_pk)?)?,
sign_sk,
},
Expand All @@ -272,12 +273,14 @@ pub fn run(cmd: Cli) -> anyhow::Result<()> {
crate::contract_updater::ContractUpdater::init(&rpc_client, &mpc_contract_id);

rt.block_on(async {
let state = Arc::new(RwLock::new(crate::protocol::NodeState::Starting));
let (sender, channel) =
MessageChannel::spawn(client, &account_id, &config, &mesh_state).await;
let (protocol, protocol_state) = MpcSignProtocol::init(
MessageChannel::spawn(client, &account_id, &config, &state, &mesh_state).await;
let protocol = MpcSignProtocol::init(
my_address,
mpc_contract_id,
account_id,
state.clone(),
rpc_client,
signer,
channel,
Expand All @@ -291,30 +294,14 @@ pub fn run(cmd: Cli) -> anyhow::Result<()> {
);

tracing::info!("protocol initialized");
let contract_handle = tokio::spawn({
let contract_state = Arc::clone(&contract_state);
let config = Arc::clone(&config);
async move { contract_updater.run(contract_state, config).await }
});
let mesh_handle = tokio::spawn({
let contract_state = Arc::clone(&contract_state);
async move { mesh.run(contract_state).await }
});
let contract_handle =
tokio::spawn(contract_updater.run(contract_state.clone(), config.clone()));
let mesh_handle = tokio::spawn(mesh.run(contract_state.clone()));
let protocol_handle =
tokio::spawn(protocol.run(contract_state, config, mesh_state));
tracing::info!("protocol thread spawned");
let cipher_sk = hpke::SecretKey::try_from_bytes(&hex::decode(cipher_sk)?)?;
let web_handle = tokio::spawn(async move {
web::run(
web_port,
sender,
cipher_sk,
protocol_state,
indexer,
eth_indexer,
)
.await
});
tracing::info!("protocol task spawned");
let web_handle =
tokio::spawn(web::run(web_port, sender, state, indexer, eth_indexer));
tracing::info!("protocol http server spawned");

contract_handle.await??;
Expand Down
2 changes: 2 additions & 0 deletions chain-signatures/node/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ pub struct LocalConfig {
#[derive(Clone, Debug)]
pub struct NetworkConfig {
pub sign_sk: near_crypto::SecretKey,
pub cipher_sk: hpke::SecretKey,
pub cipher_pk: hpke::PublicKey,
}

Expand All @@ -82,6 +83,7 @@ impl Default for NetworkConfig {
near_crypto::KeyType::ED25519,
"test-entropy",
),
cipher_sk: hpke::SecretKey::from_bytes(&[0; 32]),
cipher_pk: hpke::PublicKey::from_bytes(&[0; 32]),
}
}
Expand Down
2 changes: 1 addition & 1 deletion chain-signatures/node/src/contract_updater.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ impl ContractUpdater {
}

pub async fn run(
&self,
self,
contract_state: Arc<RwLock<Option<ProtocolState>>>,
config: Arc<RwLock<Config>>,
) -> anyhow::Result<()> {
Expand Down
1 change: 1 addition & 0 deletions chain-signatures/node/src/indexer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ struct UnvalidatedContractSignRequest {
/// A validated version of the sign request
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct ContractSignRequest {
#[serde(with = "crate::protocol::message::cbor_scalar")]
pub payload: Scalar,
pub path: String,
pub key_version: u32,
Expand Down
36 changes: 14 additions & 22 deletions chain-signatures/node/src/node_client.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::web::StateView;
use hyper::StatusCode;
use mpc_keys::hpke::Ciphered;
use reqwest::IntoUrl;
use std::str::Utf8Error;
Expand Down Expand Up @@ -31,25 +32,15 @@ impl Options {
}

#[derive(Debug, thiserror::Error)]
pub enum SendError {
#[error("http request was unsuccessful: {0}")]
Unsuccessful(String),
#[error("serialization unsuccessful: {0}")]
DataConversionError(serde_json::Error),
pub enum RequestError {
#[error("http request was unsuccessful: {0} => {1}")]
Unsuccessful(StatusCode, String),
#[error("http client error: {0}")]
ReqwestClientError(#[from] reqwest::Error),
ReqwestClient(#[from] reqwest::Error),
#[error("http response could not be parsed: {0}")]
ReqwestBodyError(reqwest::Error),
MalformedBody(reqwest::Error),
#[error("http response body is not valid utf-8: {0}")]
MalformedResponse(Utf8Error),
#[error("encryption error: {0}")]
EncryptionError(String),
#[error("http request timeout: {0}")]
Timeout(String),
#[error("participant is not alive: {0}")]
ParticipantNotAlive(String),
#[error("cannot convert into json: {0}")]
Conversion(#[from] serde_json::Error),
}

#[derive(Debug, Clone)]
Expand All @@ -69,7 +60,7 @@ impl NodeClient {
}
}

async fn post_msg(&self, url: &Url, msg: &[Ciphered]) -> Result<(), SendError> {
async fn post_msg(&self, url: &Url, msg: &[&Ciphered]) -> Result<(), RequestError> {
let resp = self
.http
.post(url.clone())
Expand All @@ -82,26 +73,27 @@ impl NodeClient {
if status.is_success() {
Ok(())
} else {
let bytes = resp.bytes().await.map_err(SendError::ReqwestBodyError)?;
let resp = std::str::from_utf8(&bytes).map_err(SendError::MalformedResponse)?;
// TODO: parse response body and convert to mpc_node::Error type.
let bytes = resp.bytes().await.map_err(RequestError::MalformedBody)?;
let resp = std::str::from_utf8(&bytes).map_err(RequestError::MalformedResponse)?;
tracing::warn!("failed to send a message to {url} with code {status}: {resp}");
Err(SendError::Unsuccessful(resp.into()))
Err(RequestError::Unsuccessful(status, resp.into()))
}
}

pub async fn msg(&self, base: impl IntoUrl, msg: &[Ciphered]) -> Result<(), SendError> {
pub async fn msg(&self, base: impl IntoUrl, msg: &[&Ciphered]) -> Result<(), RequestError> {
let mut url = base.into_url()?;
url.set_path("msg");

let strategy = ExponentialBackoff::from_millis(10).map(jitter).take(3);
Retry::spawn(strategy, || self.post_msg(&url, msg)).await
}

pub async fn msg_empty(&self, base: impl IntoUrl) -> Result<(), SendError> {
pub async fn msg_empty(&self, base: impl IntoUrl) -> Result<(), RequestError> {
self.msg(base, &[]).await
}

pub async fn state(&self, base: impl IntoUrl) -> Result<StateView, SendError> {
pub async fn state(&self, base: impl IntoUrl) -> Result<StateView, RequestError> {
let mut url = base.into_url()?;
url.set_path("state");

Expand Down
16 changes: 5 additions & 11 deletions chain-signatures/node/src/protocol/consensus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,13 +63,7 @@ pub enum ConsensusError {
#[error("cait-sith initialization error: {0}")]
CaitSithInitializationError(#[from] InitializationError),
#[error("secret storage error: {0}")]
SecretStorageError(SecretStorageError),
}

impl From<SecretStorageError> for ConsensusError {
fn from(err: SecretStorageError) -> Self {
ConsensusError::SecretStorageError(err)
}
SecretStorageError(#[from] SecretStorageError),
}

#[async_trait]
Expand Down Expand Up @@ -487,10 +481,10 @@ impl ConsensusProtocol for RunningState {
ProtocolState::Running(contract_state) => match contract_state.epoch.cmp(&self.epoch) {
Ordering::Greater => {
tracing::warn!(
"running(running): our current epoch is {} while contract state's is {}, trying to rejoin as a new participant",
self.epoch,
contract_state.epoch
);
"running(running): our current epoch is {} while contract state's is {}, trying to rejoin as a new participant",
self.epoch,
contract_state.epoch
);

Ok(NodeState::Joining(JoiningState {
participants: contract_state.participants,
Expand Down
20 changes: 20 additions & 0 deletions chain-signatures/node/src/protocol/contract/primitives.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,26 @@ impl Participants {
}
}

/// ParticipantMap used to find a participant by specific amount of participants.
#[derive(Clone, Debug)]
pub enum ParticipantMap {
Zero,
One(Participants),
Two(Participants, Participants),
}

impl ParticipantMap {
pub fn get(&self, p: &Participant) -> Option<&ParticipantInfo> {
match self {
ParticipantMap::Zero => None,
ParticipantMap::One(participants) => participants.get(p),
ParticipantMap::Two(participants1, participants2) => {
participants1.get(p).or_else(|| participants2.get(p))
}
}
}
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct CandidateInfo {
pub account_id: AccountId,
Expand Down
Loading
Loading