Skip to content

Commit 515bb61

Browse files
authored
use ValidatorId & TryFrom wherever makes sense **for now** (#108)
1 parent 87a5188 commit 515bb61

File tree

11 files changed

+63
-46
lines changed

11 files changed

+63
-46
lines changed

adapter/src/sanity.rs

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,16 @@ use std::{error, fmt};
33
use chrono::Utc;
44

55
use domain::channel::{SpecValidator, SpecValidators};
6-
use domain::{Asset, Channel};
6+
use domain::{Asset, Channel, ValidatorId};
77

88
use crate::adapter::Config;
9+
use std::convert::TryFrom;
910

1011
pub trait SanityChecker {
1112
fn check(config: &Config, channel: &Channel) -> Result<(), SanityError> {
12-
let adapter_channel_validator = match channel.spec.validators.find(&config.identity) {
13+
let identity =
14+
ValidatorId::try_from(config.identity.as_str()).expect("Identity failed to be created");
15+
let adapter_channel_validator = match channel.spec.validators.find(&identity) {
1316
// check if the channel validators include our adapter identity
1417
SpecValidator::None => return Err(SanityError::AdapterNotIncluded),
1518
SpecValidator::Leader(validator) | SpecValidator::Follower(validator) => validator,
@@ -50,7 +53,8 @@ fn all_validators_listed(validators: &SpecValidators, whitelist: &[String]) -> b
5053
let found_validators = whitelist
5154
.iter()
5255
.filter(|&allowed| {
53-
allowed == &validators.leader().id || allowed == &validators.follower().id
56+
allowed == validators.leader().id.as_ref()
57+
|| allowed == validators.follower().id.as_ref()
5458
})
5559
// this will ensure that if we find the 2 validators earlier
5660
// we don't go over the other values of the whitelist
@@ -131,7 +135,7 @@ mod test {
131135
let channel = get_channel("channel_1", &Some(passed_valid_until), None);
132136

133137
let identity = channel.spec.validators.leader().id.clone();
134-
let config = ConfigBuilder::new(&identity).build();
138+
let config = ConfigBuilder::new(identity.as_ref()).build();
135139

136140
assert_eq!(
137141
Err(SanityError::PassedValidUntil),
@@ -145,17 +149,18 @@ mod test {
145149

146150
// as identity use the leader, otherwise we won't pass the AdapterNotIncluded check
147151
let identity = channel.spec.validators.leader().id.clone();
148-
let config = ConfigBuilder::new(&identity)
152+
let config = ConfigBuilder::new(identity.as_ref())
149153
.set_validators_whitelist(&["my validator"])
150154
.build();
151155

152156
// make sure we don't use the leader or follower validators as a whitelisted validator
153157
assert_ne!(
154-
&identity, "my validator",
158+
identity.as_ref(),
159+
"my validator",
155160
"The whitelisted validator and the leader have the same id"
156161
);
157162
assert_ne!(
158-
&channel.spec.validators.follower().id,
163+
channel.spec.validators.follower().id.as_ref(),
159164
"my validator",
160165
"The whitelisted validator and the follower have the same id"
161166
);
@@ -172,7 +177,7 @@ mod test {
172177

173178
// as identity use the leader, otherwise we won't pass the AdapterNotIncluded check
174179
let identity = channel.spec.validators.leader().id.clone();
175-
let config = ConfigBuilder::new(&identity)
180+
let config = ConfigBuilder::new(identity.as_ref())
176181
.set_creators_whitelist(&["creator"])
177182
.build();
178183

@@ -193,7 +198,7 @@ mod test {
193198

194199
// as identity use the leader, otherwise we won't pass the AdapterNotIncluded check
195200
let identity = channel.spec.validators.leader().id.clone();
196-
let config = ConfigBuilder::new(&identity)
201+
let config = ConfigBuilder::new(identity.as_ref())
197202
.set_assets_whitelist(&["ASSET".into()])
198203
.build();
199204

@@ -215,7 +220,7 @@ mod test {
215220

216221
// as identity use the leader, otherwise we won't pass the AdapterNotIncluded check
217222
let identity = channel.spec.validators.leader().id.clone();
218-
let config = ConfigBuilder::new(&identity)
223+
let config = ConfigBuilder::new(identity.as_ref())
219224
// set the minimum deposit to the `channel.deposit_amount + 1`
220225
.set_minimum_deposit(&channel.deposit_amount + &1.into())
221226
.build();
@@ -233,7 +238,7 @@ mod test {
233238
let leader = channel.spec.validators.leader();
234239
// as identity use the leader, otherwise we won't pass the AdapterNotIncluded check
235240
let identity = leader.id.clone();
236-
let config = ConfigBuilder::new(&identity)
241+
let config = ConfigBuilder::new(identity.as_ref())
237242
// set the minimum deposit to the `leader.fee + 1`
238243
.set_minimum_fee(&leader.fee + &1.into())
239244
.build();

domain/src/balances_map.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ impl BalancesMap {
5454

5555
if fee_rounded > 0.into() {
5656
let entry = balances
57-
.entry(validator.id.clone())
57+
.entry(validator.id.clone().into())
5858
.or_insert_with(|| 0.into());
5959

6060
*entry += &fee_rounded;

domain/src/channel.rs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,9 @@ use serde_hex::{SerHex, StrictPfx};
99

1010
use crate::big_num::BigNum;
1111
use crate::util::serde::ts_milliseconds_option;
12-
use crate::{AdUnit, Asset, DomainError, EventSubmission, TargetingTag, ValidatorDesc};
12+
use crate::{
13+
AdUnit, Asset, DomainError, EventSubmission, TargetingTag, ValidatorDesc, ValidatorId,
14+
};
1315

1416
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Copy, Clone)]
1517
#[serde(transparent)]
@@ -195,10 +197,10 @@ impl SpecValidators {
195197
&self.0[1]
196198
}
197199

198-
pub fn find(&self, validator_id: &str) -> SpecValidator<'_> {
199-
if self.leader().id == validator_id {
200+
pub fn find(&self, validator: &ValidatorId) -> SpecValidator<'_> {
201+
if &self.leader().id == validator {
200202
SpecValidator::Leader(&self.leader())
201-
} else if self.follower().id == validator_id {
203+
} else if &self.follower().id == validator {
202204
SpecValidator::Follower(&self.follower())
203205
} else {
204206
SpecValidator::None

domain/src/validator.rs

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,12 @@ impl TryFrom<&str> for ValidatorId {
2222
}
2323
}
2424

25+
impl Into<String> for ValidatorId {
26+
fn into(self) -> String {
27+
self.0
28+
}
29+
}
30+
2531
impl AsRef<str> for ValidatorId {
2632
fn as_ref(&self) -> &str {
2733
self.0.as_str()
@@ -37,8 +43,7 @@ impl fmt::Display for ValidatorId {
3743
#[derive(Serialize, Deserialize, Debug, Clone)]
3844
#[serde(rename_all = "camelCase")]
3945
pub struct ValidatorDesc {
40-
// @TODO: Replace id `String` with `ValidatorId` https://github.com/AdExNetwork/adex-validator-stack-rust/issues/83
41-
pub id: String,
46+
pub id: ValidatorId,
4247
pub url: String,
4348
pub fee: BigNum,
4449
}
@@ -47,19 +52,21 @@ pub struct ValidatorDesc {
4752
pub mod fixtures {
4853
use fake::faker::*;
4954

55+
use super::{ValidatorDesc, ValidatorId};
5056
use crate::BigNum;
51-
52-
use super::ValidatorDesc;
57+
use std::convert::TryFrom;
5358

5459
pub fn get_validator<V: AsRef<str>>(validator_id: V, fee: Option<BigNum>) -> ValidatorDesc {
5560
let fee = fee.unwrap_or_else(|| BigNum::from(<Faker as Number>::between(1, 13)));
5661
let url = format!(
5762
"http://{}-validator-url.com/validator",
5863
validator_id.as_ref()
5964
);
65+
let validator_id =
66+
ValidatorId::try_from(validator_id.as_ref()).expect("Creating ValidatorId failed");
6067

6168
ValidatorDesc {
62-
id: validator_id.as_ref().to_string(),
69+
id: validator_id,
6370
url,
6471
fee,
6572
}

sentry/src/application/resource/channel.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,13 +54,13 @@ impl ChannelListQuery {
5454
}
5555
}
5656

57-
pub fn validator(&self) -> Option<String> {
58-
self.validator.to_owned().and_then(|s| {
57+
pub fn validator(&self) -> Option<&str> {
58+
self.validator.as_ref().and_then(|s| {
5959
if s.is_empty() {
6060
return None;
6161
}
6262

63-
Some(s)
63+
Some(s.as_str())
6464
})
6565
}
6666
}

sentry/src/application/resource/channel/channel_list/handler.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,10 @@ impl ChannelListHandler {
2222

2323
impl ChannelListHandler {
2424
#[allow(clippy::needless_lifetimes)]
25-
pub async fn handle(
26-
&self,
25+
pub async fn handle<'a>(
26+
&'a self,
2727
page: u64,
28-
validator: Option<String>,
28+
validator: Option<&'a str>,
2929
) -> Result<ChannelListResponse, ()> {
3030
let channel_list_params =
3131
ChannelListParams::new(Utc::now(), self.limit_per_page, page, validator)

sentry/src/domain/channel.rs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
use chrono::{DateTime, Utc};
22

3-
use domain::{Channel, RepositoryFuture};
3+
use domain::{Channel, RepositoryFuture, ValidatorId};
44
use domain::{ChannelId, DomainError};
5+
use std::convert::TryFrom;
56

67
pub struct ChannelListParams {
78
/// page to show, should be >= 1
@@ -11,7 +12,7 @@ pub struct ChannelListParams {
1112
/// filters `valid_until` to be `>= valid_until_ge`
1213
pub valid_until_ge: DateTime<Utc>,
1314
/// filters the channels containing a specific validator if provided
14-
pub validator: Option<String>,
15+
pub validator: Option<ValidatorId>,
1516
/// Ensures that this struct can only be created by calling `new()`
1617
_secret: (),
1718
}
@@ -21,7 +22,7 @@ impl ChannelListParams {
2122
valid_until_ge: DateTime<Utc>,
2223
limit: u32,
2324
page: u64,
24-
validator: Option<String>,
25+
validator: Option<&str>,
2526
) -> Result<Self, DomainError> {
2627
if page < 1 {
2728
return Err(DomainError::InvalidArgument(
@@ -35,7 +36,10 @@ impl ChannelListParams {
3536
));
3637
}
3738

38-
let validator = validator.and_then(|s| if s.is_empty() { None } else { Some(s) });
39+
let validator = validator
40+
.and_then(|s| if s.is_empty() { None } else { Some(s) })
41+
.map(ValidatorId::try_from)
42+
.transpose()?;
3943

4044
Ok(Self {
4145
valid_until_ge,

sentry/src/infrastructure/persistence/channel/memory_test.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -151,8 +151,7 @@ fn listing_channels_can_handles_validator_filtration_and_keeps_valid_until_filtr
151151

152152
let repository = MemoryChannelRepository::new(Some(&channels));
153153

154-
let params =
155-
ChannelListParams::new(valid_until_ge, 10, 1, Some("validator-1".to_string())).unwrap();
154+
let params = ChannelListParams::new(valid_until_ge, 10, 1, Some("validator-1")).unwrap();
156155
let list_channels = await!(repository.list(&params)).expect("Should list all channels");
157156

158157
assert_eq!(1, list_channels.len());

validator/src/application/message_propagation.rs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
1-
use std::convert::TryFrom;
21
use std::error::Error;
32
use std::fmt;
43

54
use domain::validator::message::{Message, State};
6-
use domain::{Channel, RepositoryError, ValidatorId};
5+
use domain::{Channel, RepositoryError};
76

87
use crate::domain::MessageRepository;
98

@@ -55,12 +54,10 @@ impl<S: State> MessagePropagator<S> {
5554
let mut results = Vec::default();
5655

5756
for validator in channel.spec.validators.into_iter() {
58-
// @TODO: Remove once we have ValidatorId in ValidatorDesc
59-
let validator_id = ValidatorId::try_from(validator.id.as_str()).unwrap();
6057
let add_result =
6158
await!(self
6259
.message_repository
63-
.add(&channel.id, &validator_id, message.clone()))
60+
.add(&channel.id, &validator.id, message.clone()))
6461
.map_err(Into::into);
6562
results.push(add_result);
6663
}

validator/src/application/worker.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,11 @@ pub mod single {
4949
async fn handle_channel(self, channel: Channel) -> Result<(), ()> {
5050
let channel_id = channel.id;
5151

52-
match &channel.spec.validators.find(&self.identity) {
52+
// @TODO: Update once we figure out if ValidatorId can fail from a &str
53+
let validator_id = ValidatorId::try_from(self.identity.as_str())
54+
.expect("ValidatorId doesn't have a failing case right now");
55+
56+
match &channel.spec.validators.find(&validator_id) {
5357
SpecValidator::Leader(_) => {
5458
let tick_future = self.leader.tick(channel);
5559

0 commit comments

Comments
 (0)