Skip to content

Commit 7b81338

Browse files
committed
Rename HeaderOracle and use infura mock for testing
1 parent a6f3e34 commit 7b81338

25 files changed

+1263
-400
lines changed

Cargo.lock

+990-279
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ repository = "https://github.com/ethereum/trin"
1313
discv5 = { git = "https://github.com/sigp/discv5.git", branch = "master" }
1414
ethereum-types = "0.12.1"
1515
hex = "0.4.3"
16-
log = "0.4.14"
16+
log = "0.4.17"
1717
prometheus_exporter = "0.8.4"
1818
rand = "0.8.4"
1919
rlp = "0.5.0"

ethportal-peertest/Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ rust-version = "1.58.0"
77
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
88

99
[dependencies]
10-
anyhow = "1.0.52"
10+
anyhow = "1.0.57"
1111
clap = "2.33.3"
1212
discv5 = { git = "https://github.com/sigp/discv5.git", branch = "master" }
1313
futures = "0.3.21"

ethportal-peertest/src/jsonrpc.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -362,7 +362,10 @@ pub fn make_ipc_request(ipc_path: &str, request: &JsonRpcRequest) -> anyhow::Res
362362
stream.flush().unwrap();
363363
let deser = serde_json::Deserializer::from_reader(stream);
364364
let next_obj = deser.into_iter::<Value>().next();
365-
let response_obj = next_obj.ok_or(anyhow!("Empty JsonRpc response"))?;
365+
let response_obj = match next_obj {
366+
Some(val) => val,
367+
None => return Err(anyhow!("Empty JsonRpc response")),
368+
};
366369
get_response_result(response_obj)
367370
}
368371

ethportal-peertest/src/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ pub async fn launch_node(id: u16, bootnode_enr: Option<&SszEnr>) -> anyhow::Resu
4242
Some(enr) => {
4343
let external_addr = format!(
4444
"{}:{}",
45-
enr.ip().expect("bootnode must have IP"),
45+
enr.ip4().expect("bootnode must have IP"),
4646
discovery_port
4747
);
4848
let enr_base64 = enr.to_base64();

src/lib.rs

+25-29
Original file line numberDiff line numberDiff line change
@@ -14,31 +14,27 @@ use trin_core::{
1414
discovery::Discovery, events::PortalnetEvents, storage::PortalStorage,
1515
types::messages::PortalnetConfig,
1616
},
17-
types::validation::ValidationOracle,
17+
types::validation::HeaderOracle,
1818
utils::bootnodes::parse_bootnodes,
19-
utils::infura::get_infura_url,
2019
utp::stream::UtpListener,
2120
};
2221
use trin_history::initialize_history_network;
2322
use trin_state::initialize_state_network;
2423

2524
pub async fn run_trin(
2625
trin_config: TrinConfig,
27-
infura_project_id: String,
26+
infura_url: String,
2827
) -> Result<Arc<JsonRpcExiter>, Box<dyn std::error::Error>> {
2928
trin_config.display_config();
3029

3130
let bootnode_enrs = parse_bootnodes(&trin_config.bootnodes)?;
32-
let infura_url = get_infura_url(&infura_project_id);
33-
3431
let portalnet_config = PortalnetConfig {
3532
external_addr: trin_config.external_addr,
3633
private_key: trin_config.private_key.clone(),
3734
listen_port: trin_config.discovery_port,
3835
no_stun: trin_config.no_stun,
3936
enable_metrics: trin_config.enable_metrics,
4037
bootnode_enrs,
41-
infura_url: infura_url.clone(),
4238
..Default::default()
4339
};
4440

@@ -65,53 +61,53 @@ pub async fn run_trin(
6561
PortalStorage::setup_config(discovery.local_enr().node_id(), trin_config.kb)?;
6662

6763
// Initialize validation oracle
68-
let validation_oracle = ValidationOracle {
69-
infura_url: portalnet_config.infura_url.clone(),
70-
..ValidationOracle::default()
64+
let header_oracle = HeaderOracle {
65+
infura_url: infura_url.clone(),
66+
..HeaderOracle::default()
7167
};
7268

7369
debug!("Selected networks to spawn: {:?}", trin_config.networks);
70+
// Initialize state sub-network service and event handlers, if selected
71+
let (state_handler, state_network_task, state_event_tx, state_jsonrpc_tx) =
72+
if trin_config.networks.iter().any(|val| val == STATE_NETWORK) {
73+
initialize_state_network(
74+
&discovery,
75+
utp_listener_tx.clone(),
76+
portalnet_config.clone(),
77+
storage_config.clone(),
78+
// todo: pass header_oracle into state network
79+
// - to initialize StateValidator
80+
// - for oracle to pick up handle to state_jsonrpc_tx
81+
)
82+
.await
83+
} else {
84+
(None, None, None, None)
85+
};
86+
7487
// Initialize chain history sub-network service and event handlers, if selected
7588
let (
7689
history_handler,
7790
history_network_task,
7891
history_event_tx,
7992
history_jsonrpc_tx,
80-
_validation_oracle,
93+
_header_oracle,
8194
) = if trin_config
8295
.networks
8396
.iter()
8497
.any(|val| val == HISTORY_NETWORK)
8598
{
8699
initialize_history_network(
87100
&discovery,
88-
utp_listener_tx.clone(),
101+
utp_listener_tx,
89102
portalnet_config.clone(),
90103
storage_config.clone(),
91-
validation_oracle.clone(),
104+
header_oracle.clone(),
92105
)
93106
.await
94107
} else {
95108
(None, None, None, None, None)
96109
};
97110

98-
// Initialize state sub-network service and event handlers, if selected
99-
let (state_handler, state_network_task, state_event_tx, state_jsonrpc_tx) =
100-
if trin_config.networks.iter().any(|val| val == STATE_NETWORK) {
101-
initialize_state_network(
102-
&discovery,
103-
utp_listener_tx,
104-
portalnet_config.clone(),
105-
storage_config.clone(),
106-
// todo: pass validation_oracle into state network
107-
// - to initialize StateValidator
108-
// - for oracle to pick up handle to state_jsonrpc_tx
109-
)
110-
.await
111-
} else {
112-
(None, None, None, None)
113-
};
114-
115111
// Initialize json-rpc server
116112
let (portal_jsonrpc_tx, portal_jsonrpc_rx) = mpsc::unbounded_channel::<PortalJsonRpcRequest>();
117113
let jsonrpc_trin_config = trin_config.clone();

src/main.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use trin_core::cli::TrinConfig;
2-
use trin_core::utils::infura::fetch_infura_id_from_env;
2+
use trin_core::utils::infura::build_infura_project_url_from_env;
33

44
use trin::run_trin;
55

@@ -10,9 +10,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
1010
println!("Launching trin");
1111

1212
let trin_config = TrinConfig::from_cli();
13-
let infura_project_id = fetch_infura_id_from_env();
13+
let infura_url = build_infura_project_url_from_env();
1414

15-
let exiter = run_trin(trin_config, infura_project_id).await?;
15+
let exiter = run_trin(trin_config, infura_url).await?;
1616

1717
tokio::signal::ctrl_c()
1818
.await

trin-core/Cargo.toml

+2-2
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ edition = "2021"
55
rust-version = "1.58.0"
66

77
[dependencies]
8-
anyhow = "1.0.52"
8+
anyhow = "1.0.57"
99
async-recursion = "1.0.0"
1010
async-trait = "0.1.53"
1111
base64 = "0.13.0"
@@ -27,7 +27,7 @@ hmac-sha256 = "1.1.1"
2727
httparse = "1.5.1"
2828
keccak-hash = "0.8.0"
2929
lazy_static = "1.4.0"
30-
log = "0.4.14"
30+
log = "0.4.17"
3131
num = "0.4.0"
3232
parking_lot = "0.11.2"
3333
prometheus_exporter = "0.8.4"

trin-core/src/portalnet/discovery.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ impl Discovery {
9191
if let Some(ip_address) = config.enr_address {
9292
builder.ip(ip_address);
9393
}
94-
builder.udp(config.listen_port);
94+
builder.udp4(config.listen_port);
9595
builder.build(&enr_key).unwrap()
9696
};
9797

@@ -137,7 +137,7 @@ impl Discovery {
137137
json!({
138138
"enr": self.discv5.local_enr().to_base64(),
139139
"nodeId": self.discv5.local_enr().node_id().to_string(),
140-
"ip": self.discv5.local_enr().ip().map_or("None".to_owned(), |ip| ip.to_string())
140+
"ip": self.discv5.local_enr().ip4().map_or("None".to_owned(), |ip| ip.to_string())
141141
})
142142
}
143143

trin-core/src/portalnet/overlay.rs

+7-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
use anyhow::anyhow;
2-
use std::{collections::HashSet, marker::PhantomData, sync::Arc, time::Duration};
2+
use std::{
3+
collections::HashSet,
4+
marker::{PhantomData, Sync},
5+
sync::Arc,
6+
time::Duration,
7+
};
38

49
use super::{
510
discovery::Discovery,
@@ -92,7 +97,7 @@ pub struct OverlayProtocol<TContentKey, TMetric, TValidator> {
9297
}
9398

9499
impl<
95-
TContentKey: OverlayContentKey + Send,
100+
TContentKey: OverlayContentKey + Send + Sync,
96101
TMetric: Metric + Send,
97102
TValidator: 'static + Validator<TContentKey> + Send,
98103
> OverlayProtocol<TContentKey, TMetric, TValidator>

trin-core/src/portalnet/overlay_service.rs

+28-16
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,11 @@
1-
use std::{collections::HashMap, fmt, marker::PhantomData, sync::Arc, task::Poll, time::Duration};
1+
use std::{
2+
collections::HashMap,
3+
fmt,
4+
marker::{PhantomData, Sync},
5+
sync::Arc,
6+
task::Poll,
7+
time::Duration,
8+
};
29

310
use crate::{
411
portalnet::{
@@ -266,7 +273,7 @@ pub struct OverlayService<TContentKey, TMetric, TValidator> {
266273
}
267274

268275
impl<
269-
TContentKey: OverlayContentKey + Send,
276+
TContentKey: OverlayContentKey + Send + Sync,
270277
TMetric: Metric + Send,
271278
TValidator: 'static + Validator<TContentKey> + Send,
272279
> OverlayService<TContentKey, TMetric, TValidator>
@@ -966,18 +973,23 @@ impl<
966973
return;
967974
}
968975
};
969-
let ck_clone = content_key.clone();
970-
let content_clone = content.clone();
971-
self.validator
972-
.validate_content(ck_clone, content_clone)
973-
.await;
976+
match self
977+
.validator
978+
.validate_content(&content_key, &content)
979+
.await
980+
{
981+
Ok(_) => (),
982+
Err(_) => {
983+
error!("Unable to validate received content.");
984+
return;
985+
}
986+
}
974987
match self.storage.read().should_store(&content_key) {
975988
Ok(should_store) => match should_store {
976-
true => self
977-
.storage
978-
.write()
979-
.store(&content_key, &content.into())
980-
.unwrap(),
989+
true => match self.storage.write().store(&content_key, &content.into()) {
990+
Ok(_) => (),
991+
Err(_) => error!("Content received, but not stored: Error writing to db."),
992+
},
981993
false => debug!(
982994
"Content received, but not stored: Distance falls outside current radius."
983995
),
@@ -1285,7 +1297,7 @@ mod tests {
12851297
content_key::IdentityContentKey, messages::PortalnetConfig, metric::XorMetric,
12861298
},
12871299
},
1288-
types::validation::{IdentityValidator, ValidationOracle},
1300+
types::validation::{HeaderOracle, IdentityValidator},
12891301
utils::node_id::generate_random_remote_enr,
12901302
};
12911303

@@ -1331,8 +1343,8 @@ mod tests {
13311343
let (request_tx, request_rx) = mpsc::unbounded_channel();
13321344
let (response_tx, response_rx) = mpsc::unbounded_channel();
13331345
let metrics = None;
1334-
let validation_oracle = ValidationOracle::default();
1335-
let validator = IdentityValidator { validation_oracle };
1346+
let header_oracle = HeaderOracle::default();
1347+
let validator = IdentityValidator { header_oracle };
13361348

13371349
OverlayService {
13381350
discovery,
@@ -1657,7 +1669,7 @@ mod tests {
16571669

16581670
// Modify first ENR to increment sequence number.
16591671
let updated_udp: u16 = 9000;
1660-
let _ = enr1.set_udp(updated_udp, &sk1);
1672+
let _ = enr1.set_udp4(updated_udp, &sk1);
16611673
assert_ne!(1, enr1.seq());
16621674

16631675
let mut enrs: Vec<Enr> = vec![];

trin-core/src/portalnet/types/messages.rs

-2
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,6 @@ pub struct PortalnetConfig {
117117
pub data_radius: U256,
118118
pub no_stun: bool,
119119
pub enable_metrics: bool,
120-
pub infura_url: String,
121120
}
122121

123122
impl Default for PortalnetConfig {
@@ -130,7 +129,6 @@ impl Default for PortalnetConfig {
130129
data_radius: U256::from(u64::MAX), //TODO better data_radius default?
131130
no_stun: false,
132131
enable_metrics: false,
133-
infura_url: "https://mainnet.infura.io:443/v3/".to_string(),
134132
}
135133
}
136134
}

trin-core/src/types/validation.rs

+16-8
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,11 @@ use crate::jsonrpc::types::{HistoryJsonRpcRequest, JsonRequest, Params};
77
use crate::portalnet::types::content_key::IdentityContentKey;
88
use crate::portalnet::types::messages::ByteList;
99

10-
// aka. HeaderOracle
1110
// This struct is responsible for dispatching cross-overlay-network requests
1211
// for data to perform validation. Currently, it just proxies these requests
1312
// on to infura.
1413
#[derive(Clone)]
15-
pub struct ValidationOracle {
14+
pub struct HeaderOracle {
1615
pub infura_url: String,
1716
// We could simply store the main portal jsonrpc tx channel here, rather than each
1817
// individual channel. But my sense is that this will be more useful in terms of
@@ -23,10 +22,10 @@ pub struct ValidationOracle {
2322
pub state_jsonrpc_tx: Option<bool>,
2423
}
2524

26-
impl Default for ValidationOracle {
25+
impl Default for HeaderOracle {
2726
fn default() -> Self {
2827
Self {
29-
infura_url: "https://mainnet.infura.io::443/v3/".to_string(),
28+
infura_url: "https://mainnet.infura.io:443/v3/".to_string(),
3029
history_jsonrpc_tx: None,
3130
header_gossip_jsonrpc_tx: None,
3231
block_indices_jsonrpc_tx: None,
@@ -35,7 +34,7 @@ impl Default for ValidationOracle {
3534
}
3635
}
3736

38-
impl ValidationOracle {
37+
impl HeaderOracle {
3938
// Currently falls back to infura, to be updated to use canonical block indices network.
4039
pub fn get_hash_at_height(&mut self, hex_number: String) -> anyhow::Result<String> {
4140
let request = JsonRequest {
@@ -73,21 +72,30 @@ impl ValidationOracle {
7372
// This trait is used by all overlay-network Validators to validate content in the overlay service.
7473
#[async_trait]
7574
pub trait Validator<TContentKey> {
76-
async fn validate_content(&mut self, content_key: TContentKey, content: ByteList)
75+
async fn validate_content(
76+
&mut self,
77+
content_key: &TContentKey,
78+
content: &ByteList,
79+
) -> anyhow::Result<()>
7780
where
7881
TContentKey: 'async_trait;
7982
}
8083

8184
// This is a mock Validator for use in tests where no validation is required.
8285
pub struct IdentityValidator {
83-
pub validation_oracle: ValidationOracle,
86+
pub header_oracle: HeaderOracle,
8487
}
8588

8689
#[async_trait]
8790
impl Validator<IdentityContentKey> for IdentityValidator {
88-
async fn validate_content(&mut self, _content_key: IdentityContentKey, _content: ByteList)
91+
async fn validate_content(
92+
&mut self,
93+
_content_key: &IdentityContentKey,
94+
_content: &ByteList,
95+
) -> anyhow::Result<()>
8996
where
9097
IdentityContentKey: 'async_trait,
9198
{
99+
Ok(())
92100
}
93101
}

0 commit comments

Comments
 (0)