iota_network/
utils.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5#[cfg(test)]
6pub fn build_network(f: impl FnOnce(anemo::Router) -> anemo::Router) -> anemo::Network {
7    build_network_impl(f, None)
8}
9
10#[cfg(test)]
11pub fn build_network_with_anemo_config(
12    f: impl FnOnce(anemo::Router) -> anemo::Router,
13    anemo_config: anemo::Config,
14) -> anemo::Network {
15    build_network_impl(f, Some(anemo_config))
16}
17
18#[cfg(test)]
19fn build_network_impl(
20    f: impl FnOnce(anemo::Router) -> anemo::Router,
21    anemo_config: Option<anemo::Config>,
22) -> anemo::Network {
23    let router = f(anemo::Router::new());
24    let network = anemo::Network::bind("localhost:0")
25        .private_key(random_key())
26        .config(anemo_config.unwrap_or_default())
27        .server_name("test")
28        .start(router)
29        .unwrap();
30
31    println!(
32        "starting network {} {}",
33        network.local_addr(),
34        network.peer_id(),
35    );
36    network
37}
38
39#[cfg(test)]
40fn random_key() -> [u8; 32] {
41    let mut rng = rand::thread_rng();
42    let mut bytes = [0u8; 32];
43    rand::RngCore::fill_bytes(&mut rng, &mut bytes[..]);
44    bytes
45}