garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /ports/check/src/main.rs

raw

//! The self-check's program on the ported crates: tokio's runtime on
//! several threads, its timers, tasks and channels, a blocking task waking
//! the runtime from another thread, and a TCP connection through Pinnacle's
//! mio (`ports/mio-*`), fetching the package source's catalog. Exits 0, or
//! panics.

use std::time::{Duration, Instant};
use tokio::io::{AsyncReadExt, AsyncWriteExt};

#[tokio::main(flavor = "multi_thread", worker_threads = 3)]
async fn main() {
    // Timers: a sleep lasts as long as asked; a timeout fires.
    let start = Instant::now();
    tokio::time::sleep(Duration::from_millis(30)).await;
    let slept = start.elapsed();
    assert!(slept >= Duration::from_millis(30), "slept only {slept:?}");
    let pending = tokio::time::timeout(Duration::from_millis(20), std::future::pending::<()>()).await;
    assert!(pending.is_err(), "a timeout did not fire");

    // Tasks on the workers, sending over a channel.
    let (tx, mut rx) = tokio::sync::mpsc::channel(16);
    for i in 0..16u64 {
        let tx = tx.clone();
        tokio::spawn(async move { tx.send(i).await.unwrap() });
    }
    drop(tx);
    let mut sum = 0;
    while let Some(i) = rx.recv().await {
        sum += i;
    }
    assert_eq!(sum, 120);

    // A blocking task on its own thread; its end wakes the runtime.
    let answer = tokio::task::spawn_blocking(|| {
        std::thread::sleep(Duration::from_millis(20));
        42
    })
    .await
    .unwrap();
    assert_eq!(answer, 42);

    // ring as Pinnacle has it, against the standards' vectors.
    let vectors = crypto();

    // The network, through mio: once there is an address, the catalog.
    let fetched = network().await;
    println!(
        "ports: tokio on 3 workers: slept {} ms, a timeout, 16 tasks, a blocking task; {fetched} bytes over a tokio TcpStream; ring: {vectors} vectors",
        slept.as_millis()
    );

    // Vulkan through ash, on Pinnacle's driver, where there is a 3D GPU;
    // then wgpu on it.
    if vulkan() {
        wgpu_compute();
    }
}

/// wgpu as Cartopolis has it (the Vulkan backend, its ash on Pinnacle's
/// driver): an adapter and device, a WGSL compute shader (to SPIR-V by
/// naga) doubling 1024 numbers in a storage buffer, copied to a buffer
/// mapped for reading, and checked.
fn wgpu_compute() {
    const SHADER: &str = "
        @group(0) @binding(0) var<storage, read_write> numbers: array<u32>;
        @compute @workgroup_size(64)
        fn main(@builtin(global_invocation_id) id: vec3<u32>) {
            numbers[id.x] = numbers[id.x] * 2u;
        }";
    const COUNT: usize = 1024;
    let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
        backends: wgpu::Backends::VULKAN,
        ..wgpu::InstanceDescriptor::new_without_display_handle()
    });
    let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default()))
        .expect("wgpu: no adapter");
    let name = adapter.get_info().name;
    let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default()))
        .expect("wgpu: no device");
    let size = (COUNT * 4) as u64;
    let storage = device.create_buffer(&wgpu::BufferDescriptor {
        label: Some("numbers"),
        size,
        usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST,
        mapped_at_creation: false,
    });
    let numbers: Vec<u8> = (0..COUNT as u32).flat_map(|i| i.to_le_bytes()).collect();
    queue.write_buffer(&storage, 0, &numbers);
    let readback = device.create_buffer(&wgpu::BufferDescriptor {
        label: Some("readback"),
        size,
        usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
        mapped_at_creation: false,
    });
    let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
        label: Some("double"),
        source: wgpu::ShaderSource::Wgsl(SHADER.into()),
    });
    let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
        label: Some("double"),
        layout: None,
        module: &module,
        entry_point: Some("main"),
        compilation_options: Default::default(),
        cache: None,
    });
    let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
        label: None,
        layout: &pipeline.get_bind_group_layout(0),
        entries: &[wgpu::BindGroupEntry {
            binding: 0,
            resource: storage.as_entire_binding(),
        }],
    });
    let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
    {
        let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor::default());
        pass.set_pipeline(&pipeline);
        pass.set_bind_group(0, &bind_group, &[]);
        pass.dispatch_workgroups((COUNT / 64) as u32, 1, 1);
    }
    encoder.copy_buffer_to_buffer(&storage, 0, &readback, 0, size);
    queue.submit([encoder.finish()]);
    readback
        .slice(..)
        .map_async(wgpu::MapMode::Read, |r| r.expect("wgpu: mapping failed"));
    device
        .poll(wgpu::PollType::wait_indefinitely())
        .expect("wgpu: the GPU did not finish");
    let doubled = {
        let data = readback
            .slice(..)
            .get_mapped_range()
            .expect("wgpu: the buffer was not mapped");
        data.chunks(4)
            .enumerate()
            .filter(|(i, c)| u32::from_le_bytes([c[0], c[1], c[2], c[3]]) == 2 * *i as u32)
            .count()
    };
    println!(
        "wgpu: on Pinnacle's driver ({name}): a WGSL compute shader doubled {doubled} of {COUNT} numbers"
    );
    assert_eq!(doubled, COUNT, "wgpu: the numbers came back wrong");
}

/// What the GPU fills its buffer with: "Pinn".
const FILL: u32 = u32::from_le_bytes(*b"Pinn");

/// Vulkan as wgpu takes it: ash's entry made from the driver's
/// vkGetInstanceProcAddr, an instance, the GPUs named, a device and its
/// queue, a buffer in memory mapped for the program, a command buffer
/// filling it, submitted and its fence waited for, the buffer read back.
fn vulkan() -> bool {
    use ash::vk;
    // SAFETY: the driver's vkGetInstanceProcAddr is Vulkan's, handles as
    // ash's (u64 ids).
    let entry = unsafe {
        ash::Entry::from_static_fn(ash::StaticFn {
            get_instance_proc_addr: std::mem::transmute(pinnacle_vulkan::vkGetInstanceProcAddr as *const ()),
        })
    };
    let app = vk::ApplicationInfo::default()
        .application_name(c"ports-check")
        .api_version(vk::API_VERSION_1_1);
    let Ok(instance) =
        (unsafe { entry.create_instance(&vk::InstanceCreateInfo::default().application_info(&app), None) })
    else {
        println!("vulkan: no 3D GPU");
        return false;
    };
    // SAFETY (below): every handle is the driver's, made just before.
    let physical = unsafe { instance.enumerate_physical_devices() }.expect("no physical devices");
    let first = *physical.first().expect("an instance, but no GPU");
    let properties = unsafe { instance.get_physical_device_properties(first) };
    let name = properties
        .device_name_as_c_str()
        .unwrap_or(c"?")
        .to_string_lossy()
        .into_owned();
    let family = unsafe { instance.get_physical_device_queue_family_properties(first) }
        .iter()
        .position(|f| {
            f.queue_flags
                .intersects(vk::QueueFlags::GRAPHICS | vk::QueueFlags::COMPUTE | vk::QueueFlags::TRANSFER)
        })
        .expect("no queue family that can fill a buffer") as u32;
    let priorities = [1.0];
    let queue_info = [vk::DeviceQueueCreateInfo::default()
        .queue_family_index(family)
        .queue_priorities(&priorities)];
    let device = unsafe {
        instance.create_device(
            first,
            &vk::DeviceCreateInfo::default().queue_create_infos(&queue_info),
            None,
        )
    }
    .expect("vkCreateDevice");
    let queue = unsafe { device.get_device_queue(family, 0) };

    const SIZE: u64 = 64 << 10;
    let buffer = unsafe {
        device.create_buffer(
            &vk::BufferCreateInfo::default()
                .size(SIZE)
                .usage(vk::BufferUsageFlags::TRANSFER_DST),
            None,
        )
    }
    .expect("vkCreateBuffer");
    let requirements = unsafe { device.get_buffer_memory_requirements(buffer) };
    let memory_types = unsafe { instance.get_physical_device_memory_properties(first) };
    let visible = vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT;
    let kind = (0..memory_types.memory_type_count)
        .find(|&i| {
            requirements.memory_type_bits & 1 << i != 0
                && memory_types.memory_types[i as usize]
                    .property_flags
                    .contains(visible)
        })
        .expect("no host-visible memory");
    let memory = unsafe {
        device.allocate_memory(
            &vk::MemoryAllocateInfo::default()
                .allocation_size(SIZE)
                .memory_type_index(kind),
            None,
        )
    }
    .expect("vkAllocateMemory");
    unsafe { device.bind_buffer_memory(buffer, memory, 0) }.expect("vkBindBufferMemory");
    let mapped = unsafe { device.map_memory(memory, 0, SIZE, vk::MemoryMapFlags::empty()) }
        .expect("vkMapMemory") as *const u32;

    let pool = unsafe {
        device.create_command_pool(
            &vk::CommandPoolCreateInfo::default().queue_family_index(family),
            None,
        )
    }
    .expect("vkCreateCommandPool");
    let command_buffer = unsafe {
        device.allocate_command_buffers(
            &vk::CommandBufferAllocateInfo::default()
                .command_pool(pool)
                .command_buffer_count(1),
        )
    }
    .expect("vkAllocateCommandBuffers")[0];
    unsafe {
        device
            .begin_command_buffer(
                command_buffer,
                &vk::CommandBufferBeginInfo::default().flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT),
            )
            .expect("vkBeginCommandBuffer");
        device.cmd_fill_buffer(command_buffer, buffer, 0, SIZE, FILL);
        device
            .end_command_buffer(command_buffer)
            .expect("vkEndCommandBuffer");
    }
    let fence = unsafe { device.create_fence(&vk::FenceCreateInfo::default(), None) }.expect("vkCreateFence");
    let buffers = [command_buffer];
    unsafe {
        device
            .queue_submit(
                queue,
                &[vk::SubmitInfo::default().command_buffers(&buffers)],
                fence,
            )
            .expect("vkQueueSubmit");
        device
            .wait_for_fences(&[fence], true, 5_000_000_000)
            .expect("vkWaitForFences");
    }
    let words = (SIZE / 4) as usize;
    let filled = (0..words)
        .filter(|&i| unsafe { mapped.add(i).read_volatile() } == FILL)
        .count();
    unsafe {
        device.destroy_fence(fence, None);
        device.destroy_command_pool(pool, None);
        device.unmap_memory(memory);
        device.destroy_buffer(buffer, None);
        device.free_memory(memory, None);
        device.destroy_device(None);
        instance.destroy_instance(None);
    }
    println!(
        "vulkan: through ash on Pinnacle's driver: {name}; a buffer filled, {} KiB read back as \"Pinn\"",
        filled * 4 >> 10
    );
    assert_eq!(filled, words, "the buffer read back wrong");
    true
}

async fn network() -> usize {
    let Ok(probe) = std::net::UdpSocket::bind("0.0.0.0:0") else {
        return 0;
    };
    let start = Instant::now();
    while probe.local_addr().unwrap().ip().is_unspecified() {
        assert!(
            start.elapsed() < Duration::from_secs(20),
            "the network got no address"
        );
        tokio::time::sleep(Duration::from_millis(50)).await;
    }
    let url = std::fs::read_to_string("/settings/store-url").unwrap();
    let host = url
        .trim()
        .trim_start_matches("http://")
        .trim_end_matches('/')
        .to_string();
    let mut stream = tokio::net::TcpStream::connect(&host).await.unwrap();
    stream
        .write_all(format!("GET /catalog HTTP/1.0\r\nHost: {host}\r\n\r\n").as_bytes())
        .await
        .unwrap();
    let mut response = Vec::new();
    tokio::time::timeout(Duration::from_secs(10), stream.read_to_end(&mut response))
        .await
        .expect("the catalog did not come in 10 s")
        .unwrap();
    let text = String::from_utf8_lossy(&response);
    assert!(text.starts_with("HTTP/1."), "not an HTTP answer: {text:.40}");
    assert!(text.contains(" 200 "), "the catalog was not served: {text:.40}");
    response.len()
}

fn hex(s: &str) -> Vec<u8> {
    (0..s.len())
        .step_by(2)
        .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
        .collect()
}

/// ring's port (`ports/ring-*`) against the standards' vectors: what rustls
/// and webpki ask of it. Returns how many were checked.
fn crypto() -> usize {
    use ring::{aead, agreement, digest, hkdf, hmac, rand, signature};

    // SHA-256 (FIPS 180-2) and SHA-384, of "abc".
    assert_eq!(
        digest::digest(&digest::SHA256, b"abc").as_ref(),
        hex("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
    );
    assert_eq!(
        digest::digest(&digest::SHA384, b"abc").as_ref(),
        hex(
            "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7"
        )
    );

    // HMAC-SHA-256, RFC 4231 test case 2.
    let key = hmac::Key::new(hmac::HMAC_SHA256, b"Jefe");
    assert_eq!(
        hmac::sign(&key, b"what do ya want for nothing?").as_ref(),
        hex("5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843")
    );

    // HKDF-SHA-256, RFC 5869 test case 1.
    let salt = hkdf::Salt::new(hkdf::HKDF_SHA256, &hex("000102030405060708090a0b0c"));
    let prk = salt.extract(&[0x0b; 22]);
    struct Len(usize);
    impl hkdf::KeyType for Len {
        fn len(&self) -> usize {
            self.0
        }
    }
    let info = hex("f0f1f2f3f4f5f6f7f8f9");
    let info = [info.as_slice()];
    let mut okm = [0u8; 42];
    prk.expand(&info, Len(42)).unwrap().fill(&mut okm).unwrap();
    assert_eq!(
        okm.as_slice(),
        hex("3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865")
    );

    // ChaCha20-Poly1305, RFC 8439 section 2.8.2, sealed and opened again.
    let key = aead::LessSafeKey::new(
        aead::UnboundKey::new(&aead::CHACHA20_POLY1305, &(0x80..=0x9fu8).collect::<Vec<_>>()).unwrap(),
    );
    let nonce = || aead::Nonce::try_assume_unique_for_key(&hex("070000004041424344454647")).unwrap();
    let aad = hex("50515253c0c1c2c3c4c5c6c7");
    let plain = b"Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it.";
    let mut data = plain.to_vec();
    let tag = key
        .seal_in_place_separate_tag(nonce(), aead::Aad::from(&aad), &mut data)
        .unwrap();
    assert_eq!(tag.as_ref(), hex("1ae10b594f09e26a7e902ecbd0600691"));
    data.extend_from_slice(tag.as_ref());
    assert_eq!(
        key.open_in_place(nonce(), aead::Aad::from(&aad), &mut data)
            .unwrap(),
        plain
    );
    data[0] ^= 1;
    assert!(
        key.open_in_place(nonce(), aead::Aad::from(&aad), &mut data)
            .is_err(),
        "a forgery was opened"
    );

    // AES-128-GCM, the GCM spec's test case 2.
    let key = aead::LessSafeKey::new(aead::UnboundKey::new(&aead::AES_128_GCM, &[0; 16]).unwrap());
    let mut data = vec![0u8; 16];
    let tag = key
        .seal_in_place_separate_tag(
            aead::Nonce::assume_unique_for_key([0; 12]),
            aead::Aad::empty(),
            &mut data,
        )
        .unwrap();
    assert_eq!(data, hex("0388dace60b6a392f328c2b971b2fe78"));
    assert_eq!(tag.as_ref(), hex("ab6e47d42cec13bdf53a67b21257bddf"));

    // X25519: two parties agree.
    let rng = rand::SystemRandom::new();
    let a = agreement::EphemeralPrivateKey::generate(&agreement::X25519, &rng).unwrap();
    let b = agreement::EphemeralPrivateKey::generate(&agreement::X25519, &rng).unwrap();
    let (a_pub, b_pub) = (a.compute_public_key().unwrap(), b.compute_public_key().unwrap());
    let ab = agreement::agree_ephemeral(
        a,
        &agreement::UnparsedPublicKey::new(&agreement::X25519, b_pub.as_ref()),
        |s| s.to_vec(),
    )
    .unwrap();
    let ba = agreement::agree_ephemeral(
        b,
        &agreement::UnparsedPublicKey::new(&agreement::X25519, a_pub.as_ref()),
        |s| s.to_vec(),
    )
    .unwrap();
    assert_eq!(ab, ba);

    // Ed25519, RFC 8032 test 1: the empty message.
    let public = hex("d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a");
    let sig = hex(
        "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b",
    );
    let key = signature::UnparsedPublicKey::new(&signature::ED25519, &public);
    assert!(key.verify(b"", &sig).is_ok());
    assert!(key.verify(b"x", &sig).is_err(), "a wrong message verified");

    9
}