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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
use std::{
    fmt,
    io::Write,
    net::{Ipv4Addr, SocketAddr},
    path::PathBuf,
    process::Stdio,
    time::Duration,
};

pub use fuel_core_chain_config::ChainConfig;
use fuel_core_chain_config::StateConfig;
use fuel_core_client::client::FuelClient;
use fuel_types::{BlockHeight, Word};
use fuels_core::{
    constants::WORD_SIZE,
    types::{
        coin::Coin,
        errors::{error, Error},
        message::Message,
    },
};
use portpicker::{is_free, pick_unused_port};
use serde::{de::Error as SerdeError, Deserializer, Serializer};
use serde_json::Value;
use serde_with::{DeserializeAs, SerializeAs};
use tempfile::NamedTempFile;
use tokio::{process::Command, sync::oneshot};

use crate::utils::{into_coin_configs, into_message_configs};
// Set the cache for tests to 10MB, which is the default size in `fuel-core`.
pub const DEFAULT_CACHE_SIZE: usize = 10 * 1024 * 1024;

#[derive(Clone, Debug)]
pub enum Trigger {
    Instant,
    Never,
    Interval {
        block_time: Duration,
    },
    Hybrid {
        min_block_time: Duration,
        max_tx_idle_time: Duration,
        max_block_time: Duration,
    },
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum DbType {
    InMemory,
    RocksDb,
}

#[derive(Clone, Debug)]
pub struct Config {
    pub addr: SocketAddr,
    pub max_database_cache_size: usize,
    pub database_path: PathBuf,
    pub database_type: DbType,
    pub utxo_validation: bool,
    pub manual_blocks_enabled: bool,
    pub block_production: Trigger,
    pub vm_backtrace: bool,
    pub silent: bool,
}

impl Config {
    pub fn local_node() -> Self {
        Self {
            addr: SocketAddr::new(Ipv4Addr::new(127, 0, 0, 1).into(), 0),
            max_database_cache_size: DEFAULT_CACHE_SIZE,
            database_path: Default::default(),
            database_type: DbType::InMemory,
            utxo_validation: false,
            manual_blocks_enabled: false,
            block_production: Trigger::Instant,
            vm_backtrace: false,
            silent: true,
        }
    }
}

pub type InternalDaBlockHeight = u64;

pub(crate) struct HexType;

impl<T: AsRef<[u8]>> SerializeAs<T> for HexType {
    fn serialize_as<S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serde_hex::serialize(value, serializer)
    }
}

impl<'de, T, E> DeserializeAs<'de, T> for HexType
where
    for<'a> T: TryFrom<&'a [u8], Error = E>,
    E: fmt::Display,
{
    fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
    where
        D: Deserializer<'de>,
    {
        serde_hex::deserialize(deserializer)
    }
}

pub mod serde_hex {
    use std::{convert::TryFrom, fmt};

    use hex::{FromHex, ToHex};
    use serde::{de::Error, Deserializer, Serializer};

    pub fn serialize<T, S>(target: T, ser: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
        T: ToHex,
    {
        let s = format!("0x{}", target.encode_hex::<String>());
        ser.serialize_str(&s)
    }

    pub fn deserialize<'de, T, E, D>(des: D) -> Result<T, D::Error>
    where
        D: Deserializer<'de>,
        for<'a> T: TryFrom<&'a [u8], Error = E>,
        E: fmt::Display,
    {
        let raw_string: String = serde::Deserialize::deserialize(des)?;
        let stripped_prefix = raw_string.trim_start_matches("0x");
        let bytes: Vec<u8> = FromHex::from_hex(stripped_prefix).map_err(D::Error::custom)?;
        let result = T::try_from(bytes.as_slice()).map_err(D::Error::custom)?;
        Ok(result)
    }
}

pub(crate) struct HexNumber;

impl SerializeAs<u64> for HexNumber {
    fn serialize_as<S>(value: &u64, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let bytes = value.to_be_bytes();
        serde_hex::serialize(bytes, serializer)
    }
}

impl<'de> DeserializeAs<'de, Word> for HexNumber {
    fn deserialize_as<D>(deserializer: D) -> Result<Word, D::Error>
    where
        D: Deserializer<'de>,
    {
        let mut bytes: Vec<u8> = serde_hex::deserialize(deserializer)?;
        match bytes.len() {
            len if len > WORD_SIZE => {
                return Err(D::Error::custom(format!(
                    "value can't exceed {WORD_SIZE} bytes",
                )));
            }
            len if len < WORD_SIZE => {
                // pad if length < word size
                bytes = (0..WORD_SIZE - len)
                    .map(|_| 0u8)
                    .chain(bytes.into_iter())
                    .collect();
            }
            _ => {}
        }
        // We've already verified the bytes.len == WORD_SIZE, force the conversion here.
        Ok(Word::from_be_bytes(
            bytes.try_into().expect("byte lengths checked"),
        ))
    }
}

impl SerializeAs<BlockHeight> for HexNumber {
    fn serialize_as<S>(value: &BlockHeight, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let number = u32::from(*value) as u64;
        HexNumber::serialize_as(&number, serializer)
    }
}

impl<'de> DeserializeAs<'de, BlockHeight> for HexNumber {
    fn deserialize_as<D>(deserializer: D) -> Result<BlockHeight, D::Error>
    where
        D: Deserializer<'de>,
    {
        let number: u64 = HexNumber::deserialize_as(deserializer)?;
        Ok((number as u32).into())
    }
}

pub fn get_node_config_json(
    coins: Vec<Coin>,
    messages: Vec<Message>,
    chain_config: Option<ChainConfig>,
) -> Value {
    let coin_configs = into_coin_configs(coins);
    let messages = into_message_configs(messages);

    let mut chain_config = chain_config.unwrap_or_else(ChainConfig::local_testnet);

    chain_config.initial_state = Some(StateConfig {
        coins: Some(coin_configs),
        contracts: None,
        messages: Some(messages),
        height: None,
    });

    serde_json::to_value(&chain_config).expect("Failed to build `ChainConfig` JSON")
}

fn write_temp_config_file(config: Value) -> NamedTempFile {
    let config_file = NamedTempFile::new();

    let _ = writeln!(
        config_file.as_ref().unwrap().as_file(),
        "{}",
        &config.to_string()
    );

    config_file.unwrap()
}

pub async fn new_fuel_node(
    coins: Vec<Coin>,
    messages: Vec<Message>,
    config: Config,
    chain_config: Option<ChainConfig>,
) {
    // Create a new one-shot channel for sending single values across asynchronous tasks.
    let (tx, rx) = oneshot::channel();

    tokio::spawn(async move {
        let config_json = get_node_config_json(coins, messages, chain_config);

        let temp_config_file = write_temp_config_file(config_json);

        let port = config.addr.port().to_string();
        let mut args = vec![
            "run".to_string(), // `fuel-core` is now run with `fuel-core run`
            "--ip".to_string(),
            "127.0.0.1".to_string(),
            "--port".to_string(),
            port,
            "--chain".to_string(),
            temp_config_file.path().to_str().unwrap().to_string(),
        ];

        args.extend(vec![
            "--db-type".to_string(),
            match config.database_type {
                DbType::InMemory => "in-memory",
                DbType::RocksDb => "rocks-db",
            }
            .to_string(),
        ]);

        if let DbType::RocksDb = config.database_type {
            let path = if config.database_path.as_os_str().is_empty() {
                PathBuf::from(std::env::var("HOME").expect("HOME env var missing")).join(".fuel/db")
            } else {
                config.database_path
            };
            args.extend(vec![
                "--db-path".to_string(),
                path.to_string_lossy().to_string(),
            ]);
        }

        if config.max_database_cache_size != DEFAULT_CACHE_SIZE {
            args.push("--max-database-cache-size".to_string());
            args.push(config.max_database_cache_size.to_string());
        }

        if config.utxo_validation {
            args.push("--utxo-validation".to_string());
        }

        if config.manual_blocks_enabled {
            args.push("--manual_blocks_enabled".to_string());
        }

        match config.block_production {
            Trigger::Instant => {
                args.push("--poa-instant=true".to_string());
            }
            Trigger::Never => {
                args.push("--poa-instant=false".to_string());
            }
            Trigger::Interval { block_time } => {
                args.push(format!(
                    "--poa-interval-period={}ms",
                    block_time.as_millis()
                ));
            }
            Trigger::Hybrid {
                min_block_time,
                max_tx_idle_time,
                max_block_time,
            } => {
                args.push(format!(
                    "--poa-hybrid-min-time={}ms",
                    min_block_time.as_millis()
                ));
                args.push(format!(
                    "--poa-hybrid-idle-time={}ms",
                    max_tx_idle_time.as_millis()
                ));
                args.push(format!(
                    "--poa-hybrid-max-time={}ms",
                    max_block_time.as_millis()
                ));
            }
        };

        if config.vm_backtrace {
            args.push("--vm-backtrace".to_string());
        }

        // Warn if there is more than one binary in PATH.
        let binary_name = "fuel-core";
        let paths = which::which_all(binary_name)
            .unwrap_or_else(|_| panic!("failed to list '{binary_name}' binaries"))
            .collect::<Vec<_>>();
        let path = paths
            .first()
            .unwrap_or_else(|| panic!("no '{binary_name}' in PATH"));
        if paths.len() > 1 {
            eprintln!(
                "found more than one '{}' binary in PATH, using '{}'",
                binary_name,
                path.display()
            );
        }

        let mut command = Command::new(path);
        command.stdin(Stdio::null());
        if config.silent {
            command.stdout(Stdio::null()).stderr(Stdio::null());
        }
        let running_node = command.args(args).kill_on_drop(true).env_clear().output();

        let client = FuelClient::from(config.addr);
        server_health_check(&client).await;
        // Sending single to RX to inform that the fuel core node is ready.
        tx.send(()).unwrap();

        let result = running_node
            .await
            .expect("error: Couldn't find fuel-core in PATH.");
        let stdout = String::from_utf8_lossy(&result.stdout);
        let stderr = String::from_utf8_lossy(&result.stderr);
        eprintln!("the exit status from the fuel binary was: {result:?}, stdout: {stdout}, stderr: {stderr}");
    });
    // Awaiting a signal from Tx that informs us if the fuel-core node is ready.
    rx.await.unwrap();
}

pub async fn server_health_check(client: &FuelClient) {
    let mut attempts = 5;
    let mut healthy = client.health().await.unwrap_or(false);
    let between_attempts = Duration::from_millis(300);

    while attempts > 0 && !healthy {
        healthy = client.health().await.unwrap_or(false);
        tokio::time::sleep(between_attempts).await;
        attempts -= 1;
    }

    if !healthy {
        panic!("error: Could not connect to fuel core server.")
    }
}

pub fn get_socket_address() -> SocketAddr {
    let free_port = pick_unused_port().expect("No ports free");
    SocketAddr::new("127.0.0.1".parse().unwrap(), free_port)
}

pub struct FuelService {
    pub bound_address: SocketAddr,
}

impl FuelService {
    pub async fn new_node(config: Config) -> Result<Self, Error> {
        let requested_port = config.addr.port();

        let bound_address = if requested_port == 0 {
            get_socket_address()
        } else if is_free(requested_port) {
            config.addr
        } else {
            return Err(error!(InfrastructureError, "Error: Address already in use"));
        };

        new_fuel_node(
            vec![],
            vec![],
            Config {
                addr: bound_address,
                ..config
            },
            None,
        )
        .await;

        Ok(FuelService { bound_address })
    }
}