zero-trust-rps 0.0.5

Online Multiplayer Rock Paper Scissors
Documentation
use std::{
    net::{IpAddr, SocketAddr},
    sync::Arc,
};

use quinn::{rustls::RootCertStore, ClientConfig, Endpoint};

use crate::common::{
    client::bot::run_bot, connection::get_default_transport_config, result::DynResult,
};

use super::{sockets::read_certs_from_file, ServerOptions};

pub(super) async fn server_run_bots(ip: IpAddr, options: &ServerOptions) {
    match _server_run_bots(ip, options).await {
        Ok(()) => log::debug!("finished starting bots"),
        Err(err) => log::error!("Starting bots failed: {err:?}"),
    }
}

async fn _server_run_bots(ip: IpAddr, options: &ServerOptions) -> DynResult<()> {
    if options.bots.is_empty() {
        return Ok(());
    }
    let remote_addr = SocketAddr::new(ip, options.port);

    let mut store = RootCertStore::empty();
    for cert in read_certs_from_file(options)?.0 {
        store.add(cert)?;
    }
    let mut config = ClientConfig::with_root_certificates(Arc::new(store))?;
    config.transport_config(get_default_transport_config());

    for (id, bot) in options.bots.iter().enumerate() {
        let endpoint = Endpoint::client(SocketAddr::new(ip, 0))?;

        let connection = endpoint
            .connect_with(config.clone(), remote_addr, options.domain.as_str())?
            .await?;
        tokio::spawn(run_bot(
            id,
            connection,
            *bot,
            options.domain.clone(),
            options.port,
        ));
    }

    Ok(())
}