Skip to content

Commit cf8355f

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

File tree

21 files changed

+1235
-385
lines changed

21 files changed

+1235
-385
lines changed

Cargo.lock

Lines changed: 990 additions & 279 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 1 deletion
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"

src/lib.rs

Lines changed: 25 additions & 29 deletions
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

Lines changed: 3 additions & 3 deletions
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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -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

Lines changed: 2 additions & 2 deletions
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_service.rs

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -968,16 +968,23 @@ impl<
968968
};
969969
let ck_clone = content_key.clone();
970970
let content_clone = content.clone();
971-
self.validator
971+
match self
972+
.validator
972973
.validate_content(ck_clone, content_clone)
973-
.await;
974+
.await
975+
{
976+
Ok(_) => (),
977+
Err(_) => {
978+
error!("Unable to validate received content.");
979+
return;
980+
}
981+
}
974982
match self.storage.read().should_store(&content_key) {
975983
Ok(should_store) => match should_store {
976-
true => self
977-
.storage
978-
.write()
979-
.store(&content_key, &content.into())
980-
.unwrap(),
984+
true => match self.storage.write().store(&content_key, &content.into()) {
985+
Ok(_) => (),
986+
Err(_) => error!("Content received, but not stored: Error writing to db."),
987+
},
981988
false => debug!(
982989
"Content received, but not stored: Distance falls outside current radius."
983990
),
@@ -1285,7 +1292,7 @@ mod tests {
12851292
content_key::IdentityContentKey, messages::PortalnetConfig, metric::XorMetric,
12861293
},
12871294
},
1288-
types::validation::{IdentityValidator, ValidationOracle},
1295+
types::validation::{HeaderOracle, IdentityValidator},
12891296
utils::node_id::generate_random_remote_enr,
12901297
};
12911298

@@ -1331,8 +1338,8 @@ mod tests {
13311338
let (request_tx, request_rx) = mpsc::unbounded_channel();
13321339
let (response_tx, response_rx) = mpsc::unbounded_channel();
13331340
let metrics = None;
1334-
let validation_oracle = ValidationOracle::default();
1335-
let validator = IdentityValidator { validation_oracle };
1341+
let header_oracle = HeaderOracle::default();
1342+
let validator = IdentityValidator { header_oracle };
13361343

13371344
OverlayService {
13381345
discovery,
@@ -1657,7 +1664,7 @@ mod tests {
16571664

16581665
// Modify first ENR to increment sequence number.
16591666
let updated_udp: u16 = 9000;
1660-
let _ = enr1.set_udp(updated_udp, &sk1);
1667+
let _ = enr1.set_udp4(updated_udp, &sk1);
16611668
assert_ne!(1, enr1.seq());
16621669

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

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

Lines changed: 0 additions & 2 deletions
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

Lines changed: 16 additions & 8 deletions
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
}

trin-core/src/utils/infura.rs

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,13 @@
11
use std::env;
22

3-
pub fn fetch_infura_id_from_env() -> String {
4-
match env::var("TRIN_INFURA_PROJECT_ID") {
3+
pub fn build_infura_project_url_from_env() -> String {
4+
let infura_project_id = match env::var("TRIN_INFURA_PROJECT_ID") {
55
Ok(val) => val,
66
Err(_) => panic!(
77
"Must supply Infura key as environment variable, like:\n\
88
TRIN_INFURA_PROJECT_ID=\"your-key-here\" trin"
99
),
10-
}
11-
}
10+
};
1211

13-
pub fn get_infura_url(infura_project_id: &str) -> String {
14-
return format!("https://mainnet.infura.io:443/v3/{}", infura_project_id);
12+
format!("https://mainnet.infura.io:443/v3/{}", infura_project_id)
1513
}

trin-core/src/utils/node_id.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ pub fn generate_random_remote_enr() -> (CombinedKey, Enr) {
4545

4646
let enr = EnrBuilder::new("v4")
4747
.ip(ip.into())
48-
.udp(8000)
48+
.udp4(8000)
4949
.build(&key)
5050
.unwrap();
5151

trin-core/src/utp/stream.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1401,7 +1401,7 @@ mod tests {
14011401

14021402
async fn client_setup(connected_to: Enr) -> (Enr, UtpSocket) {
14031403
let port = next_test_port();
1404-
let matching_ip = connected_to.ip().unwrap();
1404+
let matching_ip = connected_to.ip4().unwrap();
14051405
let config = PortalnetConfig {
14061406
listen_port: port,
14071407
external_addr: Some(SocketAddr::new(IpAddr::V4(matching_ip), port)),

trin-core/tests/overlay.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use trin_core::{
1414
Enr,
1515
},
1616
socket,
17-
types::validation::{IdentityValidator, ValidationOracle},
17+
types::validation::{HeaderOracle, IdentityValidator},
1818
};
1919

2020
use discv5::Discv5Event;
@@ -39,8 +39,8 @@ async fn init_overlay(
3939
let overlay_config = OverlayConfig::default();
4040
// Ignore all uTP events
4141
let (utp_listener_tx, _) = unbounded_channel::<UtpListenerRequest>();
42-
let validation_oracle = ValidationOracle::default();
43-
let validator = IdentityValidator { validation_oracle };
42+
let header_oracle = HeaderOracle::default();
43+
let validator = IdentityValidator { header_oracle };
4444

4545
OverlayProtocol::new(
4646
overlay_config,

trin-history/Cargo.toml

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,11 @@ anyhow = "1.0.52"
1212
async-trait = "0.1.53"
1313
bytes = "1.1.0"
1414
discv5 = { git = "https://github.com/sigp/discv5.git", branch = "master" }
15+
ethereum-types = "0.12.1"
1516
hex = "0.4.3"
17+
httpmock = "0.6.6"
1618
keccak-hash = "0.8.0"
17-
log = "0.4.14"
19+
log = "0.4.17"
1820
parking_lot = "0.11.2"
1921
rlp = "0.5.0"
2022
rocksdb = "0.18.0"

0 commit comments

Comments
 (0)