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

chore: replace std::sync::Mutex with parking_lot::Mutex #55

Merged
merged 1 commit into from
Sep 17, 2022
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 3 additions & 0 deletions 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 mev-boost-rs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ async-trait = "0.1.53"
url = { version = "2.2.2", default-features = false }
serde = { version = "1.0", features = ["derive"] }
thiserror = "1.0.30"
parking_lot = "0.12.1"

ethereum-consensus = { git = "https://github.com/ralexstokes/ethereum-consensus", rev = "a8110af76d97bf2bf27fb987a671808fcbdf1834" }
beacon-api-client = { git = "https://github.com/ralexstokes/beacon-api-client", rev = "7d5d8dad1648f771573f42585ad8080a45b05689" }
Expand Down
28 changes: 12 additions & 16 deletions mev-boost-rs/src/relay_mux.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,8 @@ use mev_build_rs::{
BlindedBlockProviderClient as Relay, BlindedBlockProviderError, ExecutionPayload, Network,
SignedBlindedBeaconBlock, SignedBuilderBid, SignedValidatorRegistration,
};
use std::{
collections::HashMap,
ops::Deref,
sync::{Arc, Mutex},
};
use parking_lot::Mutex;
use std::{collections::HashMap, ops::Deref, sync::Arc};
use thiserror::Error;

// See note in the `mev-relay-rs::Relay` about this constant.
Expand Down Expand Up @@ -112,7 +109,7 @@ impl RelayMux {
tokio::pin!(slots);

while let Some(slot) = slots.next().await {
let mut state = self.state.lock().unwrap();
let mut state = self.state.lock();
state
.outstanding_bids
.retain(|bid_request, _| bid_request.slot + PROPOSAL_TOLERANCE_DELAY >= slot);
Expand Down Expand Up @@ -191,11 +188,13 @@ impl BlindedBlockProvider for RelayMux {
}
}

let mut state = self.state.lock().unwrap();
// assume the next request to open a bid corresponds to the current request
// TODO consider if the relay mux should have more knowledge about the proposal
state.latest_pubkey = bid_request.public_key.clone();
state.outstanding_bids.insert(bid_request.clone(), relay_indices);
{
let mut state = self.state.lock();
// assume the next request to open a bid corresponds to the current request
// TODO consider if the relay mux should have more knowledge about the proposal
state.latest_pubkey = bid_request.public_key.clone();
state.outstanding_bids.insert(bid_request.clone(), relay_indices);
}

Ok(bids[*best_index].0.clone())
}
Expand All @@ -205,12 +204,9 @@ impl BlindedBlockProvider for RelayMux {
signed_block: &mut SignedBlindedBeaconBlock,
) -> Result<ExecutionPayload, BlindedBlockProviderError> {
let relay_indices = {
let mut state = self.state.lock().unwrap();
let mut state = self.state.lock();
let key = bid_key_from(signed_block, &state.latest_pubkey);
match state.outstanding_bids.remove(&key) {
Some(indices) => indices,
None => return Err(Error::MissingOpenBid.into()),
}
state.outstanding_bids.remove(&key).ok_or(Error::MissingOpenBid)?
};

let signed_block = &signed_block;
Expand Down
1 change: 1 addition & 0 deletions mev-build-rs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ async-trait = "0.1.53"
serde = { version = "1.0", features = ["derive"], optional = true }
serde_json = { version = "1.0.81", optional = true }
thiserror = "1.0.30"
parking_lot = "0.12.1"

ethereum-consensus = { git = "https://github.com/ralexstokes/ethereum-consensus", rev = "a8110af76d97bf2bf27fb987a671808fcbdf1834" }
beacon-api-client = { git = "https://github.com/ralexstokes/beacon-api-client", rev = "7d5d8dad1648f771573f42585ad8080a45b05689", optional = true }
Expand Down
20 changes: 9 additions & 11 deletions mev-build-rs/src/builder/engine_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,8 @@ use ethereum_consensus::{
ssz::ByteList,
state_transition::Context,
};
use std::{
collections::HashMap,
ops::Deref,
sync::{Arc, Mutex},
};
use parking_lot::Mutex;
use std::{collections::HashMap, ops::Deref, sync::Arc};

#[derive(Clone)]
pub struct EngineBuilder(Arc<EngineBuilderInner>);
Expand Down Expand Up @@ -66,15 +63,16 @@ impl EngineBuilder {
&self,
request: &PayloadRequest,
) -> Result<ExecutionPayloadWithValue, Error> {
let state = self.state.lock().expect("can lock");
let preferences = state
let (fee_recipient, gas_limit) = self
.state
.lock()
.validator_preferences
.get(&request.public_key)
.map(|preferences| {
(preferences.message.fee_recipient.clone(), preferences.message.gas_limit)
})
.ok_or_else(|| Error::MissingPreferences(request.public_key.clone()))?;

let fee_recipient = preferences.message.fee_recipient.clone();
let gas_limit = preferences.message.gas_limit;

let payload = ExecutionPayload {
parent_hash: request.parent_hash.clone(),
fee_recipient,
Expand All @@ -93,7 +91,7 @@ impl EngineBuilder {
) -> Result<(), BlindedBlockProviderError> {
// TODO this assumes registrations have already been validated by relay
// will eventually remove this assumption
let mut state = self.state.lock().expect("can lock");
let mut state = self.state.lock();
for registration in registrations {
let public_key = registration.message.public_key.clone();
state.validator_preferences.insert(public_key, registration.clone());
Expand Down
2 changes: 1 addition & 1 deletion mev-relay-rs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@ tokio = { version = "1.0", features = ["full"] }
tracing = "0.1"
futures = "0.3.21"
async-trait = "0.1.53"
parking_lot = "0.12.1"

thiserror = "1.0.30"
http = "0.2.7"
url = { version = "2.2.2", default-features = false }

serde = { version = "1.0", features = ["derive"] }

ethereum-consensus = { git = "https://github.com/ralexstokes/ethereum-consensus", rev = "a8110af76d97bf2bf27fb987a671808fcbdf1834" }
Expand Down
37 changes: 19 additions & 18 deletions mev-relay-rs/src/relay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,8 @@ use mev_build_rs::{
EngineBuilder, ExecutionPayload, ExecutionPayloadHeader, ExecutionPayloadWithValue,
SignedBlindedBeaconBlock, SignedBuilderBid, SignedValidatorRegistration,
};
use std::{
cmp::Ordering,
collections::HashMap,
ops::Deref,
sync::{Arc, Mutex},
};
use parking_lot::Mutex;
use std::{cmp::Ordering, collections::HashMap, ops::Deref, sync::Arc};
use thiserror::Error;

// `PROPOSAL_TOLERANCE_DELAY` controls how aggresively the relay drops "old" execution payloads
Expand Down Expand Up @@ -265,7 +261,7 @@ impl Relay {
// TODO grab validators more efficiently
self.load_full_validator_set().await;
}
let mut state = self.state.lock().unwrap();
let mut state = self.state.lock();
state
.execution_payloads
.retain(|bid_request, _| bid_request.slot + PROPOSAL_TOLERANCE_DELAY >= slot);
Expand All @@ -280,7 +276,7 @@ impl BlindedBlockProvider for Relay {
registrations: &mut [SignedValidatorRegistration],
) -> Result<(), BlindedBlockProviderError> {
let mut new_registrations = {
let mut state = self.state.lock().expect("can lock");
let mut state = self.state.lock();
let current_time = get_current_unix_time_in_secs();
let mut new_registrations = vec![];
for registration in registrations.iter_mut() {
Expand Down Expand Up @@ -319,18 +315,21 @@ impl BlindedBlockProvider for Relay {
let ExecutionPayloadWithValue { mut payload, value } =
self.builder.get_payload_with_value(bid_request)?;

let mut state = self.state.lock().expect("can lock");
let header = {
let mut state = self.state.lock();

let preferences = state
.validator_preferences
.get(&bid_request.public_key)
.ok_or(Error::UnknownValidator)?;
let preferences = state
.validator_preferences
.get(&bid_request.public_key)
.ok_or(Error::UnknownValidator)?;

validate_execution_payload(&payload, &value, &preferences.message)?;
validate_execution_payload(&payload, &value, &preferences.message)?;

let header = ExecutionPayloadHeader::try_from(&mut payload)?;
let header = ExecutionPayloadHeader::try_from(&mut payload)?;

state.execution_payloads.insert(bid_request.clone(), payload);
state.execution_payloads.insert(bid_request.clone(), payload);
header
};

let mut bid = BuilderBid { header, value, public_key: self.public_key.clone() };

Expand All @@ -353,8 +352,10 @@ impl BlindedBlockProvider for Relay {
public_key,
};

let mut state = self.state.lock().expect("can lock");
let mut payload = state.execution_payloads.remove(&bid_request).ok_or(Error::UnknownBid)?;
let mut payload = {
let mut state = self.state.lock();
state.execution_payloads.remove(&bid_request).ok_or(Error::UnknownBid)?
};

validate_signed_block(signed_block, &bid_request.public_key, &mut payload, &self.context)?;

Expand Down
18 changes: 11 additions & 7 deletions mev-relay-rs/src/validator_summary_provider.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use beacon_api_client::{Client, Error as ApiError, StateId, ValidatorStatus, ValidatorSummary};
use ethereum_consensus::primitives::{BlsPublicKey, ValidatorIndex};
use std::{collections::HashMap, sync::Mutex};
use parking_lot::Mutex;
use std::collections::HashMap;
use thiserror::Error;

#[derive(Debug, Error)]
Expand Down Expand Up @@ -32,7 +33,7 @@ impl ValidatorSummaryProvider {

pub async fn load(&self) -> Result<(), Error> {
let summaries = self.client.get_validators(StateId::Head, &[], &[]).await?;
let mut state = self.state.lock().expect("can lock");
let mut state = self.state.lock();
for summary in summaries.into_iter() {
let public_key = summary.validator.public_key.clone();
state.pubkeys_by_index.insert(summary.index, public_key.clone());
Expand All @@ -42,13 +43,16 @@ impl ValidatorSummaryProvider {
}

pub fn get_status(&self, public_key: &BlsPublicKey) -> Result<ValidatorStatus, Error> {
let state = self.state.lock().expect("can lock");
let validator = state.validators.get(public_key).ok_or(Error::UnknownPubkey)?;
Ok(validator.status)
let state = self.state.lock();
state
.validators
.get(public_key)
.map(|validator| validator.status)
.ok_or(Error::UnknownPubkey)
}

pub fn get_public_key(&self, index: ValidatorIndex) -> Result<BlsPublicKey, Error> {
let state = self.state.lock().expect("can lock");
state.pubkeys_by_index.get(&index).ok_or(Error::UnknownIndex).map(Clone::clone)
let state = self.state.lock();
state.pubkeys_by_index.get(&index).cloned().ok_or(Error::UnknownIndex)
}
}