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, "localhost:0".into(), None).0
8}
9
10#[cfg(test)]
11pub fn build_network_and_key(
12    f: impl FnOnce(anemo::Router) -> anemo::Router,
13) -> (anemo::Network, iota_types::crypto::NetworkKeyPair) {
14    build_network_impl(f, "localhost:0".into(), None)
15}
16
17#[cfg(test)]
18pub fn build_network_with_anemo_config(
19    f: impl FnOnce(anemo::Router) -> anemo::Router,
20    anemo_config: anemo::Config,
21) -> (anemo::Network, iota_types::crypto::NetworkKeyPair) {
22    build_network_impl(f, "localhost:0".into(), Some(anemo_config))
23}
24
25#[cfg(test)]
26pub fn build_network_with_address(
27    f: impl FnOnce(anemo::Router) -> anemo::Router,
28    address: anemo::types::Address,
29) -> (anemo::Network, iota_types::crypto::NetworkKeyPair) {
30    build_network_impl(f, address, None)
31}
32
33#[cfg(test)]
34pub fn build_network_with_address_and_anemo_config(
35    f: impl FnOnce(anemo::Router) -> anemo::Router,
36    address: anemo::types::Address,
37    anemo_config: anemo::Config,
38) -> (anemo::Network, iota_types::crypto::NetworkKeyPair) {
39    build_network_impl(f, address, Some(anemo_config))
40}
41
42#[cfg(test)]
43fn build_network_impl(
44    f: impl FnOnce(anemo::Router) -> anemo::Router,
45    address: anemo::types::Address,
46    anemo_config: Option<anemo::Config>,
47) -> (anemo::Network, iota_types::crypto::NetworkKeyPair) {
48    use fastcrypto::traits::KeyPair;
49
50    let keypair = iota_types::crypto::NetworkKeyPair::generate(&mut rand::thread_rng());
51    let router = f(anemo::Router::new());
52    let network = anemo::Network::bind(address)
53        .private_key(keypair.copy().private().0.to_bytes())
54        .config(anemo_config.unwrap_or_default())
55        .server_name("test")
56        .start(router)
57        .unwrap();
58
59    println!(
60        "starting network {} {}",
61        network.local_addr(),
62        network.peer_id(),
63    );
64    (network, keypair)
65}