fedimint_testing/
fixtures.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
use std::env;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;

use fedimint_bitcoind::{create_bitcoind, DynBitcoindRpc};
use fedimint_client::module::init::{
    ClientModuleInitRegistry, DynClientModuleInit, IClientModuleInit,
};
use fedimint_core::config::{
    ModuleInitParams, ServerModuleConfigGenParamsRegistry, ServerModuleInitRegistry,
};
use fedimint_core::core::{ModuleInstanceId, ModuleKind};
use fedimint_core::db::mem_impl::MemDatabase;
use fedimint_core::db::Database;
use fedimint_core::envs::BitcoinRpcConfig;
use fedimint_core::module::registry::ModuleRegistry;
use fedimint_core::module::{DynServerModuleInit, IServerModuleInit};
use fedimint_core::task::{MaybeSend, MaybeSync, TaskGroup};
use fedimint_core::util::SafeUrl;
use fedimint_logging::TracingSetup;
use fedimint_testing_core::test_dir;
use lightning_invoice::RoutingFees;
use ln_gateway::client::GatewayClientBuilder;
use ln_gateway::config::LightningModuleMode;
use ln_gateway::lightning::{ILnRpcClient, LightningBuilder, LightningContext};
use ln_gateway::Gateway;

use crate::btc::mock::FakeBitcoinFactory;
use crate::btc::real::RealBitcoinTest;
use crate::btc::BitcoinTest;
use crate::envs::{
    FM_PORT_ESPLORA_ENV, FM_TEST_BACKEND_BITCOIN_RPC_KIND_ENV, FM_TEST_BACKEND_BITCOIN_RPC_URL_ENV,
    FM_TEST_BITCOIND_RPC_ENV, FM_TEST_USE_REAL_DAEMONS_ENV,
};
use crate::federation::{FederationTest, FederationTestBuilder};
use crate::gateway::{FakeLightningBuilder, DEFAULT_GATEWAY_PASSWORD};

/// A default timeout for things happening in tests
pub const TIMEOUT: Duration = Duration::from_secs(10);

/// A tool for easily writing fedimint integration tests
pub struct Fixtures {
    clients: Vec<DynClientModuleInit>,
    servers: Vec<DynServerModuleInit>,
    params: ServerModuleConfigGenParamsRegistry,
    bitcoin_rpc: BitcoinRpcConfig,
    bitcoin: Arc<dyn BitcoinTest>,
    dyn_bitcoin_rpc: DynBitcoindRpc,
    id: ModuleInstanceId,
}

impl Fixtures {
    pub fn new_primary(
        client: impl IClientModuleInit + 'static,
        server: impl IServerModuleInit + MaybeSend + MaybeSync + 'static,
        params: impl ModuleInitParams,
    ) -> Self {
        // Ensure tracing has been set once
        let _ = TracingSetup::default().init();
        let real_testing = Fixtures::is_real_test();
        let task_group = TaskGroup::new();
        let (dyn_bitcoin_rpc, bitcoin, config): (
            DynBitcoindRpc,
            Arc<dyn BitcoinTest>,
            BitcoinRpcConfig,
        ) = if real_testing {
            // `backend-test.sh` overrides which Bitcoin RPC to use for electrs and esplora
            // backend tests
            let override_bitcoin_rpc_kind = env::var(FM_TEST_BACKEND_BITCOIN_RPC_KIND_ENV);
            let override_bitcoin_rpc_url = env::var(FM_TEST_BACKEND_BITCOIN_RPC_URL_ENV);

            let rpc_config = match (override_bitcoin_rpc_kind, override_bitcoin_rpc_url) {
                (Ok(kind), Ok(url)) => BitcoinRpcConfig {
                    kind: kind.parse().expect("must provide valid kind"),
                    url: url.parse().expect("must provide valid url"),
                },
                _ => BitcoinRpcConfig::get_defaults_from_env_vars()
                    .expect("must provide valid default env vars"),
            };

            let dyn_bitcoin_rpc = create_bitcoind(&rpc_config, task_group.make_handle()).unwrap();
            let bitcoincore_url = env::var(FM_TEST_BITCOIND_RPC_ENV)
                .expect("Must have bitcoind RPC defined for real tests")
                .parse()
                .expect("Invalid bitcoind RPC URL");
            let bitcoin = RealBitcoinTest::new(&bitcoincore_url, dyn_bitcoin_rpc.clone());

            (dyn_bitcoin_rpc, Arc::new(bitcoin), rpc_config)
        } else {
            let FakeBitcoinFactory { bitcoin, config } = FakeBitcoinFactory::register_new();
            let dyn_bitcoin_rpc = DynBitcoindRpc::from(bitcoin.clone());
            let bitcoin = Arc::new(bitcoin);
            (dyn_bitcoin_rpc, bitcoin, config)
        };

        Self {
            clients: vec![],
            servers: vec![],
            params: ModuleRegistry::default(),
            bitcoin_rpc: config,
            bitcoin,
            dyn_bitcoin_rpc,
            id: 0,
        }
        .with_module(client, server, params)
    }

    pub fn is_real_test() -> bool {
        env::var(FM_TEST_USE_REAL_DAEMONS_ENV) == Ok("1".to_string())
    }

    // TODO: Auto-assign instance ids after removing legacy id order
    /// Add a module to the fed
    pub fn with_module(
        mut self,
        client: impl IClientModuleInit + 'static,
        server: impl IServerModuleInit + MaybeSend + MaybeSync + 'static,
        params: impl ModuleInitParams,
    ) -> Self {
        self.params
            .attach_config_gen_params_by_id(self.id, server.module_kind(), params);
        self.clients.push(DynClientModuleInit::from(client));
        self.servers.push(DynServerModuleInit::from(server));
        self.id += 1;

        self
    }

    pub fn with_server_only_module(
        mut self,
        server: impl IServerModuleInit + MaybeSend + MaybeSync + 'static,
        params: impl ModuleInitParams,
    ) -> Self {
        self.params
            .attach_config_gen_params_by_id(self.id, server.module_kind(), params);
        self.servers.push(DynServerModuleInit::from(server));
        self.id += 1;

        self
    }

    /// Starts a new federation with default number of peers for testing
    pub async fn new_default_fed(&self) -> FederationTest {
        self.new_fed_builder().build().await
    }

    /// Creates a new `FederationTestBuilder` that can be used to build up a
    /// `FederationTest` for module tests.
    pub fn new_fed_builder(&self) -> FederationTestBuilder {
        FederationTestBuilder::new(
            self.params.clone(),
            ServerModuleInitRegistry::from(self.servers.clone()),
            ClientModuleInitRegistry::from(self.clients.clone()),
        )
    }

    /// Creates a new Gateway that can be used for module tests.
    pub async fn new_gateway(&self, lightning_module_mode: LightningModuleMode) -> Gateway {
        let server_gens = ServerModuleInitRegistry::from(self.servers.clone());
        let module_kinds = self.params.iter_modules().map(|(id, kind, _)| (id, kind));
        let decoders = server_gens.available_decoders(module_kinds).unwrap();
        let gateway_db = Database::new(MemDatabase::new(), decoders.clone());
        let clients = self.clients.clone().into_iter();

        let registry = clients
            .filter(|client| {
                // Remove LN module because the gateway adds one
                client.to_dyn_common().module_kind() != ModuleKind::from_static_str("ln")
            })
            .filter(|client| {
                // Remove LN NG module because the gateway adds one
                client.to_dyn_common().module_kind() != ModuleKind::from_static_str("lnv2")
            })
            .collect();

        let (path, _config_dir) = test_dir(&format!("gateway-{}", rand::random::<u64>()));

        // Create federation client builder for the gateway
        let client_builder: GatewayClientBuilder =
            GatewayClientBuilder::new(path.clone(), registry, 0);

        let lightning_builder: Arc<dyn LightningBuilder + Send + Sync> =
            Arc::new(FakeLightningBuilder);
        // Note: This runtime isn't used by `FakeLightningBuilder`. It is immediately
        // dropped.
        let runtime = Arc::new(tokio::runtime::Runtime::new().unwrap());
        let ln_client: Arc<dyn ILnRpcClient> = lightning_builder.build(runtime).await.into();

        let (lightning_public_key, lightning_alias, lightning_network, _, _) = ln_client
            .parsed_node_info()
            .await
            .expect("Could not get Lightning info");
        let lightning_context = LightningContext {
            lnrpc: ln_client.clone(),
            lightning_public_key,
            lightning_alias,
            lightning_network,
        };

        // Module tests do not use the webserver, so any port is ok
        let listen: SocketAddr = "127.0.0.1:9000".parse().unwrap();
        let address: SafeUrl = format!("http://{listen}").parse().unwrap();

        Gateway::new_with_custom_registry(
            lightning_builder,
            client_builder,
            listen,
            address.clone(),
            Some(DEFAULT_GATEWAY_PASSWORD.to_string()),
            Some(bitcoin::Network::Regtest),
            RoutingFees {
                base_msat: 0,
                proportional_millionths: 0,
            },
            0,
            gateway_db,
            // Manually set the gateway's state to `Running`. In tests, we do don't run the
            // webserver or intercept HTLCs, so this is necessary for instructing the
            // gateway that it is connected to the mock Lightning node.
            ln_gateway::GatewayState::Running { lightning_context },
            lightning_module_mode,
        )
        .await
        .expect("Failed to create gateway")
    }

    /// Get a server bitcoin RPC config
    pub fn bitcoin_server(&self) -> BitcoinRpcConfig {
        self.bitcoin_rpc.clone()
    }

    /// Get a client bitcoin RPC config
    // TODO: Right now we only support mocks or esplora, we should support others in
    // the future
    pub fn bitcoin_client(&self) -> BitcoinRpcConfig {
        if Fixtures::is_real_test() {
            BitcoinRpcConfig {
                kind: "esplora".to_string(),
                url: SafeUrl::parse(&format!(
                    "http://127.0.0.1:{}/",
                    env::var(FM_PORT_ESPLORA_ENV).unwrap_or(String::from("50002"))
                ))
                .expect("Failed to parse default esplora server"),
            }
        } else {
            self.bitcoin_rpc.clone()
        }
    }

    /// Get a test bitcoin fixture
    pub fn bitcoin(&self) -> Arc<dyn BitcoinTest> {
        self.bitcoin.clone()
    }

    pub fn dyn_bitcoin_rpc(&self) -> DynBitcoindRpc {
        self.dyn_bitcoin_rpc.clone()
    }
}