repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/device/src/bin/dev.rs
device/src/bin/dev.rs
//! Development device binary #![no_std] #![no_main] extern crate alloc; use core::cell::RefCell; use esp_hal::entry; use esp_storage::FlashStorage; use frostsnap_device::{esp32_run, peripherals::DevicePeripherals, resources::Resources}; #[entry] fn main() -> ! { // Initialize heap esp_alloc::heap_allocator!(256 * 1024); // Initialize ESP32 hardware let peripherals = esp_hal::init({ let mut config = esp_hal::Config::default(); config.cpu_clock = esp_hal::clock::CpuClock::max(); config }); // Initialize flash storage (must stay alive for partition references) let flash = RefCell::new(FlashStorage::new()); // Initialize all device peripherals with initial RNG let device = DevicePeripherals::init(peripherals); // Check if the device needs provisioning if device.needs_factory_provisioning() { // Run dev provisioning - this will reset the device frostsnap_device::factory::run_dev_provisioning(device); } else { // Device is already provisioned - proceed with normal boot let mut resources = Resources::init_dev(device, &flash); // Run main event loop esp32_run::run(&mut resources); } } #[panic_handler] fn panic(info: &core::panic::PanicInfo) -> ! { frostsnap_device::panic::handle_panic(info) }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/device/src/bin/widget_dev.rs
device/src/bin/widget_dev.rs
#![no_std] #![no_main] extern crate alloc; use esp_hal::{entry, timer::Timer as _}; use frostsnap_device::{peripherals::DevicePeripherals, touch_handler, DISPLAY_REFRESH_MS}; use frostsnap_widgets::debug::{EnabledDebug, OverlayDebug}; // Widget demo selection const DEMO: &str = "bip39_backup"; #[entry] fn main() -> ! { esp_alloc::heap_allocator!(256 * 1024); // Initialize ESP32 hardware let peripherals = esp_hal::init({ let mut config = esp_hal::Config::default(); config.cpu_clock = esp_hal::clock::CpuClock::max(); config }); // Initialize all device peripherals let device = DevicePeripherals::init(peripherals); // Check if the device needs provisioning if device.needs_factory_provisioning() { // Run dev provisioning - this will reset the device frostsnap_device::factory::run_dev_provisioning(device); } else { // Device is already provisioned - proceed with widget testing // Extract the components we need from DevicePeripherals let DevicePeripherals { display, mut touch_receiver, timer, .. } = *device; let mut display = frostsnap_widgets::SuperDrawTarget::new( display, frostsnap_widgets::palette::PALETTE.background, ); // Macro to run a widget with all the hardware peripherals macro_rules! run_widget { ($widget:expr) => {{ // Create the widget with debug overlay let debug_config = EnabledDebug { logs: cfg!(feature = "debug_log"), memory: cfg!(feature = "debug_mem"), fps: cfg!(feature = "debug_fps"), }; let mut widget_with_debug = OverlayDebug::new($widget, debug_config); // Set constraints widget_with_debug.set_constraints(display.bounding_box().size); let mut last_touch: Option<Point> = None; let mut current_widget_index = 0usize; // Track last redraw time let mut last_redraw_time = timer.now(); // Clear the screen with background color let _ = display.clear(PALETTE.background); // Main loop loop { let now = timer.now(); let now_ms = frostsnap_widgets::Instant::from_millis( now.duration_since_epoch().to_millis(), ); // Process all pending touch events touch_handler::process_all_touch_events( &mut touch_receiver, &mut widget_with_debug, &mut last_touch, &mut current_widget_index, now_ms, ); // Only redraw if enough time has passed since last redraw let elapsed_ms = (now - last_redraw_time).to_millis(); if elapsed_ms >= DISPLAY_REFRESH_MS { // Update last redraw time last_redraw_time = now; // Draw the UI stack (includes debug stats overlay) let _ = widget_with_debug.draw(&mut display, now_ms); } } }}; } // Use the demo_widget! macro from frostsnap_widgets frostsnap_widgets::demo_widget!(DEMO, run_widget); } } #[panic_handler] fn panic(info: &core::panic::PanicInfo) -> ! { frostsnap_device::panic::handle_panic(info) }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/device/src/bin/frontier.rs
device/src/bin/frontier.rs
//! Production device binary #![no_std] #![no_main] extern crate alloc; use core::cell::RefCell; use esp_hal::entry; use esp_storage::FlashStorage; use frostsnap_device::{esp32_run, peripherals::DevicePeripherals, resources::Resources}; #[entry] fn main() -> ! { // Initialize heap esp_alloc::heap_allocator!(256 * 1024); // Initialize hardware let peripherals = esp_hal::init({ let mut config = esp_hal::Config::default(); config.cpu_clock = esp_hal::clock::CpuClock::max(); config }); // Initialize flash storage (must stay alive for partition references) let flash = RefCell::new(FlashStorage::new()); // Initialize all device peripherals with initial RNG let device = DevicePeripherals::init(peripherals); // Check if the device needs factory provisioning if device.needs_factory_provisioning() { // Run factory provisioning - this will reset the device let config = frostsnap_device::factory::init::ProvisioningConfig { read_protect: true, // Production devices should have read protection }; frostsnap_device::factory::run_factory_provisioning(device, config); } else { // Device is already provisioned - proceed with normal boot let mut resources = Resources::init_production(device, &flash); // Run main event loop esp32_run::run(&mut resources); } } #[panic_handler] fn panic(info: &core::panic::PanicInfo) -> ! { frostsnap_device::panic::handle_panic(info) }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/device/src/flash/genuine_certificate.rs
device/src/flash/genuine_certificate.rs
use alloc::vec::Vec; use esp_storage::FlashStorage; use frostsnap_comms::genuine_certificate::Certificate; use frostsnap_core::Versioned; use frostsnap_embedded::FlashPartition; use frostsnap_embedded::ABWRITE_BINCODE_CONFIG; #[derive(Debug, Clone, bincode::Encode, bincode::Decode, PartialEq)] pub struct VersionedFactoryData { inner: Versioned<FactoryData>, } #[derive(Debug, Clone, PartialEq, bincode::Encode, bincode::Decode)] pub struct FactoryData { pub ds_encrypted_params: Vec<u8>, pub certificate: Certificate, } impl VersionedFactoryData { pub fn read<'a>( partition: FlashPartition<'a, FlashStorage>, ) -> Result<Self, bincode::error::DecodeError> { bincode::decode_from_reader::<VersionedFactoryData, _, _>( partition.bincode_reader(), ABWRITE_BINCODE_CONFIG, ) } pub fn init(encrypted_params: Vec<u8>, certificate: Certificate) -> Self { Self { inner: Versioned::V0(FactoryData { ds_encrypted_params: encrypted_params, certificate, }), } } pub fn into_factory_data(self) -> FactoryData { match self.inner { Versioned::V0(factory_data) => factory_data, } } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/device/src/flash/log.rs
device/src/flash/log.rs
use alloc::{boxed::Box, string::String}; use embedded_storage::nor_flash::NorFlash; use frostsnap_core::device::{self, SaveShareMutation}; use frostsnap_embedded::{AbSlot, FlashPartition, NorFlashLog}; #[derive(Debug, Clone, bincode::Encode, bincode::Decode)] pub enum Mutation { Core(device::Mutation), Name(String), } #[derive(Debug, Clone, bincode::Encode, bincode::Decode)] pub enum ShareSlot { SecretShare(Box<SaveShareMutation>), SavedBackup(device::restoration::SavedBackup), SavedBackup2(device::restoration::SavedBackup2), } impl ShareSlot { pub fn into_mutations(self) -> impl IntoIterator<Item = device::Mutation> { core::iter::once(match self { ShareSlot::SecretShare(save_share_mutation) => { device::Mutation::Keygen(device::keys::KeyMutation::SaveShare(save_share_mutation)) } ShareSlot::SavedBackup(legacy_saved_backup) => device::Mutation::Restoration( device::restoration::RestorationMutation::Save(legacy_saved_backup), ), ShareSlot::SavedBackup2(saved_backup) => device::Mutation::Restoration( device::restoration::RestorationMutation::Save2(saved_backup), ), }) } } /// Mutation log saves the device's core mutations but treats secret share saving mutations /// differently to enforce the one secret share per device rule. pub struct MutationLog<'a, S> { log: NorFlashLog<'a, S>, share_slot: AbSlot<'a, S>, } impl<'a, S: NorFlash> MutationLog<'a, S> { pub fn new( mut share_flash: FlashPartition<'a, S>, mut log_flash: FlashPartition<'a, S>, ) -> Self { log_flash.tag = "event-log"; share_flash.tag = "share"; let share_slot = AbSlot::new(share_flash); MutationLog { log: NorFlashLog::new(log_flash), share_slot, } } pub fn push(&mut self, value: Mutation) -> Result<(), bincode::error::EncodeError> { match value { // For these mutations (which contain secret shares of some type) we don't write them to // the log, we write them to a special part of flash. We only store one secret share at a // time. Mutation::Core(device::Mutation::Keygen(device::keys::KeyMutation::SaveShare( save_share_mutation, ))) => { self.share_slot .write(&ShareSlot::SecretShare(save_share_mutation)); } Mutation::Core(device::Mutation::Restoration( device::restoration::RestorationMutation::Save(legacy_saved_backup), )) => { // Convert legacy SavedBackup to SavedBackup2 before storing. // This code should never be reached. This code should never be // reached. let saved_backup: device::restoration::SavedBackup2 = legacy_saved_backup.into(); self.share_slot .write(&ShareSlot::SavedBackup2(saved_backup)); } Mutation::Core(device::Mutation::Restoration( device::restoration::RestorationMutation::Save2(saved_backup), )) => { self.share_slot .write(&ShareSlot::SavedBackup2(saved_backup)); } value => { self.log.push(value)?; } } Ok(()) } pub fn seek_iter( &mut self, ) -> impl Iterator<Item = Result<Mutation, bincode::error::DecodeError>> + use<'_, 'a, S> { self.log.seek_iter::<Mutation>().chain( self.share_slot .read::<ShareSlot>() .into_iter() .flat_map(|share_slot| share_slot.into_mutations()) .map(Mutation::Core) .map(Ok), ) } pub fn append( &mut self, iter: impl IntoIterator<Item = Mutation>, ) -> Result<(), bincode::error::EncodeError> { for item in iter { self.push(item)?; } Ok(()) } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/device/src/flash/header.rs
device/src/flash/header.rs
use embedded_storage::nor_flash::NorFlash; use frostsnap_comms::{HasMagicBytes, MagicBytes, MAGIC_BYTES_LEN}; use frostsnap_core::schnorr_fun::fun::{KeyPair, Scalar}; use frostsnap_embedded::{AbSlot, FlashPartition}; use crate::efuse::EfuseHmacKey; #[derive(Debug, Clone, bincode::Encode, bincode::Decode)] pub struct HeaderMagicBytes; impl HasMagicBytes for HeaderMagicBytes { const MAGIC_BYTES: [u8; MAGIC_BYTES_LEN] = *b"fshead0"; const VERSION_SIGNAL: frostsnap_comms::MagicBytesVersion = 0; } #[derive(Debug, Clone, bincode::Encode, bincode::Decode)] pub struct Header { pub magic_bytes: MagicBytes<HeaderMagicBytes>, pub body: HeaderBody, } impl Header { pub fn device_keypair(&self, hmac: &mut EfuseHmacKey) -> KeyPair { KeyPair::new(match self.body { HeaderBody::V0 { device_id_seed } => { let secret_scalar_bytes = hmac .hash("frostsnap-device-keypair", &device_id_seed) .unwrap(); Scalar::from_slice_mod_order(&secret_scalar_bytes) .expect("just got 32 bytes from fixed entropy hash") .non_zero() .expect("built using random bytes") } }) } } #[derive(Debug, Clone, bincode::Encode, bincode::Decode)] pub enum HeaderBody { V0 { device_id_seed: [u8; 32] }, } impl Header { pub fn new(device_id_seed: [u8; 32]) -> Self { Header { magic_bytes: Default::default(), body: HeaderBody::V0 { device_id_seed }, } } pub fn init(rng: &mut impl rand_core::RngCore) -> Self { let mut device_id_seed = [0u8; 32]; rng.fill_bytes(&mut device_id_seed); Header::new(device_id_seed) } } pub struct FlashHeader<'a, S> { ab: AbSlot<'a, S>, } impl<'a, S: NorFlash> FlashHeader<'a, S> { pub fn new(mut flash: FlashPartition<'a, S>) -> Self { flash.tag = "header"; let ab = AbSlot::new(flash); Self { ab } } pub fn read_header(&self) -> Option<Header> { self.ab.read() } pub fn write_header(&self, header: &Header) { self.ab.write(header) } pub fn init(&self, rng: &mut impl rand_core::RngCore) -> Header { let header = Header::init(rng); self.write_header(&header); header } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/device/src/factory/mod.rs
device/src/factory/mod.rs
pub mod init; pub use init::*;
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/device/src/factory/init.rs
device/src/factory/init.rs
use crate::flash::VersionedFactoryData; use crate::peripherals::DevicePeripherals; use alloc::boxed::Box; use core::cell::RefCell; use embedded_graphics::{ mono_font::{ascii::*, MonoTextStyle}, pixelcolor::Rgb565, prelude::*, }; use esp_storage::FlashStorage; use frostsnap_comms::{factory::*, ReceiveSerial}; use frostsnap_embedded::ABWRITE_BINCODE_CONFIG; use rand_core::{RngCore, SeedableRng}; use crate::{efuse::EfuseKeyWriter, io::SerialInterface}; /// Configuration for device provisioning pub struct ProvisioningConfig { /// Whether to read-protect the efuse keys pub read_protect: bool, } macro_rules! text_display { ($display:expr, $text:expr) => { let _ = $display.clear(Rgb565::BLACK); let character_style = MonoTextStyle::new(&FONT_10X20, Rgb565::WHITE); let text_style = embedded_graphics::text::TextStyleBuilder::new() .alignment(embedded_graphics::text::Alignment::Center) .build(); let display_width = $display.size().width as i32; let _ = embedded_graphics::text::Text::with_text_style( $text, Point::new(display_width / 2, 30), character_style, text_style, ) .draw($display); }; } macro_rules! read_message { ($upstream:expr, FactorySend::$var:ident) => { loop { match $upstream.receive() { Some(Ok(ReceiveSerial::MagicBytes(_))) => { /* do nothing */ } Some(Ok(message)) => { if let ReceiveSerial::Message(FactorySend::$var(inner)) = message { break inner; } else { panic!("expecting {} got {:?}", stringify!($var), message); } } Some(Err(e)) => { panic!("error trying to read {}: {e}", stringify!($var)); } None => { /* try again */ } } } }; } /// Run dev device provisioning - burns efuses locally without factory communication /// This function never returns - it resets the device after provisioning pub fn run_dev_provisioning(peripherals: Box<DevicePeripherals<'_>>) -> ! { // Destructure what we need let DevicePeripherals { mut display, efuse, mut initial_rng, timer, .. } = *peripherals; use embedded_graphics::{ mono_font::{ascii::FONT_10X20, MonoTextStyle}, pixelcolor::Rgb565, prelude::*, }; use esp_hal::{time::Duration, timer::Timer}; // Warning countdown before burning efuses const COUNTDOWN_SECONDS: u32 = 30; for seconds_remaining in (1..=COUNTDOWN_SECONDS).rev() { let text = alloc::format!( "WARNING\n\nDev-Device Initialization\nAbout to burn eFuses!\n\n{} seconds remaining...\n\nUnplug now to cancel!", seconds_remaining ); text_display!(&mut display, &text); // Wait 1 second let start = timer.now(); while timer.now().checked_duration_since(start).unwrap() < Duration::millis(1000) {} } // Show provisioning message text_display!(&mut display, "Dev mode: generating keys locally"); // Generate share encryption key let mut share_encryption_key = [0u8; 32]; initial_rng.fill_bytes(&mut share_encryption_key); // Generate fixed entropy key let mut fixed_entropy_key = [0u8; 32]; initial_rng.fill_bytes(&mut fixed_entropy_key); // Initialize efuses WITHOUT read protection (for dev devices) // No DS key needed for dev devices EfuseKeyWriter::new(&efuse) .read_protect(false) .add_encryption_key(share_encryption_key) .add_entropy_key(fixed_entropy_key) .write_efuses() .expect("Failed to initialize dev HMAC keys"); // Show completion text_display!(&mut display, "Dev device initialized!\n\nRestarting..."); // Reset the device esp_hal::reset::software_reset(); unreachable!() } /// Run factory provisioning for a device that needs provisioning /// This function never returns - it resets the device after provisioning pub fn run_factory_provisioning( peripherals: Box<DevicePeripherals<'_>>, config: ProvisioningConfig, ) -> ! { // Destructure what we need let DevicePeripherals { mut display, mut touch_receiver, efuse, jtag, timer, .. } = *peripherals; // Run screen test display = crate::screen_test::run(display, &mut touch_receiver, timer); // Initialize serial interface for factory communication let mut upstream = SerialInterface::<_, FactoryUpstream>::new_jtag(jtag, timer); // Initialize flash and partitions let flash = RefCell::new(FlashStorage::new()); let mut partitions = crate::partitions::Partitions::load(&flash); text_display!( &mut display, "Device not configured, waiting for factory magic bytes!" ); // Wait for factory magic bytes loop { if upstream.find_and_remove_magic_bytes() { upstream.write_magic_bytes().expect("can write magic bytes"); text_display!(&mut display, "Got factory magic bytes"); break; } } // Receive factory entropy let factory_entropy = read_message!(upstream, FactorySend::InitEntropy); text_display!(&mut display, "Got entropy"); upstream.send(DeviceFactorySend::InitEntropyOk).unwrap(); // Receive DS key let Esp32DsKey { encrypted_params, ds_hmac_key, } = read_message!(upstream, FactorySend::SetEsp32DsKey); upstream.send(DeviceFactorySend::ReceivedDsKey).unwrap(); text_display!(&mut display, "Received DS key"); // Receive certificate let certificate = read_message!(upstream, FactorySend::SetGenuineCertificate); // Write factory data to flash let factory_data = VersionedFactoryData::init(encrypted_params.clone(), certificate.clone()); partitions .factory_cert .erase_and_write_this::<{ frostsnap_embedded::WRITE_BUF_SIZE }>(&factory_data) .unwrap(); // Verify it was written successfully let read_factory_data = bincode::decode_from_reader::<VersionedFactoryData, _, _>( partitions.factory_cert.bincode_reader(), ABWRITE_BINCODE_CONFIG, ) .expect("we should have been able to read the factory data back out!"); assert_eq!(factory_data, read_factory_data); // Generate share encryption key let mut factory_rng = rand_chacha::ChaCha20Rng::from_seed(factory_entropy); let mut share_encryption_key = [0u8; 32]; factory_rng.fill_bytes(&mut share_encryption_key); // Generate user key just to occupy Key5 let mut user_key = [0u8; 32]; factory_rng.fill_bytes(&mut user_key); // Burn EFUSES with configurable read protection EfuseKeyWriter::new(&efuse) .read_protect(config.read_protect) .add_encryption_key(share_encryption_key) .add_entropy_key(factory_entropy) .add_ds_key(ds_hmac_key) .add_key( esp_hal::hmac::KeyId::Key5, user_key, crate::efuse::KeyPurpose::HmacUpstream, ) .write_efuses() .unwrap(); text_display!( &mut display, "Saved encrypted params, certificate and burnt efuse!" ); // Reset the device esp_hal::reset::software_reset(); unreachable!() }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/src/map_ext.rs
frostsnap_core/src/map_ext.rs
use alloc::collections::BTreeMap; #[allow(unused)] /// Extension trait for BTreeMap providing a take_entry method pub trait BTreeMapExt<K, V> { /// Removes the entry for the given key and returns the value (if it existed) /// along with a vacant entry for reinsertion fn take_entry(&mut self, key: K) -> (Option<V>, btree_map::VacantEntry<'_, K, V>); } impl<K: Ord, V> BTreeMapExt<K, V> for BTreeMap<K, V> { fn take_entry(&mut self, key: K) -> (Option<V>, btree_map::VacantEntry<'_, K, V>) { let value = self.remove(&key); let entry = match self.entry(key) { btree_map::Entry::Vacant(v) => v, btree_map::Entry::Occupied(_) => unreachable!("we just removed this key"), }; (value, entry) } } pub use alloc::collections::btree_map; #[cfg(feature = "std")] pub use std::collections::hash_map; #[cfg(feature = "std")] use std::collections::HashMap; /// Extension trait for HashMap providing a take_entry method #[cfg(feature = "std")] pub trait HashMapExt<K, V> { /// Removes the entry for the given key and returns the value (if it existed) /// along with a vacant entry for reinsertion fn take_entry(&mut self, key: K) -> (Option<V>, hash_map::VacantEntry<'_, K, V>); } #[cfg(feature = "std")] impl<K: Eq + std::hash::Hash, V> HashMapExt<K, V> for HashMap<K, V> { fn take_entry(&mut self, key: K) -> (Option<V>, hash_map::VacantEntry<'_, K, V>) { let value = self.remove(&key); let entry = match self.entry(key) { hash_map::Entry::Vacant(v) => v, hash_map::Entry::Occupied(_) => unreachable!("we just removed this key"), }; (value, entry) } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/src/coord_nonces.rs
frostsnap_core/src/coord_nonces.rs
use crate::{nonce_stream::*, DeviceId}; use alloc::collections::*; #[derive(Default, Clone, Debug, PartialEq)] pub struct NonceCache { by_device: BTreeMap<DeviceId, BTreeMap<NonceStreamId, NonceStreamSegment>>, } impl NonceCache { pub fn extend_segment( &mut self, device_id: DeviceId, new_segment: NonceStreamSegment, ) -> Result<bool, NonceSegmentIncompatible> { let nonce_segments = self.by_device.entry(device_id).or_default(); let segment = nonce_segments .entry(new_segment.stream_id) .or_insert(NonceStreamSegment { stream_id: new_segment.stream_id, nonces: Default::default(), index: 0, }); segment.extend(new_segment) } pub fn check_can_extend( &self, device_id: DeviceId, new_segment: &NonceStreamSegment, ) -> Result<(), NonceSegmentIncompatible> { match self.by_device.get(&device_id) { Some(device_segments) => match device_segments.get(&new_segment.stream_id) { Some(segment) => segment.check_can_extend(new_segment), None => Ok(()), }, None => Ok(()), } } pub fn new_signing_session( &self, devices: &BTreeSet<DeviceId>, n_nonces: usize, used_streams: &BTreeSet<NonceStreamId>, ) -> Result<BTreeMap<DeviceId, SigningReqSubSegment>, NotEnoughNonces> { let mut nonces_chosen: BTreeMap<DeviceId, SigningReqSubSegment> = BTreeMap::default(); for &device in devices { let by_device = self.by_device.get(&device).into_iter().flatten(); let mut nonces_available = 0; for (stream_id, stream_segment) in by_device { if used_streams.contains(stream_id) { continue; } if stream_segment.index_after_last().is_none() { continue; } if let Some(sub_segment) = stream_segment.signing_req_sub_segment(n_nonces) { nonces_chosen.insert(device, sub_segment); break; } else { nonces_available = nonces_available.max(stream_segment.nonces.len()); } } if !nonces_chosen.contains_key(&device) { return Err(NotEnoughNonces { device_id: device, available: nonces_available, need: n_nonces, }); } } Ok(nonces_chosen) } /// Returns whether a change happened or not pub fn consume( &mut self, device_id: DeviceId, stream_id: NonceStreamId, up_to_but_not_including: u32, ) -> bool { if let Some(device_streams) = self.by_device.get_mut(&device_id) { if let Some(local_segment) = device_streams.get_mut(&stream_id) { assert!( local_segment.index <= up_to_but_not_including, "tried to consume no nonces since counter {} was greater than consumption point {}", local_segment.index, up_to_but_not_including ); return local_segment.delete_up_to(up_to_but_not_including); } } false } pub fn nonces_available( &self, device_id: DeviceId, used_streams: &BTreeSet<NonceStreamId>, ) -> BTreeMap<NonceStreamId, u32> { let mut available = BTreeMap::default(); if let Some(streams) = self.by_device.get(&device_id) { for (stream_id, stream) in streams { if used_streams.contains(stream_id) { continue; } if !stream.nonces.is_empty() { available.insert(*stream_id, stream.nonces.len() as u32); } } } available } pub fn generate_nonce_stream_opening_requests( &self, device_id: DeviceId, min_streams: usize, rng: &mut impl rand_core::RngCore, ) -> impl IntoIterator<Item = CoordNonceStreamState> { let mut stream_ids = vec![]; let streams = self .by_device .get(&device_id) .cloned() .unwrap_or_default() .into_iter(); let new_streams_needed = min_streams.saturating_sub(streams.len()); for _ in 0..new_streams_needed { stream_ids.push(CoordNonceStreamState { stream_id: NonceStreamId::random(rng), index: 0, remaining: 0, }); } for (stream_id, stream) in streams { stream_ids.push(CoordNonceStreamState { stream_id, index: stream.index, remaining: stream.nonces.len().try_into().unwrap(), }) } stream_ids } } #[derive(Debug, Clone, Copy, PartialEq)] pub struct NotEnoughNonces { device_id: DeviceId, available: usize, need: usize, } impl core::fmt::Display for NotEnoughNonces { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { let NotEnoughNonces { device_id, available, need, } = self; write!(f, "coordinator doesn't have enough nonces for {device_id}. It only has {available} but needs {need}") } } #[cfg(feature = "std")] impl std::error::Error for NotEnoughNonces {}
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/src/lib.rs
frostsnap_core/src/lib.rs
#![no_std] #[cfg(feature = "std")] #[macro_use] extern crate std; #[cfg(feature = "coordinator")] pub mod coord_nonces; pub mod device_nonces; mod macros; mod map_ext; mod master_appkey; pub mod message; pub mod nonce_stream; pub mod nostr; pub mod tweak; use core::ops::RangeBounds; use schnorr_fun::{ frost::{chilldkg::certpedpop, ShareImage, ShareIndex, SharedKey}, fun::{hash::HashAdd, prelude::*}, }; pub use sha2; mod sign_task; use sha2::{digest::FixedOutput, Digest}; pub use sign_task::*; pub use bincode; pub use master_appkey::*; pub use serde; #[cfg(feature = "coordinator")] pub mod coordinator; pub mod device; pub use schnorr_fun; pub mod bitcoin_transaction; mod symmetric_encryption; pub use symmetric_encryption::*; use tweak::Xpub; #[cfg(feature = "rusqlite")] mod sqlite; #[macro_use] extern crate alloc; use alloc::{string::String, string::ToString, vec::Vec}; // rexport hex module so serialization impl macros work outside this crate pub use schnorr_fun::fun::hex; #[derive(Clone, Copy, PartialEq, Hash, Eq, Ord, PartialOrd)] pub struct DeviceId(pub [u8; 33]); impl Default for DeviceId { fn default() -> Self { Self([0u8; 33]) } } impl_display_debug_serialize! { fn to_bytes(device_id: &DeviceId) -> [u8;33] { device_id.0 } } impl_fromstr_deserialize! { name => "device id", fn from_bytes(bytes: [u8;33]) -> DeviceId { DeviceId(bytes) } } impl DeviceId { pub fn new(point: Point) -> Self { Self(point.to_bytes()) } pub fn pubkey(&self) -> Point { // ⚠ if the device id is invalid we give it nullish public key. // Honest device ids will never suffer this problem let point = Point::from_bytes(self.0); debug_assert!(point.is_some()); point.unwrap_or(schnorr_fun::fun::G.normalize()) } pub fn as_bytes(&self) -> &[u8; 33] { &self.0 } } #[derive(Debug, Clone, PartialEq, Eq)] pub enum Error { /// The device was not in a state where it could receive a message of that kind MessageKind { state: &'static str, kind: &'static str, }, /// The content of the message was invalid with respect to the state. InvalidMessage { kind: &'static str, reason: String }, } impl Error { #[cfg(feature = "coordinator")] pub fn coordinator_invalid_message(kind: &'static str, reason: impl ToString) -> Self { Self::InvalidMessage { kind, reason: reason.to_string(), } } pub fn signer_invalid_message(message: &impl Kind, reason: impl ToString) -> Self { Self::InvalidMessage { kind: message.kind(), reason: reason.to_string(), } } pub fn signer_message_error(message: &impl Kind, e: impl ToString) -> Self { Self::InvalidMessage { kind: message.kind(), reason: e.to_string(), } } } impl core::fmt::Display for Error { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { Error::MessageKind { state, kind } => write!( f, "Unexpected message of kind {kind} for this state {state}", ), Error::InvalidMessage { kind, reason } => { write!(f, "Invalid message of kind {kind}: {reason}") } } } } impl Error { pub fn gist(&self) -> String { match self { Error::MessageKind { state, kind } => format!("mk!{kind} {state}"), Error::InvalidMessage { kind, reason } => format!("im!{kind}: {reason}"), } } } pub type MessageResult<T> = Result<T, Error>; #[derive(Debug, Clone)] pub enum DoKeyGenError { WrongState, } #[derive(Debug, Clone)] pub enum ActionError { StateInconsistent(String), } impl core::fmt::Display for ActionError { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { ActionError::StateInconsistent(error) => { write!(f, "state inconsistent: {error}") } } } } #[cfg(feature = "std")] impl std::error::Error for ActionError {} /// Output very basic debug info about a type pub trait Gist { fn gist(&self) -> String; } pub trait Kind { fn kind(&self) -> &'static str; } /// The hash of a threshold access structure for a particualr key #[derive(Clone, Copy, PartialEq, Ord, PartialOrd, Eq, Hash)] pub struct AccessStructureId(pub [u8; 32]); impl AccessStructureId { pub fn from_app_poly(app_poly: &[Point<Normal, Public, Zero>]) -> Self { Self( prefix_hash("ACCESS_STRUCTURE_ID") .add(app_poly) .finalize_fixed() .into(), ) } } impl_display_debug_serialize! { fn to_bytes(as_id: &AccessStructureId) -> [u8;32] { as_id.0 } } impl_fromstr_deserialize! { name => "frostsnap access structure id", fn from_bytes(bytes: [u8;32]) -> AccessStructureId { AccessStructureId(bytes) } } /// The hash of a root key #[derive(Clone, Copy, PartialEq, PartialOrd, Ord, Eq, Hash)] pub struct KeyId(pub [u8; 32]); impl KeyId { pub fn from_rootkey(rootkey: Point) -> Self { Self::from_master_appkey(MasterAppkey::derive_from_rootkey(rootkey)) } pub fn from_master_appkey(master_appkey: MasterAppkey) -> Self { Self( prefix_hash("KEY_ID") .add(master_appkey.0) .finalize_fixed() .into(), ) } } impl_display_debug_serialize! { fn to_bytes(value: &KeyId) -> [u8;32] { value.0 } } impl_fromstr_deserialize! { name => "frostsnap key id", fn from_bytes(bytes: [u8;32]) -> KeyId { KeyId(bytes) } } fn prefix_hash(prefix: &'static str) -> sha2::Sha256 { let mut hash = sha2::Sha256::default(); hash.update((prefix.len() as u8).to_be_bytes()); hash.update(prefix); hash } #[derive(Clone, Copy, PartialEq)] /// This is the data provided by the coordinator that helps the device decrypt their share. /// Devices can't decrypt their shares on their own. pub struct CoordShareDecryptionContrib([u8; 32]); impl CoordShareDecryptionContrib { /// Master shares are not protected by much. Devices holding master shares are designed to have /// their backups stored right next them anyway. We nevertheless make the coordinator provide a /// hash of the root polynomial. The main benefit is to force the device to be talking to a /// coordinator that knows about the entire access structure (knows the polynomial). This /// prevents us from inadvertently introducing "features" that can be engaged without actual /// knowledge of the main polynomial. pub fn for_master_share( device_id: DeviceId, share_index: ShareIndex, shared_key: &SharedKey<Normal, impl ZeroChoice>, ) -> Self { Self( prefix_hash("SHARE_DECRYPTION") .add(device_id.0) .add(share_index) .add(shared_key.point_polynomial()) .finalize_fixed() .into(), ) } } impl_display_debug_serialize! { fn to_bytes(value: &CoordShareDecryptionContrib) -> [u8;32] { value.0 } } impl_fromstr_deserialize! { name => "share decryption key", fn from_bytes(bytes: [u8;32]) -> CoordShareDecryptionContrib { CoordShareDecryptionContrib(bytes) } } #[derive(Clone, Copy, PartialEq, Hash, Eq, Ord, PartialOrd)] pub struct SessionHash(pub [u8; 32]); impl SessionHash { pub fn from_certified_keygen( certified_keygen: &certpedpop::CertifiedKeygen<certpedpop::vrf_cert::CertVrfProof>, ) -> Self { let hash = sha2::Sha256::default().ds("frost-dkg-security-check"); let security_check = certified_keygen.vrf_security_check(hash); Self(security_check) } } impl_display_debug_serialize! { fn to_bytes(value: &SessionHash) -> [u8;32] { value.0 } } impl_fromstr_deserialize! { name => "session hash", fn from_bytes(bytes: [u8;32]) -> SessionHash { SessionHash(bytes) } } // Uniquely identifies an access structure for a particular `key_id`. #[derive( Debug, Clone, Copy, bincode::Encode, bincode::Decode, PartialEq, Eq, Hash, Ord, PartialOrd, )] pub struct AccessStructureRef { pub key_id: KeyId, pub access_structure_id: AccessStructureId, } impl AccessStructureRef { pub fn from_root_shared_key(root_shared_key: &SharedKey<Normal>) -> Self { let app_shared_key = Xpub::from_rootkey(root_shared_key.clone()).rootkey_to_master_appkey(); let master_appkey = MasterAppkey::from_xpub_unchecked(&app_shared_key); let access_structure_id = AccessStructureId::from_app_poly(app_shared_key.into_key().point_polynomial()); AccessStructureRef { key_id: master_appkey.key_id(), access_structure_id, } } pub fn range_for_key(key_id: KeyId) -> impl RangeBounds<AccessStructureRef> { AccessStructureRef { key_id, access_structure_id: AccessStructureId([0x00u8; 32]), }..=AccessStructureRef { key_id, access_structure_id: AccessStructureId([0xffu8; 32]), } } } #[derive(Clone, Copy, PartialEq, PartialOrd, Ord, Eq, Hash)] pub struct SignSessionId(pub [u8; Self::LEN]); impl SignSessionId { pub const LEN: usize = 32; } impl_display_debug_serialize! { fn to_bytes(value: &SignSessionId) -> [u8;32] { value.0 } } impl_fromstr_deserialize! { name => "sign session id", fn from_bytes(bytes: [u8;32]) -> SignSessionId { SignSessionId(bytes) } } #[derive(Clone, Debug, bincode::Encode, bincode::Decode, PartialEq)] pub enum Versioned<T> { V0(T), } impl<T: Clone> Versioned<&T> { pub fn cloned(&self) -> Versioned<T> { match self { Versioned::V0(v) => Versioned::V0((*v).clone()), } } } /// short randomly sampled id for a coordinator to refer to a key generation session before the key /// generation is complete. #[derive(Clone, Copy, PartialEq, PartialOrd, Ord, Eq, Hash, Default)] pub struct KeygenId(pub [u8; 16]); impl_display_debug_serialize! { fn to_bytes(keygen_id: &KeygenId) -> [u8;16] { keygen_id.0 } } impl_fromstr_deserialize! { name => "key generation id", fn from_bytes(bytes: [u8;16]) -> KeygenId { KeygenId(bytes) } } /// short randomly sampled id for a coordinator to refer to a key generation session before the key /// generation is complete. #[derive(Clone, Copy, PartialEq, PartialOrd, Ord, Eq, Hash, Default)] pub struct RestorationId(pub [u8; 16]); impl RestorationId { pub fn new(rng: &mut impl rand_core::RngCore) -> Self { let mut bytes = [0u8; 16]; rng.fill_bytes(&mut bytes); Self(bytes) } } impl_display_debug_serialize! { fn to_bytes(val: &RestorationId) -> [u8;16] { val.0 } } impl_fromstr_deserialize! { name => "restoration id", fn from_bytes(bytes: [u8;16]) -> RestorationId { RestorationId(bytes) } } /// short randomly sampled id for a coordinator to refer to a physical backup entry it asked a device to do. #[derive(Clone, Copy, PartialEq, PartialOrd, Ord, Eq, Hash, Default)] pub struct EnterPhysicalId(pub [u8; 16]); impl EnterPhysicalId { pub fn new(rng: &mut impl rand_core::RngCore) -> Self { let mut bytes = [0u8; 16]; rng.fill_bytes(&mut bytes); Self(bytes) } } impl_display_debug_serialize! { fn to_bytes(val: &EnterPhysicalId) -> [u8;16] { val.0 } } impl_fromstr_deserialize! { name => "restoration id", fn from_bytes(bytes: [u8;16]) -> EnterPhysicalId { EnterPhysicalId(bytes) } } /// In case we add access structures with more restricted properties later on #[derive(Clone, Copy, Debug, PartialEq, bincode::Decode, bincode::Encode)] pub enum AccessStructureKind { Master, }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/src/device.rs
frostsnap_core/src/device.rs
use crate::device_nonces::{self, AbSlots, MemoryNonceSlot, NonceStreamSlot}; use crate::nonce_stream::CoordNonceStreamState; use crate::symmetric_encryption::{Ciphertext, SymmetricKey}; use crate::tweak::{self, Xpub}; use crate::{ bitcoin_transaction, message::*, AccessStructureId, AccessStructureKind, AccessStructureRef, ActionError, CheckedSignTask, CoordShareDecryptionContrib, Error, KeyId, KeygenId, Kind, MessageResult, RestorationId, SessionHash, ShareImage, }; use crate::{DeviceId, SignSessionId}; use alloc::boxed::Box; use alloc::string::ToString as _; use alloc::{ collections::{BTreeMap, VecDeque}, string::String, vec::Vec, }; use core::num::NonZeroU32; use schnorr_fun::frost::chilldkg::certpedpop::{self}; use schnorr_fun::frost::{Fingerprint, PairedSecretShare, SecretShare, ShareIndex, SharedKey}; pub mod keys; use schnorr_fun::fun::KeyPair; use schnorr_fun::{frost, fun::prelude::*}; use sha2::Sha256; mod device_to_user; pub mod restoration; pub use device_to_user::*; /// The number of nonces the device will give out at a time. pub const NONCE_BATCH_SIZE: u32 = 30; #[derive(Clone, Debug, PartialEq)] pub struct FrostSigner<S = MemoryNonceSlot> { keypair: KeyPair, keys: BTreeMap<KeyId, KeyData>, nonce_slots: device_nonces::AbSlots<S>, mutations: VecDeque<Mutation>, tmp_keygen_phase1: BTreeMap<KeygenId, KeyGenPhase1>, tmp_keygen_phase2: BTreeMap<KeygenId, KeyGenPhase2>, tmp_keygen_pending_finalize: BTreeMap<KeygenId, (SessionHash, KeyGenPhase4)>, restoration: restoration::State, pub keygen_fingerprint: Fingerprint, pub nonce_batch_size: u32, } #[derive(Clone, Debug, PartialEq)] pub struct KeyData { access_structures: BTreeMap<AccessStructureId, AccessStructureData>, purpose: KeyPurpose, key_name: String, /// Do we know that the `KeyId` is genuinely the one associated with the secret shares we have? /// This point is subjective but this device is meant to be able to verified: bool, } /// So the coordindator can recognise which keys are relevant to it #[derive(Clone, Copy, Debug, PartialEq, bincode::Decode, bincode::Encode, Eq, PartialOrd, Ord)] pub enum KeyPurpose { Test, Bitcoin(#[bincode(with_serde)] bitcoin::Network), Nostr, } impl KeyPurpose { /// Returns the appropriate noun to describe what this key is used for pub fn key_type_noun(&self) -> &'static str { match self { KeyPurpose::Bitcoin(_) => "wallet", KeyPurpose::Nostr => "Nostr account", KeyPurpose::Test => "test key", } } pub fn bitcoin_network(&self) -> Option<bitcoin::Network> { match self { KeyPurpose::Bitcoin(network) => Some(*network), _ => None, } } } #[derive(Clone, Debug, PartialEq)] pub struct AccessStructureData { pub kind: AccessStructureKind, /// Keep the threshold around to make recover easier. The device tells the coordinator about it /// so they can tell the user how close they are to restoring the key. pub threshold: u16, pub shares: BTreeMap<ShareIndex, EncryptedSecretShare>, } #[derive(Clone, Copy, Debug, PartialEq, bincode::Decode, bincode::Encode)] pub struct EncryptedSecretShare { /// The image of the encrypted secret. The device stores this so it can tell the coordinator /// about it as part of the recovery system. pub share_image: ShareImage, /// The encrypted secret share pub ciphertext: Ciphertext<32, Scalar<Secret, Zero>>, } impl EncryptedSecretShare { pub fn encrypt( secret_share: SecretShare, access_structure_ref: AccessStructureRef, coord_contrib: CoordShareDecryptionContrib, symm_keygen: &mut impl DeviceSecretDerivation, rng: &mut impl rand_core::RngCore, ) -> Self { let share_image = secret_share.share_image(); let encryption_key = symm_keygen.get_share_encryption_key( access_structure_ref, secret_share.index, coord_contrib, ); let ciphertext = Ciphertext::encrypt(encryption_key, &secret_share.share, rng); EncryptedSecretShare { share_image, ciphertext, } } pub fn decrypt( &self, access_structure_ref: AccessStructureRef, coord_contrib: CoordShareDecryptionContrib, symm_keygen: &mut impl DeviceSecretDerivation, ) -> Option<SecretShare> { let encryption_key = symm_keygen.get_share_encryption_key( access_structure_ref, self.share_image.index, coord_contrib, ); self.ciphertext .decrypt(encryption_key) .map(|share| SecretShare { index: self.share_image.index, share, }) } } #[derive(Clone, Debug, PartialEq)] pub struct KeyGenPhase1 { pub device_to_share_index: BTreeMap<DeviceId, NonZeroU32>, pub input_state: certpedpop::Contributor, pub threshold: u16, pub key_name: String, pub key_purpose: KeyPurpose, pub coordinator_public_key: Point, } #[derive(Clone, Debug, PartialEq)] pub struct KeyGenPhase2 { pub keygen_id: KeygenId, pub device_to_share_index: BTreeMap<DeviceId, NonZeroU32>, paired_secret_share: PairedSecretShare, agg_input: certpedpop::AggKeygenInput, key_name: String, key_purpose: KeyPurpose, pub coordinator_public_key: Point, } #[derive(Debug, Clone, PartialEq)] pub struct KeyGenPhase3 { pub keygen_id: KeygenId, session_hash: SessionHash, key_name: String, key_purpose: KeyPurpose, t_of_n: (u16, u16), shared_key: SharedKey, secret_share: PairedSecretShare, } #[derive(Debug, Clone, PartialEq)] pub struct KeyGenPhase4 { key_name: String, key_purpose: KeyPurpose, access_structure_ref: AccessStructureRef, access_structure_kind: AccessStructureKind, encrypted_secret_share: EncryptedSecretShare, threshold: u16, } impl KeyGenPhase2 { pub fn key_name(&self) -> &str { self.key_name.as_str() } pub fn t_of_n(&self) -> (u16, u16) { ( self.agg_input.shared_key().threshold().try_into().unwrap(), self.agg_input.encryption_keys().count().try_into().unwrap(), ) } } impl KeyGenPhase3 { pub fn key_name(&self) -> &str { self.key_name.as_str() } pub fn t_of_n(&self) -> (u16, u16) { self.t_of_n } pub fn session_hash(&self) -> SessionHash { self.session_hash } } #[derive(Clone, Debug, PartialEq)] pub struct SignPhase1 { group_sign_req: GroupSignReq<CheckedSignTask>, device_sign_req: DeviceSignReq, encrypted_secret_share: EncryptedSecretShare, pub session_id: SignSessionId, } impl SignPhase1 { pub fn sign_task(&self) -> &CheckedSignTask { &self.group_sign_req.sign_task } } impl<S: NonceStreamSlot + core::fmt::Debug> FrostSigner<S> { pub fn new(keypair: KeyPair, nonce_slots: AbSlots<S>) -> Self { Self { keypair, keys: Default::default(), nonce_slots, mutations: Default::default(), tmp_keygen_phase1: Default::default(), tmp_keygen_phase2: Default::default(), tmp_keygen_pending_finalize: Default::default(), restoration: Default::default(), keygen_fingerprint: Fingerprint::FROST_V0, nonce_batch_size: NONCE_BATCH_SIZE, } } pub fn mutate(&mut self, mutation: Mutation) { if let Some(mutation) = self.apply_mutation(mutation) { self.mutations.push_back(mutation); } } pub fn apply_mutation(&mut self, mutation: Mutation) -> Option<Mutation> { use Mutation::*; match mutation { Keygen(keys::KeyMutation::NewKey { key_id, ref key_name, purpose, }) => { self.keys.insert( key_id, KeyData { purpose, access_structures: Default::default(), key_name: key_name.into(), verified: false, }, ); } Keygen(keys::KeyMutation::NewAccessStructure { access_structure_ref, kind, threshold, }) => { self.keys .entry(access_structure_ref.key_id) .and_modify(|key_data| { key_data.access_structures.insert( access_structure_ref.access_structure_id, AccessStructureData { kind, threshold, shares: Default::default(), }, ); }); } Keygen(keys::KeyMutation::SaveShare(ref boxed)) => { let SaveShareMutation { access_structure_ref, encrypted_secret_share, } = boxed.as_ref(); self.keys .entry(access_structure_ref.key_id) .and_modify(|key_data| { key_data .access_structures .entry(access_structure_ref.access_structure_id) .and_modify(|access_structure_data| { access_structure_data.shares.insert( encrypted_secret_share.share_image.index, *encrypted_secret_share, ); }); }); // Clean up any restoration backups with the same share image self.restoration .remove_backups_with_share_image(encrypted_secret_share.share_image); } Restoration(restoration_mutation) => { return self .restoration .apply_mutation_restoration(restoration_mutation) .map(Mutation::Restoration); } } Some(mutation) } pub fn staged_mutations(&mut self) -> &mut VecDeque<Mutation> { &mut self.mutations } pub fn clear_unfinished_keygens(&mut self) { self.tmp_keygen_phase1.clear(); self.tmp_keygen_phase2.clear(); self.tmp_keygen_pending_finalize.clear(); } pub fn clear_tmp_data(&mut self) { self.clear_unfinished_keygens(); self.restoration.clear_tmp_data(); } pub fn keypair(&self) -> &KeyPair { &self.keypair } pub fn device_id(&self) -> DeviceId { DeviceId::new(self.keypair().public_key()) } pub fn recv_coordinator_message( &mut self, message: CoordinatorToDeviceMessage, rng: &mut impl rand_core::RngCore, ) -> MessageResult<Vec<DeviceSend>> { use CoordinatorToDeviceMessage::*; match message.clone() { Signing(signing::CoordinatorSigning::OpenNonceStreams(open_nonce_stream)) => { let mut tasks = vec![]; // we need to order prioritize streams that already exist since not getting a // response to this message the coordinator will think that everything is ok. let (existing, new): (Vec<_>, Vec<_>) = open_nonce_stream .streams .iter() .partition(|stream| self.nonce_slots.get(stream.stream_id).is_some()); let ordered_streams = existing .into_iter() .chain::<Vec<CoordNonceStreamState>>(new) // If we take more than the total available we risk overwriting slots .take(self.nonce_slots.total_slots()); for coord_stream_state in ordered_streams { let slot = self .nonce_slots .get_or_create(coord_stream_state.stream_id, rng); if let Some(task) = slot.reconcile_coord_nonce_stream_state( coord_stream_state, self.nonce_batch_size, ) { tasks.push(task); } } // If there are no tasks, send empty response immediately // Otherwise, send tasks for async processing if tasks.is_empty() { Ok(vec![DeviceSend::ToCoordinator(Box::new( DeviceToCoordinatorMessage::Signing( signing::DeviceSigning::NonceResponse { segments: vec![] }, ), ))]) } else { Ok(vec![DeviceSend::ToUser(Box::new( DeviceToUserMessage::NonceJobs(device_nonces::NonceJobBatch::new(tasks)), ))]) } } KeyGen(keygen_msg) => match keygen_msg { self::Keygen::Begin(begin) => { let device_to_share_index = begin.device_to_share_index(); if !device_to_share_index.contains_key(&self.device_id()) { return Ok(vec![]); } let schnorr = schnorr_fun::new_with_deterministic_nonces::<Sha256>(); let share_receivers_enckeys = device_to_share_index .iter() .map(|(device, share_index)| { (ShareIndex::from(*share_index), device.pubkey()) }) .collect::<BTreeMap<_, _>>(); let my_index = device_to_share_index .get(&self.device_id()) .ok_or_else(|| { Error::signer_invalid_message( &message, format!( "my device id {} was not party of the keygen", self.device_id() ), ) })?; let (input_state, keygen_input) = certpedpop::Contributor::gen_keygen_input( &schnorr, begin.threshold as u32, &share_receivers_enckeys, (*my_index).into(), rng, ); self.tmp_keygen_phase1.insert( begin.keygen_id, KeyGenPhase1 { device_to_share_index, input_state, threshold: begin.threshold, key_name: begin.key_name.clone(), key_purpose: begin.purpose, coordinator_public_key: begin.coordinator_public_key, }, ); Ok(vec![DeviceSend::ToCoordinator(Box::new( DeviceToCoordinatorMessage::KeyGen(keygen::DeviceKeygen::Response( KeyGenResponse { keygen_id: begin.keygen_id, input: Box::new(keygen_input), }, )), ))]) } self::Keygen::CertifyPlease { keygen_id, agg_input, } => { let cert_scheme = certpedpop::vrf_cert::VrfCertScheme::<Sha256>::new( crate::message::keygen::VRF_CERT_SCHEME_ID, ); let schnorr = schnorr_fun::new_with_deterministic_nonces::<Sha256>(); let phase1 = self.tmp_keygen_phase1.remove(&keygen_id).ok_or_else(|| { Error::signer_invalid_message( &message, "no keygen state for provided keygen_id", ) })?; let my_index = phase1 .device_to_share_index .get(&self.device_id()) .expect("already checked"); //XXX: We check the fingerprint so that a (mildly) malicious // coordinator cannot create key generations without the // fingerprint. if agg_input .shared_key() .check_fingerprint::<sha2::Sha256>(self.keygen_fingerprint) .is_none() { return Err(Error::signer_invalid_message( &message, "key generation did not match the fingerprint", )); } let (paired_secret_share, vrf_cert) = phase1 .input_state .verify_receive_share_and_certify( &schnorr, &cert_scheme, (*my_index).into(), self.keypair(), &agg_input, ) .map_err(|e| { Error::signer_invalid_message( &message, format!("Failed to verify and receive share: {e}"), ) })?; let paired_secret_share = paired_secret_share.non_zero().ok_or_else(|| { Error::signer_invalid_message(&message, "keygen produced a zero shared key") })?; self.tmp_keygen_phase2.insert( keygen_id, KeyGenPhase2 { keygen_id, device_to_share_index: phase1.device_to_share_index, paired_secret_share, agg_input, key_name: phase1.key_name.clone(), key_purpose: phase1.key_purpose, coordinator_public_key: phase1.coordinator_public_key, }, ); Ok(vec![DeviceSend::ToCoordinator(Box::new( DeviceToCoordinatorMessage::KeyGen(keygen::DeviceKeygen::Certify { keygen_id, vrf_cert, }), ))]) } self::Keygen::Check { keygen_id, certificate, } => { let phase2 = self.tmp_keygen_phase2.remove(&keygen_id).ok_or_else(|| { Error::signer_invalid_message( &message, "no keygen state for provided keygen_id", ) })?; // Reconstruct the certifier with all contributor public keys let cert_scheme = certpedpop::vrf_cert::VrfCertScheme::<Sha256>::new( crate::message::keygen::VRF_CERT_SCHEME_ID, ); let mut certifier = certpedpop::Certifier::new( cert_scheme, phase2.agg_input.clone(), &[phase2.coordinator_public_key], ); // Add all certificates to the certifier for (pubkey, cert) in certificate { certifier.receive_certificate(pubkey, cert).map_err(|e| { Error::signer_invalid_message( &message, format!("Invalid certificate received: {e}"), ) })?; } // Verify we have all certificates and create the certified keygen let certified_keygen = certifier.finish().map_err(|e| { Error::signer_invalid_message( &message, format!("Missing certificates or verification failed: {e}"), ) })?; let session_hash = SessionHash::from_certified_keygen(&certified_keygen); let phase3 = KeyGenPhase3 { keygen_id, t_of_n: phase2.t_of_n(), key_name: phase2.key_name, key_purpose: phase2.key_purpose, shared_key: certified_keygen .agg_input() .shared_key() .non_zero() .expect("we contributed to coefficient -- can't be zero"), secret_share: phase2.paired_secret_share, session_hash, }; Ok(vec![DeviceSend::ToUser(Box::new( DeviceToUserMessage::CheckKeyGen { phase: Box::new(phase3), }, ))]) } self::Keygen::Finalize { keygen_id } => { let (_session_hash, keygen_pending_finalize) = self .tmp_keygen_pending_finalize .remove(&keygen_id) .ok_or(Error::signer_invalid_message( &message, format!("device doesn't have keygen for {keygen_id}"), ))?; let key_name = keygen_pending_finalize.key_name.clone(); self.save_complete_share(keygen_pending_finalize); Ok(vec![DeviceSend::ToUser(Box::new( DeviceToUserMessage::FinalizeKeyGen { key_name }, ))]) } }, Signing(signing::CoordinatorSigning::RequestSign(request_sign)) => { let self::RequestSign { group_sign_req, device_sign_req, } = *request_sign; let session_id = group_sign_req.session_id(); let key_id = KeyId::from_rootkey(device_sign_req.rootkey); let key_data = self .keys .get(&key_id) .ok_or_else(|| { Error::signer_invalid_message( &message, format!("device doesn't have key for {key_id}"), ) })? .clone(); let group_sign_req = group_sign_req .check(device_sign_req.rootkey, key_data.purpose) .map_err(|e| Error::signer_invalid_message(&message, e))?; let GroupSignReq { parties, access_structure_id, .. } = &group_sign_req; let coord_req_nonces = device_sign_req.nonces; let access_structure_data = key_data.access_structures.get(access_structure_id) .ok_or_else(|| { Error::signer_invalid_message(&message, format!("this device is not part of that access structure: {access_structure_id}")) })?.clone(); let (_, encrypted_secret_share) = parties .iter() .find_map(|party| Some((*party, *access_structure_data.shares.get(party)?))) .ok_or_else(|| { Error::signer_invalid_message( &message, "device doesn't have any of the shares requested", ) })?; // Just verify the nonce stream exists but don't check availability // The signing logic will handle cached signatures naturally let _nonce_slot = self .nonce_slots .get(coord_req_nonces.stream_id) .and_then(|slot| slot.read_slot()) .ok_or(Error::signer_invalid_message( &message, format!( "device did not have that nonce stream id {}", coord_req_nonces.stream_id ), ))?; // Removed are_nonces_available check - let the signing system handle it let phase = SignPhase1 { group_sign_req, device_sign_req, encrypted_secret_share, session_id, }; Ok(vec![DeviceSend::ToUser(Box::new( DeviceToUserMessage::SignatureRequest { phase: Box::new(phase), }, ))]) } ScreenVerify(screen_verify::ScreenVerify::VerifyAddress { master_appkey, derivation_index, }) => { let key_id = master_appkey.key_id(); // check we actually know about this key let _key_data = self .keys .get(&key_id) .ok_or_else(|| { Error::signer_invalid_message( &message, format!("device doesn't have key for {key_id}"), ) })? .clone(); let bip32_path = tweak::BitcoinBip32Path { account_keychain: tweak::BitcoinAccountKeychain::external(), index: derivation_index, }; let spk = bitcoin_transaction::LocalSpk { master_appkey, bip32_path, }; let network = self .wallet_network(key_id) .expect("cannot verify address on key that doesn't support bitcoin"); let address = bitcoin::Address::from_script(&spk.spk(), network).expect("has address form"); Ok(vec![DeviceSend::ToUser(Box::new( DeviceToUserMessage::VerifyAddress { address, bip32_path, }, ))]) } Restoration(message) => self.recv_restoration_message(message, rng), } } pub fn keygen_ack( &mut self, phase: KeyGenPhase3, symm_key_gen: &mut impl DeviceSecretDerivation, rng: &mut impl rand_core::RngCore, ) -> Result<KeyGenAck, ActionError> { let secret_share = phase.secret_share; let key_name = phase.key_name; let rootkey = secret_share.public_key(); let key_id = KeyId::from_rootkey(rootkey); let root_shared_key = Xpub::from_rootkey(phase.shared_key); let app_shared_key = root_shared_key.rootkey_to_master_appkey(); let access_structure_id = AccessStructureId::from_app_poly(app_shared_key.key.point_polynomial()); // SHARE ENCRYPTION NOTE 1: We make the device gnerate the encryption key for the share right after keygen rather // than letting the coordinator send it to the device to protect against malicious // coordinators. A coordinator could provide garbage for example and then the device would // never be able to decrypt its share again. let decryption_share_contrib = CoordShareDecryptionContrib::for_master_share( self.device_id(), secret_share.index(), &root_shared_key.key, ); let threshold = app_shared_key .key .threshold() .try_into() .expect("threshold was too large"); let access_structure_ref = AccessStructureRef { key_id, access_structure_id, }; let encrypted_secret_share = EncryptedSecretShare::encrypt( *secret_share.secret_share(), access_structure_ref, decryption_share_contrib, symm_key_gen, rng, ); self.tmp_keygen_pending_finalize.insert( phase.keygen_id, ( phase.session_hash, KeyGenPhase4 { key_name, key_purpose: phase.key_purpose, access_structure_ref, access_structure_kind: AccessStructureKind::Master, threshold, encrypted_secret_share, }, ), ); Ok(KeyGenAck { ack_session_hash: phase.session_hash, keygen_id: phase.keygen_id, }) } pub fn sign_ack( &mut self, phase: SignPhase1, symm_keygen: &mut impl DeviceSecretDerivation, ) -> Result<Vec<DeviceSend>, ActionError> { let SignPhase1 { group_sign_req: GroupSignReq { parties, agg_nonces, sign_task, access_structure_id, }, device_sign_req: DeviceSignReq { nonces: coord_nonce_state, rootkey, coord_share_decryption_contrib, }, encrypted_secret_share, session_id, } = phase; let sign_items = sign_task.sign_items(); let key_id = KeyId::from_rootkey(rootkey); let my_party_index = encrypted_secret_share.share_image.index; let access_structure_ref = AccessStructureRef { key_id, access_structure_id, }; let symmetric_key = symm_keygen.get_share_encryption_key( access_structure_ref, my_party_index, coord_share_decryption_contrib, ); let secret_share = encrypted_secret_share .ciphertext .decrypt(symmetric_key) .ok_or_else(|| { ActionError::StateInconsistent("couldn't decrypt secret share".into()) })?; let root_paired_secret_share = Xpub::from_rootkey(PairedSecretShare::new_unchecked( SecretShare { index: my_party_index, share: secret_share, }, rootkey, )); let app_paired_secret_share = root_paired_secret_share.rootkey_to_master_appkey(); let frost = frost::new_without_nonce_generation::<sha2::Sha256>(); let sign_sessions = sign_items .iter() .enumerate() .map(|(signature_index, sign_item)| { let derived_xonly_key = sign_item .app_tweak .derive_xonly_key(&app_paired_secret_share); let message = sign_item.schnorr_fun_message(); let session = frost.party_sign_session( derived_xonly_key.public_key(), parties.clone(), agg_nonces[signature_index], message, ); (derived_xonly_key, session) }); let (signature_shares, replenish_task) = self .nonce_slots .sign_guaranteeing_nonces_destroyed( session_id, coord_nonce_state, sign_sessions, symm_keygen, self.nonce_batch_size, ) .map_err(|e| ActionError::StateInconsistent(e.to_string()))?; // Run the replenishment task synchronously if present let replenish_nonces = if let Some(mut task) = replenish_task {
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
true
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/src/tweak.rs
frostsnap_core/src/tweak.rs
use bitcoin::{ bip32::*, hashes::{sha512, Hash, HashEngine, Hmac, HmacEngine}, secp256k1, NetworkKind, }; use schnorr_fun::{ frost::{PairedSecretShare, SharedKey}, fun::{g, marker::*, Point, Scalar, G}, }; #[derive( Clone, Copy, Debug, PartialEq, bincode::Encode, bincode::Decode, Eq, Hash, PartialOrd, Ord, )] pub enum AccountKind { Segwitv1 = 0, } impl AccountKind { pub fn path_segments_from_bitcoin_appkey(&self) -> impl Iterator<Item = u32> { core::iter::once(*self as u32) } } #[derive( Clone, Copy, Debug, PartialEq, bincode::Encode, bincode::Decode, Eq, Hash, PartialOrd, Ord, )] pub enum Keychain { External = 0, Internal = 1, } #[derive(Clone, Debug, PartialEq, bincode::Encode, bincode::Decode, Eq, PartialOrd, Ord)] pub enum AppTweak { TestMessage, Bitcoin(BitcoinBip32Path), Nostr, } #[derive( Clone, Copy, Debug, PartialEq, bincode::Encode, bincode::Decode, Eq, Hash, PartialOrd, Ord, )] pub struct BitcoinBip32Path { pub account_keychain: BitcoinAccountKeychain, pub index: u32, } impl BitcoinBip32Path { pub fn external(index: u32) -> Self { Self { account_keychain: BitcoinAccountKeychain::external(), index, } } pub fn internal(index: u32) -> Self { Self { account_keychain: BitcoinAccountKeychain::internal(), index, } } } impl From<BitcoinBip32Path> for DerivationPath { fn from(bip32_path: BitcoinBip32Path) -> Self { DerivationPath::from_normal_path_segments( bip32_path .account_keychain .account .path_segments_from_bitcoin_appkey() .chain(core::iter::once(bip32_path.index)), ) } } #[derive( Clone, Copy, Debug, PartialEq, bincode::Encode, bincode::Decode, Eq, Hash, PartialOrd, Ord, )] pub struct BitcoinAccount { pub kind: AccountKind, pub index: u32, } impl BitcoinAccount { pub fn path_segments_from_bitcoin_appkey(&self) -> impl Iterator<Item = u32> { self.kind .path_segments_from_bitcoin_appkey() .chain(core::iter::once(self.index)) } } impl Default for BitcoinAccount { fn default() -> Self { Self { kind: AccountKind::Segwitv1, index: 0, } } } #[derive( Clone, Copy, Debug, PartialEq, bincode::Encode, bincode::Decode, Eq, Hash, PartialOrd, Ord, )] pub struct BitcoinAccountKeychain { pub account: BitcoinAccount, pub keychain: Keychain, } impl BitcoinAccountKeychain { pub fn external() -> Self { Self { account: BitcoinAccount::default(), keychain: Keychain::External, } } pub fn internal() -> Self { Self { account: BitcoinAccount::default(), keychain: Keychain::Internal, } } pub fn path_segments_from_bitcoin_appkey(&self) -> impl Iterator<Item = u32> { self.account .path_segments_from_bitcoin_appkey() .chain(core::iter::once(self.keychain as u32)) } } impl BitcoinBip32Path { pub fn path_segments_from_bitcoin_appkey(&self) -> impl Iterator<Item = u32> { self.account_keychain .path_segments_from_bitcoin_appkey() .chain(core::iter::once(self.index)) } pub fn from_u32_slice(path: &[u32]) -> Option<Self> { if path.len() != 4 { return None; } let account_kind = match path[0] { 0 => AccountKind::Segwitv1, _ => return None, }; let account_index = path[1]; let account = BitcoinAccount { kind: account_kind, index: account_index, }; let keychain = match path[2] { 0 => Keychain::External, 1 => Keychain::Internal, _ => return None, }; let _check_it = ChildNumber::from_normal_idx(path[2]).ok()?; let index = path[3]; Some(BitcoinBip32Path { account_keychain: BitcoinAccountKeychain { account, keychain }, index, }) } } impl AppTweak { pub fn kind(&self) -> AppTweakKind { match self { AppTweak::Bitcoin { .. } => AppTweakKind::Bitcoin, AppTweak::Nostr => AppTweakKind::Nostr, AppTweak::TestMessage => AppTweakKind::TestMessage, } } pub fn derive_xonly_key<K: TweakableKey>(&self, master_appkey: &Xpub<K>) -> K::XOnly { let appkey = master_appkey.derive_bip32([self.kind() as u32]); match &self { AppTweak::Bitcoin(bip32_path) => { let concrete_internal_key = appkey.derive_bip32(bip32_path.path_segments_from_bitcoin_appkey()); let derived_key = concrete_internal_key.into_key(); let tweak = bitcoin::taproot::TapTweakHash::from_key_and_tweak( derived_key.to_libsecp_xonly(), None, ) .to_scalar(); derived_key.into_xonly_with_tweak( Scalar::<Public, _>::from_bytes_mod_order(tweak.to_be_bytes()) .non_zero() .expect("computationally unreachable"), ) } AppTweak::Nostr => appkey.into_key().into_xonly(), AppTweak::TestMessage => appkey.into_key().into_xonly(), } } } #[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Ord, Eq)] pub enum AppTweakKind { Bitcoin = 0, TestMessage = 1, Nostr = 2, } impl AppTweakKind { pub fn derivation_path(&self) -> DerivationPath { DerivationPath::master().child(ChildNumber::Normal { index: *self as u32, }) } } pub trait TweakableKey: Clone + core::fmt::Debug { type XOnly; fn to_key(&self) -> Point; fn to_libsecp_key(&self) -> secp256k1::PublicKey { self.to_key().into() } fn to_libsecp_xonly(&self) -> secp256k1::XOnlyPublicKey { self.to_key().to_libsecp_xonly() } fn tweak(self, tweak: Scalar<Public, Zero>) -> Self; fn into_xonly_with_tweak(self, tweak: Scalar<Public>) -> Self::XOnly; fn into_xonly(self) -> Self::XOnly; } impl TweakableKey for SharedKey<Normal> { type XOnly = SharedKey<EvenY>; fn to_key(&self) -> Point { self.public_key() } fn tweak(self, tweak: Scalar<Public, Zero>) -> Self { self.homomorphic_add(tweak) .non_zero() .expect("computationally unreachable") } fn into_xonly_with_tweak(self, tweak: Scalar<Public>) -> Self::XOnly { self.into_xonly() .homomorphic_add(tweak) .non_zero() .expect("computationally unreachable") .into_xonly() } fn into_xonly(self) -> Self::XOnly { SharedKey::into_xonly(self) } } impl TweakableKey for PairedSecretShare { type XOnly = PairedSecretShare<EvenY>; fn to_key(&self) -> Point { self.public_key().to_key() } fn tweak(self, tweak: Scalar<Public, Zero>) -> Self { self.homomorphic_add(tweak) .non_zero() .expect("computationally unreachable") } fn into_xonly_with_tweak(self, tweak: Scalar<Public>) -> Self::XOnly { self.into_xonly() .homomorphic_add(tweak) .non_zero() .expect("computationally unreachable") .into_xonly() } fn into_xonly(self) -> Self::XOnly { PairedSecretShare::into_xonly(self) } } impl TweakableKey for Point { type XOnly = Point<EvenY>; fn to_key(&self) -> Point { *self } fn tweak(self, tweak: Scalar<Public, Zero>) -> Self { g!(self + tweak * G) .normalize() .non_zero() .expect("if tweak is a hash this should be unreachable") } fn into_xonly_with_tweak(self, tweak: Scalar<Public>) -> Self::XOnly { let (even_y, _) = self.into_point_with_even_y(); let (tweaked_even_y, _) = g!(even_y + tweak * G) .normalize() .non_zero() .expect("if tweak is a hash this should be unreachable") .into_point_with_even_y(); tweaked_even_y } fn to_libsecp_xonly(&self) -> secp256k1::XOnlyPublicKey { secp256k1::XOnlyPublicKey::from_slice(self.to_xonly_bytes().as_ref()).unwrap() } fn into_xonly(self) -> Self::XOnly { let (even_y, _) = self.into_point_with_even_y(); even_y } } impl<T: TweakableKey> Xpub<T> { pub fn from_rootkey(rootkey: T) -> Self { Xpub { chaincode: [0u8; 32], key: rootkey, } } pub fn rootkey_to_master_appkey(&self) -> Xpub<T> { let mut master_appkey = self.clone(); master_appkey.derive_bip32_in_place([0]); master_appkey } pub fn new(key: T, chaincode: [u8; 32]) -> Self { Xpub { chaincode, key } } /// Does non-hardened derivation in place pub fn derive_bip32_in_place(&mut self, segments: impl IntoIterator<Item = u32>) { for child in segments.into_iter() { let mut hmac_engine: HmacEngine<sha512::Hash> = HmacEngine::new(&self.chaincode[..]); hmac_engine.input(&self.key().to_key().to_bytes()); hmac_engine.input(&child.to_be_bytes()); let hmac_result: Hmac<sha512::Hash> = Hmac::from_engine(hmac_engine); self.key = self.key.clone().tweak( Scalar::<Public, _>::from_slice_mod_order(&hmac_result[..32]).expect("32 bytes"), ); self.chaincode.copy_from_slice(&hmac_result[32..]); } } pub fn derive_bip32(&self, segments: impl IntoIterator<Item = u32>) -> Xpub<T> { let mut ret = self.clone(); ret.derive_bip32_in_place(segments); ret } pub fn key(&self) -> &T { &self.key } pub fn into_key(self) -> T { self.key } pub fn fingerprint(&self) -> bitcoin::bip32::Fingerprint { self.to_bitcoin_xpub_with_lies(NetworkKind::Main) .fingerprint() } /// Create a rust bitcoin xpub lying about the fields we don't care about pub fn to_bitcoin_xpub_with_lies( &self, network_kind: bitcoin::NetworkKind, ) -> bitcoin::bip32::Xpub { bitcoin::bip32::Xpub { network: network_kind, // note below this is a lie and shouldn't matter VVV depth: 0, parent_fingerprint: Fingerprint::default(), child_number: ChildNumber::from_normal_idx(0).unwrap(), // ^^^ above is a lie and shouldn't matter public_key: self.key.to_libsecp_key(), chain_code: ChainCode::from(self.chaincode), } } } /// Xpub to do bip32 deriviation without all the nonsense. #[derive( Clone, Copy, PartialEq, Eq, Ord, PartialOrd, Hash, bincode::Encode, bincode::Decode, Debug, )] pub struct Xpub<T> { pub key: T, pub chaincode: [u8; 32], } impl Xpub<SharedKey> { pub fn public_key(&self) -> Xpub<Point> { Xpub { key: self.key.public_key(), chaincode: self.chaincode, } } } pub trait DerivationPathExt { fn from_normal_path_segments(path_segments: impl IntoIterator<Item = u32>) -> Self; } impl DerivationPathExt for DerivationPath { fn from_normal_path_segments(path_segments: impl IntoIterator<Item = u32>) -> Self { DerivationPath::from_iter(path_segments.into_iter().map(|path_segment| { ChildNumber::from_normal_idx(path_segment).expect("valid normal derivation index") })) } } #[cfg(test)] mod test { use super::*; use alloc::vec::Vec; use bitcoin::secp256k1::Secp256k1; use schnorr_fun::frost::chilldkg::certpedpop; #[test] pub fn bip32_derivation_matches_rust_bitcoin() { let schnorr = schnorr_fun::new_with_deterministic_nonces::<sha2::Sha256>(); let cert_scheme = certpedpop::vrf_cert::VrfCertScheme::<sha2::Sha256>::new("chilldkg-vrf"); let output = certpedpop::simulate_keygen( &schnorr, cert_scheme, 3, 5, 5, schnorr_fun::frost::Fingerprint { tag: "frostsnap-v0", bits_per_coeff: 10, max_bits_total: 20, }, &mut rand::thread_rng(), ); let frost_key = output .certified_keygen .agg_input() .shared_key() .non_zero() .unwrap(); let root_xpub = Xpub::from_rootkey(frost_key); let secp = Secp256k1::verification_only(); let xpub = bitcoin::bip32::Xpub { network: bitcoin::Network::Bitcoin.into(), depth: 0, parent_fingerprint: Fingerprint::default(), child_number: ChildNumber::from_normal_idx(0).unwrap(), public_key: root_xpub.key.public_key().into(), chain_code: ChainCode::from(root_xpub.chaincode), }; let path = [1337u32, 42, 0]; let child_path = path .iter() .map(|i| ChildNumber::Normal { index: *i }) .collect::<Vec<_>>(); let derived_xpub = xpub.derive_pub(&secp, &child_path).unwrap(); let our_derived_xpub = root_xpub.derive_bip32(path); assert_eq!( our_derived_xpub.chaincode, *derived_xpub.chain_code.as_bytes() ); assert_eq!( our_derived_xpub.key.public_key(), derived_xpub.public_key.into() ); } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/src/master_appkey.rs
frostsnap_core/src/master_appkey.rs
use crate::{ tweak::{AppTweakKind, TweakableKey, Xpub}, KeyId, }; use alloc::string::String; use schnorr_fun::fun::prelude::*; /// A 65-byte encoded point and chaincode. This is a byte array because it's easier to pass around byte /// arrays via FFI rather than `Point`. #[derive(Clone, Copy, PartialEq, Eq, Ord, PartialOrd, Hash)] pub struct MasterAppkey(pub [u8; 65]); impl MasterAppkey { pub fn derive_from_rootkey(rootkey: Point) -> Self { let xpub = Xpub::<Point>::from_rootkey(rootkey).rootkey_to_master_appkey(); Self::from_xpub_unchecked(&xpub) } pub fn to_xpub(&self) -> Xpub<Point> { let point = Point::from_slice(&self.0[..33]).expect("invariant"); let chaincode = self.0[33..].try_into().expect("correct length"); Xpub { key: point, chaincode, } } pub fn from_xpub_unchecked<K: TweakableKey>(master_appkey_xpub: &Xpub<K>) -> Self { let mut bytes = [0u8; 65]; bytes[..33].copy_from_slice(master_appkey_xpub.key.to_key().to_bytes().as_ref()); bytes[33..].copy_from_slice(master_appkey_xpub.chaincode.as_ref()); Self(bytes) } pub fn to_redacted_string(&self) -> String { use alloc::string::ToString; let full = self.to_string(); let redacted = format!("{}...{}", &full[..4], &full[full.len() - 4..]); redacted } pub fn key_id(&self) -> KeyId { KeyId::from_master_appkey(*self) } pub fn derive_appkey(&self, appkey_kind: AppTweakKind) -> Xpub<Point> { self.to_xpub().derive_bip32([appkey_kind as u32]) } } crate::impl_display_debug_serialize! { fn to_bytes(master_appkey: &MasterAppkey) -> [u8;65] { master_appkey.0 } } crate::impl_fromstr_deserialize! { name => "master_appkey", fn from_bytes(bytes: [u8;65]) -> Option<MasterAppkey> { let _ = Point::<Normal, Public, NonZero>::from_slice(&bytes[0..33])?; Some(MasterAppkey(bytes)) } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/src/symmetric_encryption.rs
frostsnap_core/src/symmetric_encryption.rs
use chacha20poly1305::{ aead::{AeadInPlace, KeyInit}, ChaCha20Poly1305, }; use core::marker::PhantomData; #[derive(Clone, Copy, Debug, bincode::Encode, bincode::Decode, PartialEq, Eq, Ord, PartialOrd)] pub struct Ciphertext<const N: usize, T> { data: [u8; N], nonce: [u8; 12], ty: PhantomData<T>, tag: [u8; 16], } impl<const N: usize, T: bincode::Encode + bincode::Decode<()>> Ciphertext<N, T> { pub fn decrypt(&self, encryption_key: SymmetricKey) -> Option<T> { let cipher = ChaCha20Poly1305::new(&encryption_key.0.into()); let mut plaintext = self.data; cipher .decrypt_in_place_detached( &self.nonce.into(), b"", &mut plaintext[..], &self.tag.into(), ) .ok()?; let (value, _) = bincode::decode_from_slice(&plaintext, bincode::config::standard()).ok()?; Some(value) } pub fn encrypt( encryption_key: SymmetricKey, data: &T, rng: &mut impl rand_core::RngCore, ) -> Self { let mut nonce = [0u8; 12]; rng.fill_bytes(&mut nonce); let cipher = ChaCha20Poly1305::new(&encryption_key.0.into()); let mut ciphertext = [0u8; N]; let length = bincode::encode_into_slice(data, &mut ciphertext[..], bincode::config::standard()) .expect("programmer error. Couldn't encode into ciphertext."); if length != N { panic!("encoded plaintext was the wrong length. Expected {N} got {length}"); } let tag = cipher .encrypt_in_place_detached(&nonce.into(), b"", &mut ciphertext[..]) .expect("I don't understand how there could be an error here"); Self { data: ciphertext, nonce, tag: tag.into(), ty: PhantomData, } } } impl<const N: usize> Ciphertext<N, [u8; N]> { pub fn random(encrption_key: SymmetricKey, rng: &mut impl rand_core::RngCore) -> Self { let mut bytes = [0u8; N]; rng.fill_bytes(&mut bytes[..]); Self::encrypt(encrption_key, &bytes, rng) } } #[derive(Clone, Copy, Debug)] pub struct SymmetricKey(pub [u8; 32]);
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/src/sqlite.rs
frostsnap_core/src/sqlite.rs
use crate::{DeviceId, KeyId, RestorationId}; use alloc::boxed::Box; use alloc::str::FromStr; use alloc::string::ToString; use rusqlite::{ types::{FromSql, FromSqlError, ToSqlOutput}, ToSql, }; impl FromSql for DeviceId { fn column_result(value: rusqlite::types::ValueRef<'_>) -> rusqlite::types::FromSqlResult<Self> { Self::from_str(value.as_str()?).map_err(|e| FromSqlError::Other(Box::new(e))) } } impl ToSql for DeviceId { fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> { Ok(ToSqlOutput::from(self.to_string())) } } impl FromSql for KeyId { fn column_result(value: rusqlite::types::ValueRef<'_>) -> rusqlite::types::FromSqlResult<Self> { Self::from_str(value.as_str()?).map_err(|e| FromSqlError::Other(Box::new(e))) } } impl ToSql for KeyId { fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> { Ok(ToSqlOutput::from(self.to_string())) } } impl ToSql for RestorationId { fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> { Ok(ToSqlOutput::from(self.to_string())) } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/src/macros.rs
frostsnap_core/src/macros.rs
/// Implements Display, FromStr, Serialize and Deserialize for something that /// can be represented as a fixed length byte array #[macro_export] #[doc(hidden)] macro_rules! impl_fromstr_deserialize { ( name => $name:literal, fn from_bytes$(<$($tpl:ident $(: $tcl:ident)?),*>)?($input:ident : [u8;$len:literal]) -> Option<$type:path> $block:block ) => { impl$(<$($tpl $(:$tcl)?),*>)? $type { pub fn from_bytes($input: [u8; $len]) -> Option<$type> { #[allow(clippy::redundant_closure_call)] (|| { $block })() } } $crate::impl_fromstr_deserialize!(@main name => $name, fn from_bytes$(<$($tpl $(:$tcl)?),*>)?($input: [u8;$len]) -> Option<$type> $block); }; (name => $name:literal, fn from_bytes$(<$($tpl:ident $(: $tcl:ident)?),*>)?($input:ident : [u8;$len:literal]) -> $type:path $block:block ) => { impl$(<$($tpl $(:$tcl)?),*>)? $type { pub fn from_bytes($input: [u8; $len]) -> $type { #[allow(clippy::redundant_closure_call)] (|| { $block })() } } $crate::impl_fromstr_deserialize!(@main name => $name, fn from_bytes$(<$($tpl $(:$tcl)?),*>)?($input: [u8;$len]) -> Option<$type> { Some($block) }); }; ( @main name => $name:literal, fn from_bytes$(<$($tpl:ident $(: $tcl:ident)?),*>)?($input:ident : [u8;$len:literal]) -> Option<$type:path> $block:block ) => { impl$(<$($tpl $(:$tcl)?),*>)? $type { pub fn from_slice(slice: &[u8]) -> Option<$type> { if slice.len() != $len { return None; } let mut $input = [0u8;$len]; $input.copy_from_slice(&slice[..]); #[allow(clippy::redundant_closure_call)] (|| { $block })() } } impl$(<$($tpl $(:$tcl)?),*>)? core::str::FromStr for $type { type Err = $crate::hex::HexError; /// Parses the string as hex and interprets tries to convert the /// resulting byte array into the desired value. fn from_str(hex: &str) -> Result<$type , $crate::hex::HexError> { use $crate::hex::hex_val; if hex.len() % 2 == 1 { Err($crate::hex::HexError::InvalidHex) } else if $len * 2 != hex.len() { Err($crate::hex::HexError::InvalidLength) } else { let mut buf = [0u8; $len]; for (i, hex_byte) in hex.as_bytes().chunks(2).enumerate() { buf[i] = hex_val(hex_byte[0])? << 4 | hex_val(hex_byte[1])? } let $input = buf; #[allow(clippy::redundant_closure_call)] let result = (|| { $block })(); result.ok_or($crate::hex::HexError::InvalidEncoding) } } } impl<'de, $($($tpl $(: $tcl)?),*)?> $crate::serde::Deserialize<'de> for $type { fn deserialize<Deser: $crate::serde::Deserializer<'de>>( deserializer: Deser, ) -> Result<$type , Deser::Error> { { if deserializer.is_human_readable() { #[allow(unused_parens)] struct HexVisitor$(<$($tpl),*>)?$((core::marker::PhantomData<($($tpl),*)> ))?; impl<'de, $($($tpl $(: $tcl)?),*)?> $crate::serde::de::Visitor<'de> for HexVisitor$(<$($tpl),*>)? { type Value = $type ; fn expecting( &self, f: &mut core::fmt::Formatter, ) -> core::fmt::Result { write!(f, "a valid {}-byte hex encoded {}", $len, $name)?; Ok(()) } fn visit_str<E: $crate::serde::de::Error>(self, v: &str) -> Result<$type , E> { use $crate::hex::HexError::*; <$type as core::str::FromStr>::from_str(v).map_err(|e| match e { InvalidLength => E::invalid_length(v.len() / 2, &self), InvalidEncoding => E::invalid_value($crate::serde::de::Unexpected::Str(v), &self), InvalidHex => E::custom("invalid hex") }) } } #[allow(unused_parens)] return deserializer.deserialize_str(HexVisitor$((core::marker::PhantomData::<($($tpl),*)>))?); } } { #[allow(unused_parens)] struct BytesVisitor$(<$($tpl),*>)?$((core::marker::PhantomData<($($tpl),*)> ))?; impl<'de, $($($tpl $(: $tcl)?),*)?> $crate::serde::de::Visitor<'de> for BytesVisitor$(<$($tpl),*>)? { type Value = $type ; fn expecting( &self, f: &mut core::fmt::Formatter, ) -> core::fmt::Result { write!(f, "a valid {}-byte encoding of a {}", $len, $name)?; Ok(()) } fn visit_seq<A>(self, mut seq: A) -> Result<$type , A::Error> where A: $crate::serde::de::SeqAccess<'de> { let mut $input = [0u8; $len]; for i in 0..$len { $input[i] = seq.next_element()? .ok_or_else(|| $crate::serde::de::Error::invalid_length(i, &self))?; } #[allow(clippy::redundant_closure_call)] let result = (|| { $block })(); result.ok_or($crate::serde::de::Error::custom(format_args!("invalid byte encoding, expected {}", &self as &dyn $crate::serde::de::Expected))) } } #[allow(unused_parens)] deserializer.deserialize_tuple($len, BytesVisitor$((core::marker::PhantomData::<($($tpl),*)>))?) } } } impl<__Context, $($($tpl $(:$tcl)?),*)?> $crate::bincode::de::Decode<__Context> for $type { fn decode<D: $crate::bincode::de::Decoder>(decoder: &mut D) -> Result<Self, $crate::bincode::error::DecodeError> { use $crate::bincode::de::read::Reader; let mut $input = [0u8; $len]; decoder.reader().read(&mut $input)?; #[allow(clippy::redundant_closure_call)] let result = (|| { $block })(); return result.ok_or($crate::bincode::error::DecodeError::OtherString(format!("Invalid {}-byte encoding of a {}", $len, $name))); } } impl<'de, __Context, $($($tpl $(:$tcl)?),*)?> $crate::bincode::BorrowDecode<'de, __Context> for $type { fn borrow_decode<D: $crate::bincode::de::BorrowDecoder<'de>>( decoder: &mut D, ) -> core::result::Result<Self, $crate::bincode::error::DecodeError> { $crate::bincode::Decode::decode(decoder) } } }; } #[doc(hidden)] #[macro_export] macro_rules! impl_display_serialize { (fn to_bytes$(<$($tpl:ident $(: $tcl:ident)?),*>)?($self:ident : &$type:path) -> [u8;$len:literal] $block:block) => { impl$(<$($tpl $(:$tcl)?),*>)? $type { pub fn to_bytes(&self) -> [u8; $len] { let $self = self; $block } } impl$(<$($tpl $(:$tcl)?),*>)? $crate::serde::Serialize for $type { fn serialize<Ser: $crate::serde::Serializer>(&self, serializer: Ser) -> Result<Ser::Ok, Ser::Error> { use $crate::serde::ser::SerializeTuple; let $self = &self; let bytes = $block; { use $crate::hex; if serializer.is_human_readable() { return serializer.serialize_str(&hex::encode(&bytes[..])) } } //NOTE: idea taken from https://github.com/dalek-cryptography/curve25519-dalek/pull/297/files let mut tup = serializer.serialize_tuple($len)?; for byte in bytes.iter() { tup.serialize_element(byte)?; } tup.end() } } impl$(<$($tpl $(:$tcl)?),*>)? core::fmt::Display for $type { /// Displays as hex. fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { let $self = &self; let bytes = $block; for byte in bytes.iter() { write!(f, "{:02x}", byte)? } Ok(()) } } impl$(<$($tpl $(:$tcl)?),*>)? $crate::bincode::Encode for $type { fn encode<E: $crate::bincode::enc::Encoder>(&self, encoder: &mut E) -> Result<(), $crate::bincode::error::EncodeError> { use $crate::bincode::enc::write::Writer; let $self = &self; let bytes = $block; encoder.writer().write(bytes.as_ref()) } } } } #[doc(hidden)] #[macro_export] macro_rules! impl_debug { (fn to_bytes$(<$($tpl:ident $(: $tcl:ident)?),*>)?($self:ident : &$type_name:ident$(<$($tpr:path),+>)?) -> $($tail:tt)*) => { impl$(<$($tpl $(:$tcl)?),*>)? core::fmt::Debug for $type_name$(<$($tpr),+>)? { /// Formats the type as hex and any markers on the type. fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { let $self = &self; write!(f, "{}", stringify!($type_name))?; $( write!(f, "<")?; $crate::impl_debug!(@recursive_print f, $(core::any::type_name::<$tpr>().rsplit("::").next().unwrap()),*); write!(f, ">")?; )? write!(f, "(")?; $crate::impl_debug!(@output f, $self, $($tail)*); write!(f, ")")?; Ok(()) } } }; (@output $f:ident, $self:ident, Result<$(&)?[u8;$len:literal], &str> $block:block) => { let res: Result<[u8;$len], &str> = $block; match res { Ok(bytes) => { for byte in bytes.iter() { write!($f, "{:02x}", byte)? } }, Err(string) => { write!($f, "{}", string)? } } }; (@output $f:ident, $self:ident, $(&)?[u8;$len:literal] $block:block) => { let bytes = $block; for byte in bytes.iter() { write!($f, "{:02x}", byte)? } }; (@recursive_print $f:ident, $next:expr, $($tt:tt)+) => { $f.write_str($next)?; $f.write_str(",")?; $crate::impl_debug!(@recursive_print $f, $($tt)+) }; (@recursive_print $f:ident, $next:expr) => { $f.write_str($next)?; }; } #[macro_export] #[doc(hidden)] macro_rules! impl_display_debug_serialize { ($($tt:tt)+) => { $crate::impl_display_serialize!($($tt)+); $crate::impl_debug!($($tt)+); }; }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/src/nostr.rs
frostsnap_core/src/nostr.rs
use alloc::string::String; use alloc::vec::Vec; use schnorr_fun::fun::{marker::EvenY, Point}; use schnorr_fun::Signature; #[derive( Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash, Ord, PartialOrd, )] pub struct UnsignedEvent { pub id: String, pubkey: Point<EvenY>, created_at: i64, kind: u64, tags: Vec<Vec<String>>, pub content: String, pub hash_bytes: Vec<u8>, } impl UnsignedEvent { /// HACK: we only need `new` on the coordinator and serde_json doesn't work with no_std so we feature gate `new`. #[cfg(feature = "serde_json")] pub fn new( pubkey: Point<EvenY>, kind: u64, tags: Vec<Vec<String>>, content: String, created_at: i64, ) -> Self { use alloc::string::ToString; use sha2::Digest; use sha2::Sha256; let serialized_event = serde_json::json!([ 0, pubkey, created_at, kind, serde_json::json!(tags), content ]); let mut hash = Sha256::default(); hash.update(serialized_event.to_string().as_bytes()); let hash_result = hash.finalize(); let hash_result_str = format!("{hash_result:x}"); Self { id: hash_result_str, pubkey, created_at, kind, tags, content, hash_bytes: hash_result.to_vec(), } } pub fn add_signature(self, signature: Signature) -> Event { Event { id: self.id, pubkey: self.pubkey, created_at: self.created_at, kind: self.kind, tags: self.tags, content: self.content, sig: signature, } } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct Event { pub id: String, pubkey: Point<EvenY>, created_at: i64, kind: u64, tags: Vec<Vec<String>>, pub content: String, sig: Signature, }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/src/nonce_stream.rs
frostsnap_core/src/nonce_stream.rs
use alloc::collections::VecDeque; use schnorr_fun::binonce; #[derive(Debug, Clone, PartialEq, bincode::Encode, bincode::Decode)] pub struct NonceStreamSegment { pub stream_id: NonceStreamId, pub nonces: VecDeque<binonce::Nonce>, pub index: u32, } #[derive(Debug, Clone, PartialEq, bincode::Encode, bincode::Decode)] pub struct SigningReqSubSegment { pub segment: NonceStreamSegment, pub remaining: u32, } impl SigningReqSubSegment { pub fn coord_nonce_state(&self) -> CoordNonceStreamState { CoordNonceStreamState { stream_id: self.segment.stream_id, index: self.segment.index, remaining: self.remaining, } } } impl NonceStreamSegment { /// When a coordinator needs to make a signing request you take a prefix of nonces from the /// segment. You also need to know the "remaining" nonces in the segment so you can tell the /// device about it so it replenishes at the right point.j pub fn signing_req_sub_segment(&self, length: usize) -> Option<SigningReqSubSegment> { let remaining = self.nonces.len().checked_sub(length)?.try_into().ok()?; let segment = Self { stream_id: self.stream_id, nonces: self.nonces.iter().cloned().take(length).collect(), index: self.index, }; Some(SigningReqSubSegment { remaining, segment }) } pub fn index_after_last(&self) -> Option<u32> { self.index.checked_add(self.nonces.len().try_into().ok()?) } pub fn delete_up_to(&mut self, up_to_but_not_including: u32) -> bool { let mut changed = false; let to_delete = up_to_but_not_including.saturating_sub(self.index); debug_assert!(to_delete as usize <= self.nonces.len()); debug_assert!((to_delete as usize + self.index as usize) < u32::MAX as usize); for _ in 0..to_delete { self.nonces.pop_front(); self.index += 1; changed = true; } changed } fn _extend( &self, other: NonceStreamSegment, ) -> Result<NonceStreamSegment, NonceSegmentIncompatible> { let mut curr = self.clone(); if self.stream_id != other.stream_id { return Err(NonceSegmentIncompatible::StreamIdDontMatch); } other .index_after_last() .ok_or(NonceSegmentIncompatible::Overflows)?; let connect = if other.index > curr.index { curr.index + self.nonces.len() as u32 >= other.index } else { other.index + other.nonces.len() as u32 >= curr.index }; if !connect || curr.nonces.is_empty() { return Ok(if curr.nonces.len() > other.nonces.len() { debug_assert!(false, "was unable to extend update"); curr } else { other }); } let new_start = self.index.min(other.index); let mut curr_end = self.index_after_last().expect("invariant") - 1; let other_end = other.index_after_last().unwrap() - 1; let new_end = curr_end.max(other_end); while curr.index > new_start { curr.index -= 1; let other_nonce = other.get_nonce(curr.index).expect("must exist"); curr.nonces.push_front(other_nonce); } while curr_end < new_end { curr_end += 1; let other_nonce = other.get_nonce(curr_end).expect("must exist"); curr.nonces.push_back(other_nonce); } assert_eq!(curr.index, new_start, "should start at the right place now"); assert_eq!( curr.index_after_last().unwrap() - 1, new_end, "should end at the right place now" ); Ok(curr) } pub fn extend(&mut self, other: NonceStreamSegment) -> Result<bool, NonceSegmentIncompatible> { let new = self._extend(other)?; if new != *self { *self = new; return Ok(true); } Ok(false) } pub fn check_can_extend( &self, other: &NonceStreamSegment, ) -> Result<(), NonceSegmentIncompatible> { self._extend(other.clone())?; Ok(()) } fn get_nonce(&self, index: u32) -> Option<binonce::Nonce> { self.nonces .get(index.checked_sub(self.index)? as usize) .copied() } } #[derive(Debug, Clone, Copy, PartialEq)] pub enum NonceSegmentIncompatible { StreamIdDontMatch, Overflows, } impl core::fmt::Display for NonceSegmentIncompatible { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { use NonceSegmentIncompatible::*; match self { StreamIdDontMatch => write!(f, "stream ids for nonce segments didn't match"), Overflows => write!(f, "the segment we are trying to connect overflows"), } } } #[cfg(feature = "std")] impl std::error::Error for NonceSegmentIncompatible {} /// A way to index nonces on a device. /// Each device can produce a sequence of random nonces for any requested stream id #[derive(Clone, Copy, PartialEq, PartialOrd, Ord, Eq, Hash)] pub struct NonceStreamId(pub [u8; 16]); impl NonceStreamId { pub fn random(rng: &mut impl rand_core::RngCore) -> Self { let mut bytes = [0u8; 16]; rng.fill_bytes(&mut bytes); NonceStreamId(bytes) } } crate::impl_display_debug_serialize! { fn to_bytes(nonce_stream_id: &NonceStreamId) -> [u8;16] { nonce_stream_id.0 } } crate::impl_fromstr_deserialize! { name => "nonce stream id", fn from_bytes(bytes: [u8;16]) -> NonceStreamId { NonceStreamId(bytes) } } #[derive(Debug, Clone, Copy, bincode::Encode, bincode::Decode, PartialEq)] pub struct CoordNonceStreamState { pub stream_id: NonceStreamId, pub index: u32, pub remaining: u32, }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/src/sign_task.rs
frostsnap_core/src/sign_task.rs
use crate::{bitcoin_transaction, device::KeyPurpose, tweak::AppTweak, MasterAppkey}; use alloc::{boxed::Box, string::String, vec::Vec}; use bitcoin::hashes::Hash; use schnorr_fun::{Message, Schnorr, Signature}; #[derive(Debug, Clone, bincode::Encode, bincode::Decode, PartialEq, Eq, Hash)] pub enum WireSignTask { Test { message: String, }, Nostr { #[bincode(with_serde)] event: Box<crate::nostr::UnsignedEvent>, }, BitcoinTransaction(bitcoin_transaction::TransactionTemplate), } #[derive(Debug, Clone, PartialEq)] pub enum SignTask { Test { message: String, }, Nostr { event: Box<crate::nostr::UnsignedEvent>, }, BitcoinTransaction { tx_template: bitcoin_transaction::TransactionTemplate, network: bitcoin::Network, }, } #[derive(Debug, Clone, PartialEq)] /// A sign task bound to a single key. We only support signing tasks with single keys for now. pub struct CheckedSignTask { /// The appkey it the task was checked against. Indicates that for example, the Bitcoin /// transaction was signing inputs whose public key was derived from this. pub master_appkey: MasterAppkey, pub inner: SignTask, } impl WireSignTask { pub fn check( self, master_appkey: MasterAppkey, purpose: KeyPurpose, ) -> Result<CheckedSignTask, SignTaskError> { let variant = match self { WireSignTask::Test { message } => { // We allow any kind of key to sign a test message SignTask::Test { message } } WireSignTask::Nostr { event } => { if !matches!(purpose, KeyPurpose::Nostr) { return Err(SignTaskError::WrongPurpose); } SignTask::Nostr { event } } WireSignTask::BitcoinTransaction(tx_template) => { let network = match purpose { KeyPurpose::Bitcoin(network) => network, _ => return Err(SignTaskError::WrongPurpose), }; let non_matching_key = tx_template.inputs().iter().find_map(|input| { let owner = input.owner().local_owner()?; if owner.master_appkey != master_appkey { Some(owner.master_appkey) } else { None } }); if let Some(non_matching_key) = non_matching_key { return Err(SignTaskError::WrongKey { got: Box::new(non_matching_key), expected: Box::new(master_appkey), }); } if !tx_template.has_any_inputs_to_sign() { return Err(SignTaskError::NothingToSign); } if tx_template.fee().is_none() { return Err(SignTaskError::InvalidBitcoinTransaction); } SignTask::BitcoinTransaction { tx_template, network, } } }; Ok(CheckedSignTask { master_appkey, inner: variant, }) } } impl CheckedSignTask { pub fn into_inner(self) -> SignTask { self.inner } pub fn verify_final_signatures<NG>( &self, schnorr: &Schnorr<sha2::Sha256, NG>, signatures: &[Signature], ) -> bool { self.sign_items().iter().enumerate().all(|(i, item)| { item.verify_final_signature(schnorr, self.master_appkey, &signatures[i]) }) } pub fn sign_items(&self) -> Vec<SignItem> { match &self.inner { SignTask::Test { message } => vec![SignItem { message: message.as_bytes().to_vec(), app_tweak: AppTweak::TestMessage, }], SignTask::Nostr { event } => vec![SignItem { message: event.hash_bytes.clone(), app_tweak: AppTweak::Nostr, }], SignTask::BitcoinTransaction { tx_template, .. } => tx_template .iter_sighashes_of_locally_owned_inputs() .map(|(owner, sighash)| { assert_eq!( owner.master_appkey, self.master_appkey, "we should have checked this" ); SignItem { message: sighash.as_raw_hash().to_byte_array().to_vec(), app_tweak: AppTweak::Bitcoin(owner.bip32_path), } }) .collect(), } } } #[derive(Clone, Debug, bincode::Encode, bincode::Decode, PartialEq)] pub struct SignItem { pub message: Vec<u8>, pub app_tweak: AppTweak, } impl SignItem { pub fn verify_final_signature<NG>( &self, schnorr: &Schnorr<sha2::Sha256, NG>, master_appkey: MasterAppkey, signature: &Signature, ) -> bool { let derived_key = self.app_tweak.derive_xonly_key(&master_appkey.to_xpub()); self.schnorr_fun_message(); schnorr.verify(&derived_key, self.schnorr_fun_message(), signature) } pub fn schnorr_fun_message(&self) -> schnorr_fun::Message<'_> { match self.app_tweak { AppTweak::TestMessage => Message::new("frostsnap-test", &self.message[..]), AppTweak::Bitcoin(_) => Message::raw(&self.message[..]), AppTweak::Nostr => Message::raw(&self.message[..]), } } } #[derive(Clone, Debug)] pub enum SignTaskError { WrongKey { got: Box<MasterAppkey>, expected: Box<MasterAppkey>, }, WrongPurpose, InvalidBitcoinTransaction, NothingToSign, } impl core::fmt::Display for SignTaskError { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { SignTaskError::WrongKey { got, expected } => write!( f, "sign task was for key {expected} but got an item for key {got}", ), SignTaskError::InvalidBitcoinTransaction => { write!(f, "Bitcoin transaction input value was less than outputs") } SignTaskError::NothingToSign => { write!(f, "Transaction has no inputs that belong to this wallet") } SignTaskError::WrongPurpose => { write!( f, "Coordinator tried to use key for something other than its intended purpose" ) } } } } #[cfg(feature = "std")] impl std::error::Error for SignTaskError {}
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/src/device_nonces.rs
frostsnap_core/src/device_nonces.rs
use crate::{ device::DeviceSecretDerivation, nonce_stream::{CoordNonceStreamState, NonceStreamId, NonceStreamSegment}, SignSessionId, Versioned, }; use alloc::vec::Vec; use chacha20::{ cipher::{KeyIvInit, StreamCipher}, ChaCha20, }; use rand_core::RngCore; use schnorr_fun::{ binonce, frost::{NonceKeyPair, PairedSecretShare, PartySignSession, SignatureShare}, fun::prelude::*, }; /// A job that generates nonces incrementally, can be polled for work #[derive(Clone, Debug)] pub struct NonceJob { pub stream_id: NonceStreamId, seed_material: RatchetSeedMaterial, index: u32, target_index: u32, nonces: Vec<binonce::Nonce>, skip_to: u32, } impl NonceJob { /// Do one unit of work - generate a single binonce pub fn do_work(&mut self, device_hmac: &mut impl DeviceSecretDerivation) -> bool { if self.index >= self.target_index { return true; } let current_index = self.index; // Derive actual nonce seed from material AND eFuse HMAC let actual_seed_bytes = device_hmac.derive_nonce_seed(self.stream_id, current_index, &self.seed_material); let actual_seed = ChaChaSeed::from_bytes(actual_seed_bytes); let mut chacha_nonce = [0u8; 12]; chacha_nonce[0..core::mem::size_of_val(&current_index)] .copy_from_slice(current_index.to_le_bytes().as_ref()); let mut chacha = ChaCha20::new(actual_seed.as_bytes().into(), &chacha_nonce.into()); // Generate the next seed material (ratchet forward) let mut next_seed_material = [0u8; 32]; chacha.apply_keystream(&mut next_seed_material); let mut secret_nonce_bytes = [0u8; 64]; chacha.apply_keystream(&mut secret_nonce_bytes); let secret_nonce = binonce::SecretNonce::from_bytes(secret_nonce_bytes) .expect("computationally unreachable"); // Update state for next iteration self.seed_material = next_seed_material; self.index += 1; // NOTE: This guard means that some do_work calls will go much faster // than others but that's ok. The point of do_work is create an upper // bound on how much work can be done at a time. if current_index >= self.skip_to { self.nonces .push(NonceKeyPair::from_secret(secret_nonce).public()); } self.index >= self.target_index } /// Run the task synchronously until completion pub fn run_until_finished(&mut self, device_hmac: &mut impl DeviceSecretDerivation) { while !self.do_work(device_hmac) {} } /// Convert completed task into a NonceStreamSegment pub fn into_segment(self) -> NonceStreamSegment { assert!( self.index >= self.target_index, "into_segment called on unfinished NonceJob (generated {}/{} nonces)", self.index - self.skip_to, self.target_index - self.skip_to ); NonceStreamSegment { stream_id: self.stream_id, index: self.skip_to, nonces: self.nonces.into(), } } } /// A batch of nonce generation jobs that will produce a single NonceResponse #[derive(Clone, Debug)] pub struct NonceJobBatch { tasks: Vec<NonceJob>, current_task_index: usize, } impl NonceJobBatch { pub fn new(tasks: Vec<NonceJob>) -> Self { Self { tasks, current_task_index: 0, } } /// Do one unit of work - generate a single nonce from the current task pub fn do_work(&mut self, device_hmac: &mut impl DeviceSecretDerivation) -> bool { if let Some(task) = self.tasks.get_mut(self.current_task_index) { if task.do_work(device_hmac) { // Current task finished, move to next self.current_task_index += 1; } } // Return true when ALL tasks are complete self.current_task_index >= self.tasks.len() } /// Run all tasks synchronously until completion pub fn run_until_finished(&mut self, device_hmac: &mut impl DeviceSecretDerivation) { while !self.do_work(device_hmac) {} } /// Convert completed batch into NonceStreamSegments pub fn into_segments(self) -> Vec<NonceStreamSegment> { assert!( self.current_task_index >= self.tasks.len(), "into_segments called on unfinished NonceJobBatch ({}/{} tasks complete)", self.current_task_index, self.tasks.len() ); self.tasks.into_iter().map(|t| t.into_segment()).collect() } } /// Raw seed material that gets ratcheted forward and stored between uses. /// This is passed through HMAC to derive the actual ChaChaSeed. pub type RatchetSeedMaterial = [u8; 32]; #[derive(bincode::Encode, bincode::Decode, Copy, Clone, Debug, PartialEq)] pub struct ChaChaSeed([u8; 32]); impl ChaChaSeed { pub fn new(rng: &mut impl RngCore) -> Self { let mut seed = [0u8; 32]; rng.fill_bytes(&mut seed); Self(seed) } /// Only for deserialization or when we ratchet up pub fn from_bytes(bytes: [u8; 32]) -> Self { Self(bytes) } pub fn as_bytes(&self) -> &[u8; 32] { &self.0 } } #[derive(Clone, Debug, PartialEq, bincode::Encode, bincode::Decode)] pub struct SecretNonceSlot { pub index: u32, pub nonce_stream_id: NonceStreamId, pub ratchet_prg_seed_material: RatchetSeedMaterial, /// for clearing slots based on least recently used pub last_used: u32, pub signing_state: Option<SigningState>, } #[derive(Clone, Debug, PartialEq, bincode::Encode, bincode::Decode)] pub struct SigningState { pub session_id: SignSessionId, pub signature_shares: Vec<SignatureShare>, } pub trait NonceStreamSlot { fn read_slot_versioned(&mut self) -> Option<Versioned<SecretNonceSlot>>; fn write_slot_versioned(&mut self, value: Versioned<&SecretNonceSlot>); fn read_slot(&mut self) -> Option<SecretNonceSlot> { match self.read_slot_versioned()? { Versioned::V0(v) => Some(v), } } fn write_slot(&mut self, value: &SecretNonceSlot) { self.write_slot_versioned(Versioned::V0(value)) } fn initialize(&mut self, stream_id: NonceStreamId, last_used: u32, rng: &mut impl RngCore) { let mut ratchet_prg_seed_material: RatchetSeedMaterial = [0u8; 32]; rng.fill_bytes(&mut ratchet_prg_seed_material); let value = SecretNonceSlot { index: 0, nonce_stream_id: stream_id, ratchet_prg_seed_material, last_used, signing_state: None, }; self.write_slot(&value); } fn reconcile_coord_nonce_stream_state( &mut self, state: CoordNonceStreamState, nonce_batch_size: u32, ) -> Option<NonceJob> { let value = self.read_slot()?; let our_index = value.index; if our_index > state.index || state.remaining < nonce_batch_size { Some(value.nonce_task(None, nonce_batch_size as usize)) } else if our_index == state.index { None } else { Some(value.nonce_task(None, (state.index - our_index) as usize)) } } fn nonce_stream_id(&mut self) -> Option<NonceStreamId> { self.read_slot().map(|value| value.nonce_stream_id) } fn sign_guaranteeing_nonces_destroyed( &mut self, session_id: SignSessionId, coord_nonce_state: CoordNonceStreamState, last_used: u32, sessions: impl IntoIterator<Item = (PairedSecretShare<EvenY>, PartySignSession)>, device_hmac: &mut impl DeviceSecretDerivation, nonce_batch_size: u32, ) -> Result<(Vec<SignatureShare>, Option<NonceJob>), NoncesUnavailable> { let slot_value = self .read_slot() .expect("cannot sign with uninitialized slot"); assert_eq!( coord_nonce_state.stream_id, slot_value.nonce_stream_id, "wrong stream id" ); // Check if we have cached signatures for this session first let with_signatures = match &slot_value.signing_state { Some(SigningState { session_id: saved_session_id, .. }) if *saved_session_id == session_id => { // We've already got the signatures for this session on flash so we don't need to // sign. But this doesn't mean we don't need to write it to flash again. We don't // know that the previous state was erased. So we may redundantly rewrite it but // that's ok. slot_value } _ => { // Only check nonce availability if we're not using cached signatures if coord_nonce_state.index < slot_value.index { return Err(NoncesUnavailable::IndexUsed { current: slot_value.index, requested: coord_nonce_state.index, }); } let mut nonce_iter = slot_value .iter_secret_nonces(device_hmac) .skip((coord_nonce_state.index - slot_value.index) as usize); let mut signature_shares = vec![]; let mut next_prg_state: Option<(u32, RatchetSeedMaterial)> = None; for (secret_share, session) in sessions.into_iter() { let (current_index, secret_nonce, next_seed_material) = nonce_iter .next() .expect("tried to sign with nonces out of range"); let next_index = current_index + 1; next_prg_state = Some((next_index, next_seed_material)); let signature_share = session.sign(&secret_share, secret_nonce); // TODO: verify the signature share as a sanity check signature_shares.push(signature_share); } if signature_shares.is_empty() { panic!("sign sessions must not be empty"); } let (next_index, next_prg_seed_material) = next_prg_state.unwrap(); SecretNonceSlot { nonce_stream_id: slot_value.nonce_stream_id, index: next_index, last_used, ratchet_prg_seed_material: next_prg_seed_material, signing_state: Some(SigningState { session_id, signature_shares, }), } } }; self.write_slot(&with_signatures); // XXX Read the slot back in to be 100% certain it was written let read_back_state = self.read_slot().expect("guaranteed"); assert_eq!( read_back_state, with_signatures, "signature shares should have been read the same as written" ); let signature_shares = read_back_state .signing_state .expect("guaranteed") .signature_shares; let replenishment = self.reconcile_coord_nonce_stream_state(coord_nonce_state, nonce_batch_size); Ok((signature_shares, replenishment)) } } #[derive(Clone, Debug, PartialEq)] pub struct AbSlots<S> { slots: Vec<S>, last_used: u32, } impl<S: NonceStreamSlot> AbSlots<S> { pub fn new(mut slots: Vec<S>) -> Self { let last_used = slots .iter_mut() .filter_map(|slot| slot.read_slot().map(|v| v.last_used)) .max() .unwrap_or(0); Self { slots: slots.into_iter().collect(), last_used, } } pub fn sign_guaranteeing_nonces_destroyed( &mut self, session_id: SignSessionId, coord_nonce_state: CoordNonceStreamState, sessions: impl IntoIterator<Item = (PairedSecretShare<EvenY>, PartySignSession)>, device_hmac: &mut impl DeviceSecretDerivation, nonce_batch_size: u32, ) -> Result<(Vec<SignatureShare>, Option<NonceJob>), NoncesUnavailable> { let last_used = self.last_used + 1; let slot = self .get(coord_nonce_state.stream_id) .ok_or(NoncesUnavailable::Overflow)?; // Using Overflow as a placeholder for "stream not found" let out = slot.sign_guaranteeing_nonces_destroyed( session_id, coord_nonce_state, last_used, sessions, device_hmac, nonce_batch_size, )?; self.last_used = last_used; Ok(out) } fn increment_last_used(&mut self) -> u32 { self.last_used += 1; self.last_used } pub fn get_or_create(&mut self, stream_id: NonceStreamId, rng: &mut impl RngCore) -> &mut S { // the algorithm is to find the first empty slot or to choose the one with the lowest `last_used` let mut i = 0; let mut lowest_last_used = u32::MAX; let mut idx_lowest_last_used = 0; let last_used = self.increment_last_used(); let found = loop { if i >= self.slots.len() { break None; } let ab_slot = &mut self.slots[i]; let value = ab_slot.read_slot(); match value { Some(value) => { if value.nonce_stream_id == stream_id { break Some(i); } else if value.last_used < lowest_last_used { idx_lowest_last_used = i; lowest_last_used = value.last_used; } } None => { ab_slot.initialize(stream_id, last_used, rng); break Some(i); } } i += 1; }; match found { Some(i) => &mut self.slots[i], None => { let ab_slot = &mut self.slots[idx_lowest_last_used]; ab_slot.initialize(stream_id, last_used, rng); ab_slot } } } pub fn get(&mut self, stream_id: NonceStreamId) -> Option<&mut S> { //XXX: clippy is wrong about this #[allow(clippy::manual_find)] for slot in &mut self.slots { if slot.nonce_stream_id() == Some(stream_id) { return Some(slot); } } None } pub fn all_stream_ids(&mut self) -> impl Iterator<Item = NonceStreamId> + '_ { self.slots .iter_mut() .filter_map(|slot| slot.nonce_stream_id()) } pub fn total_slots(&self) -> usize { self.slots.len() } } impl SecretNonceSlot { fn iter_secret_nonces<'a>( &'a self, device_hmac: &'a mut impl DeviceSecretDerivation, ) -> impl Iterator<Item = (u32, binonce::SecretNonce, RatchetSeedMaterial)> + 'a { let mut seed_material = self.ratchet_prg_seed_material; let mut index = self.index; core::iter::from_fn(move || { if index == u32::MAX { return None; } let current_index = index; // Derive actual nonce seed from material AND eFuse HMAC let actual_seed_bytes = device_hmac.derive_nonce_seed(self.nonce_stream_id, current_index, &seed_material); let actual_seed = ChaChaSeed::from_bytes(actual_seed_bytes); let mut chacha_nonce = [0u8; 12]; chacha_nonce[0..core::mem::size_of_val(&current_index)] .copy_from_slice(current_index.to_le_bytes().as_ref()); let mut chacha = ChaCha20::new(actual_seed.as_bytes().into(), &chacha_nonce.into()); // Generate the next seed material (ratchet forward) let mut next_seed_material = [0u8; 32]; chacha.apply_keystream(&mut next_seed_material); let mut secret_nonce_bytes = [0u8; 64]; chacha.apply_keystream(&mut secret_nonce_bytes); let secret_nonce = binonce::SecretNonce::from_bytes(secret_nonce_bytes) .expect("computationally unreachable"); seed_material = next_seed_material; index += 1; Some((current_index, secret_nonce, next_seed_material)) }) } pub fn are_nonces_available(&self, index: u32, n: u32) -> Result<(), NoncesUnavailable> { let current = self.index; let requested = index; if requested < current { return Err(NoncesUnavailable::IndexUsed { current, requested }); } if index.saturating_add(n) == u32::MAX { return Err(NoncesUnavailable::Overflow); } Ok(()) } pub fn nonce_task(&self, start: Option<u32>, length: usize) -> NonceJob { let start = start.unwrap_or(self.index); if start < self.index { panic!("can't iterate erased nonces"); } let last = start.saturating_add(length.try_into().expect("length not too big")); if last == u32::MAX { panic!("cannot have an index at u32::MAX"); } NonceJob { stream_id: self.nonce_stream_id, seed_material: self.ratchet_prg_seed_material, // Start from the slot's current index, not the requested start // The task will skip forward as needed index: self.index, target_index: last, nonces: Vec::with_capacity(length), skip_to: start, } } } #[derive(Clone, Debug, PartialEq, Default)] pub struct MemoryNonceSlot { inner: Option<Versioned<SecretNonceSlot>>, } impl NonceStreamSlot for MemoryNonceSlot { fn read_slot_versioned(&mut self) -> Option<Versioned<SecretNonceSlot>> { self.inner.clone() } fn write_slot_versioned(&mut self, value: Versioned<&SecretNonceSlot>) { self.inner = Some(value.cloned()) } } #[derive(Clone, Debug)] pub enum NoncesUnavailable { IndexUsed { current: u32, requested: u32 }, Overflow, } impl core::fmt::Display for NoncesUnavailable { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { NoncesUnavailable::IndexUsed { current, requested } => { write!( f, "Attempt to reuse nonces! Current index: {current}. Requested: {requested}." ) } NoncesUnavailable::Overflow => { write!(f, "nonces were requested beyond the final index") } } } } #[cfg(feature = "std")] impl std::error::Error for NoncesUnavailable {}
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/src/message.rs
frostsnap_core/src/message.rs
use crate::device::KeyPurpose; use crate::nonce_stream::CoordNonceStreamState; use crate::{ AccessStructureId, AccessStructureRef, CheckedSignTask, CoordShareDecryptionContrib, Gist, KeygenId, MasterAppkey, SessionHash, ShareImage, SignSessionId, SignTaskError, Vec, }; use crate::{DeviceId, EnterPhysicalId, Kind, WireSignTask}; use alloc::{ boxed::Box, collections::{BTreeMap, BTreeSet}, string::String, }; use frostsnap_macros::Kind; use schnorr_fun::binonce; use schnorr_fun::frost::SharedKey; use schnorr_fun::frost::{chilldkg::certpedpop, ShareIndex}; use schnorr_fun::fun::prelude::*; use schnorr_fun::fun::Point; use schnorr_fun::Signature; use sha2::digest::Update; use sha2::Digest; pub mod keygen; pub mod screen_verify; pub mod signing; pub use keygen::Keygen; #[derive(Clone, Debug)] #[must_use] pub enum DeviceSend { ToUser(Box<crate::device::DeviceToUserMessage>), ToCoordinator(Box<DeviceToCoordinatorMessage>), } #[derive(Clone, Debug, bincode::Encode, bincode::Decode, Kind)] pub enum CoordinatorToDeviceMessage { KeyGen(keygen::Keygen), #[delegate_kind] Signing(signing::CoordinatorSigning), #[delegate_kind] Restoration(CoordinatorRestoration), #[delegate_kind] ScreenVerify(screen_verify::ScreenVerify), } #[derive(Clone, Debug, bincode::Encode, bincode::Decode, Kind)] pub enum CoordinatorRestoration { EnterPhysicalBackup { enter_physical_id: EnterPhysicalId, }, SavePhysicalBackup { share_image: ShareImage, key_name: String, purpose: KeyPurpose, threshold: u16, }, /// Consolidate the saved secret share backup into a properly encrypted backup. Consolidate(Box<ConsolidateBackup>), DisplayBackup { access_structure_ref: AccessStructureRef, coord_share_decryption_contrib: CoordShareDecryptionContrib, party_index: ShareIndex, root_shared_key: SharedKey, }, RequestHeldShares, SavePhysicalBackup2(Box<HeldShare2>), } #[derive(Clone, Debug, bincode::Encode, bincode::Decode, PartialEq)] pub struct ConsolidateBackup { pub share_index: ShareIndex, pub root_shared_key: SharedKey, pub key_name: String, pub purpose: KeyPurpose, } #[derive(Clone, Debug, bincode::Encode, bincode::Decode, PartialEq)] pub struct GroupSignReq<ST = WireSignTask> { pub parties: BTreeSet<ShareIndex>, pub agg_nonces: Vec<binonce::Nonce<Zero>>, pub sign_task: ST, pub access_structure_id: AccessStructureId, } impl<ST> GroupSignReq<ST> { pub fn n_signatures(&self) -> usize { self.agg_nonces.len() } } impl GroupSignReq<WireSignTask> { pub fn check( self, rootkey: Point, purpose: KeyPurpose, ) -> Result<GroupSignReq<CheckedSignTask>, SignTaskError> { let master_appkey = MasterAppkey::derive_from_rootkey(rootkey); Ok(GroupSignReq { parties: self.parties, agg_nonces: self.agg_nonces, sign_task: self.sign_task.check(master_appkey, purpose)?, access_structure_id: self.access_structure_id, }) } pub fn session_id(&self) -> SignSessionId { let bytes = bincode::encode_to_vec(self, bincode::config::standard()).unwrap(); SignSessionId(sha2::Sha256::new().chain(bytes).finalize().into()) } } impl Gist for CoordinatorToDeviceMessage { fn gist(&self) -> String { crate::Kind::kind(self).into() } } #[derive(Clone, Debug, bincode::Encode, bincode::Decode, Kind)] pub enum DeviceToCoordinatorMessage { KeyGen(keygen::DeviceKeygen), #[delegate_kind] Signing(signing::DeviceSigning), #[delegate_kind] Restoration(DeviceRestoration), } #[derive(Clone, Debug, bincode::Encode, bincode::Decode, Kind)] pub enum DeviceRestoration { PhysicalEntered(EnteredPhysicalBackup), PhysicalSaved(ShareImage), FinishedConsolidation { access_structure_ref: AccessStructureRef, share_index: ShareIndex, }, HeldShares(Vec<HeldShare>), HeldShares2(Vec<HeldShare2>), } #[derive(Clone, Debug, bincode::Encode, bincode::Decode, PartialEq)] pub struct HeldShare { pub access_structure_ref: Option<AccessStructureRef>, pub share_image: ShareImage, pub threshold: u16, pub key_name: String, pub purpose: KeyPurpose, } #[derive(Clone, Debug, bincode::Encode, bincode::Decode, PartialEq)] pub struct HeldShare2 { pub access_structure_ref: Option<AccessStructureRef>, pub share_image: ShareImage, pub threshold: Option<u16>, pub key_name: Option<String>, pub purpose: Option<KeyPurpose>, pub needs_consolidation: bool, } impl From<HeldShare> for HeldShare2 { fn from(legacy: HeldShare) -> Self { HeldShare2 { access_structure_ref: legacy.access_structure_ref, share_image: legacy.share_image, threshold: Some(legacy.threshold), key_name: Some(legacy.key_name), purpose: Some(legacy.purpose), needs_consolidation: legacy.access_structure_ref.is_none(), } } } #[derive(Clone, Debug, bincode::Encode, bincode::Decode, PartialEq)] pub struct KeyGenResponse { pub keygen_id: KeygenId, pub input: Box<certpedpop::KeygenInput>, } impl Gist for DeviceToCoordinatorMessage { fn gist(&self) -> String { Kind::kind(self).into() } } #[derive(Clone, Copy, Debug, bincode::Encode, bincode::Decode, PartialEq)] pub struct EnteredPhysicalBackup { pub enter_physical_id: EnterPhysicalId, pub share_image: ShareImage, } #[derive(Clone, Debug, Copy, bincode::Encode, bincode::Decode, PartialEq)] /// An encoded signature that can pass ffi boundries easily pub struct EncodedSignature(pub [u8; 64]); impl EncodedSignature { pub fn new(signature: Signature) -> Self { Self(signature.to_bytes()) } pub fn into_decoded(self) -> Option<Signature> { Signature::from_bytes(self.0) } } #[derive(Clone, Debug)] pub enum TaskKind { KeyGen, Sign, DisplayBackup, CheckBackup, VerifyAddress, } #[derive(Debug, Clone, bincode::Encode, bincode::Decode, PartialEq)] pub struct RequestSign { /// Common public parts of the signing request pub group_sign_req: GroupSignReq, /// Private part of the signing request that only the device should be able to access pub device_sign_req: DeviceSignReq, } #[derive(Debug, Clone, bincode::Encode, bincode::Decode, PartialEq)] pub struct DeviceSignReq { /// Not secret but device specific. No one needs to know this other than device. pub nonces: CoordNonceStreamState, /// the rootkey - semi secret. Should not be posted publicly. Only the device should receive this. pub rootkey: Point, /// The share decryption contribution from the coordinator. pub coord_share_decryption_contrib: CoordShareDecryptionContrib, } #[derive(Clone, Debug, bincode::Encode, bincode::Decode)] pub struct KeyGenAck { pub ack_session_hash: SessionHash, pub keygen_id: KeygenId, } impl IntoIterator for KeyGenAck { type Item = DeviceSend; type IntoIter = core::iter::Once<DeviceSend>; fn into_iter(self) -> Self::IntoIter { core::iter::once(DeviceSend::ToCoordinator(Box::new(self.into()))) } } impl From<KeyGenAck> for DeviceToCoordinatorMessage { fn from(value: KeyGenAck) -> Self { DeviceToCoordinatorMessage::KeyGen(keygen::DeviceKeygen::Ack(value)) } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/src/bitcoin_transaction.rs
frostsnap_core/src/bitcoin_transaction.rs
use alloc::vec::Vec; use alloc::{boxed::Box, collections::BTreeMap}; use bitcoin::{ consensus::Encodable, hashes::{sha256d, Hash}, key::TweakedPublicKey, sighash::SighashCache, OutPoint, Script, ScriptBuf, TapSighash, TxOut, Txid, }; use crate::{ tweak::{AppTweak, BitcoinBip32Path}, MasterAppkey, }; /// Invalid state free representation of a transaction #[derive(Clone, Debug, bincode::Encode, bincode::Decode, Eq, PartialEq, Hash)] pub struct TransactionTemplate { #[bincode(with_serde)] version: bitcoin::blockdata::transaction::Version, #[bincode(with_serde)] lock_time: bitcoin::absolute::LockTime, inputs: Vec<Input>, outputs: Vec<Output>, } pub struct PushInput<'a> { pub prev_txout: PrevTxOut<'a>, pub sequence: bitcoin::Sequence, } impl<'a> PushInput<'a> { pub fn spend_tx_output(transaction: &'a bitcoin::Transaction, vout: u32) -> Self { Self { prev_txout: PrevTxOut::Full { transaction, vout }, sequence: bitcoin::Sequence::ENABLE_RBF_NO_LOCKTIME, } } pub fn spend_outpoint(txout: &'a TxOut, outpoint: OutPoint) -> Self { Self { prev_txout: PrevTxOut::Partial { txout, outpoint }, sequence: bitcoin::Sequence::ENABLE_RBF_NO_LOCKTIME, } } pub fn with_sequence(mut self, sequence: bitcoin::Sequence) -> Self { self.sequence = sequence; self } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum PrevTxOut<'a> { Full { transaction: &'a bitcoin::Transaction, vout: u32, }, Partial { txout: &'a TxOut, outpoint: OutPoint, }, } impl<'a> PrevTxOut<'a> { pub fn txout(&self) -> &'a TxOut { match self { PrevTxOut::Full { transaction, vout } => &transaction.output[*vout as usize], PrevTxOut::Partial { txout, .. } => txout, } } pub fn outpoint(&self) -> OutPoint { match self { PrevTxOut::Full { transaction, vout } => OutPoint { txid: transaction.compute_txid(), vout: *vout, }, PrevTxOut::Partial { outpoint, .. } => *outpoint, } } } impl Default for TransactionTemplate { fn default() -> Self { Self::new() } } impl TransactionTemplate { pub fn new() -> Self { Self { version: bitcoin::blockdata::transaction::Version::TWO, lock_time: bitcoin::absolute::LockTime::ZERO, inputs: Default::default(), outputs: Default::default(), } } pub fn set_version(&mut self, version: bitcoin::blockdata::transaction::Version) { self.version = version; } pub fn set_lock_time(&mut self, lock_time: bitcoin::absolute::LockTime) { self.lock_time = lock_time; } pub fn txid(&self) -> Txid { self.to_rust_bitcoin_tx().compute_txid() } pub fn push_foreign_input(&mut self, input: PushInput) { let txout = input.prev_txout.txout(); self.inputs.push(Input { outpoint: input.prev_txout.outpoint(), owner: SpkOwner::Foreign(txout.script_pubkey.clone()), value: txout.value.to_sat(), sequence: input.sequence, }) } pub fn push_owned_input( &mut self, input: PushInput<'_>, owner: LocalSpk, ) -> Result<(), Box<SpkDoesntMatchPathError>> { let txout = input.prev_txout.txout(); let expected_spk = owner.spk(); if txout.script_pubkey != expected_spk { return Err(Box::new(SpkDoesntMatchPathError { got: txout.script_pubkey.clone(), expected: expected_spk, path: owner .bip32_path .path_segments_from_bitcoin_appkey() .collect(), master_appkey: owner.master_appkey, })); } self.inputs.push(Input { outpoint: input.prev_txout.outpoint(), owner: SpkOwner::Local(owner), value: txout.value.to_sat(), sequence: input.sequence, }); Ok(()) } pub fn push_imaginary_owned_input(&mut self, owner: LocalSpk, value: bitcoin::Amount) { let txout = TxOut { value, script_pubkey: owner.spk(), }; let mut engine = sha256d::Hash::engine(); txout.consensus_encode(&mut engine).unwrap(); let txid = Txid::from_engine(engine); let outpoint = OutPoint { txid, vout: 0 }; self.push_owned_input(PushInput::spend_outpoint(&txout, outpoint), owner) .expect("unreachable"); } pub fn push_foreign_output(&mut self, txout: TxOut) { self.outputs.push(Output { owner: SpkOwner::Foreign(txout.script_pubkey), value: txout.value.to_sat(), }); } pub fn push_owned_output(&mut self, value: bitcoin::Amount, owner: LocalSpk) { self.outputs.push(Output { owner: SpkOwner::Local(owner), value: value.to_sat(), }); } pub fn to_rust_bitcoin_tx(&self) -> bitcoin::Transaction { bitcoin::Transaction { version: self.version, lock_time: self.lock_time, input: self .inputs .iter() .map(|input| bitcoin::TxIn { previous_output: input.outpoint, sequence: input.sequence, ..Default::default() }) .collect(), output: self.outputs.iter().map(|output| output.txout()).collect(), } } pub fn inputs(&self) -> &[Input] { &self.inputs } pub fn outputs(&self) -> &[Output] { &self.outputs } pub fn iter_sighash(&self) -> impl Iterator<Item = TapSighash> { let tx = self.to_rust_bitcoin_tx(); let mut sighash_cache = SighashCache::new(tx); let schnorr_sighashty = bitcoin::sighash::TapSighashType::Default; let prevouts = self.inputs.iter().map(Input::txout).collect::<Vec<_>>(); (0..self.inputs.len()).map(move |i| { sighash_cache .taproot_key_spend_signature_hash( i, &bitcoin::sighash::Prevouts::All(&prevouts), schnorr_sighashty, ) .expect("inputs are right length") }) } pub fn iter_sighashes_of_locally_owned_inputs( &self, ) -> impl Iterator<Item = (LocalSpk, TapSighash)> + '_ { self.inputs .iter() .zip(self.iter_sighash()) .filter_map(|(input, sighash)| { let owner = input.owner.local_owner()?.clone(); Some((owner, sighash)) }) } pub fn iter_locally_owned_inputs(&self) -> impl Iterator<Item = (usize, &Input, &LocalSpk)> { self.inputs .iter() .enumerate() .filter_map(|(i, input)| Some((i, input, input.owner.local_owner()?))) } pub fn iter_locally_owned_outputs(&self) -> impl Iterator<Item = (usize, &Output, &LocalSpk)> { self.outputs .iter() .enumerate() .filter_map(|(i, output)| Some((i, output, output.owner.local_owner()?))) } /// Returns true if this transaction has any inputs that need signing by this wallet. pub fn has_any_inputs_to_sign(&self) -> bool { self.inputs .iter() .any(|input| input.owner.local_owner().is_some()) } pub fn fee(&self) -> Option<u64> { self.inputs .iter() .map(|input| input.value) .sum::<u64>() .checked_sub(self.outputs.iter().map(|output| output.value).sum()) } pub fn feerate(&self) -> Option<f64> { let mut tx = self.to_rust_bitcoin_tx(); for (i, input) in self.inputs.iter().enumerate() { if input.owner().local_owner().is_some() { tx.input[i].witness.push([0u8; 64]); } else { return None; } } let vbytes = tx.weight().to_vbytes_ceil() as f64; Some(self.fee()? as f64 / vbytes) } pub fn net_value(&self) -> BTreeMap<RootOwner, i64> { let mut spk_to_value: BTreeMap<RootOwner, i64> = Default::default(); for input in &self.inputs { let value = spk_to_value.entry(input.owner.root_owner()).or_default(); *value -= i64::try_from(input.value).expect("input ridiciously large"); } for output in &self.outputs { let value = spk_to_value.entry(output.owner.root_owner()).or_default(); *value += i64::try_from(output.value).expect("input ridiciously large"); } spk_to_value } pub fn foreign_recipients(&self) -> impl Iterator<Item = (&Script, u64)> { self.outputs .iter() .filter_map(|output| match &output.owner { SpkOwner::Foreign(spk) => Some((spk.as_script(), output.value)), _ => None, }) } pub fn user_prompt(&self, network: bitcoin::Network) -> PromptSignBitcoinTx { let fee = bitcoin::Amount::from_sat( self.fee() .expect("transaction validity should have already been checked"), ); let foreign_recipients = self .foreign_recipients() .map(|(spk, value)| { ( bitcoin::Address::from_script(spk, network) .expect("has address representation"), bitcoin::Amount::from_sat(value), ) }) .collect::<Vec<_>>(); PromptSignBitcoinTx { foreign_recipients, fee, } } } #[derive(Clone, Debug, PartialEq)] pub struct PromptSignBitcoinTx { pub foreign_recipients: Vec<(bitcoin::Address, bitcoin::Amount)>, pub fee: bitcoin::Amount, } impl PromptSignBitcoinTx { /// Calculate the total amount being sent to foreign recipients pub fn total_sent(&self) -> bitcoin::Amount { self.foreign_recipients .iter() .map(|(_, amount)| *amount) .sum() } } #[derive(Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)] pub enum RootOwner { Local(MasterAppkey), Foreign(ScriptBuf), } /// The provided spk doesn't match what was derived from the derivation path #[derive(Debug, Clone)] pub struct SpkDoesntMatchPathError { pub got: ScriptBuf, pub expected: ScriptBuf, pub path: Vec<u32>, pub master_appkey: MasterAppkey, } impl core::fmt::Display for SpkDoesntMatchPathError { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "the script pubkey {:?} didn't match what we expected {:?} at derivation path {:?} from {}", self.got, self.expected, self.path, self.master_appkey) } } #[cfg(feature = "std")] impl std::error::Error for SpkDoesntMatchPathError {} #[derive(bincode::Decode, bincode::Encode, Clone, Debug, PartialEq, Eq, Hash)] pub struct Input { #[bincode(with_serde)] outpoint: OutPoint, value: u64, owner: SpkOwner, #[bincode(with_serde)] sequence: bitcoin::Sequence, } impl Input { pub fn outpoint(&self) -> OutPoint { self.outpoint } pub fn txout(&self) -> TxOut { TxOut { value: bitcoin::Amount::from_sat(self.value), script_pubkey: self.owner.spk(), } } pub fn raw_spk(&self) -> ScriptBuf { self.owner.spk() } pub fn owner(&self) -> &SpkOwner { &self.owner } } #[derive(bincode::Encode, bincode::Decode, Clone, Debug, PartialEq, Eq, Hash)] pub struct LocalSpk { pub master_appkey: MasterAppkey, pub bip32_path: BitcoinBip32Path, } impl LocalSpk { pub fn spk(&self) -> ScriptBuf { let expected_external_xonly = AppTweak::Bitcoin(self.bip32_path).derive_xonly_key(&self.master_appkey.to_xpub()); ScriptBuf::new_p2tr_tweaked(TweakedPublicKey::dangerous_assume_tweaked( expected_external_xonly.into(), )) } } #[derive(bincode::Encode, bincode::Decode, Clone, Debug, PartialEq, Eq, Hash)] pub struct Output { pub value: u64, pub owner: SpkOwner, } impl Output { pub fn txout(&self) -> TxOut { TxOut { value: bitcoin::Amount::from_sat(self.value), script_pubkey: self.owner.spk(), } } pub fn local_owner(&self) -> Option<&LocalSpk> { self.owner.local_owner() } pub fn owner(&self) -> &SpkOwner { &self.owner } } #[derive(bincode::Encode, bincode::Decode, Clone, Debug, PartialEq, Eq, Hash)] pub enum SpkOwner { Foreign(#[bincode(with_serde)] ScriptBuf), Local(LocalSpk), } impl SpkOwner { pub fn root_owner(&self) -> RootOwner { match self { SpkOwner::Foreign(spk) => RootOwner::Foreign(spk.clone()), SpkOwner::Local(local) => RootOwner::Local(local.master_appkey), } } pub fn spk(&self) -> ScriptBuf { match self { SpkOwner::Foreign(spk) => spk.clone(), SpkOwner::Local(owner) => owner.spk(), } } pub fn local_owner_key(&self) -> Option<MasterAppkey> { match self { SpkOwner::Foreign(_) => None, SpkOwner::Local(owner) => Some(owner.master_appkey), } } pub fn local_owner(&self) -> Option<&LocalSpk> { match self { SpkOwner::Foreign(_) => None, SpkOwner::Local(owner) => Some(owner), } } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/src/coordinator.rs
frostsnap_core/src/coordinator.rs
use crate::{ coord_nonces::{NonceCache, NotEnoughNonces}, device::{KeyPurpose, NONCE_BATCH_SIZE}, map_ext::*, message::{signing::OpenNonceStreams, *}, nonce_stream::{CoordNonceStreamState, NonceStreamId}, symmetric_encryption::{Ciphertext, SymmetricKey}, tweak::Xpub, AccessStructureId, AccessStructureKind, AccessStructureRef, ActionError, CoordShareDecryptionContrib, DeviceId, Error, Gist, KeyId, KeygenId, Kind, MasterAppkey, MessageResult, RestorationId, SessionHash, ShareImage, SignItem, SignSessionId, SignTaskError, WireSignTask, }; use alloc::{ borrow::ToOwned, boxed::Box, collections::{BTreeMap, BTreeSet, VecDeque}, string::String, vec::Vec, }; use core::fmt; use frostsnap_macros::Kind; use schnorr_fun::{ frost::{ self, chilldkg::certpedpop, CoordinatorSignSession, Frost, ShareIndex, SharedKey, SignatureShare, }, fun::{prelude::*, KeyPair}, Schnorr, Signature, }; use sha2::Sha256; use std::collections::{HashMap, HashSet}; use tracing::{event, Level}; mod coordinator_to_user; pub mod keys; pub mod restoration; pub mod signing; pub use coordinator_to_user::*; pub use keys::BeginKeygen; use signing::SigningMutation; pub const MIN_NONCES_BEFORE_REQUEST: u32 = NONCE_BATCH_SIZE / 2; #[derive(Debug, Clone, Default, PartialEq)] pub struct FrostCoordinator { keys: BTreeMap<KeyId, CoordFrostKey>, key_order: Vec<KeyId>, pending_keygens: HashMap<KeygenId, KeyGenState>, nonce_cache: NonceCache, mutations: VecDeque<Mutation>, active_signing_sessions: BTreeMap<SignSessionId, ActiveSignSession>, active_sign_session_order: Vec<SignSessionId>, finished_signing_sessions: BTreeMap<SignSessionId, FinishedSignSession>, restoration: restoration::State, pub keygen_fingerprint: schnorr_fun::frost::Fingerprint, } #[derive(Debug, Clone, bincode::Encode, bincode::Decode, PartialEq)] pub struct CoordFrostKey { pub key_id: KeyId, pub complete_key: CompleteKey, pub key_name: String, pub purpose: KeyPurpose, } #[derive(Debug, Clone, bincode::Encode, bincode::Decode, PartialEq)] pub struct CompleteKey { pub master_appkey: MasterAppkey, pub encrypted_rootkey: Ciphertext<33, Point>, pub access_structures: HashMap<AccessStructureId, CoordAccessStructure>, } #[derive(Debug, Clone, PartialEq)] pub struct ShareLocation { pub device_ids: Vec<DeviceId>, pub share_index: ShareIndex, pub key_name: String, pub key_purpose: KeyPurpose, pub key_state: KeyLocationState, } #[derive(Debug, Clone, PartialEq)] pub enum KeyLocationState { Complete { access_structure_ref: AccessStructureRef, }, Restoring { restoration_id: RestorationId, }, } impl CompleteKey { pub fn coord_share_decryption_contrib( &self, access_structure_id: AccessStructureId, device_id: DeviceId, encryption_key: SymmetricKey, ) -> Option<(Point, CoordShareDecryptionContrib)> { let root_shared_key = self.root_shared_key(access_structure_id, encryption_key)?; let share_index = *self .access_structures .get(&access_structure_id)? .device_to_share_index .get(&device_id)?; Some(( root_shared_key.public_key(), CoordShareDecryptionContrib::for_master_share(device_id, share_index, &root_shared_key), )) } pub fn root_shared_key( &self, access_structure_id: AccessStructureId, encryption_key: SymmetricKey, ) -> Option<SharedKey> { let access_structure = self.access_structures.get(&access_structure_id)?; let rootkey = self.encrypted_rootkey.decrypt(encryption_key)?; let mut poly = access_structure .app_shared_key .key .point_polynomial() .to_vec(); poly[0] = rootkey.mark_zero(); debug_assert!( MasterAppkey::derive_from_rootkey(rootkey) == access_structure.master_appkey() ); Some(SharedKey::from_poly(poly).non_zero().expect("invariant")) } } #[cfg(feature = "coordinator")] #[macro_export] macro_rules! fail { ($($fail:tt)*) => {{ tracing::event!( tracing::Level::ERROR, $($fail)* ); debug_assert!(false, $($fail)*); return None; }}; } impl CoordFrostKey { pub fn get_access_structure( &self, access_structure_id: AccessStructureId, ) -> Option<CoordAccessStructure> { self.complete_key .access_structures .get(&access_structure_id) .cloned() } pub fn access_structures(&self) -> impl Iterator<Item = CoordAccessStructure> + '_ { self.complete_key.access_structures.values().cloned() } pub fn master_access_structure(&self) -> CoordAccessStructure { self.access_structures().next().unwrap() } } impl FrostCoordinator { pub fn new() -> Self { Self::default() } pub fn mutate(&mut self, mutation: Mutation) { let kind = mutation.kind(); if let Some(reduced_mutation) = self.apply_mutation(mutation) { event!(Level::DEBUG, gist = reduced_mutation.gist(), "mutating"); self.mutations.push_back(reduced_mutation); } else { event!(Level::DEBUG, kind = kind, "ignoring mutation"); } } pub fn apply_mutation(&mut self, mutation: Mutation) -> Option<Mutation> { fn ensure_key<'a>( coord: &'a mut FrostCoordinator, complete_key: self::CompleteKey, key_name: &str, purpose: KeyPurpose, ) -> &'a mut CoordFrostKey { let key_id = complete_key.master_appkey.key_id(); let exists = coord.keys.contains_key(&key_id); let key = coord.keys.entry(key_id).or_insert_with(|| CoordFrostKey { key_id, complete_key, key_name: key_name.to_owned(), purpose, }); if !exists { coord.key_order.push(key_id); } key } use Mutation::*; match mutation { Keygen(keys::KeyMutation::NewKey { ref complete_key, ref key_name, purpose, }) => { ensure_key(self, complete_key.clone(), key_name, purpose); } Keygen(keys::KeyMutation::NewAccessStructure { ref shared_key, kind, }) => { let access_structure_id = AccessStructureId::from_app_poly(shared_key.key().point_polynomial()); let appkey = MasterAppkey::from_xpub_unchecked(shared_key); let key_id = appkey.key_id(); match self.keys.get_mut(&key_id) { Some(key_data) => { let exists = key_data .complete_key .access_structures .contains_key(&access_structure_id); if exists { return None; } key_data.complete_key.access_structures.insert( access_structure_id, CoordAccessStructure { app_shared_key: shared_key.clone(), device_to_share_index: Default::default(), kind, }, ); } None => { fail!("access structure added to non-existent key"); } } } Keygen(keys::KeyMutation::NewShare { access_structure_ref, device_id, share_index, }) => match self.keys.get_mut(&access_structure_ref.key_id) { Some(key_data) => { let complete_key = &mut key_data.complete_key; match complete_key .access_structures .get_mut(&access_structure_ref.access_structure_id) { Some(access_structure) => { let changed = access_structure .device_to_share_index .insert(device_id, share_index) != Some(share_index); if !changed { return None; } } None => { fail!( "share added to non-existent access structure {:?}", access_structure_ref ); } } } None => { fail!( "share added to non-existent key: {}", access_structure_ref.key_id ); } }, Keygen(keys::KeyMutation::DeleteKey(key_id)) => { self.keys.remove(&key_id)?; self.key_order.retain(|&entry| entry != key_id); self.restoration.clear_up_key_deletion(key_id); let sessions_to_delete = self .active_signing_sessions .iter() .filter(|(_, session)| session.key_id == key_id) .map(|(&key_id, _)| key_id) .collect::<Vec<_>>(); for session_id in sessions_to_delete { self.apply_mutation(Mutation::Signing(SigningMutation::CloseSignSession { session_id, finished: None, })); } } Signing(SigningMutation::NewNonces { device_id, ref nonce_segment, }) => { match self .nonce_cache .extend_segment(device_id, nonce_segment.clone()) { Ok(changed) => { if !changed { return None; } } Err(e) => fail!("failed to extend nonce segment: {e}"), } } Signing(SigningMutation::NewSigningSession(ref signing_session_state)) => { let ssid = signing_session_state.init.group_request.session_id(); self.active_signing_sessions .insert(ssid, signing_session_state.clone()); self.active_sign_session_order.push(ssid); } Signing(SigningMutation::GotSignatureSharesFromDevice { session_id, device_id, ref signature_shares, }) => { if let Some(session_state) = self.active_signing_sessions.get_mut(&session_id) { for (progress, share) in session_state.progress.iter_mut().zip(signature_shares) { progress.signature_shares.insert(device_id, *share); } } } Signing(SigningMutation::SentSignReq { session_id, device_id, }) => { if !self .active_signing_sessions .get_mut(&session_id)? .sent_req_to_device .insert(device_id) { return None; } } Signing(SigningMutation::CloseSignSession { session_id, ref finished, }) => { let (index, _) = self .active_sign_session_order .iter() .enumerate() .find(|(_, ssid)| **ssid == session_id)?; self.active_sign_session_order.remove(index); let session_state = self .active_signing_sessions .remove(&session_id) .expect("it existed in the order"); let n_sigs = session_state.init.group_request.n_signatures(); for (device_id, nonce_segment) in &session_state.init.nonces { if session_state.sent_req_to_device.contains(device_id) { let consume_to = nonce_segment .index .checked_add(n_sigs as _) .expect("no overflow"); self.nonce_cache .consume(*device_id, nonce_segment.stream_id, consume_to); } } if let Some(signatures) = finished { self.finished_signing_sessions.insert( session_id, FinishedSignSession { init: session_state.init, signatures: signatures.clone(), key_id: session_state.key_id, }, ); } } Signing(SigningMutation::ForgetFinishedSignSession { session_id }) => { self.finished_signing_sessions.remove(&session_id); } Restoration(inner) => { return self .restoration .apply_mutation_restoration(inner, self.keygen_fingerprint) .map(Mutation::Restoration); } } Some(mutation) } pub fn take_staged_mutations(&mut self) -> VecDeque<Mutation> { core::mem::take(&mut self.mutations) } pub fn staged_mutations(&self) -> &VecDeque<Mutation> { &self.mutations } pub fn iter_keys(&self) -> impl Iterator<Item = &CoordFrostKey> + '_ { self.key_order .iter() .map(|key_id| self.keys.get(key_id).expect("invariant")) } pub fn iter_access_structures(&self) -> impl Iterator<Item = CoordAccessStructure> + '_ { self.keys .iter() .flat_map(|(_, key_data)| key_data.access_structures()) } pub fn iter_shares( &self, encryption_key: SymmetricKey, ) -> impl Iterator<Item = (ShareImage, ShareLocation)> + '_ { let complete_wallet_shares = self .iter_access_structures() .filter_map(move |access_structure| { let access_structure_ref = access_structure.access_structure_ref(); self.root_shared_key(access_structure_ref, encryption_key) .map(|root_shared_key| { (access_structure, access_structure_ref, root_shared_key) }) }) .flat_map( move |(access_structure, access_structure_ref, root_shared_key)| { let key = self .keys .get(&access_structure_ref.key_id) .expect("must exist"); let key_name = key.key_name.clone(); let key_purpose = key.purpose; access_structure.share_index_to_devices().into_iter().map( move |(share_index, device_ids)| { let share_image = root_shared_key.share_image(share_index); ( share_image, ShareLocation { device_ids, share_index, key_name: key_name.clone(), key_purpose, key_state: KeyLocationState::Complete { access_structure_ref, }, }, ) }, ) }, ); let restoration_shares = self .restoration .restorations .values() .flat_map(|restoration| { let restoration_id = restoration.restoration_id; let key_name = restoration.key_name.clone(); let key_purpose = restoration.key_purpose; restoration .access_structure .share_image_to_devices() .into_iter() .map(move |(share_image, device_ids)| { ( share_image, ShareLocation { device_ids, share_index: share_image.index, key_name: key_name.clone(), key_purpose, key_state: KeyLocationState::Restoring { restoration_id }, }, ) }) }); complete_wallet_shares.chain(restoration_shares) } pub fn find_share( &self, share_image: ShareImage, encryption_key: SymmetricKey, ) -> Option<ShareLocation> { // Check complete wallets first (they have priority) let found = self.iter_access_structures().find(|access_structure| { let access_structure_ref = access_structure.access_structure_ref(); let Some(root_shared_key) = self.root_shared_key(access_structure_ref, encryption_key) else { return false; }; let computed_share_image = root_shared_key.share_image(share_image.index); computed_share_image == share_image }); if let Some(access_structure) = found { let access_structure_ref = access_structure.access_structure_ref(); let device_ids = access_structure .share_index_to_devices() .get(&share_image.index) .cloned() .unwrap_or_default(); let key = self .keys .get(&access_structure_ref.key_id) .expect("must exist"); return Some(ShareLocation { device_ids, share_index: share_image.index, key_name: key.key_name.clone(), key_purpose: key.purpose, key_state: KeyLocationState::Complete { access_structure_ref, }, }); } // Check restorations for restoration in self.restoration.restorations.values() { let share_image_to_devices = restoration.access_structure.share_image_to_devices(); // Check physical shares if let Some(device_ids) = share_image_to_devices.get(&share_image) { return Some(ShareLocation { device_ids: device_ids.clone(), share_index: share_image.index, key_name: restoration.key_name.clone(), key_purpose: restoration.key_purpose, key_state: KeyLocationState::Restoring { restoration_id: restoration.restoration_id, }, }); } // Check virtual shares (via cached SharedKey) if let Some(shared_key) = &restoration.access_structure.shared_key { let computed_share_image = shared_key.share_image(share_image.index); if computed_share_image == share_image { return Some(ShareLocation { device_ids: Vec::new(), share_index: share_image.index, key_name: restoration.key_name.clone(), key_purpose: restoration.key_purpose, key_state: KeyLocationState::Restoring { restoration_id: restoration.restoration_id, }, }); } } } None } pub fn get_frost_key(&self, key_id: KeyId) -> Option<&CoordFrostKey> { self.keys.get(&key_id) } pub fn recv_device_message( &mut self, from: DeviceId, message: DeviceToCoordinatorMessage, ) -> MessageResult<Vec<CoordinatorSend>> { let message_kind = message.kind(); match message { DeviceToCoordinatorMessage::Signing( crate::message::signing::DeviceSigning::NonceResponse { segments }, ) => { let mut outgoing = vec![]; for new_segment in segments { self.nonce_cache .check_can_extend(from, &new_segment) .map_err(|e| { Error::coordinator_invalid_message( message_kind, format!("couldn't extend nonces: {e}"), ) })?; self.mutate(Mutation::Signing(SigningMutation::NewNonces { device_id: from, nonce_segment: new_segment, })); } outgoing.push(CoordinatorSend::ToUser( CoordinatorToUserMessage::ReplenishedNonces { device_id: from }, )); Ok(outgoing) } DeviceToCoordinatorMessage::KeyGen(keygen::DeviceKeygen::Response(response)) => { let keygen_id = response.keygen_id; let (state, entry) = self.pending_keygens.take_entry(keygen_id); match state { Some(KeyGenState::WaitingForResponses(mut state)) => { let cert_scheme = certpedpop::vrf_cert::VrfCertScheme::<Sha256>::new( crate::message::keygen::VRF_CERT_SCHEME_ID, ); let share_index = state.device_to_share_index.get(&from).ok_or( Error::coordinator_invalid_message( message_kind, "got share from device that was not part of keygen", ), )?; state .input_aggregator .add_input( &schnorr_fun::new_with_deterministic_nonces::<Sha256>(), // we use the share index as the input generator index. The input // generator at index 0 is the coordinator itself. (*share_index).into(), *response.input, ) .map_err(|e| Error::coordinator_invalid_message(message_kind, e))?; let mut outgoing = vec![CoordinatorSend::ToUser(CoordinatorToUserMessage::KeyGen { keygen_id, inner: CoordinatorToUserKeyGenMessage::ReceivedShares { from }, })]; if state.input_aggregator.is_finished() { // Remove the entry to take ownership let mut agg_input = state.input_aggregator.finish().unwrap(); agg_input.grind_fingerprint::<Sha256>(self.keygen_fingerprint); // First we calculate our (the coordinator) certificate and add our VRF outputs let sig = state .contributer .verify_agg_input(&cert_scheme, &agg_input, &state.my_keypair) .expect("will be able to certify agg_input we created"); let mut certifier = certpedpop::Certifier::new( cert_scheme, agg_input.clone(), &[state.my_keypair.public_key()], ); certifier .receive_certificate(state.my_keypair.public_key(), sig) .expect("will be able to verify our own certificate"); outgoing.push(CoordinatorSend::ToDevice { destinations: state.device_to_share_index.keys().cloned().collect(), message: Keygen::CertifyPlease { keygen_id, agg_input, } .into(), }); entry.insert(KeyGenState::WaitingForCertificates( KeyGenWaitingForCertificates { keygen_id: state.keygen_id, device_to_share_index: state.device_to_share_index, pending_key_name: state.pending_key_name, purpose: state.purpose, certifier, coordinator_keypair: state.my_keypair, }, )); } else { entry.insert(KeyGenState::WaitingForResponses(state)); } Ok(outgoing) } _ => Err(Error::coordinator_invalid_message( message_kind, "keygen wasn't in WaitingForResponses state", )), } } DeviceToCoordinatorMessage::KeyGen(keygen::DeviceKeygen::Certify { keygen_id, vrf_cert, }) => { let mut outgoing = vec![]; let (state, entry) = self.pending_keygens.take_entry(keygen_id); match state { Some(KeyGenState::WaitingForCertificates(mut state)) => { // Store device output and its certificate state.certifier .receive_certificate(from.pubkey(), vrf_cert) .map_err(|_| { Error::coordinator_invalid_message( message_kind, "Invalid VRF proof received", ) })?; // contributers are the devices plus one coordinator if state.certifier.is_finished() { let certified_keygen = state.certifier .finish() .expect("just checked is_finished"); let session_hash = SessionHash::from_certified_keygen(&certified_keygen); // Extract certificates from the certified keygen let certificate = certified_keygen .certificate() .iter() .map(|(pk, cert)| (*pk, cert.clone())) .collect(); outgoing.push(CoordinatorSend::ToDevice { destinations: state.device_to_share_index.keys().cloned().collect(), message: Keygen::Check { keygen_id, certificate, } .into(), }); outgoing.push(CoordinatorSend::ToUser(CoordinatorToUserMessage::KeyGen { keygen_id, inner: CoordinatorToUserKeyGenMessage::CheckKeyGen { session_hash }, })); // Insert new state entry.insert( KeyGenState::WaitingForAcks(KeyGenWaitingForAcks { certified_keygen, device_to_share_index: state.device_to_share_index, acks: Default::default(), pending_key_name: state.pending_key_name, purpose: state.purpose, }) ); } else { entry.insert(KeyGenState::WaitingForCertificates(state)); } Ok(outgoing) } _ => Err(Error::coordinator_invalid_message( message_kind, "received VRF proof for keygen but this keygen wasn't in WaitingForCertificates state", )), } } DeviceToCoordinatorMessage::KeyGen(keygen::DeviceKeygen::Ack(self::KeyGenAck { keygen_id, ack_session_hash, })) => { let mut outgoing = vec![]; let (state, entry) = self.pending_keygens.take_entry(keygen_id); match state { Some(KeyGenState::WaitingForAcks(mut state)) => { let session_hash = SessionHash::from_certified_keygen(&state.certified_keygen); if ack_session_hash != session_hash { entry.insert(KeyGenState::WaitingForAcks(state)); return Err(Error::coordinator_invalid_message( message_kind, "Device acked wrong keygen session hash", )); } if !state.device_to_share_index.contains_key(&from) { entry.insert(KeyGenState::WaitingForAcks(state)); return Err(Error::coordinator_invalid_message( message_kind, "Received ack from device not a member of keygen", )); } if state.acks.insert(from) { let all_acks_received = state.acks.len() == state.device_to_share_index.len(); if all_acks_received { // XXX: we don't keep around the certified keygen for anything, // although it would make sense for settings where the secret key for // the DeviceId is persisted -- this would allow them to recover their // secret share from the certified keygen. let root_shared_key = state .certified_keygen .agg_input() .shared_key() .non_zero() .expect("can't be zero we we contributed to it"); entry.insert(KeyGenState::NeedsFinalize(KeyGenNeedsFinalize { root_shared_key, device_to_share_index: state.device_to_share_index, pending_key_name: state.pending_key_name, purpose: state.purpose, })); } else {
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
true
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/src/device/device_to_user.rs
frostsnap_core/src/device/device_to_user.rs
use crate::device_nonces::NonceJobBatch; use bitcoin::{address::NetworkChecked, Address}; use tweak::BitcoinBip32Path; use super::*; /// Messages to the user often to ask them to confirm things. Often confirmations contain what we /// call a "phase" which is both the data that describes the action and what will be passed back /// into the core module once the action is confirmed to make progress. #[derive(Clone, Debug)] pub enum DeviceToUserMessage { FinalizeKeyGen { key_name: String, }, CheckKeyGen { phase: Box<KeyGenPhase3>, }, SignatureRequest { phase: Box<SignPhase1>, }, VerifyAddress { address: Address<NetworkChecked>, bip32_path: BitcoinBip32Path, }, Restoration(Box<restoration::ToUserRestoration>), NonceJobs(NonceJobBatch), }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/src/device/restoration.rs
frostsnap_core/src/device/restoration.rs
use crate::message::HeldShare2; use crate::EnterPhysicalId; use frost_backup::ShareBackup; use schnorr_fun::frost::SharedKey; use super::*; use alloc::fmt::Debug; #[derive(Clone, Debug, PartialEq, Default)] pub struct State { tmp_loaded_backups: BTreeMap<ShareImage, ShareBackup>, saved_backups: BTreeMap<ShareImage, SavedBackup2>, } impl State { pub fn apply_mutation_restoration( &mut self, mutation: RestorationMutation, ) -> Option<RestorationMutation> { use RestorationMutation::*; match &mutation { Save(legacy_saved_backup) => { // Convert legacy to new and recurse let saved_backup: SavedBackup2 = legacy_saved_backup.clone().into(); return self.apply_mutation_restoration(Save2(saved_backup)); } _UnSave(_) => { // No-op: cleanup happens automatically when SaveShare mutation is applied } Save2(saved_backup) => { let backup_share_image = saved_backup.share_backup.share_image(); self.saved_backups .insert(backup_share_image, saved_backup.clone()); } } Some(mutation) } pub fn clear_tmp_data(&mut self) { self.tmp_loaded_backups.clear(); } pub fn remove_backups_with_share_image(&mut self, share_image: ShareImage) { self.tmp_loaded_backups.remove(&share_image); self.saved_backups.remove(&share_image); } } impl<S: Debug + NonceStreamSlot> FrostSigner<S> { pub fn recv_restoration_message( &mut self, message: CoordinatorRestoration, _rng: &mut impl rand_core::RngCore, ) -> MessageResult<Vec<DeviceSend>> { use ToUserRestoration::*; match &message { &CoordinatorRestoration::EnterPhysicalBackup { enter_physical_id } => { Ok(vec![DeviceSend::ToUser(Box::new( DeviceToUserMessage::Restoration(Box::new(EnterBackup { phase: EnterBackupPhase { enter_physical_id }, })), ))]) } &CoordinatorRestoration::SavePhysicalBackup { share_image, threshold, purpose, ref key_name, } => { // Convert to new SavePhysicalBackup2 and recurse self.recv_restoration_message( CoordinatorRestoration::SavePhysicalBackup2(Box::new(HeldShare2 { access_structure_ref: None, share_image, threshold: Some(threshold), purpose: Some(purpose), key_name: Some(key_name.clone()), needs_consolidation: true, })), _rng, ) } CoordinatorRestoration::SavePhysicalBackup2(held_share) => { let share_image = held_share.share_image; let threshold = held_share.threshold; let purpose = held_share.purpose; let key_name = held_share.key_name.clone(); if let Some(share_backup) = self.restoration.tmp_loaded_backups.remove(&share_image) { self.mutate(Mutation::Restoration(RestorationMutation::Save2( self::SavedBackup2 { share_backup: share_backup.clone(), threshold, purpose, key_name: key_name.clone(), }, ))); Ok(vec![ DeviceSend::ToUser(Box::new(DeviceToUserMessage::Restoration(Box::new( ToUserRestoration::BackupSaved { share_image, key_name, purpose, threshold, }, )))), DeviceSend::ToCoordinator(Box::new( DeviceToCoordinatorMessage::Restoration( DeviceRestoration::PhysicalSaved(share_image), ), )), ]) } else { Err(Error::signer_invalid_message( &message, "couldn't find secret share saved for that restoration", )) } } CoordinatorRestoration::Consolidate(consolidate) => { let root_shared_key = &consolidate.root_shared_key; let access_structure_ref = AccessStructureRef::from_root_shared_key(root_shared_key); let share_image = root_shared_key.share_image(consolidate.share_index); // Try to get the share from saved backups or tmp loaded backups // Both contain ShareBackup now, so we validate the polynomial checksum let maybe_backup = self .restoration .saved_backups .get(&share_image) .map(|saved_backup| &saved_backup.share_backup) .or_else(|| self.restoration.tmp_loaded_backups.get(&share_image)) .cloned(); if let Some(secret_share_backup) = maybe_backup { let secret_share = secret_share_backup .extract_secret(root_shared_key) .map_err(|_| { // TODO: This needs to be a catastrophic error that // halts the whole device. Error::signer_invalid_message( &message, "polynomial checksum validation failed", ) })?; let expected_image = root_shared_key.share_image(secret_share.index); let actual_image = secret_share.share_image(); if expected_image != actual_image || secret_share.index != consolidate.share_index { Err(Error::signer_invalid_message( &message, "the image didn't match for consolidation", )) } else { let complete_share = CompleteSecretShare { access_structure_ref, key_name: consolidate.key_name.clone(), purpose: consolidate.purpose, threshold: root_shared_key.threshold() as u16, secret_share, }; let coord_contrib = CoordShareDecryptionContrib::for_master_share( self.device_id(), consolidate.share_index, root_shared_key, ); Ok(vec![DeviceSend::ToUser(Box::new( DeviceToUserMessage::Restoration(Box::new( ToUserRestoration::ConsolidateBackup(ConsolidatePhase { complete_share, coord_contrib, }), )), ))]) } } else if self .get_encrypted_share(access_structure_ref, consolidate.share_index) .is_none() { Err(Error::signer_invalid_message( &message, "we can't consolidate a share we don't know about", )) } else { // we've already consolidated it so just answer afirmatively Ok(vec![DeviceSend::ToCoordinator(Box::new( DeviceToCoordinatorMessage::Restoration( DeviceRestoration::FinishedConsolidation { access_structure_ref, share_index: consolidate.share_index, }, ), ))]) } } &CoordinatorRestoration::DisplayBackup { access_structure_ref, coord_share_decryption_contrib, party_index, ref root_shared_key, } => { // Verify that the root_shared_key corresponds to the access_structure_ref let expected_ref = AccessStructureRef::from_root_shared_key(root_shared_key); if expected_ref != access_structure_ref { return Err(Error::signer_invalid_message( &message, "root_shared_key doesn't match access_structure_ref", )); } let AccessStructureRef { key_id, access_structure_id, } = access_structure_ref; let key_data = self.keys.get(&key_id).ok_or(Error::signer_invalid_message( &message, format!( "signer doesn't have a share for this key: {}", self.keys .keys() .map(|key| key.to_string()) .collect::<Vec<_>>() .join(",") ), ))?; let access_structure_data = key_data .access_structures .get(&access_structure_id) .ok_or_else(|| { Error::signer_invalid_message( &message, "no such access structure on this device", ) })?; let encrypted_secret_share = access_structure_data .shares .get(&party_index) .ok_or_else(|| { Error::signer_invalid_message( &message, "access structure exists but this device doesn't have that share", ) })? .ciphertext; let phase = BackupDisplayPhase { access_structure_ref, party_index, encrypted_secret_share, coord_share_decryption_contrib, key_name: key_data.key_name.clone(), root_shared_key: root_shared_key.clone(), }; Ok(vec![DeviceSend::ToUser(Box::new( DeviceToUserMessage::Restoration(Box::new(DisplayBackup { key_name: phase.key_name.clone(), access_structure_ref: phase.access_structure_ref, phase, })), ))]) } CoordinatorRestoration::RequestHeldShares => { let held_shares = self.held_shares().collect(); let send = Some(DeviceSend::ToCoordinator(Box::new( DeviceToCoordinatorMessage::Restoration(DeviceRestoration::HeldShares2( held_shares, )), ))); Ok(send.into_iter().collect()) } } } pub fn tell_coordinator_about_backup_load_result( &mut self, phase: EnterBackupPhase, share_backup: ShareBackup, ) -> impl IntoIterator<Item = DeviceSend> { let mut ret = vec![]; let enter_physical_id = phase.enter_physical_id; let share_image = share_backup.share_image(); self.restoration .tmp_loaded_backups .insert(share_image, share_backup); ret.push(DeviceSend::ToCoordinator(Box::new( DeviceToCoordinatorMessage::Restoration(DeviceRestoration::PhysicalEntered( EnteredPhysicalBackup { enter_physical_id, share_image, }, )), ))); ret } pub fn held_shares(&self) -> impl Iterator<Item = HeldShare2> + '_ { // Iterator over shares from keys with master access structures let keys_iter = self.keys.iter().flat_map(move |(key_id, key_data)| { key_data.access_structures.iter().flat_map( move |(access_structure_id, access_structure)| { access_structure.shares.values().filter_map(move |share| { if access_structure.kind == AccessStructureKind::Master { Some(HeldShare2 { key_name: Some(key_data.key_name.clone()), share_image: share.share_image, access_structure_ref: Some(AccessStructureRef { access_structure_id: *access_structure_id, key_id: *key_id, }), threshold: Some(access_structure.threshold), purpose: Some(key_data.purpose), needs_consolidation: false, }) } else { None } }) }, ) }); // Iterator over shares from saved backups let backups_iter = self.restoration .saved_backups .iter() .map(|(&share_image, saved_backup)| HeldShare2 { key_name: saved_backup.key_name.clone(), access_structure_ref: None, share_image, threshold: saved_backup.threshold, purpose: saved_backup.purpose, needs_consolidation: true, }); // Chain both iterators together keys_iter.chain(backups_iter) } pub fn saved_backups(&self) -> &BTreeMap<ShareImage, SavedBackup2> { &self.restoration.saved_backups } pub fn finish_consolidation( &mut self, symm_keygen: &mut impl DeviceSecretDerivation, phase: ConsolidatePhase, rng: &mut impl rand_core::RngCore, ) -> impl IntoIterator<Item = DeviceSend> { let share_image = phase.complete_share.secret_share.share_image(); let access_structure_ref = phase.complete_share.access_structure_ref; // No need to explicitly UnSave - cleanup happens automatically in SaveShare mutation let encrypted_secret_share = EncryptedSecretShare::encrypt( phase.complete_share.secret_share, phase.complete_share.access_structure_ref, phase.coord_contrib, symm_keygen, rng, ); self.save_complete_share(KeyGenPhase4 { key_name: phase.complete_share.key_name, key_purpose: phase.complete_share.purpose, access_structure_ref: phase.complete_share.access_structure_ref, access_structure_kind: AccessStructureKind::Master, threshold: phase.complete_share.threshold, encrypted_secret_share, }); vec![DeviceSend::ToCoordinator(Box::new( DeviceToCoordinatorMessage::Restoration(DeviceRestoration::FinishedConsolidation { share_index: share_image.index, access_structure_ref, }), ))] } } #[derive(Debug, Clone, bincode::Encode, bincode::Decode, PartialEq, frostsnap_macros::Kind)] pub enum RestorationMutation { Save(SavedBackup), /// DO NOT USE: This is a no-op. Cleanup of restoration backups happens automatically /// when SaveShare mutation is applied. If you need to delete backups, create a new /// mutation for that specific purpose. _UnSave(ShareImage), Save2(SavedBackup2), } #[derive(Debug, Clone)] pub enum ToUserRestoration { EnterBackup { phase: EnterBackupPhase, }, BackupSaved { share_image: ShareImage, key_name: Option<String>, purpose: Option<KeyPurpose>, threshold: Option<u16>, }, ConsolidateBackup(ConsolidatePhase), DisplayBackup { key_name: String, access_structure_ref: AccessStructureRef, phase: BackupDisplayPhase, }, } #[derive(Debug, Clone)] pub struct ConsolidatePhase { pub complete_share: CompleteSecretShare, pub coord_contrib: CoordShareDecryptionContrib, } #[derive(Clone, Debug)] pub struct BackupDisplayPhase { pub access_structure_ref: AccessStructureRef, pub party_index: ShareIndex, pub encrypted_secret_share: Ciphertext<32, Scalar<Secret, Zero>>, pub coord_share_decryption_contrib: CoordShareDecryptionContrib, pub key_name: String, pub root_shared_key: SharedKey, } impl BackupDisplayPhase { pub fn decrypt_to_backup( &self, symm_keygen: &mut impl DeviceSecretDerivation, ) -> Result<ShareBackup, ActionError> { let encryption_key = symm_keygen.get_share_encryption_key( self.access_structure_ref, self.party_index, self.coord_share_decryption_contrib, ); let secret_share = self.encrypted_secret_share.decrypt(encryption_key).ok_or( ActionError::StateInconsistent("could not decrypt secret share".into()), )?; let secret = SecretShare { index: self.party_index, share: secret_share, }; Ok(ShareBackup::from_secret_share_and_shared_key( secret, &self.root_shared_key, )) } } #[derive(Clone, Debug)] pub struct EnterBackupPhase { pub enter_physical_id: EnterPhysicalId, } #[derive(Clone, Debug, bincode::Encode, bincode::Decode, PartialEq)] pub struct SavedBackup { pub share_backup: ShareBackup, pub threshold: u16, pub purpose: KeyPurpose, pub key_name: String, } #[derive(Clone, Debug, bincode::Encode, bincode::Decode, PartialEq)] pub struct SavedBackup2 { pub share_backup: ShareBackup, pub threshold: Option<u16>, pub purpose: Option<KeyPurpose>, pub key_name: Option<String>, } impl From<SavedBackup> for SavedBackup2 { fn from(legacy: SavedBackup) -> Self { SavedBackup2 { share_backup: legacy.share_backup, threshold: Some(legacy.threshold), purpose: Some(legacy.purpose), key_name: Some(legacy.key_name), } } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/src/device/keys.rs
frostsnap_core/src/device/keys.rs
use crate::{device::KeyPurpose, AccessStructureKind, AccessStructureRef, KeyId, Kind}; use alloc::{boxed::Box, string::String}; use frostsnap_macros::Kind as KindDerive; #[derive(Clone, Debug, bincode::Encode, bincode::Decode, PartialEq, KindDerive)] pub enum KeyMutation { NewKey { key_id: KeyId, key_name: String, purpose: KeyPurpose, }, NewAccessStructure { access_structure_ref: AccessStructureRef, threshold: u16, kind: AccessStructureKind, }, SaveShare(Box<super::SaveShareMutation>), }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/src/message/keygen.rs
frostsnap_core/src/message/keygen.rs
use schnorr_fun::frost::chilldkg::certpedpop::vrf_cert; use super::*; pub const VRF_CERT_SCHEME_ID: &str = "cert-vrf-v0"; #[derive(Clone, Debug, bincode::Encode, bincode::Decode, Kind)] pub enum Keygen { Begin(Begin), CertifyPlease { keygen_id: KeygenId, agg_input: certpedpop::AggKeygenInput, }, Check { keygen_id: KeygenId, certificate: BTreeMap<Point, vrf_cert::CertVrfProof>, }, /// Actually save key to device. Finalize { keygen_id: KeygenId, }, } impl From<Keygen> for CoordinatorToDeviceMessage { fn from(value: Keygen) -> Self { Self::KeyGen(value) } } #[derive(Clone, Debug, bincode::Encode, bincode::Decode)] pub struct Begin { pub keygen_id: KeygenId, pub devices: Vec<DeviceId>, pub threshold: u16, pub key_name: String, pub purpose: KeyPurpose, pub coordinator_public_key: Point, } impl From<Begin> for Keygen { fn from(value: Begin) -> Self { Self::Begin(value) } } impl From<Begin> for CoordinatorToDeviceMessage { fn from(value: Begin) -> Self { CoordinatorToDeviceMessage::KeyGen(value.into()) } } impl Begin { /// Generate the device to share index mapping based on the device order in the Vec pub fn device_to_share_index(&self) -> BTreeMap<DeviceId, core::num::NonZeroU32> { self.devices .iter() .enumerate() .map(|(index, device_id)| { ( *device_id, core::num::NonZeroU32::new((index as u32) + 1).expect("we added one"), ) }) .collect() } } #[derive(Clone, Debug, bincode::Encode, bincode::Decode, Kind)] pub enum DeviceKeygen { Response(super::KeyGenResponse), Certify { keygen_id: KeygenId, vrf_cert: vrf_cert::CertVrfProof, }, Ack(super::KeyGenAck), } impl From<DeviceKeygen> for DeviceToCoordinatorMessage { fn from(value: DeviceKeygen) -> Self { Self::KeyGen(value) } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/src/message/screen_verify.rs
frostsnap_core/src/message/screen_verify.rs
use crate::{Kind, MasterAppkey}; use frostsnap_macros::Kind as KindDerive; /// Screen verification messages (for verifying addresses on device screens) #[derive(Clone, Debug, bincode::Encode, bincode::Decode, KindDerive)] pub enum ScreenVerify { VerifyAddress { master_appkey: MasterAppkey, derivation_index: u32, }, }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/src/message/signing.rs
frostsnap_core/src/message/signing.rs
use crate::{ nonce_stream::{CoordNonceStreamState, NonceStreamSegment}, Kind, SignSessionId, }; use alloc::{boxed::Box, vec::Vec}; use frostsnap_macros::Kind as KindDerive; use schnorr_fun::frost::SignatureShare; /// A request to open one or more nonce streams #[derive(Clone, Debug, bincode::Encode, bincode::Decode)] pub struct OpenNonceStreams { pub streams: Vec<CoordNonceStreamState>, } impl OpenNonceStreams { /// Split into individual OpenNonceStreams messages, each with one stream pub fn split(self) -> Vec<OpenNonceStreams> { self.streams .into_iter() .map(|stream| OpenNonceStreams { streams: vec![stream], }) .collect() } } /// Coordinator to device signing messages #[derive(Clone, Debug, bincode::Encode, bincode::Decode, KindDerive)] pub enum CoordinatorSigning { RequestSign(Box<super::RequestSign>), OpenNonceStreams(OpenNonceStreams), } /// Device to coordinator signing messages #[derive(Clone, Debug, bincode::Encode, bincode::Decode, KindDerive)] pub enum DeviceSigning { NonceResponse { segments: Vec<NonceStreamSegment>, }, SignatureShare { session_id: SignSessionId, signature_shares: Vec<SignatureShare>, replenish_nonces: Option<NonceStreamSegment>, }, } impl From<DeviceSigning> for super::DeviceToCoordinatorMessage { fn from(value: DeviceSigning) -> Self { Self::Signing(value) } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/src/coordinator/restoration.rs
frostsnap_core/src/coordinator/restoration.rs
use std::collections::BTreeSet; use super::keys; use super::*; use crate::{fail, message::HeldShare2, EnterPhysicalId, RestorationId}; #[derive(Clone, Debug, PartialEq)] pub struct RestorationState { pub restoration_id: RestorationId, pub key_name: String, pub access_structure: RecoveringAccessStructure, pub key_purpose: KeyPurpose, pub fingerprint: schnorr_fun::frost::Fingerprint, } impl RestorationState { pub fn is_restorable(&self) -> bool { self.status().shared_key.is_some() } pub fn needs_to_consolidate(&self) -> impl Iterator<Item = DeviceId> + '_ { self.access_structure.needs_to_consolidate() } /// Prepare for saving a physical backup - returns the HeldShare2 to store fn prepare_save_physical_backup( &self, device_id: DeviceId, share_image: ShareImage, ) -> HeldShare2 { // Clone access structure and do a trial run to see what threshold we would get after adding this share let mut trial_access_structure = self.access_structure.clone(); // this models what the device's "HeldShare2" would look like after it saves the backup let mut held_share = HeldShare2 { access_structure_ref: None, share_image, threshold: None, key_name: Some(self.key_name.clone()), purpose: Some(self.key_purpose), needs_consolidation: true, }; let trial_recover_share = RecoverShare { held_by: device_id, held_share: held_share.clone(), }; trial_access_structure.add_share(trial_recover_share, self.fingerprint); if let Some(_shared_key) = &trial_access_structure.shared_key { // Check if this specific share is compatible with the recovered key let compatibility = trial_access_structure.compatibility(share_image); if compatibility == ShareCompatibility::Compatible { // NOTE: If the restoration has succeeded with this new share we // populate the access structure metadata. Note that we *could* // consolidate at this point if we wanted to by sending the // shared_key over but to keep things simple and predictable we // consolidate only after the user has confirmed the restoration. held_share.threshold = trial_access_structure.effective_threshold(); held_share.access_structure_ref = trial_access_structure.access_structure_ref(); } // If incompatible, we don't populate threshold/access_structure_ref to avoid // the metadata incorrectly suggesting compatibility later when shared_key becomes None } held_share } pub fn status(&self) -> RestorationStatus { let restoration_access_ref = self.access_structure.access_structure_ref(); let shares = self .access_structure .held_shares .iter() .map(|recover_share| { let mut compatibility = self .access_structure .compatibility(recover_share.held_share.share_image); // If it's uncertain we try and use the metadata to determine likely compatibility. // This *could* change in the future. if compatibility == ShareCompatibility::Uncertain { if let (Some(restoration_ref), Some(share_ref)) = ( restoration_access_ref, recover_share.held_share.access_structure_ref, ) { compatibility = if restoration_ref == share_ref { ShareCompatibility::Compatible } else { ShareCompatibility::Incompatible }; } } RestorationShare { device_id: recover_share.held_by, index: recover_share .held_share .share_image .index .try_into() .expect("share index is small"), compatibility, } }) .collect(); RestorationStatus { threshold: self.access_structure.effective_threshold(), shares, shared_key: self.access_structure.shared_key.clone(), } } } #[derive(Clone, Debug, PartialEq, Eq)] pub struct RestorationStatus { pub threshold: Option<u16>, pub shares: Vec<RestorationShare>, pub shared_key: Option<SharedKey>, } impl RestorationStatus { pub fn share_count(&self) -> ShareCount { let explicitly_incompatible = self .shares .iter() .filter(|s| s.compatibility == ShareCompatibility::Incompatible) .count() as u16; let needed = self.threshold; let (got, incompatible) = if self.shared_key.is_some() { let compatible_count = self .shares .iter() .filter(|s| s.compatibility == ShareCompatibility::Compatible) .map(|s| s.index) .collect::<std::collections::BTreeSet<_>>() .len() as u16; (Some(compatible_count), explicitly_incompatible) } else { let total_unique = self .shares .iter() .map(|s| s.index) .collect::<std::collections::BTreeSet<_>>() .len() as u16; match needed { Some(threshold) if total_unique >= threshold => { // We haven't recovered the shared key but we have enough // shares. This means some must be incompatible but we don't // know which ones or exactly how many are compatible. let min_incompatible = total_unique - threshold + 1; let incompatible_lower_bound = min_incompatible.max(explicitly_incompatible); (None, incompatible_lower_bound) } _ => (Some(total_unique), explicitly_incompatible), } }; ShareCount { got, needed, incompatible, } } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct ShareCount { pub got: Option<u16>, pub needed: Option<u16>, pub incompatible: u16, } #[derive(Clone, Copy, Debug, PartialEq, Eq, bincode::Encode, bincode::Decode)] pub enum ShareCompatibility { Compatible, Incompatible, Uncertain, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct RestorationShare { pub device_id: DeviceId, pub index: u16, pub compatibility: ShareCompatibility, } #[derive(Clone, Debug, bincode::Encode, bincode::Decode, PartialEq)] pub struct RecoverShare { pub held_by: DeviceId, pub held_share: HeldShare2, } #[derive(Debug, Clone, Default, PartialEq)] pub struct State { pub(super) restorations: BTreeMap<RestorationId, restoration::RestorationState>, /// This is where we remember consolidations we need to do from restorations we've finished. pub(super) pending_physical_consolidations: BTreeSet<PendingConsolidation>, /// For when we ask a device to enter a backup and we plan to immediately consolidate it because /// we already know the access structure. tmp_waiting_consolidate: BTreeSet<PendingConsolidation>, tmp_waiting_save: BTreeMap<(DeviceId, ShareImage), (RestorationId, HeldShare2)>, } impl State { pub fn apply_mutation_restoration( &mut self, mutation: RestorationMutation, fingerprint: schnorr_fun::frost::Fingerprint, ) -> Option<RestorationMutation> { use RestorationMutation::*; match mutation { NewRestoration { restoration_id, ref key_name, threshold, key_purpose, } => { // Convert legacy to new and recurse return self.apply_mutation_restoration( NewRestoration2 { restoration_id, key_name: key_name.clone(), starting_threshold: Some(threshold), key_purpose, }, fingerprint, ); } NewRestoration2 { restoration_id, ref key_name, starting_threshold: threshold, key_purpose, } => { self.restorations.insert( restoration_id, RestorationState { restoration_id, key_name: key_name.clone(), access_structure: RecoveringAccessStructure { starting_threshold: threshold, held_shares: Default::default(), shared_key: None, }, key_purpose, fingerprint, }, ); } RestorationProgress { restoration_id, device_id, access_structure_ref, share_image, } => { // Convert legacy to new format let held_share = HeldShare2 { access_structure_ref, share_image, threshold: None, key_name: self .restorations .get(&restoration_id) .map(|s| s.key_name.clone()), purpose: self .restorations .get(&restoration_id) .map(|s| s.key_purpose), needs_consolidation: access_structure_ref.is_none(), }; return self.apply_mutation_restoration( RestorationProgress2 { restoration_id, device_id, held_share, }, fingerprint, ); } RestorationProgress2 { restoration_id, device_id, ref held_share, } => { if let Some(state) = self.restorations.get_mut(&restoration_id) { if state .access_structure .has_got_share(device_id, held_share.share_image) { return None; } // Check for AccessStructureRef conflicts if let Some(new_ref) = held_share.access_structure_ref { if let Some(existing_ref) = state.access_structure.access_structure_ref() { if existing_ref != new_ref { fail!("access_structure_ref didn't match"); } } } let recover_share = RecoverShare { held_by: device_id, held_share: held_share.clone(), }; state.access_structure.add_share(recover_share, fingerprint); } else { fail!("restoration id didn't exist") } } DeleteRestoration { restoration_id } => { let existed = self.restorations.remove(&restoration_id).is_some(); if !existed { return None; } } DeviceNeedsConsolidation(consolidation) => { let changed = self.pending_physical_consolidations.insert(consolidation); if !changed { return None; } } DeviceFinishedConsolidation(consolidation) => { if !self.pending_physical_consolidations.remove(&consolidation) { fail!("pending physical restoration did not exist"); } } DeleteRestorationShare { restoration_id, device_id, share_image, } => { if let Some(restoration) = self.restorations.get_mut(&restoration_id) { if !restoration.access_structure.remove_share( device_id, share_image, restoration.fingerprint, ) { return None; } } else { fail!("restoration id didn't exist"); } } } Some(mutation.clone()) } pub fn clear_up_key_deletion(&mut self, key_id: KeyId) { self.pending_physical_consolidations .retain(|consolidation| consolidation.access_structure_ref.key_id != key_id); self.tmp_waiting_consolidate .retain(|consolidation| consolidation.access_structure_ref.key_id != key_id); } pub fn clear_tmp_data(&mut self) { self.tmp_waiting_consolidate.clear(); self.tmp_waiting_save.clear(); } } impl FrostCoordinator { pub fn start_restoring_key( &mut self, key_name: String, threshold: Option<u16>, key_purpose: KeyPurpose, restoration_id: RestorationId, ) { assert!(!self.restoration.restorations.contains_key(&restoration_id)); self.mutate(Mutation::Restoration( RestorationMutation::NewRestoration2 { restoration_id, key_name, starting_threshold: threshold, key_purpose, }, )); } pub fn request_held_shares(&self, id: DeviceId) -> impl Iterator<Item = CoordinatorSend> { core::iter::once(CoordinatorSend::ToDevice { message: CoordinatorToDeviceMessage::Restoration( CoordinatorRestoration::RequestHeldShares, ), destinations: [id].into(), }) } pub fn tell_device_to_load_physical_backup( &self, enter_physical_id: EnterPhysicalId, device_id: DeviceId, ) -> impl IntoIterator<Item = CoordinatorSend> { vec![CoordinatorSend::ToDevice { message: CoordinatorToDeviceMessage::Restoration( CoordinatorRestoration::EnterPhysicalBackup { enter_physical_id }, ), destinations: [device_id].into(), }] } /// Check a physical backup loaded by a device that you know belongs to a certain access structure. pub fn check_physical_backup( &self, access_structure_ref: AccessStructureRef, phase: PhysicalBackupPhase, encryption_key: SymmetricKey, ) -> Result<ShareIndex, CheckBackupError> { let AccessStructureRef { key_id, access_structure_id, } = access_structure_ref; let share_index = phase.backup.share_image.index; let CoordFrostKey { complete_key, .. } = self .keys .get(&key_id) .ok_or(CheckBackupError::NoSuchAccessStructure)?; let root_shared_key = complete_key .root_shared_key(access_structure_id, encryption_key) .ok_or(CheckBackupError::DecryptionError)?; let expected_image = root_shared_key.share_image(share_index); if phase.backup.share_image != expected_image { return Err(CheckBackupError::ShareImageIsWrong); } Ok(share_index) } pub fn tell_device_to_save_physical_backup( &mut self, phase: PhysicalBackupPhase, restoration_id: RestorationId, ) -> impl IntoIterator<Item = CoordinatorSend> { let state = match self.get_restoration_state(restoration_id) { Some(state) => state, None => return vec![], }; let PhysicalBackupPhase { backup: EnteredPhysicalBackup { share_image, .. }, from, } = phase; // Prepare the HeldShare let held_share = state.prepare_save_physical_backup(from, share_image); // Save the restoration_id and held_share for when the device confirms self.restoration .tmp_waiting_save .insert((from, share_image), (restoration_id, held_share.clone())); vec![CoordinatorSend::ToDevice { message: CoordinatorToDeviceMessage::Restoration( CoordinatorRestoration::SavePhysicalBackup2(Box::new(held_share)), ), destinations: [from].into(), }] } /// This is for telling the device to consolidate a backup when we have recovered the key already. /// If the key is recovering you have to consolidate it after recovery has finished. pub fn tell_device_to_consolidate_physical_backup( &mut self, phase: PhysicalBackupPhase, access_structure_ref: AccessStructureRef, encryption_key: SymmetricKey, ) -> Result<TellDeviceConsolidateBackup, CheckBackupError> { self.check_physical_backup(access_structure_ref, phase, encryption_key)?; let PhysicalBackupPhase { backup: EnteredPhysicalBackup { enter_physical_id: _, share_image, }, from, } = phase; let root_shared_key = self .root_shared_key(access_structure_ref, encryption_key) .expect("invariant"); let frost_key = self .get_frost_key(access_structure_ref.key_id) .expect("invariant"); let key_name = frost_key.key_name.clone(); let purpose = frost_key.purpose; self.restoration .tmp_waiting_consolidate .insert(PendingConsolidation { device_id: from, access_structure_ref, share_index: share_image.index, }); Ok(TellDeviceConsolidateBackup { device_id: from, share_index: share_image.index, root_shared_key, key_name, purpose, }) } pub fn add_recovery_share_to_restoration( &mut self, restoration_id: RestorationId, recover_share: &RecoverShare, encryption_key: SymmetricKey, ) -> Result<(), RestoreRecoverShareError> { self.check_recover_share_compatible_with_restoration( restoration_id, recover_share, encryption_key, )?; self.mutate(Mutation::Restoration( RestorationMutation::RestorationProgress2 { restoration_id, device_id: recover_share.held_by, held_share: recover_share.held_share.clone(), }, )); Ok(()) } pub fn check_recover_share_compatible_with_restoration( &self, restoration_id: RestorationId, recover_share: &RecoverShare, encryption_key: SymmetricKey, ) -> Result<(), RestoreRecoverShareError> { let restoration = self .restoration .restorations .get(&restoration_id) .ok_or(RestoreRecoverShareError::UnknownRestorationId)?; // ❗ Don't check purpose or key_name - they could be wrong or missing // in physical backups. They are informational but shouldn't prevent it // being added to the restoration. If they are not compatible the access // structure ref check will catch it immediately or the fingerprint check will // exclude it from the restoration later. // Use find_share to check if share exists elsewhere if let Some(location) = self.find_share(recover_share.held_share.share_image, encryption_key) { match location.key_state { KeyLocationState::Restoring { restoration_id: found_id, } if found_id == restoration_id => { // Found in same restoration if location.device_ids.contains(&recover_share.held_by) { // Same device in same restoration return Err(RestoreRecoverShareError::AlreadyGotThisShare); } // Different device in same restoration is OK (adding redundancy) } _ => { // Found in different restoration or complete wallet return Err(RestoreRecoverShareError::ShareBelongsElsewhere { location: Box::new(location), }); } } } // Check AccessStructureRef compatibility let new_ref = recover_share.held_share.access_structure_ref; let existing_ref = restoration.access_structure.access_structure_ref(); if let (Some(new), Some(existing)) = (new_ref, existing_ref) { if new != existing { return Err(RestoreRecoverShareError::AcccessStructureMismatch); } } Ok(()) } pub fn check_physical_backup_compatible_with_restoration( &self, restoration_id: RestorationId, phase: PhysicalBackupPhase, encryption_key: SymmetricKey, ) -> Result<(), RestorePhysicalBackupError> { self.restoration .restorations .get(&restoration_id) .ok_or(RestorePhysicalBackupError::UnknownRestorationId)?; // Use find_share to check if share exists elsewhere if let Some(location) = self.find_share(phase.backup.share_image, encryption_key) { match location.key_state { KeyLocationState::Restoring { restoration_id: found_id, } if found_id == restoration_id => { // Found in same restoration if location.device_ids.contains(&phase.from) { // Same device in same restoration return Err(RestorePhysicalBackupError::AlreadyGotThisShare); } // Different device in same restoration is OK (adding redundancy) } _ => { // Found in different restoration or complete wallet return Err(RestorePhysicalBackupError::ShareBelongsElsewhere { location: Box::new(location), }); } } } Ok(()) } pub fn finish_restoring( &mut self, restoration_id: RestorationId, encryption_key: SymmetricKey, rng: &mut impl rand_core::RngCore, ) -> Result<AccessStructureRef, RestorationError> { let state = self .restoration .restorations .get(&restoration_id) .cloned() .ok_or(RestorationError::UnknownRestorationId)?; // Get cached shared key let root_shared_key = state .access_structure .shared_key .as_ref() .ok_or(RestorationError::NotEnoughShares)? .clone(); let access_structure_ref = AccessStructureRef::from_root_shared_key(&root_shared_key); let device_to_share_index = state .access_structure .compatible_device_to_share_index() .expect("shared_key is Some so compatible_device_to_share_index should return Some"); self.mutate_new_key( state.key_name.clone(), root_shared_key, device_to_share_index.clone(), encryption_key, state.key_purpose, rng, ); for device_id in state.needs_to_consolidate() { self.mutate(Mutation::Restoration( RestorationMutation::DeviceNeedsConsolidation(PendingConsolidation { device_id, access_structure_ref, share_index: device_to_share_index[&device_id], }), )) } self.mutate(Mutation::Restoration( RestorationMutation::DeleteRestoration { restoration_id }, )); Ok(access_structure_ref) } pub fn get_restoration_state(&self, restoration_id: RestorationId) -> Option<RestorationState> { self.restoration.restorations.get(&restoration_id).cloned() } /// Recovers a share to an existing access structure pub fn recover_share( &mut self, access_structure_ref: AccessStructureRef, recover_share: &RecoverShare, encryption_key: SymmetricKey, ) -> Result<(), RecoverShareError> { self.check_recover_share_compatible_with_key( access_structure_ref, recover_share, encryption_key, )?; let share_index = recover_share.held_share.share_image.index; self.mutate(Mutation::Keygen(keys::KeyMutation::NewShare { access_structure_ref, device_id: recover_share.held_by, share_index, })); let was_a_physical_backup = recover_share.held_share.access_structure_ref.is_none(); if was_a_physical_backup { self.mutate(Mutation::Restoration( RestorationMutation::DeviceNeedsConsolidation(PendingConsolidation { device_id: recover_share.held_by, access_structure_ref, share_index, }), )) } Ok(()) } pub fn check_recover_share_compatible_with_key( &self, access_structure_ref: AccessStructureRef, recover_share: &RecoverShare, encryption_key: SymmetricKey, ) -> Result<(), RecoverShareError> { let frost_key = self.get_frost_key(access_structure_ref.key_id) .ok_or(RecoverShareError { key_purpose: self .keys .get(&access_structure_ref.key_id) .map(|k| k.purpose) .unwrap_or(KeyPurpose::Test), kind: RecoverShareErrorKind::NoSuchAccessStructure, })?; let key_purpose = frost_key.purpose; let access_structure = self.get_access_structure(access_structure_ref) .ok_or(RecoverShareError { key_purpose, kind: RecoverShareErrorKind::NoSuchAccessStructure, })?; if let Some(got) = recover_share.held_share.access_structure_ref { if got != access_structure_ref { return Err(RecoverShareError { key_purpose, kind: RecoverShareErrorKind::AccessStructureMismatch, }); } } if access_structure .device_to_share_index .contains_key(&recover_share.held_by) { return Err(RecoverShareError { key_purpose, kind: RecoverShareErrorKind::AlreadyGotThisShare, }); } let root_shared_key = frost_key .complete_key .root_shared_key(access_structure_ref.access_structure_id, encryption_key) .ok_or(RecoverShareError { key_purpose, kind: RecoverShareErrorKind::DecryptionError, })?; let share_image = recover_share.held_share.share_image; let expected_image = root_shared_key.share_image(share_image.index); if expected_image != share_image { return Err(RecoverShareError { key_purpose, kind: RecoverShareErrorKind::ShareImageIsWrong, }); } Ok(()) } pub fn cancel_restoration(&mut self, restoration_id: RestorationId) { self.mutate(Mutation::Restoration( RestorationMutation::DeleteRestoration { restoration_id }, )) } pub fn start_restoring_key_from_recover_share( &mut self, recover_share: &RecoverShare, restoration_id: RestorationId, ) -> Result<(), StartRestorationFromShareError> { let held_share = &recover_share.held_share; // Check if key_name and purpose are present let key_name = held_share .key_name .clone() .ok_or(StartRestorationFromShareError::MissingMetadata)?; let key_purpose = held_share .purpose .ok_or(StartRestorationFromShareError::MissingMetadata)?; assert!(!self.restoration.restorations.contains_key(&restoration_id)); if let Some(access_structure_ref) = held_share.access_structure_ref { assert!(self.get_access_structure(access_structure_ref).is_none()); } self.mutate(Mutation::Restoration( RestorationMutation::NewRestoration2 { restoration_id, key_name, starting_threshold: held_share.threshold, key_purpose, }, )); self.mutate(Mutation::Restoration( RestorationMutation::RestorationProgress2 { restoration_id, device_id: recover_share.held_by, held_share: held_share.clone(), }, )); Ok(()) } pub fn recv_restoration_message( &mut self, from: DeviceId, message: DeviceRestoration, ) -> MessageResult<Vec<CoordinatorSend>> { match message { DeviceRestoration::PhysicalEntered(entered_physical_backup) => { //XXX: We could check if a restoration id exists before sending out the message but // it's not a good idea becuase atm it's valid to ask a device to enter a backup // when you're not keeping track of the restoration id for the purpose of doing a // backup check. Ok(vec![CoordinatorSend::ToUser( CoordinatorToUserMessage::Restoration( ToUserRestoration::PhysicalBackupEntered(Box::new(PhysicalBackupPhase { backup: entered_physical_backup, from, })), ), )]) } DeviceRestoration::PhysicalSaved(share_image) => { if let Some((restoration_id, held_share)) = self .restoration .tmp_waiting_save .remove(&(from, share_image)) { self.mutate(Mutation::Restoration( RestorationMutation::RestorationProgress2 { restoration_id, device_id: from, held_share, }, )); Ok(vec![CoordinatorSend::ToUser( CoordinatorToUserMessage::Restoration( ToUserRestoration::PhysicalBackupSaved { device_id: from, restoration_id, share_index: share_image.index, }, ), )]) } else { Err(Error::coordinator_invalid_message( message.kind(), "coordinator not waiting for that share to be saved", )) } } DeviceRestoration::FinishedConsolidation { access_structure_ref, share_index, } => { let consolidation = PendingConsolidation { device_id: from, access_structure_ref, share_index, }; // we have to distinguish between two types of finished consolidations: // // 1. We've just asked the device to enter a backup for a access structure we knew about when we asked them
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
true
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/src/coordinator/signing.rs
frostsnap_core/src/coordinator/signing.rs
use crate::{nonce_stream::NonceStreamSegment, DeviceId, KeyId, Kind, SignSessionId}; use alloc::vec::Vec; use frostsnap_macros::Kind as KindDerive; use schnorr_fun::frost::SignatureShare; use super::FrostCoordinator; #[derive(Clone, Debug, bincode::Encode, bincode::Decode, PartialEq, KindDerive)] pub enum SigningMutation { NewNonces { device_id: DeviceId, nonce_segment: NonceStreamSegment, }, NewSigningSession(super::ActiveSignSession), SentSignReq { session_id: SignSessionId, device_id: DeviceId, }, GotSignatureSharesFromDevice { session_id: SignSessionId, device_id: DeviceId, signature_shares: Vec<SignatureShare>, }, CloseSignSession { session_id: SignSessionId, finished: Option<Vec<super::EncodedSignature>>, }, ForgetFinishedSignSession { session_id: SignSessionId, }, } impl SigningMutation { pub fn tied_to_key(&self, coord: &FrostCoordinator) -> Option<KeyId> { match self { SigningMutation::NewNonces { .. } => None, SigningMutation::NewSigningSession(active_sign_session) => { Some(active_sign_session.key_id) } SigningMutation::SentSignReq { session_id, .. } | SigningMutation::GotSignatureSharesFromDevice { session_id, .. } | SigningMutation::CloseSignSession { session_id, .. } | SigningMutation::ForgetFinishedSignSession { session_id } => { Some(coord.get_sign_session(*session_id)?.key_id()) } } } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/src/coordinator/coordinator_to_user.rs
frostsnap_core/src/coordinator/coordinator_to_user.rs
use super::*; use frostsnap_macros::Kind; #[derive(Clone, Debug, Kind)] pub enum CoordinatorToUserMessage { KeyGen { keygen_id: KeygenId, inner: CoordinatorToUserKeyGenMessage, }, Signing(CoordinatorToUserSigningMessage), Restoration(super::restoration::ToUserRestoration), ReplenishedNonces { device_id: DeviceId, }, } impl Gist for CoordinatorToUserMessage { fn gist(&self) -> String { crate::Kind::kind(self).into() } } #[derive(Clone, Debug)] pub enum CoordinatorToUserSigningMessage { GotShare { session_id: SignSessionId, from: DeviceId, }, Signed { session_id: SignSessionId, signatures: Vec<EncodedSignature>, }, } #[derive(Clone, Debug)] pub enum CoordinatorToUserKeyGenMessage { ReceivedShares { from: DeviceId, }, CheckKeyGen { session_hash: SessionHash, }, KeyGenAck { from: DeviceId, all_acks_received: bool, }, }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/src/coordinator/keys.rs
frostsnap_core/src/coordinator/keys.rs
use crate::coordinator::CompleteKey; use crate::tweak::Xpub; use crate::{ device::KeyPurpose, AccessStructureKind, AccessStructureRef, DeviceId, KeyId, KeygenId, Kind, }; use alloc::{collections::BTreeMap, collections::BTreeSet, string::String, vec::Vec}; use frostsnap_macros::Kind as KindDerive; use schnorr_fun::frost::{ShareIndex, SharedKey}; /// API input for beginning a key generation (without coordinator_public_key) #[derive(Clone, Debug)] pub struct BeginKeygen { pub keygen_id: KeygenId, pub devices_in_order: Vec<DeviceId>, pub device_to_share_index: BTreeMap<DeviceId, core::num::NonZeroU32>, pub threshold: u16, pub key_name: String, pub purpose: KeyPurpose, } impl BeginKeygen { pub fn new_with_id( devices: Vec<DeviceId>, threshold: u16, key_name: String, purpose: KeyPurpose, keygen_id: KeygenId, ) -> Self { let device_to_share_index: BTreeMap<_, _> = devices .iter() .enumerate() .map(|(index, device_id)| { ( *device_id, core::num::NonZeroU32::new((index + 1) as u32).expect("we added one"), ) }) .collect(); Self { devices_in_order: devices, device_to_share_index, threshold, key_name, purpose, keygen_id, } } pub fn new( devices: Vec<DeviceId>, threshold: u16, key_name: String, purpose: KeyPurpose, rng: &mut impl rand_core::RngCore, // for the keygen id ) -> Self { let mut id = [0u8; 16]; rng.fill_bytes(&mut id[..]); Self::new_with_id( devices, threshold, key_name, purpose, KeygenId::from_bytes(id), ) } pub fn devices(&self) -> BTreeSet<DeviceId> { self.device_to_share_index.keys().cloned().collect() } } #[derive(Clone, Debug, bincode::Encode, bincode::Decode, PartialEq, KindDerive)] pub enum KeyMutation { NewKey { key_name: String, purpose: KeyPurpose, complete_key: CompleteKey, }, NewAccessStructure { shared_key: Xpub<SharedKey>, kind: AccessStructureKind, }, NewShare { access_structure_ref: AccessStructureRef, device_id: DeviceId, share_index: ShareIndex, }, DeleteKey(KeyId), }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/tests/endtoend.rs
frostsnap_core/tests/endtoend.rs
use common::TEST_ENCRYPTION_KEY; use frostsnap_core::bitcoin_transaction::{LocalSpk, TransactionTemplate}; use frostsnap_core::device::KeyPurpose; use frostsnap_core::tweak::BitcoinBip32Path; use frostsnap_core::EnterPhysicalId; use frostsnap_core::{MasterAppkey, WireSignTask}; use rand::seq::IteratorRandom; use rand_chacha::rand_core::SeedableRng; use rand_chacha::ChaCha20Rng; use schnorr_fun::{fun::prelude::*, Schnorr}; use std::collections::{BTreeMap, BTreeSet}; mod common; mod env; use crate::common::Run; use crate::env::TestEnv; #[test] fn when_we_generate_a_key_we_should_be_able_to_sign_with_it_multiple_times() { let n_parties = 3; let threshold = 2; let schnorr = Schnorr::<sha2::Sha256>::verify_only(); let mut env = TestEnv::default(); let mut test_rng = ChaCha20Rng::from_seed([123u8; 32]); let mut run = Run::start_after_keygen_and_nonces( n_parties, threshold, &mut env, &mut test_rng, 1, KeyPurpose::Test, ); let device_list = run.devices.keys().cloned().collect::<Vec<_>>(); let session_hash = env .coordinator_check .expect("coordinator should have seen session_hash"); assert_eq!( env.keygen_checks.keys().cloned().collect::<BTreeSet<_>>(), run.device_set() ); assert!( env.keygen_checks.values().all(|v| *v == session_hash), "devices should have seen the same hash" ); assert_eq!(env.coordinator_got_keygen_acks, run.device_set()); assert_eq!(env.received_keygen_shares, run.device_set()); let key_data = run.coordinator.iter_keys().next().unwrap().clone(); let access_structure_ref = key_data .access_structures() .next() .unwrap() .access_structure_ref(); for (message, signers) in [("johnmcafee47", [0, 1]), ("pyramid schmee", [1, 2])] { env.signatures.clear(); env.sign_tasks.clear(); env.received_signing_shares.clear(); let task = WireSignTask::Test { message: message.into(), }; let complete_key = key_data.complete_key.clone(); let checked_task = task .clone() .check(complete_key.master_appkey, KeyPurpose::Test) .unwrap(); let signing_set = BTreeSet::from_iter(signers.iter().map(|i| device_list[*i])); let session_id = run .coordinator .start_sign( access_structure_ref, task.clone(), &signing_set, &mut test_rng, ) .unwrap(); for &device in &signing_set { let sign_req = run.coordinator .request_device_sign(session_id, device, TEST_ENCRYPTION_KEY); run.extend(sign_req); } run.run_until_finished(&mut env, &mut test_rng).unwrap(); assert_eq!( env.received_signing_shares.get(&session_id).unwrap(), &signing_set ); assert!(checked_task .verify_final_signatures(&schnorr, env.signatures.get(&session_id).unwrap())); // check view of the coordianttor and device nonces are the same // TODO: maybe try and do this check again // for &device in &device_set { // let coord_nonces = run.coordinator.device_nonces().get(&device).cloned(); // let coord_nonce_counter = coord_nonces // .clone() // .map(|nonces| nonces.start_index) // .unwrap_or(0); // let device_nonce_counter = run.device(device).nonce_counter(); // assert_eq!(device_nonce_counter, coord_nonce_counter); // let coord_next_nonce = // coord_nonces.and_then(|nonces| nonces.nonces.iter().next().cloned()); // let device_nonce = run // .devices // .get(&device) // .unwrap() // .generate_public_nonces(device_nonce_counter) // .next(); // assert_eq!(device_nonce, coord_next_nonce); // } } } #[test] fn test_display_backup() { use rand::seq::SliceRandom; let n_parties = 3; let threshold = 2; let mut env = TestEnv::default(); let mut test_rng = ChaCha20Rng::from_seed([123u8; 32]); let mut run = Run::start_after_keygen( n_parties, threshold, &mut env, &mut test_rng, KeyPurpose::Test, ); let device_list = run.devices.keys().cloned().collect::<Vec<_>>(); let access_structure_ref = run .coordinator .iter_access_structures() .next() .unwrap() .access_structure_ref(); assert_eq!( env.backups.len(), 0, "no backups should have been displayed automatically" ); env.backups = BTreeMap::new(); // clear backups so we can request one again for a party let display_backup = run .coordinator .request_device_display_backup(device_list[0], access_structure_ref, TEST_ENCRYPTION_KEY) .unwrap(); run.extend(display_backup); run.run_until_finished(&mut env, &mut test_rng).unwrap(); assert_eq!(env.backups.len(), 1); let mut display_backup = run .coordinator .request_device_display_backup(device_list[1], access_structure_ref, TEST_ENCRYPTION_KEY) .unwrap(); display_backup.extend( run.coordinator .request_device_display_backup( device_list[2], access_structure_ref, TEST_ENCRYPTION_KEY, ) .unwrap(), ); run.extend(display_backup); run.run_until_finished(&mut env, &mut test_rng).unwrap(); assert_eq!(env.backups.len(), 3); // Get the SharedKey from the coordinator for validation let root_shared_key = run .coordinator .root_shared_key(access_structure_ref, TEST_ENCRYPTION_KEY) .expect("Should be able to get root shared key"); let decoded_backups = env .backups .values() .map(|(_name, backup)| { // Extract and validate the share with the polynomial checksum backup .clone() .extract_secret(&root_shared_key) .expect("Polynomial checksum should be valid") }) .collect::<Vec<_>>(); let interpolated_joint_secret = schnorr_fun::frost::SecretShare::recover_secret( &decoded_backups .choose_multiple(&mut test_rng, 2) .cloned() .collect::<Vec<_>>(), ) .non_zero() .unwrap(); let key_data = run .coordinator .get_frost_key(access_structure_ref.key_id) .unwrap(); assert_eq!( MasterAppkey::derive_from_rootkey(g!(interpolated_joint_secret * G).normalize()), key_data.complete_key.master_appkey ); } #[test] fn test_verify_address() { let n_parties = 3; let threshold = 2; let mut env = TestEnv::default(); let mut test_rng = ChaCha20Rng::from_seed([123u8; 32]); let mut run = Run::start_after_keygen( n_parties, threshold, &mut env, &mut test_rng, KeyPurpose::Bitcoin(bitcoin::Network::Bitcoin), ); let key_data = run.coordinator.iter_keys().next().unwrap().clone(); let verify_request = run.coordinator.verify_address(key_data.key_id, 0).unwrap(); run.extend(verify_request); run.run_until_finished(&mut env, &mut test_rng).unwrap(); assert_eq!(env.verification_requests.len(), 3); } #[test] fn when_we_abandon_a_sign_request_we_should_be_able_to_start_a_new_one() { let mut test_rng = ChaCha20Rng::from_seed([42u8; 32]); let mut env = TestEnv::default(); let mut run = Run::start_after_keygen_and_nonces(1, 1, &mut env, &mut test_rng, 1, KeyPurpose::Test); let device_set = run.device_set(); for _ in 0..101 { let access_structure_ref = run .coordinator .iter_access_structures() .next() .unwrap() .access_structure_ref(); let uncompleting_sign_task = WireSignTask::Test { message: "frostsnap in taiwan".into(), }; let _unused_sign_session_id = run .coordinator .start_sign( access_structure_ref, uncompleting_sign_task, &device_set, &mut test_rng, ) .unwrap(); // fully cancel sign request run.coordinator.cancel_sign_session(_unused_sign_session_id); let completing_sign_task = WireSignTask::Test { message: "rip purple boards rip blue boards rip frostypedeV1".into(), }; let used_sign_session_id = run .coordinator .start_sign( access_structure_ref, completing_sign_task, &device_set, &mut test_rng, ) .unwrap(); for &device_id in &device_set { let sign_req = run.coordinator.request_device_sign( used_sign_session_id, device_id, TEST_ENCRYPTION_KEY, ); run.extend(sign_req); } // Test that this run completes without erroring, fully replenishing the nonces run.run_until_finished(&mut env, &mut test_rng).unwrap(); } } #[test] fn signing_a_bitcoin_transaction_produces_valid_signatures() { let n_parties = 3; let threshold = 2; let schnorr = Schnorr::<sha2::Sha256>::verify_only(); let mut test_rng = ChaCha20Rng::from_seed([42u8; 32]); let mut env = TestEnv::default(); let mut run = Run::start_after_keygen_and_nonces( n_parties, threshold, &mut env, &mut test_rng, 1, KeyPurpose::Bitcoin(bitcoin::Network::Bitcoin), ); let device_set = run.device_set(); let access_structure_ref = run .coordinator .iter_access_structures() .next() .unwrap() .access_structure_ref(); let key_data = run .coordinator .get_frost_key(access_structure_ref.key_id) .unwrap(); let mut tx_template = TransactionTemplate::new(); let master_appkey = key_data.complete_key.master_appkey; tx_template.push_imaginary_owned_input( LocalSpk { master_appkey, bip32_path: BitcoinBip32Path::external(7), }, bitcoin::Amount::from_sat(42_000), ); tx_template.push_imaginary_owned_input( LocalSpk { master_appkey, bip32_path: BitcoinBip32Path::internal(42), }, bitcoin::Amount::from_sat(1_337_000), ); let task = WireSignTask::BitcoinTransaction(tx_template); let checked_task = task .clone() .check( master_appkey, KeyPurpose::Bitcoin(bitcoin::Network::Bitcoin), ) .unwrap(); let set = device_set .iter() .choose_multiple(&mut test_rng, 2) .into_iter() .cloned() .collect(); let session_id = run .coordinator .start_sign(access_structure_ref, task.clone(), &set, &mut test_rng) .unwrap(); for &device_id in &set { let sign_req = run.coordinator .request_device_sign(session_id, device_id, TEST_ENCRYPTION_KEY); run.extend(sign_req); } run.run_until_finished(&mut env, &mut test_rng).unwrap(); assert!( checked_task.verify_final_signatures(&schnorr, env.signatures.get(&session_id).unwrap()) ); // TODO: test actual transaction validity } #[test] fn check_share_for_valid_share_works() { let n_parties = 3; let threshold = 2; let mut test_rng = ChaCha20Rng::from_seed([42u8; 32]); let mut env = TestEnv::default(); let mut run = Run::start_after_keygen( n_parties, threshold, &mut env, &mut test_rng, KeyPurpose::Test, ); let device_set = run.device_set(); let enter_physical_id = EnterPhysicalId::new(&mut test_rng); let access_structure_ref = run .coordinator .iter_access_structures() .next() .unwrap() .access_structure_ref(); for device_id in device_set.iter().cloned() { let display_backup = run .coordinator .request_device_display_backup(device_id, access_structure_ref, TEST_ENCRYPTION_KEY) .unwrap(); run.extend(display_backup); run.run_until_finished(&mut env, &mut test_rng).unwrap(); // Assign the valid backup that was just displayed for this device let (_, backup) = env.backups.get(&device_id).unwrap().clone(); env.backup_to_enter.insert(device_id, backup); let enter_backup = run .coordinator .tell_device_to_load_physical_backup(enter_physical_id, device_id); run.extend(enter_backup); run.run_until_finished(&mut env, &mut test_rng).unwrap(); } assert_eq!(env.physical_backups_entered.len(), n_parties); for physical_backup in env.physical_backups_entered.clone() { run.coordinator .check_physical_backup(access_structure_ref, physical_backup, TEST_ENCRYPTION_KEY) .unwrap(); } } #[test] fn check_share_for_invalid_share_fails() { let n_parties = 3; let threshold = 2; let mut test_rng = ChaCha20Rng::from_seed([42u8; 32]); let mut env = TestEnv::default(); let mut run = Run::start_after_keygen( n_parties, threshold, &mut env, &mut test_rng, KeyPurpose::Test, ); let enter_physical_id = EnterPhysicalId::new(&mut test_rng); let device_set = run.device_set(); // Prepare invalid backups for testing let invalid_backups: Vec<frost_backup::ShareBackup> = vec![ "#1 MISS DRAFT FOLD BRIGHT HURRY CONCERT SOURCE CLUB EQUIP ELEGANT TOY LYRICS CAR CABIN SYRUP LECTURE TEAM EQUIP WET ECHO LINK SILVER PURCHASE LECTURE NEXT".parse().unwrap(), "#2 BEST MIXTURE FOOT HABIT WORLD OBSERVE ADVICE ANNUAL ISSUE CAUSE PROPERTY GUESS RETURN HURDLE WEASEL CUP ONCE NOVEL MARCH VALVE BLIND TRIGGER CHAIR ACTOR MONTH".parse().unwrap(), "#3 PANDA SPHERE HAIR BRAVE VIRUS CATTLE LOOP WRAP RAMP READY TIP BODY GIANT OYSTER DIZZY CRUSH DANGER SNOW PLANET SHOVE LIQUID CLAW RICE AMONG JOB".parse().unwrap(), ]; let access_structure_ref = run .coordinator .iter_access_structures() .next() .unwrap() .access_structure_ref(); // Collect devices into a vector to access by index let devices: Vec<_> = device_set.iter().cloned().collect(); for (i, &device_id) in devices.iter().enumerate() { let display_backup = run .coordinator .request_device_display_backup(device_id, access_structure_ref, TEST_ENCRYPTION_KEY) .unwrap(); run.extend(display_backup); run.run_until_finished(&mut env, &mut test_rng).unwrap(); // Assign invalid backup for this device to enter env.backup_to_enter .insert(device_id, invalid_backups[i].clone()); let enter_backup = run .coordinator .tell_device_to_load_physical_backup(enter_physical_id, device_id); run.extend(enter_backup); run.run_until_finished(&mut env, &mut test_rng).unwrap(); } assert_eq!(env.physical_backups_entered.len(), n_parties); for physical_backup in env.physical_backups_entered { run.coordinator .check_physical_backup(access_structure_ref, physical_backup, TEST_ENCRYPTION_KEY) .unwrap_err(); } } #[test] fn restore_a_share_by_connecting_devices_to_a_new_coordinator() { let n_parties = 3; let threshold = 2; let mut test_rng = ChaCha20Rng::from_seed([42u8; 32]); let mut env = TestEnv::default(); let mut run = Run::start_after_keygen( n_parties, threshold, &mut env, &mut test_rng, KeyPurpose::Test, ); let device_set = run.device_set(); run.check_mutations(); let access_structure = run.coordinator.iter_access_structures().next().unwrap(); // replace coordinator with a fresh one that doesn't know about the key run.clear_coordinator(); let restoring_devices = device_set.iter().cloned().take(2).collect::<Vec<_>>(); for device_id in restoring_devices { let messages = run.coordinator.request_held_shares(device_id); run.extend(messages); } run.run_until_finished(&mut env, &mut test_rng).unwrap(); let restoration = run.coordinator.restoring().next().unwrap(); run.coordinator .finish_restoring( restoration.restoration_id, TEST_ENCRYPTION_KEY, &mut test_rng, ) .unwrap(); let restored_access_structure = run .coordinator .iter_access_structures() .next() .expect("two devices should have been enough to restore the share"); assert_eq!( restored_access_structure.access_structure_ref(), access_structure.access_structure_ref() ); assert_eq!( restored_access_structure.device_to_share_indicies().len(), 2 ); let final_device = device_set.iter().cloned().nth(2).unwrap(); let messages = run.coordinator.request_held_shares(final_device); run.extend(messages); run.run_until_finished(&mut env, &mut test_rng).unwrap(); let restored_access_structure = run .coordinator .iter_access_structures() .next() .expect("should still be restored"); assert_eq!( run.coordinator .get_frost_key(access_structure.access_structure_ref().key_id) .unwrap() .purpose, KeyPurpose::Test, "check the purpose was restored" ); assert_eq!(restored_access_structure, access_structure); } #[test] fn delete_then_restore_a_key_by_connecting_devices_to_coordinator() { let n_parties = 3; let threshold = 2; let mut rng = ChaCha20Rng::from_seed([42u8; 32]); let mut env = TestEnv::default(); let mut run = Run::start_after_keygen(n_parties, threshold, &mut env, &mut rng, KeyPurpose::Test); let device_set = run.device_set(); run.check_mutations(); let access_structure = run.coordinator.iter_access_structures().next().unwrap(); let access_structure_ref = access_structure.access_structure_ref(); run.coordinator.delete_key(access_structure_ref.key_id); assert_eq!(run.coordinator.iter_access_structures().count(), 0); assert_eq!( run.coordinator.get_frost_key(access_structure_ref.key_id), None ); let mut recover_next_share = |run: &mut Run, i: usize, rng: &mut ChaCha20Rng| { let device_id = device_set.iter().cloned().skip(i).take(1).next().unwrap(); let messages = run.coordinator.request_held_shares(device_id); run.extend(messages); run.run_until_finished(&mut env, rng).unwrap(); }; recover_next_share(&mut run, 0, &mut rng); assert!( !run.coordinator.staged_mutations().is_empty(), "recovering share should mutate something" ); run.check_mutations(); // this clears mutations recover_next_share(&mut run, 0, &mut rng); assert!( run.coordinator.staged_mutations().is_empty(), "recovering share again should not mutate" ); let restoration = run .coordinator .restoring() .next() .expect("one device should be enough to restore the key"); let restoration_id = restoration.restoration_id; assert!(!restoration.is_restorable()); assert_eq!( restoration.access_structure.access_structure_ref(), Some(access_structure_ref) ); recover_next_share(&mut run, 1, &mut rng); assert!( !run.coordinator.staged_mutations().is_empty(), "recovering share should mutate something" ); let restoration = run .coordinator .get_restoration_state(restoration_id) .unwrap(); assert!(restoration.is_restorable()); run.coordinator .finish_restoring(restoration.restoration_id, TEST_ENCRYPTION_KEY, &mut rng) .unwrap(); assert_eq!(run.coordinator.restoring().count(), 0); recover_next_share(&mut run, 2, &mut rng); let restored_access_structure = run.coordinator.iter_access_structures().next().unwrap(); assert_eq!( restored_access_structure, access_structure, "should have fully recovered the access structure now" ); run.check_mutations(); recover_next_share(&mut run, 0, &mut rng); assert!( run.coordinator.staged_mutations().is_empty(), "receiving same shares again should not mutate" ); recover_next_share(&mut run, 1, &mut rng); recover_next_share(&mut run, 2, &mut rng); } #[test] fn we_should_be_able_to_switch_between_sign_sessions() { let n_parties = 3; let threshold = 2; let mut test_rng = ChaCha20Rng::from_seed([42u8; 32]); let mut env = TestEnv::default(); let mut run = Run::start_after_keygen_and_nonces( n_parties, threshold, &mut env, &mut test_rng, 2, KeyPurpose::Test, ); let device_set = run.device_set(); let access_structure_ref = run .coordinator .iter_access_structures() .next() .unwrap() .access_structure_ref(); let sign_task_1 = WireSignTask::Test { message: "one".into(), }; let signing_set_1 = device_set.iter().cloned().take(2).collect(); let ssid1 = run .coordinator .start_sign( access_structure_ref, sign_task_1, &signing_set_1, &mut test_rng, ) .unwrap(); let signing_set_2 = device_set.iter().cloned().skip(1).take(2).collect(); let sign_task_2 = WireSignTask::Test { message: "two".into(), }; let ssid2 = run .coordinator .start_sign( access_structure_ref, sign_task_2, &signing_set_2, &mut test_rng, ) .unwrap(); let mut signers_1 = signing_set_1.into_iter(); let mut signers_2 = signing_set_2.into_iter(); for _ in 0..2 { let sign_req = run.coordinator.request_device_sign( ssid1, signers_1.next().unwrap(), TEST_ENCRYPTION_KEY, ); run.extend(sign_req); run.run_until_finished(&mut env, &mut test_rng).unwrap(); let sign_req = run.coordinator.request_device_sign( ssid2, signers_2.next().unwrap(), TEST_ENCRYPTION_KEY, ); run.extend(sign_req); run.run_until_finished(&mut env, &mut test_rng).unwrap(); } assert_eq!(env.signatures.len(), 2); } #[test] fn nonces_available_should_heal_itself_when_outcome_of_sign_request_is_ambigious() { let mut test_rng = ChaCha20Rng::from_seed([42u8; 32]); let mut env = TestEnv::default(); let mut run = Run::start_after_keygen_and_nonces(1, 1, &mut env, &mut test_rng, 1, KeyPurpose::Test); let device_set = run.device_set(); let device_id = device_set.iter().cloned().next().unwrap(); let available_at_start = run.coordinator.nonces_available(device_id); let access_structure_ref = run .coordinator .iter_access_structures() .next() .unwrap() .access_structure_ref(); let sign_task = WireSignTask::Test { message: "one".into(), }; let ssid = run .coordinator .start_sign(access_structure_ref, sign_task, &device_set, &mut test_rng) .unwrap(); // we going to take the request but not send it. // Coordinator is now unsure if it ever reached the device. let _sign_req = run .coordinator .request_device_sign(ssid, device_id, TEST_ENCRYPTION_KEY); let nonces_available_after_request = run.coordinator.nonces_available(device_id); assert_ne!(nonces_available_after_request, available_at_start); run.coordinator.cancel_sign_session(ssid); let nonces_available_after_cancel = run.coordinator.nonces_available(device_id); assert_ne!( nonces_available_after_cancel, available_at_start, "canceling should not reclaim ambigious nonces" ); // now we simulate reconnecting the device. The coordinator should recognise once of its nonce // streams has less nonces than usual and reset that stream. Since the device never signed the // request it should happily reset the stream to what it was before. run.extend(run.coordinator.maybe_request_nonce_replenishment( &BTreeSet::from([device_id]), 1, &mut test_rng, )); run.run_until_finished(&mut env, &mut test_rng).unwrap(); let nonces_available = run.coordinator.nonces_available(device_id); assert_eq!(nonces_available, available_at_start); }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/tests/restoration.rs
frostsnap_core/tests/restoration.rs
use common::TEST_ENCRYPTION_KEY; use frostsnap_core::device::KeyPurpose; use frostsnap_core::EnterPhysicalId; use rand_chacha::rand_core::SeedableRng; use rand_chacha::ChaCha20Rng; mod common; mod env; use crate::common::Run; use crate::env::TestEnv; #[test] fn restore_2_of_3_with_physical_backups_propagates_threshold() { let mut test_rng = ChaCha20Rng::from_seed([99u8; 32]); let mut env = TestEnv::default(); // Create a 2-of-3 key let mut run = Run::start_after_keygen_and_nonces(3, 2, &mut env, &mut test_rng, 2, KeyPurpose::Test); let device_set = run.device_set(); let _devices: Vec<_> = device_set.iter().cloned().collect(); let key_data = run.coordinator.iter_keys().next().unwrap(); let access_structure_ref = key_data .access_structures() .next() .unwrap() .access_structure_ref(); // Display backups for all devices for &device_id in &device_set { let display_backup = run .coordinator .request_device_display_backup(device_id, access_structure_ref, TEST_ENCRYPTION_KEY) .unwrap(); run.extend(display_backup); } run.run_until_finished(&mut env, &mut test_rng).unwrap(); assert_eq!(env.backups.len(), 3); // Get the backups let backups: Vec<_> = env .backups .values() .map(|(_, backup)| backup.clone()) .collect(); // Clear the coordinator and create fresh devices to simulate starting fresh restoration run.clear_coordinator(); let devices: Vec<_> = (0..3).map(|_| run.new_device(&mut test_rng)).collect(); // Assign backups to devices before they enter them for (i, &device_id) in devices.iter().enumerate() { env.backup_to_enter.insert(device_id, backups[i].clone()); } // Start restoration WITHOUT specifying threshold let restoration_id = frostsnap_core::RestorationId::new(&mut test_rng); run.coordinator.start_restoring_key( "Restored Wallet".to_string(), None, // No threshold specified KeyPurpose::Test, restoration_id, ); // First device enters its backup - coordinator doesn't know threshold yet let enter_physical_id_1 = EnterPhysicalId::new(&mut test_rng); let enter_backup_1 = run .coordinator .tell_device_to_load_physical_backup(enter_physical_id_1, devices[0]); run.extend(enter_backup_1); run.run_until_finished(&mut env, &mut test_rng).unwrap(); let physical_backup_phase_1 = *env .physical_backups_entered .last() .expect("Should have a physical backup phase"); // Check and save the first backup let check_result = run .coordinator .check_physical_backup_compatible_with_restoration( restoration_id, physical_backup_phase_1, TEST_ENCRYPTION_KEY, ); assert!(check_result.is_ok(), "First backup should be compatible"); let save_messages_1 = run .coordinator .tell_device_to_save_physical_backup(physical_backup_phase_1, restoration_id); run.extend(save_messages_1); run.run_until_finished(&mut env, &mut test_rng).unwrap(); // Second device enters its backup let enter_physical_id_2 = EnterPhysicalId::new(&mut test_rng); let enter_backup_2 = run .coordinator .tell_device_to_load_physical_backup(enter_physical_id_2, devices[1]); run.extend(enter_backup_2); run.run_until_finished(&mut env, &mut test_rng).unwrap(); let physical_backup_phase_2 = *env .physical_backups_entered .last() .expect("Should have a physical backup phase"); let save_messages_2 = run .coordinator .tell_device_to_save_physical_backup(physical_backup_phase_2, restoration_id); run.extend(save_messages_2); run.run_until_finished(&mut env, &mut test_rng).unwrap(); // Third device enters its backup let enter_physical_id_3 = EnterPhysicalId::new(&mut test_rng); let enter_backup_3 = run .coordinator .tell_device_to_load_physical_backup(enter_physical_id_3, devices[2]); run.extend(enter_backup_3); run.run_until_finished(&mut env, &mut test_rng).unwrap(); let physical_backup_phase_3 = *env .physical_backups_entered .last() .expect("Should have a physical backup phase"); let save_messages_3 = run .coordinator .tell_device_to_save_physical_backup(physical_backup_phase_3, restoration_id); run.extend(save_messages_3); run.run_until_finished(&mut env, &mut test_rng).unwrap(); // Check that the second device has the threshold in its saved backup let device_2 = run.device(devices[1]); let saved_backups_2 = device_2.saved_backups(); let saved_backup_2 = saved_backups_2 .get(&physical_backup_phase_2.backup.share_image) .expect("Second device should have saved the backup"); assert_eq!( saved_backup_2.threshold, Some(2), "Second device should know the threshold is 2 (discovered through fuzzy recovery when it entered its share)" ); // Check that the third device has the threshold in its saved backup let device_3 = run.device(devices[2]); let saved_backups_3 = device_3.saved_backups(); let saved_backup_3 = saved_backups_3 .get(&physical_backup_phase_3.backup.share_image) .expect("Third device should have saved the backup"); assert_eq!( saved_backup_3.threshold, Some(2), "Third device should know the threshold is 2 (discovered through fuzzy recovery of first two shares)" ); // Now finish the restoration let restoration_state = run .coordinator .get_restoration_state(restoration_id) .expect("Restoration should exist"); assert!( restoration_state.is_restorable(), "Should be restorable with 2 out of 3 shares" ); let restored_access_structure_ref = run .coordinator .finish_restoring(restoration_id, TEST_ENCRYPTION_KEY, &mut test_rng) .expect("Should finish restoring"); // Verify the key was restored with the correct threshold let _restored_key = run .coordinator .get_frost_key(restored_access_structure_ref.key_id) .expect("Restored key should exist"); let restored_access_structure = run .coordinator .get_access_structure(restored_access_structure_ref) .expect("Restored access structure should exist"); assert_eq!( restored_access_structure.threshold(), 2, "Restored key should have threshold of 2" ); // Now consolidate the physical backups on all devices for &device_id in &devices { if run .coordinator .has_backups_that_need_to_be_consolidated(device_id) { let consolidate_messages = run .coordinator .consolidate_pending_physical_backups(device_id, TEST_ENCRYPTION_KEY); run.extend(consolidate_messages); } } run.run_until_finished(&mut env, &mut test_rng).unwrap(); // Verify all devices now have properly encrypted shares for (i, &device_id) in devices.iter().enumerate() { assert!( !run.coordinator .has_backups_that_need_to_be_consolidated(device_id), "Device {:?} should have all backups consolidated", device_id ); // Verify the device actually has the encrypted share let device = run.device(device_id); let share_index = backups[i].share_image().index; let _encrypted_share = device .get_encrypted_share(restored_access_structure_ref, share_index) .unwrap_or_else(|| { panic!( "Device {:?} should have consolidated share at index {:?}", device_id, share_index ) }); } // Verify the restored access structure matches the original assert_eq!( restored_access_structure_ref, access_structure_ref, "Restored access structure should match original" ); } #[test] fn deleting_restoration_shares_reverts_state() { let mut test_rng = ChaCha20Rng::from_seed([100u8; 32]); let mut env = TestEnv::default(); // Create a 2-of-3 key let mut run = Run::start_after_keygen_and_nonces(3, 2, &mut env, &mut test_rng, 2, KeyPurpose::Test); let device_set = run.device_set(); let key_data = run.coordinator.iter_keys().next().unwrap(); let access_structure_ref = key_data .access_structures() .next() .unwrap() .access_structure_ref(); // Display backups for all devices for &device_id in &device_set { let display_backup = run .coordinator .request_device_display_backup(device_id, access_structure_ref, TEST_ENCRYPTION_KEY) .unwrap(); run.extend(display_backup); } run.run_until_finished(&mut env, &mut test_rng).unwrap(); let backups: Vec<_> = env .backups .values() .map(|(_, backup)| backup.clone()) .collect(); // Clear the coordinator and create fresh devices run.clear_coordinator(); let devices: Vec<_> = (0..3).map(|_| run.new_device(&mut test_rng)).collect(); for (i, &device_id) in devices.iter().enumerate() { env.backup_to_enter.insert(device_id, backups[i].clone()); } // Start restoration let restoration_id = frostsnap_core::RestorationId::new(&mut test_rng); run.coordinator.start_restoring_key( "Test Wallet".to_string(), None, KeyPurpose::Test, restoration_id, ); // Add all three shares for &device_id in &devices { let enter_physical_id = EnterPhysicalId::new(&mut test_rng); let enter_backup = run .coordinator .tell_device_to_load_physical_backup(enter_physical_id, device_id); run.extend(enter_backup); run.run_until_finished(&mut env, &mut test_rng).unwrap(); let physical_backup_phase = *env .physical_backups_entered .last() .expect("Should have a physical backup phase"); let save_messages = run .coordinator .tell_device_to_save_physical_backup(physical_backup_phase, restoration_id); run.extend(save_messages); run.run_until_finished(&mut env, &mut test_rng).unwrap(); } // Before removal: we have 3 shares and the key is recovered let restoration_state_before = run .coordinator .get_restoration_state(restoration_id) .expect("Restoration should exist"); assert!( restoration_state_before.is_restorable(), "Should be restorable with 3 shares" ); assert_eq!( restoration_state_before.status().shares.len(), 3, "Should have 3 shares" ); assert!( restoration_state_before.status().shared_key.is_some(), "Shared key should be recovered" ); // Remove the third share run.coordinator .delete_restoration_share(restoration_id, devices[2]); // After removal: we should still have 2 shares and key still recovered (2-of-3 only needs 2) let restoration_state_after_one_removal = run .coordinator .get_restoration_state(restoration_id) .expect("Restoration should exist"); assert!( restoration_state_after_one_removal.is_restorable(), "Should still be restorable with 2 shares" ); assert_eq!( restoration_state_after_one_removal.status().shares.len(), 2, "Should have 2 shares after removal" ); assert!( restoration_state_after_one_removal .status() .shared_key .is_some(), "Shared key should still be recovered with 2 shares" ); // Remove another share - now we should lose the shared_key run.coordinator .delete_restoration_share(restoration_id, devices[1]); let restoration_state_after_two_removals = run .coordinator .get_restoration_state(restoration_id) .expect("Restoration should exist"); assert!( !restoration_state_after_two_removals.is_restorable(), "Should NOT be restorable with only 1 share (need 2 for 2-of-3)" ); assert_eq!( restoration_state_after_two_removals.status().shares.len(), 1, "Should have 1 share after second removal" ); assert!( restoration_state_after_two_removals .status() .shared_key .is_none(), "Shared key should be None with only 1 share" ); } #[test] fn consolidate_backup_with_polynomial_checksum_validation() { let mut test_rng = ChaCha20Rng::from_seed([43u8; 32]); let mut env = TestEnv::default(); // Do a 2-of-2 keygen to get valid keys let mut run = Run::start_after_keygen_and_nonces(2, 2, &mut env, &mut test_rng, 2, KeyPurpose::Test); let device_set = run.device_set(); let key_data = run.coordinator.iter_keys().next().unwrap(); let access_structure_ref = key_data .access_structures() .next() .unwrap() .access_structure_ref(); // Display backups for all devices for &device_id in &device_set { let display_backup = run .coordinator .request_device_display_backup(device_id, access_structure_ref, TEST_ENCRYPTION_KEY) .unwrap(); run.extend(display_backup); } run.run_until_finished(&mut env, &mut test_rng).unwrap(); // Now we have backups in env.backups assert_eq!(env.backups.len(), 2); // Pick the first device let device_id = *env.backups.keys().next().unwrap(); let (_, backup) = env.backups.get(&device_id).unwrap().clone(); // Assign the backup for this device to enter env.backup_to_enter.insert(device_id, backup); // Tell the device to enter backup mode let enter_physical_id = frostsnap_core::EnterPhysicalId::new(&mut test_rng); let enter_backup = run .coordinator .tell_device_to_load_physical_backup(enter_physical_id, device_id); run.extend(enter_backup); run.run_until_finished(&mut env, &mut test_rng).unwrap(); // The env should have received an EnterBackup message and we simulate entering it // The TestEnv will handle entering the backup we already have for this device // Get the PhysicalBackupPhase from the env that was populated when the device responded let physical_backup_phase = *env .physical_backups_entered .last() .expect("Should have a physical backup phase"); let consolidate = run .coordinator .tell_device_to_consolidate_physical_backup( physical_backup_phase, access_structure_ref, TEST_ENCRYPTION_KEY, ) .unwrap(); run.extend(consolidate); // This should succeed because the polynomial checksum is valid run.run_until_finished(&mut env, &mut test_rng).unwrap(); // Verify that the device now has the consolidated share let device = run.device(device_id); let _encrypted_share = device .get_encrypted_share( access_structure_ref, physical_backup_phase.backup.share_image.index, ) .expect("Device should have the consolidated share"); // Verify the coordinator also knows about this share assert!( run.coordinator.knows_about_share( device_id, access_structure_ref, physical_backup_phase.backup.share_image.index ), "Coordinator should know about the consolidated share" ); }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/tests/share_location.rs
frostsnap_core/tests/share_location.rs
use common::TEST_ENCRYPTION_KEY; use frostsnap_core::coordinator::KeyLocationState; use frostsnap_core::device::KeyPurpose; use frostsnap_core::message::HeldShare2; use frostsnap_core::DeviceId; use rand_chacha::rand_core::SeedableRng; use rand_chacha::ChaCha20Rng; mod common; mod env; use crate::common::Run; use crate::env::TestEnv; /// Tests that find_share correctly locates a share in a complete wallet held by a single device. /// /// Setup: Generate a 2-of-3 key. /// Action: Query for a share that exists on one device in the complete wallet. /// Expected: find_share returns the ShareLocation with: /// - device_ids containing only that one device /// - KeyLocationState::Complete with the correct access_structure_ref /// - The correct share_index and key_name #[test] fn test_find_share_in_complete_wallet_single_device() { let mut test_rng = ChaCha20Rng::from_seed([2u8; 32]); let mut env = TestEnv::default(); let run = Run::start_after_keygen(3, 2, &mut env, &mut test_rng, KeyPurpose::Test); let key_data = run.coordinator.iter_keys().next().unwrap().clone(); let access_structure = key_data.access_structures().next().unwrap(); let access_structure_ref = access_structure.access_structure_ref(); // Use iter_shares to get a share from the complete wallet let (share_image, expected_location) = run .coordinator .iter_shares(TEST_ENCRYPTION_KEY) .next() .unwrap(); // Verify the location from iter_shares assert_eq!(expected_location.device_ids.len(), 1); let first_device_id = expected_location.device_ids[0]; // Now test find_share let result = run.coordinator.find_share(share_image, TEST_ENCRYPTION_KEY); assert!(result.is_some(), "Should find share in complete wallet"); let location = result.unwrap(); assert_eq!(location.key_name, key_data.key_name); assert_eq!(location.device_ids, vec![first_device_id]); assert_eq!(location.share_index, share_image.index); match location.key_state { KeyLocationState::Complete { access_structure_ref: found_ref, } => { assert_eq!(found_ref, access_structure_ref); } _ => panic!("Expected Complete key state"), } } /// Tests that find_share returns all devices holding the same share in a complete wallet. /// /// Setup: Generate a 2-of-3 key, then use recover_share to restore the same physical backup /// onto a second device (simulating loading a backup onto multiple devices). /// Action: Query for the share that now exists on two different devices. /// Expected: find_share returns ShareLocation with device_ids containing both devices, /// since the same share (same ShareImage) exists on multiple devices. #[test] fn test_find_share_in_complete_wallet_multiple_devices() { let mut test_rng = ChaCha20Rng::from_seed([3u8; 32]); let mut env = TestEnv::default(); let mut run = Run::start_after_keygen(3, 2, &mut env, &mut test_rng, KeyPurpose::Test); let key_data = run.coordinator.iter_keys().next().unwrap().clone(); let access_structure = key_data.access_structures().next().unwrap(); let access_structure_ref = access_structure.access_structure_ref(); // Use iter_shares to get a share from the complete wallet let (share_image, location) = run .coordinator .iter_shares(TEST_ENCRYPTION_KEY) .next() .unwrap(); let first_device_id = location.device_ids[0]; let share_index = share_image.index; // Create a new device (not part of the original keygen) to simulate // loading a physical backup onto a fresh device let new_device = DeviceId([99u8; 33]); // Create the recover share for the second device with the same share let held_share = HeldShare2 { access_structure_ref: Some(access_structure_ref), share_image, key_name: Some(key_data.key_name.clone()), purpose: Some(key_data.purpose), threshold: Some(access_structure.threshold()), needs_consolidation: false, }; let recover_share = frostsnap_core::coordinator::restoration::RecoverShare { held_by: new_device, held_share, }; // Add the share to the existing access structure run.coordinator .recover_share(access_structure_ref, &recover_share, TEST_ENCRYPTION_KEY) .expect("should be able to add duplicate share"); // Now find_share should return both devices let result = run.coordinator.find_share(share_image, TEST_ENCRYPTION_KEY); assert!(result.is_some()); let location = result.unwrap(); assert_eq!( location.device_ids.len(), 2, "Should find share on two devices" ); assert!(location.device_ids.contains(&first_device_id)); assert!(location.device_ids.contains(&new_device)); assert_eq!(location.share_index, share_index); match location.key_state { KeyLocationState::Complete { access_structure_ref: found_ref, } => { assert_eq!(found_ref, access_structure_ref); } _ => panic!("Expected Complete key state"), } } /// Tests that find_share locates a virtual share in a complete wallet. /// /// Setup: Generate a 2-of-3 key where devices have indices 1, 2, 3. /// Action: Compute a share_image for a valid but unassigned index (e.g., 4). /// Expected: find_share returns ShareLocation with: /// - device_ids EMPTY (no device has this share) /// - KeyLocationState::Complete with the correct access_structure_ref /// - The share exists mathematically via the root_shared_key #[test] fn test_find_share_virtual_in_complete_wallet() { let mut test_rng = ChaCha20Rng::from_seed([9u8; 32]); let mut env = TestEnv::default(); let run = Run::start_after_keygen(3, 2, &mut env, &mut test_rng, KeyPurpose::Test); let key_data = run.coordinator.iter_keys().next().unwrap().clone(); let access_structure = key_data.access_structures().next().unwrap(); let access_structure_ref = access_structure.access_structure_ref(); // Get the root shared key to compute a virtual share let root_shared_key = run .coordinator .root_shared_key(access_structure_ref, TEST_ENCRYPTION_KEY) .unwrap(); // Find an index that no device has let assigned_indices: std::collections::HashSet<_> = access_structure .device_to_share_indicies() .values() .cloned() .collect(); // Use index 4 which won't be assigned in a 2-of-3 key (devices get 1, 2, 3) let virtual_index = schnorr_fun::fun::Scalar::from(core::num::NonZeroU32::new(4).expect("4 is non-zero")); assert!(!assigned_indices.contains(&virtual_index)); let virtual_share_image = root_shared_key.share_image(virtual_index); // Find this virtual share let result = run .coordinator .find_share(virtual_share_image, TEST_ENCRYPTION_KEY); assert!( result.is_some(), "Should find virtual share in complete wallet" ); let location = result.unwrap(); assert!( location.device_ids.is_empty(), "Virtual share should have no device_ids" ); assert_eq!(location.share_index, virtual_index); assert_eq!(location.key_name, key_data.key_name); match location.key_state { KeyLocationState::Complete { access_structure_ref: found_ref, } => { assert_eq!(found_ref, access_structure_ref); } _ => panic!("Expected Complete key state"), } } /// Tests that find_share locates a share that's been physically collected during restoration. /// /// Setup: Generate a key, clear the coordinator, then start restoration by requesting /// a held share from one device. /// Action: Query for the share that was physically provided by the device. /// Expected: find_share returns ShareLocation with: /// - device_ids containing the device that provided the share /// - KeyLocationState::Restoring with the restoration_id /// - The share is "physical" because a device actually sent it #[test] fn test_find_share_in_restoration_physical() { let mut test_rng = ChaCha20Rng::from_seed([4u8; 32]); let mut env = TestEnv::default(); let mut run = Run::start_after_keygen(3, 2, &mut env, &mut test_rng, KeyPurpose::Test); let device_set = run.device_set(); // Clear coordinator to start restoration run.clear_coordinator(); // Request shares from first device let first_device = device_set.iter().next().cloned().unwrap(); let messages = run.coordinator.request_held_shares(first_device); run.extend(messages); run.run_until_finished(&mut env, &mut test_rng).unwrap(); let restoration = run.coordinator.restoring().next().unwrap(); let held_share = &restoration.access_structure.held_shares[0]; let share_image = held_share.held_share.share_image; let result = run.coordinator.find_share(share_image, TEST_ENCRYPTION_KEY); assert!(result.is_some(), "Should find share in restoration"); let location = result.unwrap(); assert_eq!(location.device_ids, vec![first_device]); assert_eq!(location.share_index, share_image.index); assert_eq!(location.key_name, restoration.key_name); match location.key_state { KeyLocationState::Restoring { restoration_id } => { assert_eq!(restoration_id, restoration.restoration_id); } _ => panic!("Expected Restoring key state"), } } /// Tests that find_share locates a "virtual" share via the cached SharedKey in a restoration. /// /// Setup: Generate a 2-of-3 key, clear the coordinator, then restore /// by collecting shares from only 2 devices (meeting the threshold). /// Action: Query for the share from the third device that was NOT physically collected. /// Expected: find_share returns ShareLocation with: /// - device_ids EMPTY (no device physically provided this share) /// - KeyLocationState::Restoring with the restoration_id /// - The share is "virtual" because fuzzy recovery succeeded and cached the SharedKey, /// so we can compute that this ShareImage exists mathematically, even though no /// device has provided it yet. #[test] fn test_find_share_in_restoration_virtual() { let mut test_rng = ChaCha20Rng::from_seed([5u8; 32]); let mut env = TestEnv::default(); let mut run = Run::start_after_keygen(3, 2, &mut env, &mut test_rng, KeyPurpose::Test); // Get all shares before clearing coordinator let all_shares: Vec<_> = run.coordinator.iter_shares(TEST_ENCRYPTION_KEY).collect(); assert_eq!(all_shares.len(), 3, "Should have 3 shares in 2-of-3 key"); let device_set = run.device_set(); // Clear coordinator to start restoration run.clear_coordinator(); // Request shares from only 2 devices (threshold is 2) let restoring_devices: Vec<_> = device_set.iter().cloned().take(2).collect(); for device_id in &restoring_devices { let messages = run.coordinator.request_held_shares(*device_id); run.extend(messages); } run.run_until_finished(&mut env, &mut test_rng).unwrap(); let restoration = run.coordinator.restoring().next().unwrap(); // The restoration should have recovered (threshold met) assert!(restoration.is_restorable()); // Find a share from the third device that wasn't included in the restoration let third_device = device_set.iter().cloned().nth(2).unwrap(); let (third_device_share_image, _) = all_shares .iter() .find(|(_, loc)| loc.device_ids.contains(&third_device)) .unwrap(); let third_device_share_image = *third_device_share_image; let third_device_share_index = third_device_share_image.index; // This share should be found "virtually" - we know it exists via the recovered SharedKey // but no device has physically provided it to this coordinator let result = run .coordinator .find_share(third_device_share_image, TEST_ENCRYPTION_KEY); assert!( result.is_some(), "Should find share virtually via cached SharedKey" ); let location = result.unwrap(); assert!( location.device_ids.is_empty(), "Virtual share should have no device_ids" ); assert_eq!(location.share_index, third_device_share_index); assert_eq!(location.key_name, restoration.key_name); } /// Tests that find_share detects when trying to add a duplicate share to the same restoration. /// /// Setup: Generate a key, clear the coordinator, start restoration with one device's share. /// Action: Query for the share that was just added to the restoration. /// Expected: find_share returns the ShareLocation pointing to the ongoing restoration, /// which allows the caller to detect "this share is already in this restoration" /// and prevent duplicate addition. #[test] fn test_find_share_duplicate_same_restoration() { let mut test_rng = ChaCha20Rng::from_seed([6u8; 32]); let mut env = TestEnv::default(); let mut run = Run::start_after_keygen(3, 2, &mut env, &mut test_rng, KeyPurpose::Test); let device_set = run.device_set(); run.clear_coordinator(); // Add first device's share let first_device = device_set.iter().next().cloned().unwrap(); let messages = run.coordinator.request_held_shares(first_device); run.extend(messages); run.run_until_finished(&mut env, &mut test_rng).unwrap(); let restoration = run.coordinator.restoring().next().unwrap(); let share_image = restoration.access_structure.held_shares[0] .held_share .share_image; // Try to find this share (which already exists in the restoration) let result = run.coordinator.find_share(share_image, TEST_ENCRYPTION_KEY); assert!(result.is_some(), "Should find share already in restoration"); let location = result.unwrap(); match location.key_state { KeyLocationState::Restoring { restoration_id } => { assert_eq!(restoration_id, restoration.restoration_id); } _ => panic!("Expected Restoring key state"), } assert_eq!(location.device_ids, vec![first_device]); } /// Tests that find_share detects conflicts when a share exists in one restoration and /// someone tries to add it to a different restoration. /// /// Setup: Generate a key, clear coordinator, start first restoration with device 1, /// then start second restoration with device 2. /// Action: Query for the share from device 1 (which is in first restoration). /// Expected: find_share returns the ShareLocation pointing to the FIRST restoration, /// not the second one. This allows detecting cross-restoration conflicts. #[test] fn test_find_share_conflict_different_restorations() { let mut test_rng = ChaCha20Rng::from_seed([7u8; 32]); let mut env = TestEnv::default(); let mut run = Run::start_after_keygen(3, 2, &mut env, &mut test_rng, KeyPurpose::Test); let device_set = run.device_set(); run.clear_coordinator(); // Start first restoration with device 1 let first_device = device_set.iter().next().cloned().unwrap(); let messages = run.coordinator.request_held_shares(first_device); run.extend(messages); run.run_until_finished(&mut env, &mut test_rng).unwrap(); let first_restoration = run.coordinator.restoring().next().unwrap(); let share_image = first_restoration.access_structure.held_shares[0] .held_share .share_image; let first_restoration_id = first_restoration.restoration_id; // Start a second restoration with device 2 let second_device = device_set.iter().nth(1).cloned().unwrap(); let messages = run.coordinator.request_held_shares(second_device); run.extend(messages); run.run_until_finished(&mut env, &mut test_rng).unwrap(); // Now try to find the share from first restoration // It should be found in the first restoration let result = run.coordinator.find_share(share_image, TEST_ENCRYPTION_KEY); assert!(result.is_some(), "Should find share in first restoration"); let location = result.unwrap(); match location.key_state { KeyLocationState::Restoring { restoration_id } => { assert_eq!( restoration_id, first_restoration_id, "Should find in first restoration, not second" ); } _ => panic!("Expected Restoring key state"), } } /// Tests that find_share prioritizes complete wallets over ongoing restorations. /// /// Setup: Generate a complete key, then start a restoration with a different device /// (simulating trying to restore while some keys already exist). /// Action: Query for a share that exists in the complete wallet. /// Expected: find_share returns ShareLocation pointing to the Complete wallet, not the /// ongoing restoration. This allows detecting "this share already exists in a /// complete wallet, don't try to restore it into a new wallet." #[test] fn test_find_share_conflict_complete_vs_restoration() { let mut test_rng = ChaCha20Rng::from_seed([8u8; 32]); let mut env = TestEnv::default(); let mut run = Run::start_after_keygen(3, 2, &mut env, &mut test_rng, KeyPurpose::Test); let key_data = run.coordinator.iter_keys().next().unwrap().clone(); let access_structure = key_data.access_structures().next().unwrap(); let access_structure_ref = access_structure.access_structure_ref(); // Use iter_shares to get a share from the complete wallet let (share_image, location) = run .coordinator .iter_shares(TEST_ENCRYPTION_KEY) .next() .unwrap(); let first_device = location.device_ids[0]; let device_set = run.device_set(); // Now start a restoration with a different device let second_device = device_set .iter() .find(|&&d| d != first_device) .cloned() .unwrap(); let messages = run.coordinator.request_held_shares(second_device); run.extend(messages); run.run_until_finished(&mut env, &mut test_rng).unwrap(); // Try to find the first device's share - it should be found in the complete wallet let result = run.coordinator.find_share(share_image, TEST_ENCRYPTION_KEY); assert!( result.is_some(), "Should find share in complete wallet even with restoration ongoing" ); let location = result.unwrap(); match location.key_state { KeyLocationState::Complete { access_structure_ref: found_ref, } => { assert_eq!(found_ref, access_structure_ref); } _ => panic!("Expected Complete key state, not restoration"), } assert_eq!(location.device_ids, vec![first_device]); }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/tests/feerate_calculation.rs
frostsnap_core/tests/feerate_calculation.rs
use bitcoin::{Amount, ScriptBuf, TxOut}; use frostsnap_core::bitcoin_transaction::{LocalSpk, TransactionTemplate}; use frostsnap_core::tweak::BitcoinBip32Path; use frostsnap_core::MasterAppkey; use schnorr_fun::fun::G; /// Test that TransactionTemplate.feerate() correctly estimates the feerate /// of a signed transaction based on real signet transaction: /// https://mempool.space/signet/tx/0c6f19d7f0544543df6ccb0f853a2518e60edd505acbe3111a098900d9b3033d /// /// This transaction has: /// - 2 taproot keyspend inputs (5,000 + 11,000 sats) /// - 1 output (15,831 sats) /// - Fee: 169 sats /// - Weight: 674 WU /// - vSize: 168.5 bytes #[test] fn test_feerate_estimation_accuracy() { let mut template = TransactionTemplate::new(); // Create dummy master appkey (doesn't matter for weight calculation) let master_appkey = MasterAppkey::derive_from_rootkey(G.normalize()); // Create dummy local SPK for the inputs let local_spk = LocalSpk { master_appkey, bip32_path: BitcoinBip32Path::external(0), }; // Add 2 owned inputs matching the real transaction amounts template.push_imaginary_owned_input(local_spk.clone(), Amount::from_sat(5_000)); template.push_imaginary_owned_input(local_spk, Amount::from_sat(11_000)); // Use the actual output scriptPubKey from the real transaction let output_script = ScriptBuf::from_hex("5120a62baa9e7c1aeda63492f2129cc8226a39db1bc05a9c11e45a61cb751a11061d") .unwrap(); // Add output matching the real transaction template.push_foreign_output(TxOut { value: Amount::from_sat(15_831), script_pubkey: output_script, }); // Get the estimated feerate from template let template_feerate = template.feerate().expect("should calculate feerate"); let template_fee = template.fee().expect("should calculate fee"); // The real transaction has these metrics const EXPECTED_VSIZE: f64 = 168.5; const EXPECTED_FEE: u64 = 169; const EXPECTED_FEERATE: f64 = EXPECTED_FEE as f64 / EXPECTED_VSIZE; // The fee should match exactly assert_eq!( template_fee, EXPECTED_FEE, "Fee mismatch: template calculated {}, expected {}", template_fee, EXPECTED_FEE ); // The feerate should match within 0.1 sat/vB let difference = (template_feerate - EXPECTED_FEERATE).abs(); assert!( difference < 0.1, "Feerate estimation is off by {:.2} sat/vB. Expected {:.2}, got {:.2}", difference, EXPECTED_FEERATE, template_feerate ); }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/tests/proptest.rs
frostsnap_core/tests/proptest.rs
mod common; use common::*; use proptest::{ array, prelude::*, sample, test_runner::{Config, RngAlgorithm, TestRng}, }; use std::collections::{BTreeMap, BTreeSet}; use frostsnap_core::{ bitcoin_transaction::{LocalSpk, TransactionTemplate}, coordinator::{ BeginKeygen, CoordinatorToUserKeyGenMessage, CoordinatorToUserMessage, CoordinatorToUserSigningMessage, }, device::{DeviceToUserMessage, KeyGenPhase3, KeyPurpose, SignPhase1}, message::{self, DeviceSend, DeviceToCoordinatorMessage}, tweak::BitcoinBip32Path, AccessStructureRef, DeviceId, KeygenId, SignSessionId, WireSignTask, }; use proptest_state_machine::{ prop_state_machine, strategy::ReferenceStateMachine, StateMachineTest, }; #[derive(Clone, Debug)] struct RefState { run_start: Run, pending_keygens: BTreeMap<KeygenId, RefKeygen>, finished_keygens: Vec<RefFinishedKey>, sign_sessions: Vec<RefSignSession>, device_nonce_streams: BTreeMap<DeviceId, Vec<RefNonceStream>>, n_nonce_slots: usize, n_desired_nonce_streams_coord: usize, nonce_batch_size: u32, } impl RefState { pub fn n_devices(&self) -> usize { self.run_start.devices.len() } fn is_stream_locked(&self, device_id: DeviceId, stream_id: usize) -> bool { self.sign_sessions.iter().any(|session| { !session.canceled && session.device_streams.get(&device_id) == Some(&stream_id) }) } fn get_device_stream_for_signing_session( &mut self, session: &RefSignSession, device_id: &DeviceId, ) -> &mut RefNonceStream { let stream_id = session.device_streams[device_id]; &mut self.device_nonce_streams.get_mut(device_id).unwrap()[stream_id] } fn find_available_stream(&self, device_id: DeviceId, n_inputs: usize) -> Option<usize> { self.device_nonce_streams .get(&device_id)? .iter() .enumerate() .find(|(stream_id, stream)| { !self.is_stream_locked(device_id, *stream_id) && stream.nonces_available >= n_inputs }) .map(|(stream_id, _)| stream_id) } fn max_available_nonces_for_device(&self, device_id: DeviceId) -> usize { self.device_nonce_streams .get(&device_id) .and_then(|streams| { streams .iter() .enumerate() .filter(|(stream_id, _)| !self.is_stream_locked(device_id, *stream_id)) .map(|(_, stream)| stream.nonces_available) .max() }) .unwrap_or(0) } fn cancel_session_and_consume_nonces(&mut self, session_idx: usize) { let session = &mut self.sign_sessions[session_idx]; session.canceled = true; let session = session.clone(); let devices_to_consume: Vec<_> = session .sent_req_to .difference(&session.got_sigs_from) .cloned() .collect(); for device_id in devices_to_consume { let stream = self.get_device_stream_for_signing_session(&session, &device_id); stream.nonces_available = stream.nonces_available.saturating_sub(session.n_inputs); } } pub fn available_signing_devices(&self) -> BTreeSet<DeviceId> { // A device is available if it has at least one unlocked stream with at least 1 nonce self.device_nonce_streams .iter() .filter(|(device_id, streams)| { streams.iter().enumerate().any(|(stream_id, stream)| { !self.is_stream_locked(**device_id, stream_id) && stream.nonces_available > 0 }) }) .map(|(device_id, _)| *device_id) .collect() } } #[derive(Clone, Debug)] struct RefSignSession { key_index: usize, devices: BTreeSet<DeviceId>, n_inputs: usize, device_streams: BTreeMap<DeviceId, usize>, // DeviceId -> stream_id got_sigs_from: BTreeSet<DeviceId>, sent_req_to: BTreeSet<DeviceId>, canceled: bool, } impl RefSignSession { pub fn finished(&self) -> bool { self.devices == self.got_sigs_from } pub fn active(&self) -> bool { !self.finished() && !self.canceled } } #[derive(Clone, Debug)] struct RefKeygen { do_keygen: BeginKeygen, devices_confirmed: BTreeSet<DeviceId>, } #[derive(Clone, Debug)] struct RefFinishedKey { do_keygen: BeginKeygen, deleted: bool, } #[derive(Clone, Debug)] struct RefNonceStream { nonces_available: usize, } #[derive(Clone, Debug)] enum Transition { CStartKeygen(BeginKeygen), DKeygenAck { device_id: DeviceId, keygen_id: KeygenId, }, CKeygenConfirm { keygen_id: KeygenId, }, CNonceReplenish { device_id: DeviceId, }, CStartSign { key_index: usize, devices: BTreeSet<DeviceId>, n_inputs: usize, }, CSendSignRequest { session_index: usize, device_id: DeviceId, }, CCancelSignSession { session_index: usize, }, DAckSignRequest { session_index: usize, device_id: DeviceId, }, CDeleteKey { key_index: usize, }, } impl ReferenceStateMachine for RefState { type State = RefState; type Transition = Transition; fn init_state() -> BoxedStrategy<Self::State> { (1u16..8, 1usize..10, 1usize..4) .prop_map( move |(n_devices, n_nonce_slots, n_desired_nonce_streams_coord)| { let mut rng = TestRng::deterministic_rng(RngAlgorithm::ChaCha); let nonce_batch_size = 4u32; // Small batch size for testing let run = Run::generate_with_nonce_slots_and_batch_size( n_devices.into(), &mut rng, n_nonce_slots, nonce_batch_size, ); RefState { run_start: run, pending_keygens: Default::default(), finished_keygens: Default::default(), sign_sessions: Default::default(), device_nonce_streams: Default::default(), // Start with no streams, CNonceReplenish will add them n_nonce_slots, n_desired_nonce_streams_coord, nonce_batch_size, } }, ) .boxed() } fn transitions(state: &Self::State) -> BoxedStrategy<Self::Transition> { let mut trans = vec![]; { let possible_devices = sample::select(state.run_start.device_vec()); let devices_and_threshold = proptest::collection::btree_set(possible_devices, 1..=state.n_devices()) .prop_flat_map(|devices| (Just(devices.clone()), 1..=devices.len())); let name = proptest::string::string_regex("[A-Z][a-z][a-z]") .unwrap() .no_shrink(); let keygen_id = array::uniform::<_, 16>(0..=u8::MAX)/* testing colliding keygen ids is not of interest */ .no_shrink(); let keygen_trans = (keygen_id, devices_and_threshold, name) .prop_map(move |(keygen_id, (devices, threshold), key_name)| { Transition::CStartKeygen(BeginKeygen::new_with_id( devices.into_iter().collect(), threshold as u16, key_name, KeyPurpose::Bitcoin(bitcoin::Network::Regtest), KeygenId::from_bytes(keygen_id), )) }) .boxed(); trans.push((1, keygen_trans)); } for (&keygen_id, keygen) in &state.pending_keygens { let candidates = keygen .do_keygen .device_to_share_index .keys() .filter(|device_id| !keygen.devices_confirmed.contains(device_id)) .cloned() .collect::<Vec<_>>(); if candidates.is_empty() { trans.push((10, Just(Transition::CKeygenConfirm { keygen_id }).boxed())); } else { let device_ack = sample::select(candidates) .prop_map(move |device_id| Transition::DKeygenAck { keygen_id, device_id, }) .boxed(); trans.push((10, device_ack)); } } let nonce_req = sample::select(state.run_start.device_vec()) .prop_map(|device_id| Transition::CNonceReplenish { device_id }) .boxed(); trans.push((3, nonce_req)); // sign request { let candidate_keys = state .finished_keygens .iter() .cloned() .enumerate() .filter_map(|(key_index, key)| { let available = key .do_keygen .devices() .intersection(&state.available_signing_devices()) .cloned() .map(|device_id| { (device_id, state.max_available_nonces_for_device(device_id)) }) .collect::<Vec<_>>(); if available.len() > key.do_keygen.threshold as usize { Some((key_index, key, available)) } else { None } }) .collect::<Vec<_>>(); if !candidate_keys.is_empty() { let start_sign = sample::select(candidate_keys) .prop_flat_map(|(key_index, key, available_devices)| { let sample = sample::select(available_devices); let signing_set = proptest::collection::btree_set( sample, key.do_keygen.threshold as usize, ); signing_set .prop_flat_map(move |devices| { // Calculate minimum available nonces across selected devices let min_available_nonces = devices .iter() .map(|(_, nonces_available)| *nonces_available) .min() .unwrap_or(0); assert!(min_available_nonces > 0, "devices_with_nonces filter should ensure all devices have available nonces"); let devices: BTreeSet<DeviceId> = devices.into_iter().map(|(device_id, _)| device_id).collect(); // Generate n_inputs between 1 and min available (1..=min_available_nonces) .prop_map(move |n_inputs| { Some(Transition::CStartSign { key_index, devices: devices.clone(), n_inputs, }) }) .boxed() } ) .boxed() } ) .prop_filter_map("filter out None transitions", |x| x) .boxed(); trans.push((2, start_sign)); } } let unfinished_sesssions = state .sign_sessions .iter() .filter(|session| !session.active()) .enumerate(); for (index, session) in unfinished_sesssions { // coord send sign request { let candidates = session .devices .iter() // NOTE: We allow re-sending sign requests to device we've already sent it to but haven't got it from yet. .filter(|id| !session.got_sigs_from.contains(id)) .copied() .collect::<Vec<_>>(); if !candidates.is_empty() { let next_to_ask = sample::select(candidates); let sign_req = next_to_ask .prop_map(move |device_id| Transition::CSendSignRequest { session_index: index, device_id, }) .boxed(); trans.push((10, sign_req)); } } // device ack sign request { let candidates = session.sent_req_to.clone().into_iter().collect::<Vec<_>>(); if !candidates.is_empty() { let selected = sample::select(candidates); let ack_sign = selected .prop_map(move |device_id| Transition::DAckSignRequest { session_index: index, device_id, }) .boxed(); trans.push((10, ack_sign)); } } } // Coordinator cancel if !state.sign_sessions.is_empty() { let cancel_session = sample::select((0..state.sign_sessions.len()).collect::<Vec<_>>()) .prop_map(|session_index| Transition::CCancelSignSession { session_index }) .boxed(); trans.push((1, cancel_session)); } if !state.finished_keygens.is_empty() { let deletion_candidate = sample::select((0..state.finished_keygens.len()).collect::<Vec<_>>()); let to_delete = deletion_candidate .prop_map(|key_index| Transition::CDeleteKey { key_index }) .boxed(); trans.push((1, to_delete)); } proptest::strategy::Union::new_weighted(trans).boxed() } fn preconditions(state: &Self::State, transition: &Self::Transition) -> bool { match transition { Transition::CStartKeygen(do_key_gen) => { !state.pending_keygens.contains_key(&do_key_gen.keygen_id) && state .run_start .device_set() .is_superset(&do_key_gen.devices()) } Transition::DKeygenAck { device_id, keygen_id, } => match state.pending_keygens.get(keygen_id) { Some(keygen_state) => { keygen_state .do_keygen .device_to_share_index .contains_key(device_id) && !keygen_state.devices_confirmed.contains(device_id) } None => false, }, Transition::CKeygenConfirm { keygen_id } => { match state.pending_keygens.get(keygen_id) { Some(keygen_state) => { keygen_state.devices_confirmed.len() == keygen_state.do_keygen.device_to_share_index.len() } None => false, } } Transition::CNonceReplenish { device_id } => { state.run_start.device_set().contains(device_id) } Transition::CStartSign { key_index, devices, n_inputs, } => match state.finished_keygens.get(*key_index) { Some(keygen) => { if !keygen.deleted && keygen.do_keygen.devices().is_superset(devices) && state.available_signing_devices().is_superset(devices) { // Check that all devices have enough nonces available for n_inputs devices.iter().all(|device_id| { state.max_available_nonces_for_device(*device_id) >= *n_inputs }) } else { false } } None => false, }, Transition::CSendSignRequest { session_index, device_id, } => match state.sign_sessions.get(*session_index) { Some(session) => { session.devices.contains(device_id) && session.key_index < state.finished_keygens.len() && !state.finished_keygens[session.key_index].deleted && !session.canceled } None => false, }, Transition::CCancelSignSession { session_index } => { match state.sign_sessions.get(*session_index) { Some(session) => { session.key_index < state.finished_keygens.len() && !state.finished_keygens[session.key_index].deleted && !session.canceled } None => false, } } Transition::DAckSignRequest { session_index, device_id, } => match state.sign_sessions.get(*session_index) { Some(session) => { session.sent_req_to.contains(device_id) && session.key_index < state.finished_keygens.len() && !state.finished_keygens[session.key_index].deleted && !session.got_sigs_from.contains(device_id) && !session.canceled } None => false, }, &Transition::CDeleteKey { key_index } => key_index < state.finished_keygens.len(), } } fn apply(mut state: Self::State, transition: &Self::Transition) -> Self::State { match transition.clone() { Transition::CStartKeygen(do_keygen) => { state.pending_keygens.insert( do_keygen.keygen_id, RefKeygen { do_keygen, devices_confirmed: Default::default(), }, ); } Transition::DKeygenAck { keygen_id, device_id, } => { if let Some(state) = state.pending_keygens.get_mut(&keygen_id) { state.devices_confirmed.insert(device_id); } } Transition::CKeygenConfirm { keygen_id } => { if let Some(keygen) = state.pending_keygens.remove(&keygen_id) { state.finished_keygens.push(RefFinishedKey { do_keygen: keygen.do_keygen, deleted: false, }); } } Transition::CNonceReplenish { device_id } => { // Initialize or replenish nonce streams for this device let streams = state .device_nonce_streams .entry(device_id) .or_insert_with(|| { // Create n_nonce_slots streams for this device (0..state.n_nonce_slots) .map(|_| RefNonceStream { nonces_available: 0, }) .collect() }); // Replenish up to n_desired_nonce_streams_coord streams // The coordinator requests this many streams to be replenished let streams_to_replenish = streams.iter_mut().take(state.n_desired_nonce_streams_coord); for stream in streams_to_replenish { stream.nonces_available = state.nonce_batch_size as usize; } } Transition::CStartSign { key_index, devices, n_inputs, } => { // Assign streams to each device (locking them) let mut device_streams = BTreeMap::new(); for device in &devices { // Find the first available stream for this device let stream_id = state .find_available_stream(*device, n_inputs) .expect("state transition should be valid"); device_streams.insert(*device, stream_id); } state.sign_sessions.push(RefSignSession { key_index, devices, n_inputs, device_streams, got_sigs_from: Default::default(), sent_req_to: Default::default(), canceled: false, }) } Transition::CSendSignRequest { session_index, device_id, } => { let session = state.sign_sessions.get_mut(session_index).unwrap(); session.sent_req_to.insert(device_id); // Nonces aren't consumed here - they're only consumed if session is canceled } Transition::CCancelSignSession { session_index } => { state.cancel_session_and_consume_nonces(session_index); } Transition::DAckSignRequest { session_index, device_id, } => { let session = &mut state.sign_sessions[session_index]; session.got_sigs_from.insert(device_id); let session = session.clone(); let nonce_batch_size = state.nonce_batch_size as usize; // Replenish nonces after signing (device sends back replenishment) let stream = state.get_device_stream_for_signing_session(&session, &device_id); stream.nonces_available = nonce_batch_size; } Transition::CDeleteKey { key_index } => { let sessions_to_cancel: Vec<_> = state .sign_sessions .iter() .enumerate() .filter(|(_, session)| session.key_index == key_index) .map(|(idx, _)| idx) .collect(); for session_idx in sessions_to_cancel { state.cancel_session_and_consume_nonces(session_idx); } state.finished_keygens[key_index].deleted = true; } } state } } /// This tests that all valid transitions can occur without panicking. This has marginal benefit for /// security but tests any state transition the user should be able to make happen while using the system. struct HappyPathTest { run: Run, rng: TestRng, env: ProptestEnv, finished_keygens: Vec<AccessStructureRef>, sign_sessions: Vec<SignSessionId>, } #[derive(Default, Debug)] pub struct ProptestEnv { device_keygen_acks: BTreeMap<KeygenId, BTreeMap<DeviceId, KeyGenPhase3>>, sign_reqs: BTreeMap<SignSessionId, BTreeMap<DeviceId, SignPhase1>>, coordinator_keygen_acks: BTreeSet<KeygenId>, finished_signatures: BTreeSet<SignSessionId>, } impl Env for ProptestEnv { fn user_react_to_coordinator( &mut self, _run: &mut Run, message: CoordinatorToUserMessage, _rng: &mut impl RngCore, ) { match message { CoordinatorToUserMessage::KeyGen { keygen_id, inner: CoordinatorToUserKeyGenMessage::KeyGenAck { all_acks_received: true, .. }, } => { self.coordinator_keygen_acks.insert(keygen_id); } CoordinatorToUserMessage::Signing(signing_update) => match signing_update { CoordinatorToUserSigningMessage::GotShare { .. } => { /* ignore for now */ } CoordinatorToUserSigningMessage::Signed { session_id, .. } => { self.finished_signatures.insert(session_id); } }, _ => { /* nothing needs doing */ } } } fn user_react_to_device( &mut self, run: &mut Run, from: DeviceId, message: DeviceToUserMessage, _rng: &mut impl RngCore, ) { use DeviceToUserMessage::*; match message { FinalizeKeyGen { .. } => { // TODO: Do we need to keep track of keygen-finalized messages received by the user? // TODO: Ignore for now. } CheckKeyGen { phase, .. } => { let pending = self.device_keygen_acks.entry(phase.keygen_id).or_default(); pending.insert(from, *phase); } SignatureRequest { phase } => { self.sign_reqs .entry(phase.session_id) .or_default() .insert(from, *phase); } Restoration(_msg) => { // TODO: proptest restoration } VerifyAddress { .. } => { // we dont actually confirm on the device } NonceJobs(mut batch) => { // Run the batch to completion and send a single response batch.run_until_finished(&mut TestDeviceKeyGen); let segments = batch.into_segments(); let response = DeviceSend::ToCoordinator(Box::new(DeviceToCoordinatorMessage::Signing( message::signing::DeviceSigning::NonceResponse { segments }, ))); run.extend_from_device(from, vec![response]); } } } } impl StateMachineTest for HappyPathTest { type SystemUnderTest = Self; type Reference = RefState; fn init_test( ref_state: &<Self::Reference as ReferenceStateMachine>::State, ) -> Self::SystemUnderTest { let rng = TestRng::deterministic_rng(RngAlgorithm::ChaCha); HappyPathTest { run: ref_state.run_start.clone(), rng, env: ProptestEnv::default(), finished_keygens: Default::default(), sign_sessions: Default::default(), } } fn apply( mut state: Self::SystemUnderTest, ref_state: &<Self::Reference as ReferenceStateMachine>::State, transition: <Self::Reference as ReferenceStateMachine>::Transition, ) -> Self::SystemUnderTest { let HappyPathTest { run, rng, env, finished_keygens, sign_sessions, } = &mut state; match transition { Transition::CStartKeygen(do_keygen) => { use rand_chacha::{rand_core::SeedableRng, ChaCha20Rng}; let mut seed = [0u8; 32]; rng.fill_bytes(&mut seed); let mut coordinator_rng = ChaCha20Rng::from_seed(seed); let do_keygen = run .coordinator .begin_keygen(do_keygen, &mut coordinator_rng) .unwrap(); run.extend(do_keygen); } Transition::DKeygenAck { keygen_id, device_id, } => { let pending = env.device_keygen_acks.get_mut(&keygen_id).unwrap(); let phase = pending.remove(&device_id).unwrap(); let ack = run .device(device_id) .keygen_ack(phase, &mut TestDeviceKeyGen, rng) .unwrap(); run.extend_from_device(device_id, ack); } Transition::CKeygenConfirm { keygen_id } => { if env.coordinator_keygen_acks.remove(&keygen_id) { let send_finalize_keygen = run .coordinator .finalize_keygen(keygen_id, TEST_ENCRYPTION_KEY, rng) .unwrap(); let access_structure_ref = send_finalize_keygen.access_structure_ref; run.extend(send_finalize_keygen); finished_keygens.push(access_structure_ref); } else { panic!("CKeygenConfirm for non-existent keygen"); } } Transition::CNonceReplenish { device_id } => { let messages = run.coordinator.maybe_request_nonce_replenishment( &BTreeSet::from([device_id]), ref_state.n_desired_nonce_streams_coord, rng, ); run.extend(messages); } Transition::CStartSign { key_index, devices, n_inputs, } => { let as_ref = finished_keygens[key_index]; let key_data = run.coordinator.get_frost_key(as_ref.key_id).unwrap(); let master_appkey = key_data.complete_key.master_appkey; // Generate a bitcoin transaction with n_inputs let mut tx_template = TransactionTemplate::new(); // Add n_inputs owned inputs with random amounts let mut total_in = 0u64; for i in 0..n_inputs { let amount = 100_000 + (rng.next_u64() % 900_000); // 100k to 1M sats total_in += amount; tx_template.push_imaginary_owned_input( LocalSpk { master_appkey, bip32_path: BitcoinBip32Path::external(i as u32), }, bitcoin::Amount::from_sat(amount), ); } // Add output with some fee let fee = 10_000; // 10k sats fee let change = total_in.saturating_sub(fee); if change > 0 { tx_template.push_owned_output( bitcoin::Amount::from_sat(change), LocalSpk { master_appkey, bip32_path: BitcoinBip32Path::internal(0), }, ); } let task = WireSignTask::BitcoinTransaction(tx_template); let session_id = run .coordinator .start_sign(as_ref, task, &devices, rng) .unwrap(); sign_sessions.push(session_id); } Transition::CSendSignRequest { session_index, device_id, } => { let session_id = sign_sessions[session_index]; let req = run.coordinator .request_device_sign(session_id, device_id, TEST_ENCRYPTION_KEY); run.extend(req); } Transition::CCancelSignSession { session_index } => { let session_id = sign_sessions[session_index]; run.coordinator.cancel_sign_session(session_id); } Transition::DAckSignRequest { session_index, device_id, } => { let session_id = sign_sessions[session_index]; let phase = env .sign_reqs .get_mut(&session_id) .unwrap() .remove(&device_id) .unwrap(); let sign_ack = run .device(device_id) .sign_ack(phase, &mut TestDeviceKeyGen) .unwrap(); run.extend_from_device(device_id, sign_ack); } Transition::CDeleteKey { key_index } => {
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
true
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/tests/coordinator_backward_compat.rs
frostsnap_core/tests/coordinator_backward_compat.rs
/// Tests to ensure backward compatibility of coordinator mutations mod common; use frostsnap_core::coordinator::{ keys::KeyMutation, restoration::{PendingConsolidation, RestorationMutation}, signing::SigningMutation, ActiveSignSession, CompleteKey, CoordAccessStructure, Mutation, SignSessionProgress, StartSign, }; use frostsnap_core::device::KeyPurpose; use frostsnap_core::message::HeldShare2; use frostsnap_core::message::{EncodedSignature, GroupSignReq}; use frostsnap_core::nonce_stream::{CoordNonceStreamState, NonceStreamId, NonceStreamSegment}; use frostsnap_core::tweak::AppTweak; use frostsnap_core::tweak::Xpub; use frostsnap_core::{ AccessStructureId, AccessStructureKind, AccessStructureRef, KeyId, Kind, MasterAppkey, SignItem, WireSignTask, }; use frostsnap_core::{DeviceId, RestorationId, SignSessionId}; use schnorr_fun::frost::{ShareImage, SharedKey}; use schnorr_fun::{binonce, fun::prelude::*}; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque}; #[test] fn test_all_coordinator_mutations() { // Create test data let share_image = ShareImage { index: s!(1).public(), image: g!(42 * G).normalize().mark_zero(), }; let access_structure_ref = AccessStructureRef { key_id: KeyId([3u8; 32]), access_structure_id: AccessStructureId([4u8; 32]), }; let pending_consolidation = PendingConsolidation { device_id: DeviceId([5u8; 33]), access_structure_ref, share_index: s!(1).public(), }; // Create test data for Keygen mutations let master_appkey = MasterAppkey::derive_from_rootkey(g!(42 * G).normalize()); // Create encrypted rootkey for CompleteKey using proper encryption use frostsnap_core::{Ciphertext, SymmetricKey}; let test_key = SymmetricKey([42u8; 32]); let test_rootkey = g!(7 * G).normalize(); use rand::SeedableRng; let mut rng = rand::rngs::StdRng::seed_from_u64(1337); let encrypted_rootkey = Ciphertext::encrypt(test_key, &test_rootkey, &mut rng); // Create SharedKey for Xpub let poly = vec![ g!(42 * G).normalize().mark_zero(), g!(7 * G).normalize().mark_zero(), ]; let shared_key = SharedKey::from_poly(poly).non_zero().unwrap(); let xpub_shared_key = Xpub { key: shared_key, chaincode: [2u8; 32], }; // Create CoordAccessStructure for CompleteKey using proper constructor let device_to_share_index: BTreeMap<DeviceId, schnorr_fun::frost::ShareIndex> = [(DeviceId([5u8; 33]), s!(1).public())] .into_iter() .collect(); let coord_access_structure = CoordAccessStructure::new( xpub_shared_key.clone(), device_to_share_index, AccessStructureKind::Master, ); let mut access_structures = HashMap::new(); access_structures.insert(AccessStructureId([4u8; 32]), coord_access_structure); let complete_key = CompleteKey { master_appkey, encrypted_rootkey, access_structures, }; // Create test data for complex Signing mutations // Create NonceStreamSegment with actual binonce::Nonce let nonce_segment = NonceStreamSegment { stream_id: NonceStreamId([7u8; 16]), nonces: { let mut nonces = VecDeque::new(); // Create a binonce::Nonce from two Points let nonce = binonce::Nonce([g!(10 * G).normalize(), g!(11 * G).normalize()]); nonces.push_back(nonce); nonces }, index: 1, }; // Create SignSessionProgress using its new function with deterministic RNG let sign_session_progress = { let frost = schnorr_fun::frost::Frost::< sha2::Sha256, schnorr_fun::nonce::Deterministic<sha2::Sha256>, >::default(); let app_shared_key = Xpub { key: SharedKey::from_poly(vec![ g!(27 * G).normalize().mark_zero(), g!(28 * G).normalize().mark_zero(), ]) .non_zero() .unwrap(), chaincode: [29u8; 32], }; let sign_item = SignItem { message: b"test message to sign".to_vec(), app_tweak: AppTweak::TestMessage, }; let mut nonces = BTreeMap::new(); nonces.insert( s!(1).public(), binonce::Nonce([g!(30 * G).normalize(), g!(31 * G).normalize()]), ); nonces.insert( s!(2).public(), binonce::Nonce([g!(32 * G).normalize(), g!(33 * G).normalize()]), ); // Use a deterministic RNG for consistent test results use rand::SeedableRng; let mut rng = rand::rngs::StdRng::seed_from_u64(42); SignSessionProgress::new(&frost, app_shared_key, sign_item, nonces, &mut rng) }; // Create ActiveSignSession with proper GroupSignReq let active_sign_session = ActiveSignSession { progress: vec![sign_session_progress], init: StartSign { nonces: { let mut nonces = BTreeMap::new(); // Add some device nonce states nonces.insert( DeviceId([16u8; 33]), CoordNonceStreamState { stream_id: NonceStreamId([17u8; 16]), index: 2, remaining: 10, }, ); nonces.insert( DeviceId([18u8; 33]), CoordNonceStreamState { stream_id: NonceStreamId([19u8; 16]), index: 3, remaining: 15, }, ); nonces }, group_request: GroupSignReq { parties: { let mut parties = BTreeSet::new(); parties.insert(s!(1).public()); parties.insert(s!(2).public()); parties.insert(s!(3).public()); parties }, agg_nonces: vec![ // Add some aggregate nonces binonce::Nonce([ g!(20 * G).normalize().mark_zero(), g!(21 * G).normalize().mark_zero(), ]), binonce::Nonce([ g!(22 * G).normalize().mark_zero(), g!(23 * G).normalize().mark_zero(), ]), ], sign_task: WireSignTask::Test { message: "test message for signing".to_string(), }, access_structure_id: AccessStructureId([14u8; 32]), }, }, key_id: KeyId([13u8; 32]), sent_req_to_device: { let mut devices = HashSet::new(); devices.insert(DeviceId([16u8; 33])); devices.insert(DeviceId([18u8; 33])); devices }, }; // Create SignatureShare - it's just a Scalar<Public, Zero> let signature_shares = vec![s!(15).public().mark_zero()]; // Create EncodedSignature let encoded_sig = EncodedSignature([14u8; 64]); // Create all mutation variants we want to test let mutations = vec![ // Restoration mutations Mutation::Restoration(RestorationMutation::NewRestoration { restoration_id: RestorationId([1u8; 16]), key_name: "test_key".to_string(), threshold: 2, key_purpose: KeyPurpose::Bitcoin(bitcoin::Network::Bitcoin), }), Mutation::Restoration(RestorationMutation::RestorationProgress { restoration_id: RestorationId([1u8; 16]), device_id: DeviceId([2u8; 33]), share_image, access_structure_ref: None, }), Mutation::Restoration(RestorationMutation::RestorationProgress { restoration_id: RestorationId([1u8; 16]), device_id: DeviceId([2u8; 33]), share_image, access_structure_ref: Some(access_structure_ref), }), Mutation::Restoration(RestorationMutation::DeleteRestorationShare { restoration_id: RestorationId([1u8; 16]), device_id: DeviceId([2u8; 33]), share_image, }), Mutation::Restoration(RestorationMutation::DeleteRestoration { restoration_id: RestorationId([1u8; 16]), }), Mutation::Restoration(RestorationMutation::DeviceNeedsConsolidation( pending_consolidation, )), Mutation::Restoration(RestorationMutation::DeviceFinishedConsolidation( pending_consolidation, )), // New restoration mutations Mutation::Restoration(RestorationMutation::NewRestoration2 { restoration_id: RestorationId([1u8; 16]), key_name: "test_key".to_string(), starting_threshold: Some(2), key_purpose: KeyPurpose::Bitcoin(bitcoin::Network::Bitcoin), }), Mutation::Restoration(RestorationMutation::RestorationProgress2 { restoration_id: RestorationId([1u8; 16]), device_id: DeviceId([2u8; 33]), held_share: HeldShare2 { access_structure_ref: Some(access_structure_ref), share_image, threshold: Some(2), key_name: Some("test_key".to_string()), purpose: Some(KeyPurpose::Bitcoin(bitcoin::Network::Bitcoin)), needs_consolidation: true, }, }), // Keygen mutations Mutation::Keygen(KeyMutation::NewKey { key_name: "test_key".to_string(), purpose: KeyPurpose::Bitcoin(bitcoin::Network::Bitcoin), complete_key, }), Mutation::Keygen(KeyMutation::NewAccessStructure { shared_key: xpub_shared_key, kind: AccessStructureKind::Master, }), Mutation::Keygen(KeyMutation::NewShare { access_structure_ref: AccessStructureRef { key_id: KeyId([3u8; 32]), access_structure_id: AccessStructureId([4u8; 32]), }, device_id: DeviceId([5u8; 33]), share_index: s!(1).public(), }), Mutation::Keygen(KeyMutation::DeleteKey(KeyId([3u8; 32]))), // Signing mutations Mutation::Signing(SigningMutation::NewNonces { device_id: DeviceId([6u8; 33]), nonce_segment, }), Mutation::Signing(SigningMutation::NewSigningSession(active_sign_session)), Mutation::Signing(SigningMutation::SentSignReq { session_id: SignSessionId([12u8; 32]), device_id: DeviceId([6u8; 33]), }), Mutation::Signing(SigningMutation::GotSignatureSharesFromDevice { session_id: SignSessionId([12u8; 32]), device_id: DeviceId([6u8; 33]), signature_shares, }), Mutation::Signing(SigningMutation::CloseSignSession { session_id: SignSessionId([12u8; 32]), finished: Some(vec![encoded_sig]), }), Mutation::Signing(SigningMutation::ForgetFinishedSignSession { session_id: SignSessionId([12u8; 32]), }), ]; // Test each mutation for mutation in mutations { match mutation.clone() { Mutation::Restoration(RestorationMutation::NewRestoration { .. }) => { assert_bincode_hex_eq!( mutation, "02000101010101010101010101010101010108746573745f6b6579020100" ); } Mutation::Restoration(RestorationMutation::RestorationProgress { access_structure_ref: None, .. }) => { assert_bincode_hex_eq!( mutation, "020101010101010101010101010101010101020202020202020202020202020202020202020202020202020202020202020202000000000000000000000000000000000000000000000000000000000000000102fe8d1eb1bcb3432b1db5833ff5f2226d9cb5e65cee430558c18ed3a3c86ce1af00" ); } Mutation::Restoration(RestorationMutation::RestorationProgress { access_structure_ref: Some(_), .. }) => { assert_bincode_hex_eq!( mutation, "020101010101010101010101010101010101020202020202020202020202020202020202020202020202020202020202020202000000000000000000000000000000000000000000000000000000000000000102fe8d1eb1bcb3432b1db5833ff5f2226d9cb5e65cee430558c18ed3a3c86ce1af0103030303030303030303030303030303030303030303030303030303030303030404040404040404040404040404040404040404040404040404040404040404" ); } Mutation::Restoration(RestorationMutation::DeleteRestorationShare { .. }) => { assert_bincode_hex_eq!( mutation, "020201010101010101010101010101010101020202020202020202020202020202020202020202020202020202020202020202000000000000000000000000000000000000000000000000000000000000000102fe8d1eb1bcb3432b1db5833ff5f2226d9cb5e65cee430558c18ed3a3c86ce1af" ); } Mutation::Restoration(RestorationMutation::DeleteRestoration { .. }) => { assert_bincode_hex_eq!(mutation, "020301010101010101010101010101010101"); } Mutation::Restoration(RestorationMutation::DeviceNeedsConsolidation(_)) => { assert_bincode_hex_eq!( mutation, "0204050505050505050505050505050505050505050505050505050505050505050505030303030303030303030303030303030303030303030303030303030303030304040404040404040404040404040404040404040404040404040404040404040000000000000000000000000000000000000000000000000000000000000001" ); } Mutation::Restoration(RestorationMutation::DeviceFinishedConsolidation(_)) => { assert_bincode_hex_eq!( mutation, "0205050505050505050505050505050505050505050505050505050505050505050505030303030303030303030303030303030303030303030303030303030303030304040404040404040404040404040404040404040404040404040404040404040000000000000000000000000000000000000000000000000000000000000001" ); } Mutation::Keygen(KeyMutation::NewKey { .. }) => { assert_bincode_hex_eq!( mutation, "000008746573745f6b65790100036a73f983b472e3ef6a6336bd6600ac2d49ef96ec284fc9da3c378156316baeb8941593f4651c7a0062624f959ecc292a412ebf57e7c497b9b007e87d5816e879b3cf6b65cd04d3f661e9227ecb1352668d1ae0b4d2b74aad3d5e30cc35ad8cfeaccaf41fde30f8caa72c5dad232e80495aeb47d4fe7e72e343252f8b1b0104040404040404040404040404040404040404040404040404040404040404040202fe8d1eb1bcb3432b1db5833ff5f2226d9cb5e65cee430558c18ed3a3c86ce1af025cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc020202020202020202020202020202020202020202020202020202020202020201050505050505050505050505050505050505050505050505050505050505050505000000000000000000000000000000000000000000000000000000000000000100" ); } Mutation::Keygen(KeyMutation::NewAccessStructure { .. }) => { assert_bincode_hex_eq!( mutation, "00010202fe8d1eb1bcb3432b1db5833ff5f2226d9cb5e65cee430558c18ed3a3c86ce1af025cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc020202020202020202020202020202020202020202020202020202020202020200" ); } Mutation::Keygen(KeyMutation::NewShare { .. }) => { assert_bincode_hex_eq!( mutation, "0002030303030303030303030303030303030303030303030303030303030303030304040404040404040404040404040404040404040404040404040404040404040505050505050505050505050505050505050505050505050505050505050505050000000000000000000000000000000000000000000000000000000000000001" ); } Mutation::Keygen(KeyMutation::DeleteKey(_)) => { assert_bincode_hex_eq!( mutation, "00030303030303030303030303030303030303030303030303030303030303030303" ); } Mutation::Signing(SigningMutation::NewNonces { .. }) => { assert_bincode_hex_eq!( mutation, "0100060606060606060606060606060606060606060606060606060606060606060606070707070707070707070707070707070103a0434d9e47f3c86235477c7b1ae6ae5d3442d49b1943c2b752a68e2a47e247c703774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb01" ); } Mutation::Signing(SigningMutation::NewSigningSession(_)) => { assert_bincode_hex_eq!( mutation, "0101011474657374206d65737361676520746f207369676e00e4c0f99327353b433529c3866724204c4cc4537ff70fb1d9e63d19f33a2acfe4ae0e79e032ed91b6dd96d578e3f57a6794fc2a90bc4a33f94887b73f50484176279e7da397bd000278831221e2af872cca129bc310d612e77de05d1c459bfe69f0f15eb113f0ae254fe2a32d1b5c9653b3531ebd2169ca38d3667bac0c3be8e20329d39ee36b67586040d955065276b1eb4c75e0a06d7fd7fe7e1693aedbce9e1a03bf23c1542d16eab70b1051eaf832823cfc4c6f1dcdbafd81e37918e6f874ef8b020000000000000000000000000000000000000000000000000000000000000001026d2b085e9e382ed10b69fc311a03f8641ccfff21574de0927513a49d9a688a00036a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4000000000000000000000000000000000000000000000000000000000000000202d30199d74fb5a22d47b6e054e2f378cedacffcb89904a61d75d0dbd407143e65031697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a55ddbd8dd9c88337982ae52c0ecf50f73e97a8b083de7b0990da1e78f580857da000203daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee87290255eb67d7b7238a70a7fa6f64d5dc3c826b31536da6eb344dc39a66f904f979681d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d0210101010101010101010101010101010101010101010101010101010101010101011111111111111111111111111111111020a12121212121212121212121212121212121212121212121212121212121212121213131313131313131313131313131313030f0300000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000302024ce119c96e2fa357200b559b2f7dd5a5f02d5290aff74b03f3e471b273211c9702352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d503421f5fc9a21065445c96fdb91c0c1e2f2431741c72713b4b99ddcb316f31e9fc032fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f001874657374206d65737361676520666f72207369676e696e670e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d0d02101010101010101010101010101010101010101010101010101010101010101010121212121212121212121212121212121212121212121212121212121212121212" ); } Mutation::Signing(SigningMutation::SentSignReq { .. }) => { assert_bincode_hex_eq!( mutation, "01020c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c060606060606060606060606060606060606060606060606060606060606060606" ); } Mutation::Signing(SigningMutation::GotSignatureSharesFromDevice { .. }) => { assert_bincode_hex_eq!( mutation, "01030c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c06060606060606060606060606060606060606060606060606060606060606060601000000000000000000000000000000000000000000000000000000000000000f" ); } Mutation::Signing(SigningMutation::CloseSignSession { .. }) => { assert_bincode_hex_eq!( mutation, "01040c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c01010e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e" ); } Mutation::Signing(SigningMutation::ForgetFinishedSignSession { .. }) => { assert_bincode_hex_eq!( mutation, "01050c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c" ); } Mutation::Restoration(RestorationMutation::NewRestoration2 { .. }) => { assert_bincode_hex_eq!( mutation, "02060101010101010101010101010101010108746573745f6b657901020100" ); } Mutation::Restoration(RestorationMutation::RestorationProgress2 { .. }) => { assert_bincode_hex_eq!( mutation, "0207010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202020103030303030303030303030303030303030303030303030303030303030303030404040404040404040404040404040404040404040404040404040404040404000000000000000000000000000000000000000000000000000000000000000102fe8d1eb1bcb3432b1db5833ff5f2226d9cb5e65cee430558c18ed3a3c86ce1af01020108746573745f6b657901010001" ); } } } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/tests/device_backward_compat.rs
frostsnap_core/tests/device_backward_compat.rs
/// Tests to ensure backward compatibility of device mutations mod common; use frost_backup::ShareBackup; use frostsnap_core::device::{ restoration::*, EncryptedSecretShare, KeyPurpose, Mutation, SaveShareMutation, }; use frostsnap_core::{AccessStructureId, AccessStructureKind, Kind}; use schnorr_fun::frost::{SecretShare, ShareImage, SharedKey}; use schnorr_fun::fun::prelude::*; #[test] fn test_all_device_mutations() { // Create test data let secret_share = SecretShare { index: s!(1).public(), share: s!(42).mark_zero(), }; let poly = vec![ g!(42 * G).normalize().mark_zero(), g!(7 * G).normalize().mark_zero(), ]; let shared_key = SharedKey::from_poly(poly).non_zero().unwrap(); let share_backup = ShareBackup::from_secret_share_and_shared_key(secret_share, &shared_key); let share_image = ShareImage { index: s!(1).public(), image: g!(42 * G).normalize().mark_zero(), }; // Create test EncryptedSecretShare with properly encrypted data use frostsnap_core::{Ciphertext, SymmetricKey}; let test_key = SymmetricKey([77u8; 32]); let test_secret_share = s!(99).mark_zero(); use rand::SeedableRng; let mut rng = rand::rngs::StdRng::seed_from_u64(7777); let encrypted_share = EncryptedSecretShare { share_image, ciphertext: Ciphertext::encrypt(test_key, &test_secret_share, &mut rng), }; // Create all mutation variants we want to test let mutations = vec![ // Keygen mutations Mutation::Keygen(frostsnap_core::device::keys::KeyMutation::NewKey { key_id: frostsnap_core::KeyId([1u8; 32]), key_name: "test_key".to_string(), purpose: KeyPurpose::Bitcoin(bitcoin::Network::Bitcoin), }), Mutation::Keygen( frostsnap_core::device::keys::KeyMutation::NewAccessStructure { access_structure_ref: frostsnap_core::AccessStructureRef { key_id: frostsnap_core::KeyId([1u8; 32]), access_structure_id: AccessStructureId([2u8; 32]), }, threshold: 2, kind: AccessStructureKind::Master, }, ), Mutation::Keygen(frostsnap_core::device::keys::KeyMutation::SaveShare( Box::new(SaveShareMutation { access_structure_ref: frostsnap_core::AccessStructureRef { key_id: frostsnap_core::KeyId([1u8; 32]), access_structure_id: AccessStructureId([2u8; 32]), }, encrypted_secret_share: encrypted_share, }), )), // Restoration mutations Mutation::Restoration(RestorationMutation::Save(SavedBackup { share_backup: share_backup.clone(), threshold: 2, purpose: KeyPurpose::Bitcoin(bitcoin::Network::Bitcoin), key_name: "test_key".to_string(), })), Mutation::Restoration(RestorationMutation::Save2(SavedBackup2 { share_backup, threshold: Some(2), purpose: Some(KeyPurpose::Bitcoin(bitcoin::Network::Bitcoin)), key_name: Some("test_key".to_string()), })), Mutation::Restoration(RestorationMutation::_UnSave(share_image)), ]; // Test each mutation for mutation in mutations { match mutation.clone() { Mutation::Keygen(frostsnap_core::device::keys::KeyMutation::NewKey { .. }) => { assert_bincode_hex_eq!( mutation, "0000010101010101010101010101010101010101010101010101010101010101010108746573745f6b65790100" ); } Mutation::Keygen(frostsnap_core::device::keys::KeyMutation::NewAccessStructure { .. }) => { assert_bincode_hex_eq!( mutation, "0001010101010101010101010101010101010101010101010101010101010101010102020202020202020202020202020202020202020202020202020202020202020200" ); } Mutation::Restoration(RestorationMutation::Save(_)) => { assert_bincode_hex_eq!( mutation, "01000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000002aeb02010008746573745f6b6579" ); } Mutation::Restoration(RestorationMutation::Save2(_)) => { assert_bincode_hex_eq!( mutation, "01020000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000002aeb01020101000108746573745f6b6579" ); } Mutation::Restoration(RestorationMutation::_UnSave(_)) => { assert_bincode_hex_eq!( mutation, "0101000000000000000000000000000000000000000000000000000000000000000102fe8d1eb1bcb3432b1db5833ff5f2226d9cb5e65cee430558c18ed3a3c86ce1af" ); } Mutation::Keygen(frostsnap_core::device::keys::KeyMutation::SaveShare(_)) => { assert_bincode_hex_eq!( mutation, "000201010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202000000000000000000000000000000000000000000000000000000000000000102fe8d1eb1bcb3432b1db5833ff5f2226d9cb5e65cee430558c18ed3a3c86ce1afb1dde6fd8607b05ecd33fcdf96eaef828be8955ad2af175f7b4f231e83dac8a2a89393d068530505297b93b9dc5b740d59a1ebee4d9a5924acda8cca" ); } } } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/tests/malicious.rs
frostsnap_core/tests/malicious.rs
//! Tests for a malicious actions. A malicious coordinator, a malicious device or both. use common::TEST_ENCRYPTION_KEY; use env::TestEnv; use frostsnap_core::coordinator::{BeginKeygen, CoordinatorSend}; use frostsnap_core::device::KeyPurpose; use frostsnap_core::message::{ keygen::DeviceKeygen, CoordinatorToDeviceMessage, DeviceSend, DeviceToCoordinatorMessage, Keygen, }; use frostsnap_core::WireSignTask; use rand_chacha::rand_core::SeedableRng; use rand_chacha::ChaCha20Rng; use crate::common::{Run, Send}; mod common; mod env; /// Models a coordinator maliciously replacing a public polynomial contribution and providing a /// correct share under that malicious polynomial. The device that has had their share replaced /// should notice it and abort. #[test] fn keygen_maliciously_replace_public_poly() { let mut test_rng = ChaCha20Rng::from_seed([42u8; 32]); let mut other_rng = ChaCha20Rng::from_seed([21u8; 32]); let mut run = Run::generate(1, &mut test_rng); let device_set = run.device_set(); let mut shadow_device = run.devices.values().next().unwrap().clone(); use rand_chacha::rand_core::{RngCore, SeedableRng}; let mut seed = [0u8; 32]; test_rng.fill_bytes(&mut seed); let mut coordinator_rng = ChaCha20Rng::from_seed(seed); let keygen_init = run .coordinator .begin_keygen( BeginKeygen::new( device_set.into_iter().collect(), 1, "test".into(), KeyPurpose::Test, &mut test_rng, ), &mut coordinator_rng, ) .unwrap(); let do_keygen = keygen_init .clone() .into_iter() .find_map(|msg| match msg { CoordinatorSend::ToDevice { message: dokeygen @ CoordinatorToDeviceMessage::KeyGen(Keygen::Begin(_)), .. } => Some(dokeygen), _ => None, }) .unwrap(); run.extend(keygen_init.clone()); let result = run.run_until(&mut TestEnv::default(), &mut test_rng, move |run| { for send in run.message_queue.iter_mut() { if let Send::DeviceToCoordinator { from: _, message: DeviceToCoordinatorMessage::KeyGen(DeviceKeygen::Response(input)), } = send { // A "man in the middle" replace the polynomial the coordinator actually // receives with a different one generated with different randomness. This should // cause the device to detect the switch and abort. let malicious_messages = shadow_device .recv_coordinator_message(do_keygen.clone(), &mut other_rng) .unwrap(); let malicious_keygen_response = malicious_messages .into_iter() .find_map(|send| match send { DeviceSend::ToCoordinator(boxed) => match *boxed { DeviceToCoordinatorMessage::KeyGen(DeviceKeygen::Response( response, )) => Some(response), _ => None, }, _ => None, }) .unwrap(); *input = malicious_keygen_response; } } run.message_queue.is_empty() }); assert!(result.is_err()); } /// Send different signing requests with the same nonces twice. /// The device should reject signing the second request. #[test] #[should_panic(expected = "Attempt to reuse nonces")] fn send_sign_req_with_same_nonces_but_different_message() { let mut test_rng = ChaCha20Rng::from_seed([42u8; 32]); let mut run = Run::start_after_keygen_and_nonces( 1, 1, &mut TestEnv::default(), &mut test_rng, 1, KeyPurpose::Test, ); let device_set = run.device_set(); let key_data = run.coordinator.iter_keys().next().unwrap(); let task1 = WireSignTask::Test { message: "utxo.club!".into(), }; let access_structure_ref = key_data .access_structures() .next() .unwrap() .access_structure_ref(); let session_id = run .coordinator .start_sign(access_structure_ref, task1, &device_set, &mut test_rng) .unwrap(); let mut sign_req = None; for device_id in &device_set { sign_req = Some(run.coordinator.request_device_sign( session_id, *device_id, TEST_ENCRYPTION_KEY, )); run.extend(sign_req.clone().unwrap()); } run.run_until_finished(&mut TestEnv::default(), &mut test_rng) .unwrap(); let mut sign_req = sign_req.unwrap(); sign_req.request_sign.group_sign_req.sign_task = WireSignTask::Test { message: "we lost track of first FROST txn on bitcoin mainnet @ bushbash 2022".into(), }; run.extend(sign_req); // This will panic when sign_ack tries to reuse nonces run.run_until_finished(&mut TestEnv::default(), &mut test_rng) .unwrap(); } /// Test that a malicious coordinator providing wrong root_shared_key during consolidation /// is detected by the polynomial checksum validation #[test] fn malicious_consolidation_wrong_root_shared_key() { use schnorr_fun::fun::{poly, prelude::*}; let mut test_rng = ChaCha20Rng::from_seed([44u8; 32]); let mut env = TestEnv::default(); // Do a 3-of-3 keygen to have enough degrees of freedom for the attack let mut run = Run::start_after_keygen_and_nonces(3, 3, &mut env, &mut test_rng, 3, KeyPurpose::Test); let device_set = run.device_set(); let key_data = run.coordinator.iter_keys().next().unwrap(); let access_structure_ref = key_data .access_structures() .next() .unwrap() .access_structure_ref(); // Display backups for all devices for &device_id in &device_set { let display_backup = run .coordinator .request_device_display_backup(device_id, access_structure_ref, TEST_ENCRYPTION_KEY) .unwrap(); run.extend(display_backup); } run.run_until_finished(&mut env, &mut test_rng).unwrap(); // We should have backups in the env assert_eq!(env.backups.len(), 3); // Pick the first device let device_id = *env.backups.keys().next().unwrap(); let (_, backup) = env.backups.get(&device_id).unwrap().clone(); // Assign the backup for this device to enter env.backup_to_enter.insert(device_id, backup); // Tell the device to enter backup mode let enter_physical_id = frostsnap_core::EnterPhysicalId::new(&mut test_rng); let enter_backup = run .coordinator .tell_device_to_load_physical_backup(enter_physical_id, device_id); run.extend(enter_backup); run.run_until_finished(&mut env, &mut test_rng).unwrap(); // Get the PhysicalBackupPhase from the env that was populated when the device responded let physical_backup_phase = *env .physical_backups_entered .last() .expect("Should have a physical backup phase"); // Get the proper consolidation message from the coordinator let mut consolidate_message = run .coordinator .tell_device_to_consolidate_physical_backup( physical_backup_phase, access_structure_ref, TEST_ENCRYPTION_KEY, ) .unwrap(); // Create a malicious root_shared_key that: // 1. Has the same public key (first coefficient) // 2. Evaluates to the correct share for this device // 3. But is a different polynomial overall // This is the most pernicious attack - everything the device can verify looks correct! let device_share_image = physical_backup_phase.backup.share_image; // Create a malicious polynomial by interpolating through: // - The device's correct share point // - One other correct point from the polynomial // - One malicious point that's NOT on the correct polynomial let other_index = if consolidate_message.share_index == s!(2).public() { s!(3).public() } else { s!(2).public() }; let malicious_share_images = [ device_share_image, // Use a point that's on the correct polynomial consolidate_message.root_shared_key.share_image(other_index), // Create a malicious point that's NOT on the correct polynomial schnorr_fun::frost::ShareImage { index: s!(99).public(), image: g!(77 * G).normalize().mark_zero(), }, ]; // Interpolate to get the malicious polynomial let malicious_shares: Vec<(schnorr_fun::frost::ShareIndex, Point<Normal, Public, Zero>)> = malicious_share_images .iter() .map(|img| (img.index, img.image)) .collect(); let malicious_interpolated = poly::point::interpolate(&malicious_shares); let malicious_poly_points: Vec<Point<Normal, Public, Zero>> = poly::point::normalize(malicious_interpolated).collect(); let malicious_shared_key = schnorr_fun::frost::SharedKey::from_poly(malicious_poly_points.clone()); // Verify it evaluates to the correct share for this device assert_eq!( malicious_shared_key.share_image(consolidate_message.share_index), device_share_image, "Malicious key should evaluate to correct share for device" ); // But it's a different polynomial overall assert_ne!( malicious_shared_key.point_polynomial(), consolidate_message.root_shared_key.point_polynomial(), "Malicious key should be a different polynomial" ); // Mutate the consolidation message to have the malicious root_shared_key consolidate_message.root_shared_key = malicious_shared_key.non_zero().expect("Should be non-zero"); // Send the malicious consolidation to the device run.extend(consolidate_message); let result = run.run_until_finished(&mut env, &mut test_rng); // The device should reject this because the polynomial checksum doesn't match assert!( result.is_err(), "Device should reject consolidation with wrong root_shared_key" ); let error_msg = result.unwrap_err().to_string(); assert!( error_msg.contains("polynomial checksum validation failed"), "Should fail to consolidate due to checksum mismatch, got: {}", error_msg ); }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/tests/nonce_generation.rs
frostsnap_core/tests/nonce_generation.rs
mod common; use common::TestDeviceKeyGen; use frostsnap_core::device_nonces::{NonceJobBatch, RatchetSeedMaterial, SecretNonceSlot}; use frostsnap_core::nonce_stream::NonceStreamId; #[test] fn test_nonce_generation_deterministic() { // Fixed test data let nonce_stream_id = NonceStreamId([ 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10, ]); let ratchet_prg_seed_material: RatchetSeedMaterial = [ 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x00, ]; let slot_value = SecretNonceSlot { index: 0, nonce_stream_id, ratchet_prg_seed_material, last_used: 0, signing_state: None, }; let mut device_hmac = TestDeviceKeyGen; // Generate 3 nonces using a NonceJobBatch with a single job let task = slot_value.nonce_task(None, 3); let mut batch = NonceJobBatch::new(vec![task]); batch.run_until_finished(&mut device_hmac); let segments = batch.into_segments(); assert_eq!(segments.len(), 1, "Should have exactly one segment"); let nonces: Vec<String> = segments[0] .nonces .iter() .map(|nonce| nonce.to_string()) .collect(); // These are the expected nonce values captured from the original iterator implementation // Using TestDeviceKeyGen which uses HMAC with TEST_ENCRYPTION_KEY assert_eq!(nonces.len(), 3); let expected_nonces = ["03db824cdfb550fdfa8064aa69dc0cc9c8274c820fb8281b2d2443ad8d93e1d5fc02384fa6f82d96f2b31c871c05c19fef10a4885eb719a83b513f7b584932f3c960", "02a96b24205745a07255455672b47dc3a3ed8a5ad1e35ddfdb674d52b17b63da8a0357a55f16e389d4559c4d869443caa6c959eef34643d29878f3fc4567ed110334", "032dd9784b0f54987dd14a65cb81a7a9bbfbd91cbf30b72b40ba31dcc70b764e70027aea249a118f651a1da7861095604ccb2258aa78f10a34e751c65fb9c59a17c3"]; for (i, (actual, expected)) in nonces.iter().zip(expected_nonces.iter()).enumerate() { assert_eq!(actual, expected, "Nonce {} mismatch", i); } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/tests/env/test_env.rs
frostsnap_core/tests/env/test_env.rs
use crate::common::{Env, Run, TestDeviceKeyGen, TEST_ENCRYPTION_KEY}; use bitcoin::Address; use frostsnap_core::coordinator::restoration::RecoverShare; use frostsnap_core::device::{self, DeviceToUserMessage}; use frostsnap_core::message::{self, DeviceSend, DeviceToCoordinatorMessage, EncodedSignature}; use frostsnap_core::tweak::BitcoinBip32Path; use frostsnap_core::{ coordinator::{ CoordinatorToUserKeyGenMessage, CoordinatorToUserMessage, CoordinatorToUserSigningMessage, }, CheckedSignTask, DeviceId, KeyId, RestorationId, SessionHash, SignSessionId, }; use rand::RngCore; use schnorr_fun::Signature; use std::collections::{BTreeMap, BTreeSet}; #[derive(Default)] pub struct TestEnv { // keygen pub keygen_checks: BTreeMap<DeviceId, SessionHash>, pub received_keygen_shares: BTreeSet<DeviceId>, pub coordinator_check: Option<SessionHash>, pub coordinator_got_keygen_acks: BTreeSet<DeviceId>, pub keygen_acks: BTreeSet<KeyId>, // backups pub backups: BTreeMap<DeviceId, (String, frost_backup::ShareBackup)>, pub physical_backups_entered: Vec<frostsnap_core::coordinator::restoration::PhysicalBackupPhase>, // nonces pub received_nonce_replenishes: BTreeSet<DeviceId>, // signing pub received_signing_shares: BTreeMap<SignSessionId, BTreeSet<DeviceId>>, pub sign_tasks: BTreeMap<DeviceId, CheckedSignTask>, pub signatures: BTreeMap<SignSessionId, Vec<Signature>>, pub verification_requests: BTreeMap<DeviceId, (Address, BitcoinBip32Path)>, // Explicit mapping of which backup each device should enter pub backup_to_enter: BTreeMap<DeviceId, frost_backup::ShareBackup>, } impl Env for TestEnv { fn user_react_to_coordinator( &mut self, run: &mut Run, message: CoordinatorToUserMessage, rng: &mut impl RngCore, ) { match message { CoordinatorToUserMessage::KeyGen { keygen_id, inner: keygen_message, } => match keygen_message { CoordinatorToUserKeyGenMessage::ReceivedShares { from, .. } => { assert!( self.received_keygen_shares.insert(from), "should not have already received" ) } CoordinatorToUserKeyGenMessage::CheckKeyGen { session_hash, .. } => { assert!( self.coordinator_check.replace(session_hash).is_none(), "should not have already set this" ); } CoordinatorToUserKeyGenMessage::KeyGenAck { from, all_acks_received, } => { assert!( self.coordinator_got_keygen_acks.insert(from), "should only receive this once" ); if all_acks_received { assert_eq!( self.coordinator_got_keygen_acks.len(), self.received_keygen_shares.len() ); let send_finalize_keygen = run .coordinator .finalize_keygen(keygen_id, TEST_ENCRYPTION_KEY, rng) .unwrap(); self.keygen_acks .insert(send_finalize_keygen.access_structure_ref.key_id); run.extend(send_finalize_keygen); } } }, CoordinatorToUserMessage::Signing(signing_message) => match signing_message { CoordinatorToUserSigningMessage::GotShare { from, session_id } => { assert!( self.received_signing_shares .entry(session_id) .or_default() .insert(from), "should only send share once" ); } CoordinatorToUserSigningMessage::Signed { session_id, signatures, } => { let sigs = self.signatures.entry(session_id).or_default(); assert!(sigs.is_empty(), "should only get the signed event once"); sigs.extend( signatures .into_iter() .map(EncodedSignature::into_decoded) .map(Option::unwrap), ); } }, CoordinatorToUserMessage::Restoration(msg) => { use frostsnap_core::coordinator::restoration::ToUserRestoration::*; match msg { GotHeldShares { held_by, shares, .. } => { // This logic here is just about doing something sensible in the context of a test. // We start a new restoration if we get a new share but don't already know about it. for held_share in shares { let recover_share = RecoverShare { held_by, held_share: held_share.clone(), }; match held_share.access_structure_ref { Some(access_structure_ref) if run .coordinator .get_access_structure(access_structure_ref) .is_some() => { if !run.coordinator.knows_about_share( held_by, access_structure_ref, held_share.share_image.index, ) { run.coordinator .recover_share( access_structure_ref, &recover_share, TEST_ENCRYPTION_KEY, ) .unwrap(); } } _ => { let existing_restoration = run.coordinator.restoring().find(|state| { state.access_structure.access_structure_ref() == held_share.access_structure_ref }); match existing_restoration { Some(existing_restoration) => { if !existing_restoration .access_structure .has_got_share_image( recover_share.held_by, recover_share.held_share.share_image, ) { run.coordinator .add_recovery_share_to_restoration( existing_restoration.restoration_id, &recover_share, TEST_ENCRYPTION_KEY, ) .unwrap(); } } None => run .coordinator .start_restoring_key_from_recover_share( &recover_share, RestorationId::new(rng), ) .unwrap(), } } } } } PhysicalBackupEntered(physical_backup_phase) => { self.physical_backups_entered.push(*physical_backup_phase); } _ => { /* ignored */ } } } CoordinatorToUserMessage::ReplenishedNonces { device_id } => { self.received_nonce_replenishes.insert(device_id); } } } fn user_react_to_device( &mut self, run: &mut Run, from: DeviceId, message: DeviceToUserMessage, rng: &mut impl RngCore, ) { match message { DeviceToUserMessage::FinalizeKeyGen { .. } => {} DeviceToUserMessage::CheckKeyGen { phase, .. } => { self.keygen_checks.insert(from, phase.session_hash()); let ack = run .device(from) .keygen_ack(*phase, &mut TestDeviceKeyGen, rng) .unwrap(); run.extend_from_device(from, ack); } DeviceToUserMessage::SignatureRequest { phase } => { self.sign_tasks.insert(from, phase.sign_task().clone()); let sign_ack = run .device(from) .sign_ack(*phase, &mut TestDeviceKeyGen) .unwrap(); run.extend_from_device(from, sign_ack); } DeviceToUserMessage::Restoration(restoration) => { use device::restoration::ToUserRestoration::*; match *restoration { DisplayBackup { key_name, access_structure_ref: _, phase, } => { let backup = phase .decrypt_to_backup(&mut TestDeviceKeyGen) .expect("failed to decrypt backup"); self.backups.insert(from, (key_name, backup)); } EnterBackup { phase } => { let device = run.device(from); let share_backup = self .backup_to_enter .remove(&from) .expect("Test must assign backup for device to enter"); let response = device.tell_coordinator_about_backup_load_result(phase, share_backup); run.extend_from_device(from, response); } ConsolidateBackup(phase) => { let ack = run.device(from).finish_consolidation( &mut TestDeviceKeyGen, phase, rng, ); run.extend_from_device(from, ack); } BackupSaved { .. } => { /* informational */ } } } DeviceToUserMessage::VerifyAddress { address, bip32_path, } => { self.verification_requests .insert(from, (address, bip32_path)); } DeviceToUserMessage::NonceJobs(mut batch) => { // Run the batch to completion and send a single response batch.run_until_finished(&mut TestDeviceKeyGen); let segments = batch.into_segments(); let response = DeviceSend::ToCoordinator(Box::new(DeviceToCoordinatorMessage::Signing( message::signing::DeviceSigning::NonceResponse { segments }, ))); run.extend_from_device(from, vec![response]); } } } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/tests/env/mod.rs
frostsnap_core/tests/env/mod.rs
mod test_env; pub use test_env::TestEnv;
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_core/tests/common/mod.rs
frostsnap_core/tests/common/mod.rs
use bitcoin::hashes::{sha256, Hash, HashEngine, Hmac, HmacEngine}; use frostsnap_core::device::{DeviceSecretDerivation, DeviceToUserMessage, KeyPurpose}; use frostsnap_core::message::{CoordinatorToDeviceMessage, DeviceSend, DeviceToCoordinatorMessage}; use frostsnap_core::{ coordinator::{ BeginKeygen, CoordinatorSend, CoordinatorToUserKeyGenMessage, CoordinatorToUserMessage, FrostCoordinator, }, device::FrostSigner, DeviceId, SymmetricKey, }; use frostsnap_core::{AccessStructureRef, MessageResult}; use rand::RngCore; use schnorr_fun::frost::ShareIndex; use std::collections::{BTreeMap, BTreeSet, VecDeque}; pub const TEST_ENCRYPTION_KEY: SymmetricKey = SymmetricKey([42u8; 32]); pub const TEST_FINGERPRINT: schnorr_fun::frost::Fingerprint = schnorr_fun::frost::Fingerprint { bits_per_coeff: 2, max_bits_total: 6, tag: "test", }; #[derive(Debug, Clone)] #[allow(clippy::large_enum_variant)] // we're in a test pub enum Send { DeviceToUser { message: DeviceToUserMessage, from: DeviceId, }, CoordinatorToUser(CoordinatorToUserMessage), DeviceToCoordinator { from: DeviceId, message: DeviceToCoordinatorMessage, }, CoordinatorToDevice { destinations: BTreeSet<DeviceId>, message: CoordinatorToDeviceMessage, }, } impl From<CoordinatorSend> for Send { fn from(value: CoordinatorSend) -> Self { match value { CoordinatorSend::ToDevice { message, destinations, } => Send::CoordinatorToDevice { destinations, message, }, CoordinatorSend::ToUser(v) => v.into(), } } } impl From<CoordinatorToUserMessage> for Send { fn from(value: CoordinatorToUserMessage) -> Self { Send::CoordinatorToUser(value) } } impl Send { pub fn device_send(from: DeviceId, device_send: DeviceSend) -> Self { match device_send { DeviceSend::ToCoordinator(message) => Send::DeviceToCoordinator { from, message: *message, }, DeviceSend::ToUser(message) => Send::DeviceToUser { message: *message, from, }, } } } pub struct TestDeviceKeyGen; impl DeviceSecretDerivation for TestDeviceKeyGen { fn get_share_encryption_key( &mut self, _access_structure_ref: AccessStructureRef, _party_index: ShareIndex, _coord_key: frostsnap_core::CoordShareDecryptionContrib, ) -> SymmetricKey { TEST_ENCRYPTION_KEY } fn derive_nonce_seed( &mut self, nonce_stream_id: frostsnap_core::nonce_stream::NonceStreamId, index: u32, seed_material: &[u8; 32], ) -> [u8; 32] { let mut engine = HmacEngine::<sha256::Hash>::new(&TEST_ENCRYPTION_KEY.0); engine.input(nonce_stream_id.to_bytes().as_slice()); engine.input(&index.to_le_bytes()); engine.input(seed_material); let hmac_result = Hmac::<sha256::Hash>::from_engine(engine); *hmac_result.as_byte_array() } } #[allow(unused)] pub trait Env { fn user_react_to_coordinator( &mut self, run: &mut Run, message: CoordinatorToUserMessage, rng: &mut impl RngCore, ) { match message { CoordinatorToUserMessage::KeyGen { keygen_id, inner: CoordinatorToUserKeyGenMessage::KeyGenAck { all_acks_received: true, .. }, } => { let send_finalize_keygen = run .coordinator .finalize_keygen(keygen_id, TEST_ENCRYPTION_KEY, rng) .unwrap(); run.extend(send_finalize_keygen); } _ => { /* nothing needs doing */ } } } fn user_react_to_device( &mut self, run: &mut Run, from: DeviceId, message: DeviceToUserMessage, rng: &mut impl RngCore, ) { match message { DeviceToUserMessage::FinalizeKeyGen { .. } => {} DeviceToUserMessage::CheckKeyGen { phase, .. } => { let ack = run .device(from) .keygen_ack(*phase, &mut TestDeviceKeyGen, rng) .unwrap(); run.extend_from_device(from, ack); } DeviceToUserMessage::SignatureRequest { phase } => { let sign_ack = run .device(from) .sign_ack(*phase, &mut TestDeviceKeyGen) .unwrap(); run.extend_from_device(from, sign_ack); } DeviceToUserMessage::Restoration(restoration) => { use frostsnap_core::device::restoration::ToUserRestoration::*; match *restoration { ConsolidateBackup(phase) => { let ack = run.device(from).finish_consolidation( &mut TestDeviceKeyGen, phase, rng, ); run.extend_from_device(from, ack); } _ => { /* do nothing */ } }; } DeviceToUserMessage::VerifyAddress { .. } => { // we dont actually confirm on the device } _ => { /* do nothing */ } } } } #[derive(Clone)] pub struct Run { pub coordinator: FrostCoordinator, pub devices: BTreeMap<DeviceId, FrostSigner>, pub message_queue: VecDeque<Send>, pub transcript: Vec<Send>, pub start_coordinator: FrostCoordinator, pub start_devices: BTreeMap<DeviceId, FrostSigner>, } impl core::fmt::Debug for Run { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Run") .field("coordinator", &"..") .field("devices", &self.device_set()) .field("message_queue", &self.message_queue) .field("transcript", &self.transcript) .field("start_coordinator", &"..") .field("start_devices", &"..") .finish() } } impl Run { pub fn generate_with_nonce_slots_and_batch_size( n_devices: usize, rng: &mut impl rand_core::RngCore, nonce_slots: usize, nonce_batch_size: u32, ) -> Self { let mut coordinator = FrostCoordinator::new(); coordinator.keygen_fingerprint = TEST_FINGERPRINT; Self::new( coordinator, (0..n_devices) .map(|_| { let mut signer = FrostSigner::new_random_with_nonce_batch_size( rng, nonce_slots, nonce_batch_size, ); signer.keygen_fingerprint = TEST_FINGERPRINT; (signer.device_id(), signer) }) .collect(), ) } pub fn generate(n_devices: usize, rng: &mut impl rand_core::RngCore) -> Self { Self::generate_with_nonce_slots_and_batch_size(n_devices, rng, 8, 10) } #[allow(unused)] pub fn start_after_keygen( n_devices: usize, threshold: u16, env: &mut impl Env, rng: &mut impl rand_core::RngCore, purpose: KeyPurpose, ) -> Self { let mut run = Self::generate(n_devices, rng); use rand_chacha::{rand_core::SeedableRng, ChaCha20Rng}; let mut seed = [0u8; 32]; rng.fill_bytes(&mut seed); let mut coordinator_rng = ChaCha20Rng::from_seed(seed); let keygen_init = run .coordinator .begin_keygen( BeginKeygen::new( run.devices.keys().cloned().collect::<Vec<_>>(), threshold, "my new key".to_string(), purpose, rng, ), &mut coordinator_rng, ) .unwrap(); let keygen_id = keygen_init.0.keygen_id; run.extend(keygen_init); run.run_until_finished(env, rng).unwrap(); run } #[allow(unused)] pub fn start_after_keygen_and_nonces( n_devices: usize, threshold: u16, env: &mut impl Env, rng: &mut impl rand_core::RngCore, n_nonce_streams: usize, purpose: KeyPurpose, ) -> Self { let mut run = Self::start_after_keygen(n_devices, threshold, env, rng, purpose); run.extend(run.coordinator.maybe_request_nonce_replenishment( &run.device_set(), n_nonce_streams, rng, )); run.run_until_finished(env, rng).unwrap(); run } pub fn new(coordinator: FrostCoordinator, devices: BTreeMap<DeviceId, FrostSigner>) -> Self { Self { start_coordinator: coordinator.clone(), start_devices: devices.clone(), coordinator, devices, message_queue: Default::default(), transcript: Default::default(), } } #[allow(unused)] pub fn clear_coordinator(&mut self) { let mut coordinator = FrostCoordinator::new(); coordinator.keygen_fingerprint = TEST_FINGERPRINT; self.coordinator = coordinator.clone(); self.start_coordinator = coordinator; } #[allow(unused)] pub fn new_device(&mut self, rng: &mut impl rand_core::RngCore) -> DeviceId { let mut signer = FrostSigner::new_random_with_nonce_batch_size(rng, 8, 10); signer.keygen_fingerprint = TEST_FINGERPRINT; let device_id = signer.device_id(); self.devices.insert(device_id, signer.clone()); self.start_devices.insert(device_id, signer); device_id } pub fn device_set(&self) -> BTreeSet<DeviceId> { self.devices.keys().cloned().collect() } #[allow(unused)] pub fn device_vec(&self) -> Vec<DeviceId> { self.devices.keys().cloned().collect() } pub fn run_until_finished<E: Env>( &mut self, env: &mut E, rng: &mut impl rand_core::RngCore, ) -> MessageResult<()> { self.run_until(env, rng, |_| false) } pub fn extend(&mut self, iter: impl IntoIterator<Item = impl Into<Send>>) { self.message_queue .extend(iter.into_iter().map(|v| v.into())); } pub fn extend_from_device( &mut self, from: DeviceId, iter: impl IntoIterator<Item = DeviceSend>, ) { self.message_queue .extend(iter.into_iter().map(|v| Send::device_send(from, v))) } pub fn device(&mut self, id: DeviceId) -> &mut FrostSigner { self.devices.get_mut(&id).unwrap() } pub fn run_until<E: Env>( &mut self, env: &mut E, rng: &mut impl rand_core::RngCore, mut until: impl FnMut(&mut Run) -> bool, ) -> MessageResult<()> { while !until(self) { let to_send = match self.message_queue.pop_front() { Some(message) => message, None => break, }; self.transcript.push(to_send.clone()); match to_send { Send::DeviceToUser { message, from } => { env.user_react_to_device(self, from, message, rng); } Send::CoordinatorToUser(message) => { env.user_react_to_coordinator(self, message, rng); } Send::DeviceToCoordinator { from, message } => { self.message_queue.extend( self.coordinator .recv_device_message(from, message)? .into_iter() .map(Send::from), ); } Send::CoordinatorToDevice { destinations, message, } => { for destination in destinations { self.message_queue.extend( self.devices .get_mut(&destination) .unwrap() .recv_coordinator_message(message.clone(), rng)? .into_iter() .map(|v| Send::device_send(destination, v)), ); } } } } Ok(()) } pub fn check_mutations(&mut self) { let mutations = self.coordinator.take_staged_mutations(); for mutation in mutations { self.start_coordinator.apply_mutation(mutation); } assert_eq!( self.start_coordinator, { let mut tmp = self.coordinator.clone(); tmp.clear_tmp_data(); tmp }, "coordinator should be the same after applying mutations" ); for (device_id, device) in &mut self.devices { let mut device = device.clone(); device.clear_tmp_data(); let mutations = device.staged_mutations().drain(..).collect::<Vec<_>>(); let start_device = self.start_devices.get_mut(device_id).unwrap(); *start_device.nonce_slots() = device.nonce_slots().clone(); for mutation in mutations { start_device.apply_mutation(mutation); } assert_eq!( *start_device, device, "device should be the same after applying mutations" ); } } } impl Drop for Run { fn drop(&mut self) { self.check_mutations(); } } /// Macro for testing backward compatibility of bincode serialization #[macro_export] macro_rules! assert_bincode_hex_eq { ($mutation:expr, $expected_hex:expr) => { // Decode hex string to bytes let expected_bytes = frostsnap_core::hex::decode($expected_hex) .expect(&format!("Failed to parse hex for {:?}", $mutation.kind())); // Decode the bytes back to the type let (decoded, _) = bincode::decode_from_slice(&expected_bytes, bincode::config::standard()) .expect(&format!("Failed to decode hex for {:?}", $mutation.kind())); // Compare the decoded value with the original assert_eq!($mutation, decoded, "Mismatch for {:?}", $mutation.kind()); }; }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/bobbing_carat.rs
frostsnap_widgets/src/bobbing_carat.rs
use crate::super_draw_target::SuperDrawTarget; use crate::{image::Image, translate::Translate, Widget}; use embedded_graphics::{ draw_target::DrawTarget, geometry::{Point, Size}, }; use embedded_iconoir::{prelude::IconoirNewIcon, size24px::navigation::NavArrowUp}; /// A carat icon that bobs up and down pub struct BobbingCarat<C: crate::WidgetColor> { translate: Translate<Image<embedded_iconoir::Icon<C, NavArrowUp>>>, } impl<C: crate::WidgetColor> BobbingCarat<C> where C: Copy, { pub fn new(color: C, background_color: C) -> Self { let icon = NavArrowUp::new(color); let image_widget = Image::new(icon); let mut translate = Translate::new(image_widget, background_color); // Set up bobbing animation - move up and down by 5 pixels over 1 second translate.set_repeat(true); translate.animate_to(Point::new(0, 5), 500); // 500ms down, 500ms back up Self { translate } } } impl<C: crate::WidgetColor> crate::DynWidget for BobbingCarat<C> where C: Copy, { fn set_constraints(&mut self, max_size: Size) { self.translate.set_constraints(max_size); } fn sizing(&self) -> crate::Sizing { self.translate.sizing() } fn force_full_redraw(&mut self) { self.translate.force_full_redraw(); } } impl<C: crate::WidgetColor> Widget for BobbingCarat<C> where C: Copy, { type Color = C; fn draw<D>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, current_time: crate::Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { self.translate.draw(target, current_time) } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/any_of.rs
frostsnap_widgets/src/any_of.rs
use crate::{AnyDynWidget, DynWidget, Instant, Widget}; use alloc::boxed::Box; use core::any::{Any, TypeId}; use embedded_graphics::{ draw_target::DrawTarget, geometry::{Point, Size}, }; /// A widget that can be any one of the types in the tuple T /// This provides type-safe dynamic dispatch for widgets pub struct AnyOf<T> { inner: Box<dyn AnyDynWidget>, _phantom: core::marker::PhantomData<T>, } impl<T> AnyOf<T> { /// Create a new AnyOf from a widget that must be one of the types in T pub fn new<W: AnyDynWidget + 'static>(widget: W) -> Self { Self { inner: Box::new(widget), _phantom: core::marker::PhantomData, } } /// Try to get a mutable reference to the inner widget as a specific type pub fn downcast_mut<W: Any>(&mut self) -> Option<&mut W> { let widget = self.inner.as_mut() as &mut dyn Any; widget.downcast_mut::<W>() } /// Try to get a reference to the inner widget as a specific type pub fn downcast_ref<W: Any>(&self) -> Option<&W> { let widget = self.inner.as_ref() as &dyn Any; widget.downcast_ref::<W>() } } // Helper macro to implement DynWidget for AnyOf macro_rules! impl_any_of { ($($t:ident),+) => { impl<$($t: AnyDynWidget + PartialEq + 'static),+> PartialEq for AnyOf<($($t,)+)> { fn eq(&self, other: &Self) -> bool { let self_type_id = self.inner.as_ref().type_id(); let other_type_id = other.inner.as_ref().type_id(); // First check if they're the same type if self_type_id != other_type_id { return false; } // Try to downcast to each possible type and compare $( if self_type_id == TypeId::of::<$t>() { let self_widget = self.inner.as_ref() as &dyn Any; let other_widget = other.inner.as_ref() as &dyn Any; let self_widget = self_widget.downcast_ref::<$t>().unwrap(); let other_widget = other_widget.downcast_ref::<$t>().unwrap(); return self_widget == other_widget; } )+ // This should never happen if AnyOf is constructed properly false } } impl<$($t: AnyDynWidget + 'static),+> DynWidget for AnyOf<($($t,)+)> { fn set_constraints(&mut self, max_size: Size) { self.inner.set_constraints(max_size) } fn sizing(&self) -> crate::Sizing { self.inner.sizing() } fn handle_touch(&mut self, point: Point, current_time: Instant, is_release: bool) -> Option<crate::KeyTouch> { self.inner.handle_touch(point, current_time, is_release) } fn handle_vertical_drag(&mut self, prev_y: Option<u32>, new_y: u32, is_release: bool) { self.inner.handle_vertical_drag(prev_y, new_y, is_release) } fn force_full_redraw(&mut self) { self.inner.force_full_redraw() } } impl<$($t: Widget<Color = COLOR> + 'static),+, COLOR: crate::WidgetColor> Widget for AnyOf<($($t,)+)> { type Color = COLOR; fn draw<DT>(&mut self, target: &mut crate::super_draw_target::SuperDrawTarget<DT, COLOR>, current_time: Instant) -> Result<(), DT::Error> where DT: DrawTarget<Color = COLOR>, { let type_id = self.inner.as_ref().type_id(); $( if type_id == TypeId::of::<$t>() { let widget = self.inner.as_mut() as &mut dyn Any; let widget = widget.downcast_mut::<$t>().unwrap(); return widget.draw(target, current_time); } )+ // This should never happen if AnyOf is constructed properly panic!("AnyOf inner widget type not in tuple"); } } }; } // Generate implementations for tuples of different sizes impl_any_of!(A); impl_any_of!(A, B); impl_any_of!(A, B, C); impl_any_of!(A, B, C, D); impl_any_of!(A, B, C, D, E); impl_any_of!(A, B, C, D, E, F); impl_any_of!(A, B, C, D, E, F, G); impl_any_of!(A, B, C, D, E, F, G, H); impl_any_of!(A, B, C, D, E, F, G, H, I); impl_any_of!(A, B, C, D, E, F, G, H, I, J); impl_any_of!(A, B, C, D, E, F, G, H, I, J, K); impl_any_of!(A, B, C, D, E, F, G, H, I, J, K, L); impl_any_of!(A, B, C, D, E, F, G, H, I, J, K, L, M); impl_any_of!(A, B, C, D, E, F, G, H, I, J, K, L, M, N); impl_any_of!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/cursor.rs
frostsnap_widgets/src/cursor.rs
use crate::palette::PALETTE; use crate::super_draw_target::SuperDrawTarget; use crate::Widget; use embedded_graphics::{ pixelcolor::Rgb565, prelude::*, primitives::{PrimitiveStyle, Rectangle}, }; // Font size matching the one used in bip39_input_preview const FONT_SIZE: Size = Size::new(16, 24); #[derive(Debug)] pub struct Cursor { last_toggle: Option<crate::Instant>, last_draw_rect: Option<Rectangle>, rect: Rectangle, enabled: bool, } impl Cursor { pub fn new(position: Point) -> Self { Self { last_toggle: None, rect: Rectangle { top_left: position, size: Size::new(FONT_SIZE.width - 4, 2), }, last_draw_rect: None, enabled: true, } } pub fn set_position(&mut self, new_position: Point) { self.rect.top_left = new_position; self.last_toggle = None; } pub fn enabled(&mut self, enabled: bool) { if enabled == self.enabled { return; } if !enabled { self.last_toggle = None; } self.enabled = enabled; } } impl crate::DynWidget for Cursor { fn set_constraints(&mut self, _max_size: Size) { // Cursor has a fixed size } fn sizing(&self) -> crate::Sizing { self.rect.size.into() } } impl Widget for Cursor { type Color = Rgb565; fn draw<D>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, current_time: crate::Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { if let Some(last_draw_rect) = self.last_draw_rect { if self.rect != last_draw_rect || !self.enabled { last_draw_rect .into_styled(PrimitiveStyle::with_fill(PALETTE.background)) .draw(target)?; self.last_draw_rect = None; } } if !self.enabled { return Ok(()); } let toggle_time = match self.last_toggle { Some(last_toggle) => current_time.saturating_duration_since(last_toggle) >= 600, None => true, }; if toggle_time { if let Some(last_draw_rect) = self.last_draw_rect.take() { last_draw_rect .into_styled(PrimitiveStyle::with_fill(PALETTE.background)) .draw(target)?; } else { self.rect .into_styled(PrimitiveStyle::with_fill(PALETTE.primary)) .draw(target)?; self.last_draw_rect = Some(self.rect); } self.last_toggle = Some(current_time); } Ok(()) } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/prelude.rs
frostsnap_widgets/src/prelude.rs
//! Common imports for frostsnap_widgets //! //! Import this module with `use crate::prelude::*;` to get access to commonly used traits and types. pub use crate::layout::*; pub use crate::text::Text; pub use crate::Instant; pub use crate::SuperDrawTarget; pub use crate::{DynWidget, Widget};
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/device_name.rs
frostsnap_widgets/src/device_name.rs
use super::{Column, Row, Text as TextWidget}; use crate::DefaultTextStyle; use crate::{cursor::Cursor, palette::PALETTE, prelude::*, GrayToAlpha, Image, Switcher}; use alloc::string::String; use embedded_graphics::{ pixelcolor::{Gray8, Rgb565}, text::renderer::TextRenderer, }; use tinybmp::Bmp; /// A widget for displaying device name with optional edit mode cursor #[derive(frostsnap_macros::Widget)] pub struct DeviceName { /// The device name text widget with optional cursor #[widget_delegate] text_widget: Container<Switcher<Row<(TextWidget, Option<Cursor>)>>>, } impl DeviceName { /// Create a new device name widget pub fn new<S: Into<String>>(name: S) -> Self { let name_string = name.into(); let char_style = DefaultTextStyle::new(crate::FONT_LARGE, PALETTE.on_background); let text = TextWidget::new(name_string, char_style.clone()); let row = Row::new((text, None::<Cursor>)) .with_main_axis_alignment(crate::MainAxisAlignment::Center); let switcher = Switcher::new(row); let container = Container::new(switcher) .with_width(u32::MAX) .with_height(char_style.line_height()); Self { text_widget: container, } } /// Get the current name pub fn name(&self) -> &str { self.text_widget.child.current().children.0.text() } /// Set a new device name pub fn set_name<S: Into<String>>(&mut self, name: S) { let name_string = name.into(); let char_style = DefaultTextStyle::new(crate::FONT_LARGE, PALETTE.on_background); let text = TextWidget::new(name_string, char_style); let row = Row::new((text, None::<Cursor>)) .with_main_axis_alignment(crate::MainAxisAlignment::Center) .with_cross_axis_alignment(crate::CrossAxisAlignment::End); self.text_widget.child.switch_to(row); } /// Enable the cursor for edit mode pub fn enable_cursor(&mut self) { let current_row = self.text_widget.child.current(); if current_row.children.1.is_none() { // Get the current text let text_widget = current_row.children.0.clone(); // Create a cursor at the end of the text let cursor = Cursor::new(embedded_graphics::prelude::Point::zero()); let new_row = Row::new((text_widget, Some(cursor))) .with_main_axis_alignment(crate::MainAxisAlignment::Center) .with_cross_axis_alignment(crate::CrossAxisAlignment::End); self.text_widget.child.switch_to(new_row); } } /// Disable the cursor pub fn disable_cursor(&mut self) { let current_row = self.text_widget.child.current(); if current_row.children.1.is_some() { // Get the current text let text_widget = current_row.children.0.clone(); let new_row = Row::new((text_widget, None::<Cursor>)) .with_main_axis_alignment(crate::MainAxisAlignment::Center) .with_cross_axis_alignment(crate::CrossAxisAlignment::End); self.text_widget.child.switch_to(new_row); } } /// Check if cursor is enabled pub fn is_cursor_enabled(&self) -> bool { self.text_widget.child.current().children.1.is_some() } } const LOGO_DATA: &[u8] = include_bytes!("../assets/frostsnap-icon-80x96.bmp"); /// A screen showing the Frostsnap logo and the DeviceName widget #[derive(frostsnap_macros::Widget)] pub struct DeviceNameScreen { #[widget_delegate] column: Column<(Image<GrayToAlpha<Bmp<'static, Gray8>, Rgb565>>, DeviceName)>, } impl DeviceNameScreen { /// Get a reference to the inner DeviceName widget fn device_name_widget(&self) -> &DeviceName { &self.column.children.1 } /// Get a mutable reference to the inner DeviceName widget fn device_name_widget_mut(&mut self) -> &mut DeviceName { &mut self.column.children.1 } pub fn new(device_name: String) -> Self { let logo_bmp = Bmp::<Gray8>::from_slice(LOGO_DATA).expect("Failed to load BMP"); let logo_colored = Image::new(GrayToAlpha::new(logo_bmp, PALETTE.logo)); // Create DeviceName widget let device_name_widget = DeviceName::new(device_name); // Create the column with main axis alignment for spacing let column = Column::new((logo_colored, device_name_widget)) .with_main_axis_alignment(crate::MainAxisAlignment::SpaceEvenly); Self { column } } /// Get the current device name pub fn name(&self) -> &str { self.device_name_widget().name() } /// Set a new device name pub fn set_name<S: Into<String>>(&mut self, name: S) { self.device_name_widget_mut().set_name(name); } } // All trait implementations are now generated by the derive macro
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/hold_to_confirm_border.rs
frostsnap_widgets/src/hold_to_confirm_border.rs
use super::{compressed_point::CompressedPoint, pixel_recorder::PixelRecorder, rat::Frac, Widget}; use crate::fader::FadingDrawTarget; use crate::super_draw_target::SuperDrawTarget; use alloc::vec::Vec; use embedded_graphics::{ draw_target::DrawTarget, pixelcolor::{BinaryColor, PixelColor, Rgb565}, prelude::*, primitives::{PrimitiveStyleBuilder, Rectangle, RoundedRectangle}, }; /// Generate both the original and mirrored pixel for a given compressed point fn mirror_pixel<C: PixelColor>( pixel: CompressedPoint, screen_width: i32, color: C, ) -> [Pixel<C>; 2] { let point = pixel.to_point(); let mirrored_x = screen_width - 1 - point.x; [ Pixel(point, color), Pixel(Point::new(mirrored_x, point.y), color), ] } #[derive(Debug, PartialEq)] pub struct HoldToConfirmBorder<W, C> where W: Widget<Color = C>, C: PixelColor, { pub child: W, progress: Frac, // 0 to 1 (percentage of border completed) last_drawn_progress: Frac, constraints: Option<Size>, sizing: crate::Sizing, border_pixels: Vec<CompressedPoint>, // Recorded border pixels (compressed) border_width: u32, border_color: C, background_color: C, // Fade state for border only fade_progress: Frac, fade_start_time: Option<crate::Instant>, fade_duration_ms: u64, is_fading: bool, } impl<W, C> HoldToConfirmBorder<W, C> where W: Widget<Color = C>, C: PixelColor, { pub fn new(child: W, border_width: u32, border_color: C, background_color: C) -> Self { Self { child, progress: Frac::ZERO, last_drawn_progress: Frac::ZERO, constraints: None, sizing: crate::Sizing { width: 0, height: 0, ..Default::default() }, border_pixels: Vec::new(), border_width, border_color, background_color, fade_progress: Frac::ZERO, fade_start_time: None, fade_duration_ms: 0, is_fading: false, } } pub fn set_progress(&mut self, progress: Frac) { self.progress = progress; } pub fn get_progress(&self) -> Frac { self.progress } pub fn border_width(&self) -> u32 { self.border_width } pub fn start_fade_out(&mut self, duration_ms: u64) { self.is_fading = true; self.fade_duration_ms = duration_ms; self.fade_start_time = None; // Will be set on first draw self.fade_progress = Frac::ZERO; } pub fn is_faded_out(&self) -> bool { self.is_fading && self.fade_progress == Frac::ONE } fn record_border_pixels(&mut self, screen_size: Size) { const CORNER_RADIUS: u32 = 42; // Create a recorder clipped to only the left half to save memory. // We're going to draw the other half by mirroring around the y-axis. let mut recorder = PixelRecorder::new(); let middle_x = screen_size.width as i32 / 2; let left_half_area = Rectangle::new( Point::new(0, 0), Size::new((middle_x + 1) as u32, screen_size.height), ); let mut clipped_recorder = recorder.clipped(&left_half_area); // Draw the rounded rectangle directly to the clipped recorder // This will only record pixels in the left half use embedded_graphics::primitives::{CornerRadii, StrokeAlignment}; let _ = RoundedRectangle::new( Rectangle::new(Point::new(0, 0), screen_size), CornerRadii::new(Size::new(CORNER_RADIUS, CORNER_RADIUS)), ) .into_styled( PrimitiveStyleBuilder::new() .stroke_color(BinaryColor::Off) .stroke_width(self.border_width) .stroke_alignment(StrokeAlignment::Inside) .build(), ) .draw(&mut clipped_recorder); // Sort the left-half pixels let mut pixels = recorder.pixels; pixels.sort_unstable_by_key(|cp| { let point = cp.to_point(); let mut y_bucket = point.y; if y_bucket < self.border_width as i32 { y_bucket = 0; } else if y_bucket > (screen_size.height as i32 - self.border_width as i32 - 1) { y_bucket = i32::MAX; } // For left-half pixels, closer to middle should come first let x_distance = middle_x - point.x; let final_distance = if point.y > screen_size.height as i32 / 2 { -x_distance } else { x_distance }; (y_bucket, final_distance) }); pixels.shrink_to_fit(); // Store the sorted left-half pixels self.border_pixels = pixels; self.constraints = Some(screen_size); // Store screen size for mirroring } } impl<W, C> crate::DynWidget for HoldToConfirmBorder<W, C> where W: Widget<Color = C>, C: PixelColor, { fn set_constraints(&mut self, max_size: Size) { self.constraints = Some(max_size); // Give child less space to account for the border let child_max_size = Size::new( max_size.width.saturating_sub(2 * self.border_width), max_size.height.saturating_sub(2 * self.border_width), ); self.child.set_constraints(child_max_size); // Update our cached sizing let child_sizing = self.child.sizing(); self.sizing = crate::Sizing { width: child_sizing.width + 2 * self.border_width, height: child_sizing.height + 2 * self.border_width, ..Default::default() }; self.record_border_pixels(max_size); } fn sizing(&self) -> crate::Sizing { self.sizing } fn handle_touch( &mut self, point: Point, current_time: crate::Instant, lift_up: bool, ) -> Option<super::KeyTouch> { // Always forward to child self.child.handle_touch(point, current_time, lift_up) } fn handle_vertical_drag(&mut self, prev_y: Option<u32>, new_y: u32, _is_release: bool) { // Always forward to child self.child.handle_vertical_drag(prev_y, new_y, _is_release); } fn force_full_redraw(&mut self) { self.last_drawn_progress = Frac::ZERO; // Also propagate to child self.child.force_full_redraw(); } } // Only implement Widget for Rgb565 since we need fading support impl<W> Widget for HoldToConfirmBorder<W, Rgb565> where W: Widget<Color = Rgb565>, { type Color = Rgb565; fn draw<D>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, current_time: crate::Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { let offset = Point::new(self.border_width as i32, self.border_width as i32); let child_size = self.child.sizing(); let child_area = Rectangle::new(offset, Size::new(child_size.width, child_size.height)); let mut cropped = target.clone().crop(child_area); self.child.draw(&mut cropped, current_time)?; // Don't draw anything if fully faded out if self.is_faded_out() { return Ok(()); } // Create fading target if we're fading if self.is_fading { let start_time = self.fade_start_time.get_or_insert(current_time); let elapsed = current_time.saturating_duration_since(*start_time); self.fade_progress = Frac::from_ratio(elapsed as u32, self.fade_duration_ms as u32); let mut fading_target = FadingDrawTarget { target, fade_progress: self.fade_progress, target_color: self.background_color, }; // Draw with mirroring for fading let screen_width = self.constraints.unwrap().width as i32; let border_color = self.border_color; // Use flat_map to draw both original and mirrored pixels let pixels_iter = self .border_pixels .iter() .flat_map(move |&pixel| mirror_pixel(pixel, screen_width, border_color)); fading_target.draw_iter(pixels_iter) } else { // We're drawing double the pixels (each stored pixel + its mirror) let total_pixels = self.border_pixels.len(); let mut current_progress_pixels = (self.progress * total_pixels as u32).floor() as usize; let mut last_progress_pixels = (self.last_drawn_progress * total_pixels as u32).floor() as usize; let color = if current_progress_pixels > last_progress_pixels { self.border_color } else { core::mem::swap(&mut current_progress_pixels, &mut last_progress_pixels); self.background_color }; let screen_width = self.constraints.unwrap().width as i32; let pixels_iter = self.border_pixels[last_progress_pixels..current_progress_pixels] .iter() .flat_map(move |&pixel| mirror_pixel(pixel, screen_width, color)); target.draw_iter(pixels_iter)?; self.last_drawn_progress = self.progress; Ok(()) } } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/vec_framebuffer.rs
frostsnap_widgets/src/vec_framebuffer.rs
//! Vec-based framebuffer implementation for dynamic sizing //! This is a translation of embedded-graphics framebuffer that uses Vec instead of const generics use alloc::vec::Vec; use core::convert::Infallible; use embedded_graphics::{ draw_target::DrawTarget, geometry::{OriginDimensions, Point, Size}, iterator::raw::RawDataSlice, pixelcolor::{ raw::{LittleEndian, RawData, RawU1, RawU16, RawU2, RawU4, RawU8}, BinaryColor, Gray2, Gray4, Gray8, PixelColor, Rgb565, }, primitives::Rectangle, Pixel, }; /// A framebuffer with dynamic dimensions using Vec storage #[derive(Clone, PartialEq)] pub struct VecFramebuffer<C> where C: PixelColor, { /// Raw pixel data stored in a Vec pub data: Vec<u8>, /// Width of the framebuffer in pixels pub width: usize, /// Height of the framebuffer in pixels pub height: usize, _phantom: core::marker::PhantomData<C>, } impl<C> VecFramebuffer<C> where C: PixelColor, { /// Calculate the required buffer size in bytes for the given dimensions #[inline] pub fn buffer_size(width: usize, height: usize) -> usize { let bits_per_pixel = C::Raw::BITS_PER_PIXEL; let total_bits = width * height * bits_per_pixel; // Round up to nearest byte total_bits.div_ceil(8) } /// Create a new framebuffer with the given dimensions pub fn new(width: usize, height: usize) -> Self { let buffer_size = Self::buffer_size(width, height); Self { data: vec![0; buffer_size], width, height, _phantom: core::marker::PhantomData, } } /// Get the raw data as a slice #[inline] pub fn data(&self) -> &[u8] { &self.data } /// Get the raw data as a mutable slice #[inline] pub fn data_mut(&mut self) -> &mut [u8] { &mut self.data } } // Implement OriginDimensions trait impl<C> OriginDimensions for VecFramebuffer<C> where C: PixelColor, { fn size(&self) -> Size { Size::new(self.width as u32, self.height as u32) } } /// Iterator over colors in a VecFramebuffer pub struct ContiguousPixels<'a, C> where C: PixelColor, RawDataSlice<'a, C::Raw, LittleEndian>: IntoIterator<Item = C::Raw>, { iter: <RawDataSlice<'a, C::Raw, LittleEndian> as IntoIterator>::IntoIter, } impl<'a, C> Iterator for ContiguousPixels<'a, C> where C: PixelColor + From<C::Raw>, RawDataSlice<'a, C::Raw, LittleEndian>: IntoIterator<Item = C::Raw>, { type Item = C; fn next(&mut self) -> Option<Self::Item> { self.iter.next().map(|raw| raw.into()) } } impl<C> VecFramebuffer<C> where C: PixelColor, for<'a> RawDataSlice<'a, C::Raw, LittleEndian>: IntoIterator<Item = C::Raw>, { /// Returns an iterator over all colors in the framebuffer pub fn contiguous_pixels(&self) -> ContiguousPixels<'_, C> { ContiguousPixels { iter: RawDataSlice::<C::Raw, LittleEndian>::new(&self.data).into_iter(), } } } // Implementation for Rgb565 (16-bit color) impl VecFramebuffer<Rgb565> { /// Set a pixel at the given point #[inline] pub fn set_pixel(&mut self, point: Point, color: Rgb565) { if let (Ok(x), Ok(y)) = (usize::try_from(point.x), usize::try_from(point.y)) { if x < self.width && y < self.height { let pixel_index = y * self.width + x; let byte_index = pixel_index * 2; let raw: RawU16 = color.into(); let value = raw.into_inner(); // Little endian: low byte first self.data[byte_index] = (value & 0xFF) as u8; self.data[byte_index + 1] = ((value >> 8) & 0xFF) as u8; } } } /// Get a pixel at the given point #[inline] pub fn get_pixel(&self, point: Point) -> Option<Rgb565> { if let (Ok(x), Ok(y)) = (usize::try_from(point.x), usize::try_from(point.y)) { if x < self.width && y < self.height { let pixel_index = y * self.width + x; let byte_index = pixel_index * 2; // Little endian: low byte first let value = self.data[byte_index] as u16 | ((self.data[byte_index + 1] as u16) << 8); let raw = RawU16::new(value); return Some(raw.into()); } } None } /// Clear the framebuffer with the given color pub fn clear(&mut self, color: Rgb565) { let raw: RawU16 = color.into(); let value = raw.into_inner(); let byte0 = (value & 0xFF) as u8; let byte1 = ((value >> 8) & 0xFF) as u8; for chunk in self.data.chunks_exact_mut(2) { chunk[0] = byte0; chunk[1] = byte1; } } /// Fill a rectangular region with a color pub fn fill_rect(&mut self, rect: Rectangle, color: Rgb565) { let start_x = rect.top_left.x.max(0) as usize; let start_y = rect.top_left.y.max(0) as usize; let end_x = ((rect.top_left.x + rect.size.width as i32).min(self.width as i32)) as usize; let end_y = ((rect.top_left.y + rect.size.height as i32).min(self.height as i32)) as usize; let raw: RawU16 = color.into(); let value = raw.into_inner(); let byte0 = (value & 0xFF) as u8; let byte1 = ((value >> 8) & 0xFF) as u8; for y in start_y..end_y { for x in start_x..end_x { let pixel_index = y * self.width + x; let byte_index = pixel_index * 2; self.data[byte_index] = byte0; self.data[byte_index + 1] = byte1; } } } } impl DrawTarget for VecFramebuffer<Rgb565> { type Color = Rgb565; type Error = Infallible; fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error> where I: IntoIterator<Item = Pixel<Self::Color>>, { for Pixel(point, color) in pixels { self.set_pixel(point, color); } Ok(()) } fn fill_contiguous<I>(&mut self, area: &Rectangle, colors: I) -> Result<(), Self::Error> where I: IntoIterator<Item = Self::Color>, { let start_x = area.top_left.x.max(0) as usize; let start_y = area.top_left.y.max(0) as usize; let end_x = ((area.top_left.x + area.size.width as i32).min(self.width as i32)) as usize; let end_y = ((area.top_left.y + area.size.height as i32).min(self.height as i32)) as usize; let mut colors_iter = colors.into_iter(); for y in start_y..end_y { for x in start_x..end_x { if let Some(color) = colors_iter.next() { let pixel_index = y * self.width + x; let byte_index = pixel_index * 2; let raw: RawU16 = color.into(); let value = raw.into_inner(); self.data[byte_index] = (value & 0xFF) as u8; self.data[byte_index + 1] = ((value >> 8) & 0xFF) as u8; } else { return Ok(()); } } } Ok(()) } fn fill_solid(&mut self, area: &Rectangle, color: Self::Color) -> Result<(), Self::Error> { self.fill_rect(*area, color); Ok(()) } fn clear(&mut self, color: Self::Color) -> Result<(), Self::Error> { <VecFramebuffer<Rgb565>>::clear(self, color); Ok(()) } } // Implementation for Gray8 (8-bit grayscale) impl VecFramebuffer<Gray8> { /// Set a pixel at the given point #[inline] pub fn set_pixel(&mut self, point: Point, color: Gray8) { if let (Ok(x), Ok(y)) = (usize::try_from(point.x), usize::try_from(point.y)) { if x < self.width && y < self.height { let pixel_index = y * self.width + x; let raw: RawU8 = color.into(); self.data[pixel_index] = raw.into_inner(); } } } /// Get a pixel at the given point #[inline] pub fn get_pixel(&self, point: Point) -> Option<Gray8> { if let (Ok(x), Ok(y)) = (usize::try_from(point.x), usize::try_from(point.y)) { if x < self.width && y < self.height { let pixel_index = y * self.width + x; let raw = RawU8::new(self.data[pixel_index]); return Some(raw.into()); } } None } /// Clear the framebuffer with the given color pub fn clear(&mut self, color: Gray8) { let raw: RawU8 = color.into(); let value = raw.into_inner(); self.data.fill(value); } /// Fill a rectangular region with a color pub fn fill_rect(&mut self, rect: Rectangle, color: Gray8) { let start_x = rect.top_left.x.max(0) as usize; let start_y = rect.top_left.y.max(0) as usize; let end_x = ((rect.top_left.x + rect.size.width as i32).min(self.width as i32)) as usize; let end_y = ((rect.top_left.y + rect.size.height as i32).min(self.height as i32)) as usize; let raw: RawU8 = color.into(); let value = raw.into_inner(); for y in start_y..end_y { for x in start_x..end_x { let pixel_index = y * self.width + x; self.data[pixel_index] = value; } } } } impl DrawTarget for VecFramebuffer<Gray8> { type Color = Gray8; type Error = Infallible; fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error> where I: IntoIterator<Item = Pixel<Self::Color>>, { for Pixel(point, color) in pixels { self.set_pixel(point, color); } Ok(()) } fn fill_contiguous<I>(&mut self, area: &Rectangle, colors: I) -> Result<(), Self::Error> where I: IntoIterator<Item = Self::Color>, { let start_x = area.top_left.x.max(0) as usize; let start_y = area.top_left.y.max(0) as usize; let end_x = ((area.top_left.x + area.size.width as i32).min(self.width as i32)) as usize; let end_y = ((area.top_left.y + area.size.height as i32).min(self.height as i32)) as usize; let mut colors_iter = colors.into_iter(); for y in start_y..end_y { let row_start = y * self.width + start_x; let row_end = y * self.width + end_x; for pixel_index in row_start..row_end { if let Some(color) = colors_iter.next() { let raw: RawU8 = color.into(); self.data[pixel_index] = raw.into_inner(); } else { return Ok(()); } } } Ok(()) } fn fill_solid(&mut self, area: &Rectangle, color: Self::Color) -> Result<(), Self::Error> { let start_x = area.top_left.x.max(0) as usize; let start_y = area.top_left.y.max(0) as usize; let end_x = ((area.top_left.x + area.size.width as i32).min(self.width as i32)) as usize; let end_y = ((area.top_left.y + area.size.height as i32).min(self.height as i32)) as usize; let raw: RawU8 = color.into(); let value = raw.into_inner(); // For Gray8, we can optimize by filling entire rows at once for y in start_y..end_y { let row_start = y * self.width + start_x; let row_end = y * self.width + end_x; self.data[row_start..row_end].fill(value); } Ok(()) } fn clear(&mut self, color: Self::Color) -> Result<(), Self::Error> { <VecFramebuffer<Gray8>>::clear(self, color); Ok(()) } } // Implementation for Gray4 (4-bit grayscale) impl VecFramebuffer<Gray4> { /// Set a pixel at the given point #[inline] pub fn set_pixel(&mut self, point: Point, color: Gray4) { if let (Ok(x), Ok(y)) = (usize::try_from(point.x), usize::try_from(point.y)) { if x < self.width && y < self.height { let pixel_index = y * self.width + x; let byte_index = pixel_index / 2; let nibble_shift = if pixel_index.is_multiple_of(2) { 4 } else { 0 }; let raw: RawU4 = color.into(); let value = raw.into_inner(); // Clear the nibble let mask = !(0xF << nibble_shift); self.data[byte_index] &= mask; // Set the new value self.data[byte_index] |= (value & 0xF) << nibble_shift; } } } /// Get a pixel at the given point #[inline] pub fn get_pixel(&self, point: Point) -> Option<Gray4> { if let (Ok(x), Ok(y)) = (usize::try_from(point.x), usize::try_from(point.y)) { if x < self.width && y < self.height { let pixel_index = y * self.width + x; let byte_index = pixel_index / 2; let nibble_shift = if pixel_index.is_multiple_of(2) { 4 } else { 0 }; let value = (self.data[byte_index] >> nibble_shift) & 0xF; let raw = RawU4::new(value); return Some(raw.into()); } } None } /// Clear the framebuffer with the given color pub fn clear(&mut self, color: Gray4) { let raw: RawU4 = color.into(); let value = raw.into_inner(); // If both nibbles are the same, we can use fill let fill_byte = (value << 4) | value; self.data.fill(fill_byte); // Handle odd width case where the last pixel might not be paired if !(self.width * self.height).is_multiple_of(2) { let last_pixel_index = self.width * self.height - 1; let byte_index = last_pixel_index / 2; let nibble_shift = if last_pixel_index.is_multiple_of(2) { 4 } else { 0 }; let mask = !(0xF << nibble_shift); self.data[byte_index] &= mask; self.data[byte_index] |= (value & 0xF) << nibble_shift; } } /// Fill a rectangular region with a color pub fn fill_rect(&mut self, rect: Rectangle, color: Gray4) { let start_x = rect.top_left.x.max(0) as usize; let start_y = rect.top_left.y.max(0) as usize; let end_x = ((rect.top_left.x + rect.size.width as i32).min(self.width as i32)) as usize; let end_y = ((rect.top_left.y + rect.size.height as i32).min(self.height as i32)) as usize; let raw: RawU4 = color.into(); let value = raw.into_inner(); for y in start_y..end_y { for x in start_x..end_x { let pixel_index = y * self.width + x; let byte_index = pixel_index / 2; let nibble_shift = if pixel_index.is_multiple_of(2) { 4 } else { 0 }; let mask = !(0xF << nibble_shift); self.data[byte_index] &= mask; self.data[byte_index] |= (value & 0xF) << nibble_shift; } } } } impl DrawTarget for VecFramebuffer<Gray4> { type Color = Gray4; type Error = Infallible; fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error> where I: IntoIterator<Item = Pixel<Self::Color>>, { for Pixel(point, color) in pixels { self.set_pixel(point, color); } Ok(()) } fn fill_solid(&mut self, area: &Rectangle, color: Self::Color) -> Result<(), Self::Error> { self.fill_rect(*area, color); Ok(()) } fn clear(&mut self, color: Self::Color) -> Result<(), Self::Error> { <VecFramebuffer<Gray4>>::clear(self, color); Ok(()) } } // Implementation for Gray2 (2-bit grayscale) impl VecFramebuffer<Gray2> { /// Set a pixel at the given point #[inline] pub fn set_pixel(&mut self, point: Point, color: Gray2) { if let (Ok(x), Ok(y)) = (usize::try_from(point.x), usize::try_from(point.y)) { if x < self.width && y < self.height { let pixel_index = y * self.width + x; let byte_index = pixel_index / 4; let bit_index = 6 - ((pixel_index % 4) * 2); // 2 bits per pixel let raw: RawU2 = color.into(); let value = raw.into_inner(); // Clear the 2 bits let mask = !(0b11 << bit_index); self.data[byte_index] &= mask; // Set the new value self.data[byte_index] |= (value & 0b11) << bit_index; } } } /// Get a pixel at the given point #[inline] pub fn get_pixel(&self, point: Point) -> Option<Gray2> { if let (Ok(x), Ok(y)) = (usize::try_from(point.x), usize::try_from(point.y)) { if x < self.width && y < self.height { let pixel_index = y * self.width + x; let byte_index = pixel_index / 4; let bit_index = 6 - ((pixel_index % 4) * 2); let value = (self.data[byte_index] >> bit_index) & 0b11; let raw = RawU2::new(value); return Some(raw.into()); } } None } /// Clear the framebuffer with the given color pub fn clear(&mut self, color: Gray2) { let raw: RawU2 = color.into(); let value = raw.into_inner(); // Create a byte with all 4 pixels set to the same value let fill_byte = (value << 6) | (value << 4) | (value << 2) | value; self.data.fill(fill_byte); // Handle any remaining pixels if width*height is not divisible by 4 let total_pixels = self.width * self.height; let remainder = total_pixels % 4; if remainder != 0 { let last_byte_index = total_pixels / 4; let mut last_byte = 0u8; for i in 0..remainder { let bit_index = 6 - (i * 2); last_byte |= (value & 0b11) << bit_index; } self.data[last_byte_index] = last_byte; } } /// Fill a rectangular region with a color pub fn fill_rect(&mut self, rect: Rectangle, color: Gray2) { let start_x = rect.top_left.x.max(0) as usize; let start_y = rect.top_left.y.max(0) as usize; let end_x = ((rect.top_left.x + rect.size.width as i32).min(self.width as i32)) as usize; let end_y = ((rect.top_left.y + rect.size.height as i32).min(self.height as i32)) as usize; let raw: RawU2 = color.into(); let value = raw.into_inner(); for y in start_y..end_y { for x in start_x..end_x { let pixel_index = y * self.width + x; let byte_index = pixel_index / 4; let bit_index = 6 - ((pixel_index % 4) * 2); let mask = !(0b11 << bit_index); self.data[byte_index] &= mask; self.data[byte_index] |= (value & 0b11) << bit_index; } } } } impl DrawTarget for VecFramebuffer<Gray2> { type Color = Gray2; type Error = Infallible; fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error> where I: IntoIterator<Item = Pixel<Self::Color>>, { for Pixel(point, color) in pixels { self.set_pixel(point, color); } Ok(()) } fn fill_solid(&mut self, area: &Rectangle, color: Self::Color) -> Result<(), Self::Error> { self.fill_rect(*area, color); Ok(()) } fn clear(&mut self, color: Self::Color) -> Result<(), Self::Error> { <VecFramebuffer<Gray2>>::clear(self, color); Ok(()) } } // Implementation for BinaryColor (1-bit monochrome) impl VecFramebuffer<BinaryColor> { /// Convert pixel coordinates to byte index and bit position #[inline] fn pixel_to_bit_index(&self, x: usize, y: usize) -> (usize, u8) { let pixel_index = y * self.width + x; let byte_index = pixel_index >> 3; // Equivalent to / 8 let bit_index = 7 - ((pixel_index & 7) as u8); // Equivalent to % 8, MSB first (byte_index, bit_index) } /// Set a pixel at the given point #[inline] pub fn set_pixel(&mut self, point: Point, color: BinaryColor) { if let (Ok(x), Ok(y)) = (usize::try_from(point.x), usize::try_from(point.y)) { if x < self.width && y < self.height { let (byte_index, bit_index) = self.pixel_to_bit_index(x, y); match color { BinaryColor::On => self.data[byte_index] |= 1 << bit_index, BinaryColor::Off => self.data[byte_index] &= !(1 << bit_index), } } } } /// Get a pixel at the given point #[inline] pub fn get_pixel(&self, point: Point) -> Option<BinaryColor> { if let (Ok(x), Ok(y)) = (usize::try_from(point.x), usize::try_from(point.y)) { if x < self.width && y < self.height { let (byte_index, bit_index) = self.pixel_to_bit_index(x, y); let value = (self.data[byte_index] >> bit_index) & 1; let raw = RawU1::new(value); return Some(raw.into()); } } None } /// Clear the framebuffer with the given color pub fn clear(&mut self, color: BinaryColor) { let raw: RawU1 = color.into(); let fill_byte = if raw.into_inner() != 0 { 0xFF } else { 0x00 }; self.data.fill(fill_byte); } /// Iterate over all pixels that are set to On /// /// NOTE: This could potentially be optimized by iterating byte-by-byte and skipping /// empty bytes (0x00), but this would require division operations to convert byte /// indices back to pixel coordinates. Benchmarking should be done first to verify /// that such an optimization actually improves performance for typical use cases. pub fn on_pixels(&self) -> impl Iterator<Item = Point> + '_ { let width = self.width; let height = self.height; (0..height).flat_map(move |y| { (0..width).filter_map(move |x| { let (byte_index, bit_index) = self.pixel_to_bit_index(x, y); let bit = ((self.data[byte_index] >> bit_index) & 1) != 0; if bit { Some(Point::new(x as i32, y as i32)) } else { None } }) }) } /// Fill a rectangular region with a color pub fn fill_rect(&mut self, rect: Rectangle, color: BinaryColor) { let start_x = rect.top_left.x.max(0) as usize; let start_y = rect.top_left.y.max(0) as usize; let end_x = ((rect.top_left.x + rect.size.width as i32).min(self.width as i32)) as usize; let end_y = ((rect.top_left.y + rect.size.height as i32).min(self.height as i32)) as usize; let raw: RawU1 = color.into(); let bit_value = raw.into_inner(); for y in start_y..end_y { for x in start_x..end_x { let pixel_index = y * self.width + x; let byte_index = pixel_index / 8; let bit_index = 7 - (pixel_index % 8); if bit_value != 0 { self.data[byte_index] |= 1 << bit_index; } else { self.data[byte_index] &= !(1 << bit_index); } } } } } impl DrawTarget for VecFramebuffer<BinaryColor> { type Color = BinaryColor; type Error = Infallible; fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error> where I: IntoIterator<Item = Pixel<Self::Color>>, { for Pixel(point, color) in pixels { self.set_pixel(point, color); } Ok(()) } fn fill_solid(&mut self, area: &Rectangle, color: Self::Color) -> Result<(), Self::Error> { self.fill_rect(*area, color); Ok(()) } fn clear(&mut self, color: Self::Color) -> Result<(), Self::Error> { <VecFramebuffer<BinaryColor>>::clear(self, color); Ok(()) } } use embedded_graphics::{ image::{ImageDrawable, ImageRaw}, Drawable, }; // Implement ImageDrawable for VecFramebuffer impl<C> ImageDrawable for VecFramebuffer<C> where C: PixelColor + From<<C as PixelColor>::Raw>, for<'a> ImageRaw<'a, C, LittleEndian>: ImageDrawable<Color = C>, { type Color = C; fn draw<D>(&self, target: &mut D) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { // Create an ImageRaw from our data and draw it let raw_image = ImageRaw::<C, LittleEndian>::new(&self.data, self.width as u32); embedded_graphics::image::Image::new(&raw_image, Point::zero()).draw(target) } fn draw_sub_image<D>( &self, target: &mut D, area: &embedded_graphics::primitives::Rectangle, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { // For sub-image drawing, we can use the same approach // The area parameter would allow us to draw only a portion if needed let raw_image = ImageRaw::<C, LittleEndian>::new(&self.data, self.width as u32); embedded_graphics::image::Image::new(&raw_image, area.top_left).draw(target) } } // Performance notes: // 1. The clear() method is optimized for Gray8 and BinaryColor using fill() // 2. Batch pixel setting could use SIMD instructions where available // 3. Consider alignment for better cache performance // 4. The bit manipulation for sub-byte pixels could potentially be optimized with lookup tables // 5. Consider unsafe variants for hot paths where bounds checking is redundant // 6. The fill_rect could be optimized to copy bytes directly for aligned regions // 7. For 16/24/32-bit pixels, we could use slice::copy_from_slice for bulk operations
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/screen_test.rs
frostsnap_widgets/src/screen_test.rs
use crate::{ palette::PALETTE, DefaultTextStyle, DynWidget, HoldToConfirm, Instant, SuperDrawTarget, Text, Widget, FONT_MED, HOLD_TO_CONFIRM_TIME_SHORT_MS, }; use alloc::{format, vec::Vec}; use embedded_graphics::{ mono_font::{iso_8859_1::FONT_10X20, MonoTextStyle}, pixelcolor::Rgb565, prelude::*, primitives::{PrimitiveStyleBuilder, Rectangle}, text::{Baseline, Text as EgText}, }; const ACTION_LIFT_UP: u8 = 1; // Target cells with colors for each corner const TARGET_CELLS: [(i32, i32, Rgb565); 4] = [ (0, 0, Rgb565::RED), // Top left (5, 0, Rgb565::GREEN), // Top right (0, 6, Rgb565::YELLOW), // Bottom left (5, 6, Rgb565::BLUE), // Bottom right ]; /// Current phase of the screen test enum Phase { Testing { failures: i32, active: [bool; 4], prev_action: Option<u8>, needs_redraw: bool, touch_points: Vec<Point>, // Store all touch points to draw red dots }, Menu { failures: i32, hold_to_confirm: HoldToConfirm<Text>, start_again_rect: Rectangle, prev_action: Option<u8>, needs_redraw: bool, }, } pub struct ScreenTest { phase: Phase, grid_spacing: i32, screen_width: i32, screen_height: i32, max_size: Size, } impl Default for ScreenTest { fn default() -> Self { Self::new() } } impl ScreenTest { pub fn new() -> Self { Self { phase: Phase::Testing { failures: 0, active: [true; 4], prev_action: None, needs_redraw: true, touch_points: Vec::new(), }, grid_spacing: 40, screen_width: 240, screen_height: 280, max_size: Size::zero(), } } fn target_rect(cell: (i32, i32), grid_spacing: i32) -> Rectangle { let (cell_x, cell_y) = cell; Rectangle::new( Point::new(cell_x * grid_spacing + 1, cell_y * grid_spacing + 1), Size::new((grid_spacing - 2) as u32, (grid_spacing - 2) as u32), ) } fn draw_failures<D>(target: &mut D, failures: i32, screen_width: i32) -> Result<(), D::Error> where D: DrawTarget<Color = Rgb565>, { let text = format!("Failures: {failures}"); let text_width = 10 * text.len() as i32; let text_height = 20; let text_x = (screen_width - text_width) / 2; let text_y = 2; // Draw white background Rectangle::new( Point::new(text_x, text_y), Size::new(text_width as u32, text_height as u32), ) .into_styled( PrimitiveStyleBuilder::new() .fill_color(Rgb565::WHITE) .build(), ) .draw(target)?; // Draw red text EgText::with_baseline( &text, Point::new(text_x, text_y), MonoTextStyle::new(&FONT_10X20, Rgb565::RED), Baseline::Top, ) .draw(target)?; Ok(()) } fn draw_testing<D>( target: &mut D, failures: i32, active: &[bool; 4], grid_spacing: i32, screen_width: i32, screen_height: i32, touch_points: &[Point], ) -> Result<(), D::Error> where D: DrawTarget<Color = Rgb565>, { // Clear screen target.clear(Rgb565::BLACK)?; // Draw grid lines let grid_line_style = PrimitiveStyleBuilder::new() .fill_color(Rgb565::WHITE) .build(); for x in (0..screen_width).step_by(grid_spacing as usize) { Rectangle::new(Point::new(x, 0), Size::new(1, screen_height as u32)) .into_styled(grid_line_style) .draw(target)?; } for y in (0..screen_height).step_by(grid_spacing as usize) { Rectangle::new(Point::new(0, y), Size::new(screen_width as u32, 1)) .into_styled(grid_line_style) .draw(target)?; } // Draw active target squares for (i, &(cell_x, cell_y, color)) in TARGET_CELLS.iter().enumerate() { if active[i] { Self::target_rect((cell_x, cell_y), grid_spacing) .into_styled(PrimitiveStyleBuilder::new().fill_color(color).build()) .draw(target)?; } } // Draw failures counter Self::draw_failures(target, failures, screen_width)?; // Draw red dots at touch points for &touch_point in touch_points { Rectangle::new(touch_point, Size::new(2, 2)) .into_styled(PrimitiveStyleBuilder::new().fill_color(Rgb565::RED).build()) .draw(target)?; } Ok(()) } pub fn is_completed(&self) -> bool { matches!(&self.phase, Phase::Menu { hold_to_confirm, .. } if hold_to_confirm.is_completed()) } pub fn get_failures(&self) -> i32 { match &self.phase { Phase::Testing { failures, .. } | Phase::Menu { failures, .. } => *failures, } } } impl DynWidget for ScreenTest { fn set_constraints(&mut self, max_size: Size) { self.max_size = max_size; } fn sizing(&self) -> crate::Sizing { self.max_size.into() } fn handle_touch( &mut self, point: Point, current_time: Instant, is_release: bool, ) -> Option<crate::KeyTouch> { let action = if is_release { ACTION_LIFT_UP } else { 0 }; let grid_spacing = self.grid_spacing; let screen_width = self.screen_width; let screen_height = self.screen_height; match &mut self.phase { Phase::Testing { failures, active, prev_action, needs_redraw, touch_points, } => { if action == ACTION_LIFT_UP && *prev_action == Some(ACTION_LIFT_UP) { return None; } *prev_action = Some(action); if action != ACTION_LIFT_UP { return None; } touch_points.push(point); let mut hit_target = false; for (i, &(cell_x, cell_y, _)) in TARGET_CELLS.iter().enumerate() { if active[i] && Self::target_rect((cell_x, cell_y), grid_spacing).contains(point) { active[i] = false; hit_target = true; break; } } if !hit_target { *failures += 1; } *needs_redraw = true; // Check if all targets are cleared if active.iter().all(|&a| !a) { // Transition to menu phase let final_failures = *failures; let test_complete_text = format!("Test Complete\n\nFailures: {final_failures}"); let text_widget = Text::new( test_complete_text, DefaultTextStyle::new(FONT_MED, PALETTE.on_background), ) .with_alignment(embedded_graphics::text::Alignment::Center); let mut hold_to_confirm = HoldToConfirm::new(HOLD_TO_CONFIRM_TIME_SHORT_MS, text_widget); // Set constraints for the hold_to_confirm widget (below start again button) let button_y = 20; let button_height = 60; let button_spacing = 10; let widget_y = button_y + button_height + button_spacing; let widget_height = screen_height - widget_y; hold_to_confirm .set_constraints(Size::new(screen_width as u32, widget_height as u32)); let button_width = (screen_width * 80) / 100; let button_x = (screen_width - button_width) / 2; let start_again_rect = Rectangle::new( Point::new(button_x, button_y), Size::new(button_width as u32, button_height as u32), ); self.phase = Phase::Menu { failures: final_failures, hold_to_confirm, start_again_rect, prev_action: None, needs_redraw: true, }; } None } Phase::Menu { hold_to_confirm, start_again_rect, prev_action, .. } => { if action == ACTION_LIFT_UP && *prev_action == Some(ACTION_LIFT_UP) { return None; } *prev_action = Some(action); if is_release && start_again_rect.contains(point) { // Set prev_action to prevent touch from being processed again self.phase = Phase::Testing { failures: 0, active: [true; 4], prev_action: Some(ACTION_LIFT_UP), needs_redraw: true, touch_points: Vec::new(), }; return None; } // Pass touch to HoldToConfirm widget (translate coordinates) let button_y = 20; let button_height = 60; let button_spacing = 10; let widget_y = button_y + button_height + button_spacing; if point.y >= widget_y { let widget_point = Point::new(point.x, point.y - widget_y); hold_to_confirm.handle_touch(widget_point, current_time, is_release); } None } } } fn force_full_redraw(&mut self) { if let Phase::Menu { hold_to_confirm, .. } = &mut self.phase { hold_to_confirm.force_full_redraw(); } } } impl Widget for ScreenTest { type Color = Rgb565; fn draw<D>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, current_time: Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { match &mut self.phase { Phase::Testing { failures, active, needs_redraw, touch_points, .. } => { if *needs_redraw { Self::draw_testing( target, *failures, active, self.grid_spacing, self.screen_width, self.screen_height, touch_points, )?; *needs_redraw = false; } } Phase::Menu { hold_to_confirm, start_again_rect, needs_redraw, .. } => { if *needs_redraw { target.clear(Rgb565::BLACK)?; start_again_rect .into_styled( PrimitiveStyleBuilder::new() .fill_color(Rgb565::WHITE) .build(), ) .draw(target)?; let button_text_style = MonoTextStyle::new(&FONT_10X20, Rgb565::BLACK); let start_text = "Start Again"; let button_width = (self.screen_width * 80) / 100; let button_x = (self.screen_width - button_width) / 2; let button_y = 20; let button_height = 60; let text_height = 20; let start_text_width = 10 * start_text.len() as i32; let start_text_x = button_x + (button_width - start_text_width) / 2; let start_text_y = button_y + (button_height - text_height) / 2; EgText::with_baseline( start_text, Point::new(start_text_x, start_text_y), button_text_style, Baseline::Top, ) .draw(target)?; *needs_redraw = false; } // Always draw HoldToConfirm widget (it has animations) let button_y = 20; let button_height = 60; let button_spacing = 10; let widget_y = button_y + button_height + button_spacing; hold_to_confirm.draw( &mut target.clone().translate(Point::new(0, widget_y)), current_time, )?; } } Ok(()) } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/lib.rs
frostsnap_widgets/src/lib.rs
#![no_std] #![allow(clippy::type_complexity)] #[cfg(feature = "std")] #[macro_use] extern crate std; #[macro_use] pub extern crate alloc; use embedded_graphics::prelude::*; pub mod compressed_point; pub mod palette; pub mod pixel_recorder; // Widget modules pub mod address_display; pub mod animation_speed; pub mod backup; pub mod bitmap; pub mod checkmark; pub mod cursor; pub mod debug; pub mod fader; pub mod hold_to_confirm; pub mod hold_to_confirm_border; pub mod icons; pub mod image; pub mod key_touch; pub mod one_time_clear_hack; pub mod rat; // pub mod page_by_page; // pub mod page_demo; pub mod page_slider; pub mod progress; pub mod progress_bars; pub mod widget_list; // pub mod buffered; pub mod any_of; pub mod bitcoin_amount_display; pub mod bobbing_carat; pub mod circle_button; pub mod demo_widget; pub mod device_name; pub mod fade_switcher; pub mod firmware_upgrade; pub mod fps; pub mod gray4_style; pub mod keygen_check; pub mod layout; pub mod p2tr_address_display; pub mod prelude; pub mod screen_test; pub mod scroll_bar; pub mod share_index; pub mod sign_message; pub mod sign_prompt; pub mod slide_in_transition; pub mod standby; pub mod string_ext; mod super_draw_target; pub mod swipe_up_chevron; pub mod switcher; pub mod text; pub mod touch_listener; pub mod translate; pub mod vec_framebuffer; pub mod widget_color; // Re-export key types pub use key_touch::{Key, KeyTouch}; // pub use page_by_page::PageByPage; // pub use page_demo::PageDemo; pub use page_slider::PageSlider; pub use share_index::ShareIndexWidget; pub use sign_message::SignMessageConfirm; pub use sign_prompt::SignTxPrompt; pub use super_draw_target::SuperDrawTarget; pub use widget_color::{ColorInterpolate, WidgetColor}; pub use widget_list::*; // Re-export tinybmp for use in demos and public API pub use tinybmp; // Re-export all widget items pub use address_display::{AddressDisplay, AddressWithPath}; pub use backup::*; pub use checkmark::*; pub use cursor::*; pub use fader::*; pub use hold_to_confirm::HoldToConfirm; pub use hold_to_confirm_border::HoldToConfirmBorder; pub use image::{GrayToAlpha, Image}; pub use layout::{ Align, Alignment, Center, Column, Container, CrossAxisAlignment, MainAxisAlignment, MainAxisSize, Padding, Row, SizedBox, Stack, }; pub use one_time_clear_hack::OneTimeClearHack; pub use rat::{Frac, Rat}; // pub use hold_to_confirm_button::*; pub use bobbing_carat::BobbingCarat; pub use circle_button::*; pub use device_name::*; pub use fade_switcher::FadeSwitcher; pub use firmware_upgrade::{FirmwareUpgradeConfirm, FirmwareUpgradeProgress}; pub use fps::Fps; pub use icons::IconWidget; pub use keygen_check::*; pub use progress::{ProgressBar, ProgressIndicator}; pub use progress_bars::*; pub use screen_test::ScreenTest; pub use scroll_bar::*; pub use slide_in_transition::*; pub use standby::*; pub use swipe_up_chevron::*; pub use switcher::Switcher; pub use text::*; pub use touch_listener::TouchListener; pub use translate::*; // Font re-exports use frostsnap_fonts::{ Gray4Font, NOTO_SANS_17_REGULAR, NOTO_SANS_18_MEDIUM, NOTO_SANS_24_BOLD, NOTO_SANS_MONO_28_BOLD, }; use gray4_style::Gray4TextStyle; pub const FONT_HUGE_MONO: &Gray4Font = &NOTO_SANS_MONO_28_BOLD; pub const FONT_LARGE: &Gray4Font = &NOTO_SANS_24_BOLD; pub const FONT_MED: &Gray4Font = &NOTO_SANS_18_MEDIUM; pub const FONT_SMALL: &Gray4Font = &NOTO_SANS_17_REGULAR; // Type alias for default text styling pub type DefaultTextStyle = Gray4TextStyle; // U8g2 fonts for keyboards (monochrome framebuffers) use u8g2_fonts::U8g2TextStyle; pub const HOLD_TO_CONFIRM_TIME_SHORT_MS: u32 = 1000; pub const HOLD_TO_CONFIRM_TIME_MS: u32 = 2000; pub const HOLD_TO_CONFIRM_TIME_LONG_MS: u32 = 6000; /// Sizing information for a widget #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct Sizing { pub width: u32, pub height: u32, /// The actual area within the sized area where this widget will draw. /// If None, assumes the widget may draw to the entire sized area. /// Widgets like Column, Row, and Padding should set this to the actual area /// they give their children to draw in. pub dirty_rect: Option<embedded_graphics::primitives::Rectangle>, } impl From<Size> for Sizing { fn from(size: Size) -> Self { Sizing { width: size.width, height: size.height, dirty_rect: None, } } } impl Sizing { /// Returns the dirty rectangle, or constructs one from width/height if not set pub fn dirty_rect(&self) -> embedded_graphics::primitives::Rectangle { self.dirty_rect.unwrap_or_else(|| { embedded_graphics::primitives::Rectangle::new( embedded_graphics::prelude::Point::zero(), Size::new(self.width, self.height), ) }) } } impl From<Sizing> for Size { fn from(sizing: Sizing) -> Self { Size::new(sizing.width, sizing.height) } } /// A trait for widgets that can be used as trait objects /// This contains all the non-generic methods from Widget pub trait DynWidget { /// Set maximum available size for this widget. Parent calls this before asking for size. /// This must be called before sizing(). fn set_constraints(&mut self, max_size: Size); /// Get sizing information for this widget given its constraints. /// Must be called after set_constraints. fn sizing(&self) -> Sizing; /// Handle touch events. Returns true if the touch was handled. fn handle_touch( &mut self, _point: Point, _current_time: crate::Instant, _lift_up: bool, ) -> Option<KeyTouch> { None } /// Handle vertical drag events. Returns true if the drag was handled. fn handle_vertical_drag(&mut self, _prev_y: Option<u32>, _new_y: u32, _is_release: bool) {} /// Force a full redraw of the widget /// This is typically used when the widget needs to be redrawn completely, /// such as when fading or other visual effects require a complete refresh fn force_full_redraw(&mut self) { // Default implementation does nothing // Widgets that need this functionality should override } } /// A trait that combines DynWidget with Any for downcasting pub trait AnyDynWidget: core::any::Any + DynWidget {} /// Blanket implementation for any type that implements both Any and DynWidget impl<T: core::any::Any + DynWidget> AnyDynWidget for T {} /// A trait for drawable widgets that can handle user interactions pub trait Widget: DynWidget { /// The color type this widget natively draws in type Color: WidgetColor; /// Draw the widget to the target fn draw<D>( &mut self, target: &mut super_draw_target::SuperDrawTarget<D, Self::Color>, current_time: crate::Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>; } // Implement Widget for () to allow empty containers impl Widget for () { type Color = embedded_graphics::pixelcolor::Rgb565; fn draw<D>( &mut self, _target: &mut super_draw_target::SuperDrawTarget<D, Self::Color>, _current_time: crate::Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { // Empty widget draws nothing Ok(()) } } // Implement Widget for Box<T> where T: Widget impl<T: Widget + ?Sized> Widget for alloc::boxed::Box<T> { type Color = T::Color; fn draw<D>( &mut self, target: &mut super_draw_target::SuperDrawTarget<D, Self::Color>, current_time: crate::Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { (**self).draw(target, current_time) } } // Implement DynWidget for Box<T> where T: DynWidget impl<T: DynWidget + ?Sized> DynWidget for alloc::boxed::Box<T> { fn set_constraints(&mut self, max_size: Size) { (**self).set_constraints(max_size) } fn sizing(&self) -> Sizing { (**self).sizing() } fn handle_touch( &mut self, point: Point, current_time: crate::Instant, is_release: bool, ) -> Option<KeyTouch> { (**self).handle_touch(point, current_time, is_release) } fn handle_vertical_drag(&mut self, prev_y: Option<u32>, new_y: u32, is_release: bool) { (**self).handle_vertical_drag(prev_y, new_y, is_release) } fn force_full_redraw(&mut self) { (**self).force_full_redraw() } } // Implement DynWidget for Option<T> where T: DynWidget impl<T: DynWidget> DynWidget for Option<T> { fn set_constraints(&mut self, max_size: Size) { if let Some(widget) = self { widget.set_constraints(max_size) } } fn sizing(&self) -> Sizing { if let Some(widget) = self { widget.sizing() } else { Size::new(0, 0).into() } } fn handle_touch( &mut self, point: Point, current_time: crate::Instant, is_release: bool, ) -> Option<KeyTouch> { if let Some(widget) = self { widget.handle_touch(point, current_time, is_release) } else { None } } fn handle_vertical_drag(&mut self, prev_y: Option<u32>, new_y: u32, is_release: bool) { if let Some(widget) = self { widget.handle_vertical_drag(prev_y, new_y, is_release) } } fn force_full_redraw(&mut self) { if let Some(widget) = self { widget.force_full_redraw() } } } // Implement Widget for Option<W> where W: Widget impl<W: Widget> Widget for Option<W> { type Color = W::Color; fn draw<D>( &mut self, target: &mut super_draw_target::SuperDrawTarget<D, Self::Color>, current_time: Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { if let Some(widget) = self { widget.draw(target, current_time) } else { Ok(()) } } } /// Milliseconds since device start #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct Instant(u64); impl Instant { /// Create from milliseconds pub fn from_millis(millis: u64) -> Self { Self(millis) } /// Get milliseconds value pub fn as_millis(&self) -> u64 { self.0 } /// Calculate duration since an earlier instant /// Returns None if earlier is later than self pub fn duration_since(&self, earlier: Instant) -> Option<u64> { self.0.checked_sub(earlier.0) } /// Calculate duration since an earlier instant, saturating at 0 pub fn saturating_duration_since(&self, earlier: Instant) -> u64 { self.0.saturating_sub(earlier.0) } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/address_display.rs
frostsnap_widgets/src/address_display.rs
use crate::{ any_of::AnyOf, layout::Column, p2tr_address_display::P2trAddressDisplay, palette::PALETTE, text::Text, DefaultTextStyle, MainAxisAlignment, FONT_HUGE_MONO, FONT_LARGE, }; use alloc::{ boxed::Box, string::{String, ToString}, }; use embedded_graphics::text::Alignment; use frostsnap_fonts::Gray4Font; use frostsnap_macros::Widget; // Font for displaying addresses - uses monospace for better readability const ADDRESS_FONT: &Gray4Font = FONT_HUGE_MONO; /// A widget that displays only a Bitcoin address (without derivation path) #[derive(Widget)] pub struct AddressDisplay { #[widget_delegate] container: Box<AnyOf<(P2trAddressDisplay, Text)>>, } impl AddressDisplay { pub fn new(address: bitcoin::Address) -> Self { use bitcoin::AddressType; let address_str = address.to_string(); // Check if this is a taproot address using the proper method if address.address_type() == Some(AddressType::P2tr) { // Use P2trAddressDisplay for taproot addresses let container = Box::new(AnyOf::new(P2trAddressDisplay::new(&address_str))); Self { container } } else { // For non-taproot addresses, format with spaces every 4 characters let mut formatted = String::new(); let mut space_count = 0; // Add spaces every 4 characters, replacing the third space with a newline for (i, ch) in address_str.chars().enumerate() { if i > 0 && i % 4 == 0 { space_count += 1; // Every third space becomes a newline if space_count % 3 == 0 { formatted.push('\n'); } else { formatted.push(' '); } } formatted.push(ch); } // Create the address text let address_text = Text::new( formatted, DefaultTextStyle::new(ADDRESS_FONT, PALETTE.on_background), ) .with_alignment(Alignment::Center); let container = Box::new(AnyOf::new(address_text)); Self { container } } } pub fn set_rand_highlight(&mut self, rand_highlight: u32) { // Try to downcast to P2trAddressDisplay and apply highlighting if let Some(p2tr_display) = self.container.downcast_mut::<P2trAddressDisplay>() { p2tr_display.set_rand_highlight(rand_highlight); } } } /// A widget that displays a Bitcoin address with its index #[derive(Widget)] pub struct AddressWithPath { #[widget_delegate] container: Column<(Text, AddressDisplay)>, } impl AddressWithPath { pub fn new(address: bitcoin::Address, address_index: u32) -> Self { let address_display = AddressDisplay::new(address); // Create the address index text (e.g., "Address #5") let index_text = Text::new( alloc::format!("Address #{}", address_index), DefaultTextStyle::new(FONT_LARGE, PALETTE.text_secondary), ) .with_alignment(Alignment::Center); // Create a column to stack them vertically (index above address) let container = Column::builder() .push(index_text) .gap(8) .push(address_display) .with_main_axis_alignment(MainAxisAlignment::SpaceEvenly); Self { container } } pub fn set_rand_highlight(&mut self, rand_highlight: u32) { // Apply highlighting to the address display self.container.children.1.set_rand_highlight(rand_highlight); } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/rat.rs
frostsnap_widgets/src/rat.rs
use core::fmt; use core::ops::{Add, Div, Mul, Sub}; /// The base denominator for rational number representation const DENOMINATOR: u32 = 10_000; /// A rational number represented as (numerator * DENOMINATOR) / denominator #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct Rat(pub(crate) u32); impl Rat { pub const fn from_int(int: u32) -> Self { Self(int * DENOMINATOR) } /// Create from a numerator and denominator pub const fn from_ratio(numerator: u32, denominator: u32) -> Self { if denominator == 0 { // everything over 0 should be large! return Self(u32::MAX); } let value = ((numerator as u64 * DENOMINATOR as u64) / denominator as u64) as u32; Self(value) } /// Minimum value (0) pub const ZERO: Self = Self(0); pub const MIN: Self = Self::ZERO; /// Value representing 1.0 pub const ONE: Self = Self(DENOMINATOR); /// Maximum value pub const MAX: Self = Self(u32::MAX); /// Round to the nearest whole number pub fn round(&self) -> u32 { let whole = self.0 / DENOMINATOR; let frac = self.0 % DENOMINATOR; if frac >= DENOMINATOR / 2 { whole + 1 } else { whole } } /// Round down to the nearest whole number (floor) pub fn floor(&self) -> u32 { self.0 / DENOMINATOR } /// Round up to the nearest whole number (ceil) pub fn ceil(&self) -> u32 { let whole = self.0 / DENOMINATOR; let frac = self.0 % DENOMINATOR; if frac > 0 { whole + 1 } else { whole } } } impl Mul<u32> for Rat { type Output = Rat; fn mul(self, rhs: u32) -> Self::Output { Rat(self.0 * rhs) } } impl Mul<Rat> for u32 { type Output = Rat; fn mul(self, rhs: Rat) -> Self::Output { Rat(self * rhs.0) } } impl Mul<i32> for Rat { type Output = i32; fn mul(self, rhs: i32) -> Self::Output { ((rhs as i64 * self.0 as i64) / DENOMINATOR as i64) as i32 } } impl Mul<Rat> for i32 { type Output = i32; fn mul(self, rhs: Rat) -> Self::Output { ((self as i64 * rhs.0 as i64) / DENOMINATOR as i64) as i32 } } impl Mul<Rat> for Rat { type Output = Rat; fn mul(self, rhs: Rat) -> Self::Output { let value = ((self.0 as u64 * rhs.0 as u64) / DENOMINATOR as u64) as u32; Rat(value) } } impl Div<u32> for Rat { type Output = u32; fn div(self, rhs: u32) -> Self::Output { self.0 / rhs } } impl Default for Rat { fn default() -> Self { Self::ZERO } } impl Add for Rat { type Output = Self; fn add(self, rhs: Self) -> Self::Output { Self(self.0.saturating_add(rhs.0)) } } impl Sub for Rat { type Output = Self; fn sub(self, rhs: Self) -> Self::Output { Self(self.0.saturating_sub(rhs.0)) } } impl Sub<u32> for Rat { type Output = Rat; fn sub(self, rhs: u32) -> Self::Output { self - Rat::from_int(rhs) } } impl Sub<Rat> for u32 { type Output = Rat; fn sub(self, rhs: Rat) -> Self::Output { Rat::from_int(self) - rhs } } impl Mul<embedded_graphics::geometry::Point> for Rat { type Output = embedded_graphics::geometry::Point; fn mul(self, rhs: embedded_graphics::geometry::Point) -> Self::Output { embedded_graphics::geometry::Point::new(self * rhs.x, self * rhs.y) } } impl Mul<Rat> for embedded_graphics::geometry::Point { type Output = embedded_graphics::geometry::Point; fn mul(self, rhs: Rat) -> Self::Output { rhs * self } } impl fmt::Debug for Rat { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}/{}", self.0, DENOMINATOR) } } impl fmt::Display for Rat { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let whole = self.0 / DENOMINATOR; let frac = self.0 % DENOMINATOR; if frac == 0 { write!(f, "{}", whole) } else { // Format with up to 4 decimal places, trimming trailing zeros let frac_str = format!("{:04}", frac); let trimmed = frac_str.trim_end_matches('0'); if trimmed.is_empty() { write!(f, "{}", whole) } else { write!(f, "{}.{}", whole, trimmed) } } } } /// A fraction between 0 and 1, automatically clamped #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct Frac(Rat); impl Frac { /// Create a new Frac from a Rat, clamping to [0, 1] pub fn new(rat: Rat) -> Self { Self(rat.min(Rat::ONE)) } /// Create from a numerator and denominator, clamping to [0, 1] pub fn from_ratio(numerator: u32, denominator: u32) -> Self { let rat = Rat::from_ratio(numerator, denominator); Self::new(rat) } /// Get the inner Rat value pub fn as_rat(&self) -> Rat { self.0 } /// Zero fraction pub const ZERO: Self = Self(Rat::ZERO); pub const MIN: Self = Self::ZERO; /// One fraction pub const ONE: Self = Self(Rat::ONE); pub const MAX: Self = Self::ONE; } impl Mul<u32> for Frac { type Output = Rat; fn mul(self, rhs: u32) -> Self::Output { Rat(self.0 .0 * rhs) } } impl Mul<Frac> for u32 { type Output = Rat; fn mul(self, rhs: Frac) -> Self::Output { Rat(self * rhs.0 .0) } } impl Mul<Frac> for Frac { type Output = Frac; fn mul(self, rhs: Frac) -> Self::Output { // When multiplying two Fracs (both ≤ 1), result is guaranteed to be in [0,1] // We can directly use Rat * Rat which handles the fixed-point arithmetic Frac(self.0 * rhs.0) } } impl Mul<embedded_graphics::geometry::Point> for Frac { type Output = embedded_graphics::geometry::Point; fn mul(self, rhs: embedded_graphics::geometry::Point) -> Self::Output { self.0 * rhs } } impl Mul<Frac> for embedded_graphics::geometry::Point { type Output = embedded_graphics::geometry::Point; fn mul(self, rhs: Frac) -> Self::Output { self * rhs.0 } } impl Add for Frac { type Output = Self; fn add(self, rhs: Self) -> Self::Output { // Add the underlying Rat values and clamp to 1 Self::new(self.0 + rhs.0) } } impl Sub for Frac { type Output = Self; fn sub(self, rhs: Self) -> Self::Output { // Subtract and clamp at 0 (since Rat uses saturating_sub) Self(self.0 - rhs.0) } } impl fmt::Debug for Frac { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Frac({:?})", self.0) } } impl fmt::Display for Frac { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // Delegate to Rat's Display implementation fmt::Display::fmt(&self.0, f) } } /// The base denominator for FatRat rational number representation (1 trillion) const FAT_DENOMINATOR: u64 = 1_000_000_000_000; /// A rational number with higher precision, represented as (numerator * FAT_DENOMINATOR) / denominator /// Uses u64 for larger range than Rat #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct FatRat(pub(crate) u64); impl FatRat { pub const fn from_int(int: u64) -> Self { Self(int * FAT_DENOMINATOR) } /// Create from a numerator and denominator pub const fn from_ratio(numerator: u64, denominator: u64) -> Self { if denominator == 0 { // everything over 0 should be large! return Self(u64::MAX); } // Use u128 to avoid overflow let value = ((numerator as u128 * FAT_DENOMINATOR as u128) / denominator as u128) as u64; Self(value) } /// Minimum value (0) pub const ZERO: Self = Self(0); pub const MIN: Self = Self::ZERO; /// Value representing 1.0 pub const ONE: Self = Self(FAT_DENOMINATOR); /// Maximum value pub const MAX: Self = Self(u64::MAX); /// Round to the nearest whole number pub fn round(&self) -> u64 { let whole = self.0 / FAT_DENOMINATOR; let frac = self.0 % FAT_DENOMINATOR; if frac >= FAT_DENOMINATOR / 2 { whole + 1 } else { whole } } /// Round down to the nearest whole number (floor) pub fn floor(&self) -> u64 { self.0 / FAT_DENOMINATOR } /// Round up to the nearest whole number (ceil) pub fn ceil(&self) -> u64 { let whole = self.0 / FAT_DENOMINATOR; let frac = self.0 % FAT_DENOMINATOR; if frac > 0 { whole + 1 } else { whole } } /// Get the whole part (same as floor) pub const fn whole_part(&self) -> u64 { self.0 / FAT_DENOMINATOR } /// Get the fractional part (internal use) const fn fractional_part(&self) -> u64 { self.0 % FAT_DENOMINATOR } /// Returns an iterator over all decimal digits after the decimal point (up to 12 digits) pub fn decimal_digits(self) -> impl Iterator<Item = u8> { let mut remaining = self.fractional_part(); // Start with 10^11 to get first decimal digit let mut window = 10_u64.pow(11); core::iter::from_fn(move || { if window == 0 { return None; } let digit = (remaining / window) as u8; remaining -= digit as u64 * window; window /= 10; Some(digit) }) } /// Format as a decimal string with up to 12 decimal places /// Returns a tuple of (whole_part, decimal_part) as strings pub fn format_parts( &self, decimal_places: usize, ) -> (alloc::string::String, alloc::string::String) { assert!( decimal_places <= 12, "Cannot have more than 12 decimal places" ); let whole = self.whole_part(); let frac = self.fractional_part(); // Scale down the fractional part if we want fewer decimal places let divisor = 10_u64.pow((12 - decimal_places) as u32); let scaled_frac = frac / divisor; // Format fractional part with leading zeros let decimal = alloc::format!("{:0width$}", scaled_frac, width = decimal_places); (alloc::format!("{}", whole), decimal) } /// Format as "X.YYYYYY" string with specified decimal places pub fn format_decimal(&self, decimal_places: usize) -> alloc::string::String { let (whole, decimal) = self.format_parts(decimal_places); if decimal.is_empty() { whole } else { alloc::format!("{}.{}", whole, decimal) } } } impl Mul<u64> for FatRat { type Output = FatRat; fn mul(self, rhs: u64) -> Self::Output { FatRat(self.0.saturating_mul(rhs)) } } impl Mul<FatRat> for u64 { type Output = FatRat; fn mul(self, rhs: FatRat) -> Self::Output { FatRat(self.saturating_mul(rhs.0)) } } impl Mul<i64> for FatRat { type Output = i64; fn mul(self, rhs: i64) -> Self::Output { ((rhs as i128 * self.0 as i128) / FAT_DENOMINATOR as i128) as i64 } } impl Mul<FatRat> for i64 { type Output = i64; fn mul(self, rhs: FatRat) -> Self::Output { ((self as i128 * rhs.0 as i128) / FAT_DENOMINATOR as i128) as i64 } } impl Mul<FatRat> for FatRat { type Output = FatRat; fn mul(self, rhs: FatRat) -> Self::Output { let value = ((self.0 as u128 * rhs.0 as u128) / FAT_DENOMINATOR as u128) as u64; FatRat(value) } } impl Div<u64> for FatRat { type Output = FatRat; fn div(self, rhs: u64) -> Self::Output { if rhs == 0 { FatRat(u64::MAX) } else { FatRat(self.0 / rhs) } } } impl Div<FatRat> for FatRat { type Output = FatRat; fn div(self, rhs: FatRat) -> Self::Output { if rhs.0 == 0 { FatRat(u64::MAX) } else { let value = ((self.0 as u128 * FAT_DENOMINATOR as u128) / rhs.0 as u128) as u64; FatRat(value) } } } impl Add<FatRat> for FatRat { type Output = FatRat; fn add(self, rhs: FatRat) -> Self::Output { FatRat(self.0.saturating_add(rhs.0)) } } impl Sub<FatRat> for FatRat { type Output = FatRat; fn sub(self, rhs: FatRat) -> Self::Output { FatRat(self.0.saturating_sub(rhs.0)) } } impl fmt::Debug for FatRat { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "FatRat({}/{})", self.0, FAT_DENOMINATOR) } } impl fmt::Display for FatRat { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let whole = self.0 / FAT_DENOMINATOR; let frac = self.0 % FAT_DENOMINATOR; if frac == 0 { write!(f, "{}", whole) } else { // Show up to 6 decimal places by default let divisor = 10_u64.pow(6); let scaled_frac = frac / divisor; write!(f, "{}.{:06}", whole, scaled_frac) } } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/palette.rs
frostsnap_widgets/src/palette.rs
use embedded_graphics::pixelcolor::Rgb565; pub struct MaterialDarkPalette565 { pub primary: Rgb565, pub on_primary: Rgb565, pub primary_container: Rgb565, pub on_primary_container: Rgb565, pub secondary: Rgb565, pub on_secondary: Rgb565, pub secondary_container: Rgb565, pub on_secondary_container: Rgb565, pub tertiary: Rgb565, pub on_tertiary: Rgb565, pub tertiary_container: Rgb565, pub on_tertiary_container: Rgb565, pub background: Rgb565, pub on_background: Rgb565, pub surface: Rgb565, pub on_surface: Rgb565, pub surface_variant: Rgb565, pub on_surface_variant: Rgb565, pub outline: Rgb565, pub error: Rgb565, pub on_error: Rgb565, pub confirm_progress: Rgb565, pub logo: Rgb565, /// Secondary text color - darker gray for labels and supporting text /// Following Material Design ~60% opacity guideline (medium emphasis) pub text_secondary: Rgb565, /// Disabled text color - very dark gray for de-emphasized content /// Following Material Design ~38% opacity guideline (disabled state) pub text_disabled: Rgb565, /// Warning color - yellow/amber for warning states pub warning: Rgb565, } pub const PALETTE: MaterialDarkPalette565 = MaterialDarkPalette565 { primary: Rgb565::new(2, 37, 22), on_primary: Rgb565::new(31, 63, 31), primary_container: Rgb565::new(1, 26, 16), on_primary_container: Rgb565::new(28, 60, 28), secondary: Rgb565::new(22, 43, 29), on_secondary: Rgb565::new(4, 3, 14), secondary_container: Rgb565::new(6, 8, 15), on_secondary_container: Rgb565::new(27, 54, 29), tertiary: Rgb565::new(21, 58, 25), on_tertiary: Rgb565::new(1, 23, 6), tertiary_container: Rgb565::new(2, 34, 9), on_tertiary_container: Rgb565::new(27, 59, 28), background: Rgb565::new(0, 0, 0), on_background: Rgb565::new(28, 57, 28), surface: Rgb565::new(2, 6, 5), on_surface: Rgb565::new(28, 57, 28), surface_variant: Rgb565::new(6, 16, 10), on_surface_variant: Rgb565::new(25, 54, 27), outline: Rgb565::new(16, 41, 21), error: Rgb565::new(29, 45, 22), on_error: Rgb565::new(12, 5, 2), confirm_progress: Rgb565::new(3, 46, 16), logo: Rgb565::new(0, 55, 30), // Medium gray for secondary text (~60% of white - Material Design medium emphasis) // RGB565: 5 bits red, 6 bits green, 5 bits blue // ~60% would be: R=19/31, G=38/63, B=19/31 text_secondary: Rgb565::new(19, 38, 19), // Dark gray for disabled text (~38% of white - Material Design disabled state) // ~38% would be: R=12/31, G=24/63, B=12/31 text_disabled: Rgb565::new(12, 24, 12), // Yellow/amber warning color // RGB565: R=30/31, G=50/63, B=0/31 for a bright yellow warning: Rgb565::new(30, 50, 0), };
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/animation_speed.rs
frostsnap_widgets/src/animation_speed.rs
use crate::Frac; /// Animation speed curve for controlling how animations progress over time #[derive(Clone, Copy, Debug, PartialEq)] pub enum AnimationSpeed { /// Linear interpolation - constant speed throughout Linear, /// Cubic bezier ease-out curve (0.0, 0.0, 0.58, 1.0) /// Starts fast and slows down at the end EaseOut, } impl AnimationSpeed { /// Apply the animation speed curve to a progress value (0.0 to 1.0) /// Returns the eased progress value pub fn apply(&self, progress: Frac) -> Frac { match self { AnimationSpeed::Linear => progress, AnimationSpeed::EaseOut => { // Ease-out cubic bezier approximation using fixed point math // This approximates the curve (0.0, 0.0, 0.58, 1.0) // Formula: 1 - (1 - t)³ let one_minus_t = Frac::ONE - progress; let one_minus_t_squared = one_minus_t * one_minus_t; let one_minus_t_cubed = one_minus_t_squared * one_minus_t; Frac::ONE - one_minus_t_cubed } } } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/image.rs
frostsnap_widgets/src/image.rs
use crate::super_draw_target::SuperDrawTarget; use crate::Widget; use embedded_graphics::{ draw_target::DrawTarget, geometry::{Point, Size}, image::ImageDrawable, pixelcolor::PixelColor, prelude::*, primitives::Rectangle, Pixel, }; /// A widget that wraps any ImageDrawable as a widget pub struct Image<I> { image: I, needs_redraw: bool, } impl<I> Image<I> { /// Create a new image widget pub fn new(image: I) -> Self { Self { image, needs_redraw: true, } } } impl<I> crate::DynWidget for Image<I> where I: OriginDimensions, { fn set_constraints(&mut self, _max_size: Size) { // Image has a fixed size based on its content } fn sizing(&self) -> crate::Sizing { self.image.size().into() } fn force_full_redraw(&mut self) { self.needs_redraw = true; } } impl<I> Widget for Image<I> where I: ImageDrawable + OriginDimensions, I::Color: crate::WidgetColor, { type Color = I::Color; fn draw<D: DrawTarget<Color = Self::Color>>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, _current_time: crate::Instant, ) -> Result<(), D::Error> { if !self.needs_redraw { return Ok(()); } // Draw image at origin (0, 0) embedded_graphics::image::Image::new(&self.image, Point::zero()).draw(target)?; self.needs_redraw = false; Ok(()) } } // Specialized Widget impl for GrayToAlpha that uses SuperDrawTarget's background_color impl<I, C> Widget for Image<GrayToAlpha<I, C>> where I: ImageDrawable + OriginDimensions, I::Color: embedded_graphics::pixelcolor::GrayColor, C: crate::WidgetColor, { type Color = C; fn draw<D: DrawTarget<Color = Self::Color>>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, _current_time: crate::Instant, ) -> Result<(), D::Error> { if !self.needs_redraw { return Ok(()); } let background_color = target.background_color(); let mut mapped = GrayToAlphaDrawTarget { inner: target, foreground_color: self.image.foreground_color, background_color, _phantom: core::marker::PhantomData, }; embedded_graphics::image::Image::new(&self.image.image, Point::zero()).draw(&mut mapped)?; self.needs_redraw = false; Ok(()) } } /// Wraps a grayscale ImageDrawable and blends it with a foreground color /// /// The grayscale luma value is interpreted as alpha - dark pixels (0) use the foreground color, /// light pixels (255) use the background color from SuperDrawTarget, and intermediate values /// are interpolated between the two. pub struct GrayToAlpha<I, C> { image: I, foreground_color: C, } impl<I, C> GrayToAlpha<I, C> where I: ImageDrawable, I::Color: embedded_graphics::pixelcolor::GrayColor, C: PixelColor, { /// Create a new grayscale to alpha blended image /// /// # Arguments /// * `image` - The grayscale image source /// * `foreground_color` - Color to use for dark pixels (luma 0) /// /// Light pixels (luma 255) will use the background color from SuperDrawTarget at draw time. pub fn new(image: I, foreground_color: C) -> Self { Self { image, foreground_color, } } } impl<I, C> OriginDimensions for GrayToAlpha<I, C> where I: ImageDrawable + OriginDimensions, I::Color: embedded_graphics::pixelcolor::GrayColor, C: PixelColor, { fn size(&self) -> Size { self.image.size() } } /// A DrawTarget wrapper that converts grayscale to color via alpha blending struct GrayToAlphaDrawTarget<'a, D, CSrc, C> { inner: &'a mut D, foreground_color: C, background_color: C, _phantom: core::marker::PhantomData<CSrc>, } impl<'a, D, CSrc, C> DrawTarget for GrayToAlphaDrawTarget<'a, D, CSrc, C> where D: DrawTarget<Color = C>, CSrc: embedded_graphics::pixelcolor::GrayColor, C: crate::ColorInterpolate, { type Color = CSrc; type Error = D::Error; fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error> where I: IntoIterator<Item = Pixel<Self::Color>>, { self.inner .draw_iter(pixels.into_iter().map(|Pixel(point, gray)| { let intensity = gray.luma(); let frac = crate::Frac::from_ratio(intensity as u32, 255); let color = self .foreground_color .interpolate(self.background_color, frac); Pixel(point, color) })) } fn fill_contiguous<I>(&mut self, area: &Rectangle, colors: I) -> Result<(), Self::Error> where I: IntoIterator<Item = Self::Color>, { let mapped_colors = colors.into_iter().map(|gray| { let intensity = gray.luma(); let frac = crate::Frac::from_ratio(intensity as u32, 255); self.foreground_color .interpolate(self.background_color, frac) }); self.inner.fill_contiguous(area, mapped_colors) } fn fill_solid(&mut self, area: &Rectangle, gray: Self::Color) -> Result<(), Self::Error> { let intensity = gray.luma(); let frac = crate::Frac::from_ratio(intensity as u32, 255); let color = self .foreground_color .interpolate(self.background_color, frac); self.inner.fill_solid(area, color) } fn clear(&mut self, gray: Self::Color) -> Result<(), Self::Error> { let intensity = gray.luma(); let frac = crate::Frac::from_ratio(intensity as u32, 255); let color = self .foreground_color .interpolate(self.background_color, frac); self.inner.clear(color) } } impl<'a, D, CSrc, C> Dimensions for GrayToAlphaDrawTarget<'a, D, CSrc, C> where D: DrawTarget<Color = C>, CSrc: embedded_graphics::pixelcolor::GrayColor, C: PixelColor, { fn bounding_box(&self) -> Rectangle { self.inner.bounding_box() } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/fade_switcher.rs
frostsnap_widgets/src/fade_switcher.rs
use crate::super_draw_target::SuperDrawTarget; use crate::{DynWidget, Fader, Instant, Widget}; use embedded_graphics::{ draw_target::DrawTarget, geometry::{Point, Size}, pixelcolor::Rgb565, }; /// A widget that smoothly fades between widgets of the same type pub struct FadeSwitcher<T> where T: Widget<Color = Rgb565>, { current: Fader<T>, prev: Option<Fader<T>>, fade_duration_ms: u32, constraints: Option<Size>, pub shrink_to_fit: bool, } impl<T> FadeSwitcher<T> where T: Widget<Color = Rgb565>, { /// Create a new FadeSwitcher with an initial widget pub fn new(initial: T, fade_duration_ms: u32) -> Self { let mut child = Fader::new_faded_out(initial); child.start_fade_in(fade_duration_ms as _); Self { current: child, prev: None, fade_duration_ms, constraints: None, shrink_to_fit: false, } } /// Configure the FadeSwitcher to shrink to fit the first child pub fn with_shrink_to_fit(mut self) -> Self { self.shrink_to_fit = true; self } /// Switch to a new widget with a fade transition pub fn switch_to(&mut self, widget: T) { let mut new_fader = Fader::new_faded_out(widget); // Set constraints on the new fader if let Some(constraints) = self.constraints { new_fader.set_constraints(constraints); } let mut prev_fader = core::mem::replace(&mut self.current, new_fader); if self.prev.is_none() { // we only care about fading out the old widget if it was ever drawn. An existing `self.prev` means it wasn't. prev_fader.start_fade(self.fade_duration_ms as u64); self.prev = Some(prev_fader); } } pub fn instant_switch_to(&mut self, widget: T) { self.switch_to(widget); if let Some(prev) = &mut self.prev { prev.instant_fade(); } } pub fn instant_fade(&mut self) { self.current.instant_fade(); } /// Get a reference to the current widget pub fn current(&self) -> &T { &self.current.child } /// Get a mutable reference to the current widget pub fn current_mut(&mut self) -> &mut T { &mut self.current.child } } impl<T> crate::DynWidget for FadeSwitcher<T> where T: Widget<Color = Rgb565>, { fn set_constraints(&mut self, max_size: Size) { let constraints = if self.shrink_to_fit { self.current.set_constraints(max_size); self.current.sizing().into() } else { self.current.set_constraints(max_size); max_size }; self.constraints = Some(constraints); if let Some(ref mut prev) = self.prev { prev.set_constraints(constraints); } } fn sizing(&self) -> crate::Sizing { let size = self.constraints.unwrap(); crate::Sizing { width: size.width, height: size.height, dirty_rect: None, } } fn handle_touch( &mut self, point: Point, current_time: Instant, is_release: bool, ) -> Option<crate::KeyTouch> { // Only handle touch for the current widget self.current.handle_touch(point, current_time, is_release) } fn handle_vertical_drag(&mut self, prev_y: Option<u32>, new_y: u32, is_release: bool) { // Only handle drag for the current widget self.current.handle_vertical_drag(prev_y, new_y, is_release) } fn force_full_redraw(&mut self) { self.current.force_full_redraw(); if let Some(prev) = &mut self.prev { prev.force_full_redraw(); } } } impl<T> Widget for FadeSwitcher<T> where T: Widget<Color = Rgb565>, { type Color = Rgb565; fn draw<D>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, current_time: crate::Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { // Draw the previous widget if it's still fading out if let Some(prev) = &mut self.prev { prev.draw(target, current_time)?; // Remove it once fully faded if prev.is_faded_out() && self.current.is_faded_out() { self.current.start_fade_in(self.fade_duration_ms as u64); self.prev = None; } } if self.prev.is_some() { return Ok(()); } self.current.draw(target, current_time)?; Ok(()) } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/standby.rs
frostsnap_widgets/src/standby.rs
use crate::DefaultTextStyle; use crate::{ any_of::AnyOf, device_name::DeviceName, palette::PALETTE, prelude::*, FadeSwitcher, GrayToAlpha, }; use alloc::string::{String, ToString}; use embedded_graphics::{ pixelcolor::{Gray8, Rgb565}, text::Alignment, }; use frostsnap_core::message::HeldShare2; use tinybmp::Bmp; pub const LOGO_DATA: &[u8] = include_bytes!("../assets/frostsnap-icon-80x96.bmp"); const WARNING_ICON_DATA: &[u8] = include_bytes!("../assets/warning-icon-24x24.bmp"); type Image = crate::Image<GrayToAlpha<Bmp<'static, Gray8>, Rgb565>>; /// Blank standby content - shows welcome message #[derive(frostsnap_macros::Widget)] pub struct StandbyBlank { #[widget_delegate] content: Center<Column<(Text, Text, Text)>>, } impl Default for StandbyBlank { fn default() -> Self { Self::new() } } impl StandbyBlank { pub fn new() -> Self { let text_style = DefaultTextStyle::new(crate::FONT_MED, PALETTE.on_background); let url_style = DefaultTextStyle::new(crate::FONT_MED, PALETTE.primary); let text_line1 = Text::new("Get started with", text_style.clone()); let text_line2 = Text::new("Frostsnap", text_style); let url_text = Text::new("frostsnap.com/start", url_style); let column = Column::builder() .push(text_line1) .gap(4) .push(text_line2) .gap(16) .push(url_text) .with_cross_axis_alignment(crate::CrossAxisAlignment::Center); let content = Center::new(column); Self { content } } } /// Standby content showing key information #[derive(frostsnap_macros::Widget)] pub struct StandbyHasKey { #[widget_delegate] content: Column<(Option<Row<(Image, Text)>>, Text, Text, DeviceName)>, } impl StandbyHasKey { pub fn new(device_name: impl Into<String>, held_share: HeldShare2) -> Self { let recovery_warning = if held_share.access_structure_ref.is_none() { let warning_bmp = Bmp::<Gray8>::from_slice(WARNING_ICON_DATA).expect("Failed to load warning BMP"); let warning_icon = Image::new(GrayToAlpha::new(warning_bmp, PALETTE.warning)); let warning_text = Text::new( "Recovery Mode", DefaultTextStyle::new(crate::FONT_MED, PALETTE.warning), ); Some( Row::builder() .push(warning_icon) .gap(4) .push(warning_text) .with_cross_axis_alignment(crate::CrossAxisAlignment::End), ) } else { None }; let key_style = DefaultTextStyle::new(crate::FONT_MED, PALETTE.on_surface_variant); let key_text = Text::new(held_share.key_name.unwrap_or("??".to_string()), key_style) .with_alignment(Alignment::Center); let share_index: u16 = held_share.share_image.index.try_into().unwrap(); let key_index_text = Text::new( format!("Key #{}", share_index), DefaultTextStyle::new(crate::FONT_SMALL, PALETTE.text_secondary), ) .with_alignment(Alignment::Center); let device_name_widget = DeviceName::new(device_name); let content = Column::builder() .push(recovery_warning) .gap(8) .push(key_text) .gap(12) .push(key_index_text) .gap(4) .push(device_name_widget) .with_cross_axis_alignment(crate::CrossAxisAlignment::Center); Self { content } } } /// Main standby widget that can show startup (empty), blank (welcome), or has-key content #[derive(frostsnap_macros::Widget)] pub struct Standby { #[widget_delegate] content: Center< Column<( Padding<Image>, FadeSwitcher<Option<AnyOf<(StandbyBlank, StandbyHasKey)>>>, )>, >, } impl Default for Standby { fn default() -> Self { Self::new() } } impl Standby { /// Create a new Standby widget in startup mode (just logo, empty body) pub fn new() -> Self { let logo_bmp = Bmp::<Gray8>::from_slice(LOGO_DATA).expect("Failed to load BMP"); let logo = Image::new(GrayToAlpha::new(logo_bmp, PALETTE.logo)); let padded_logo = Padding::only(logo).top(30).bottom(20).build(); let fade_switcher = FadeSwitcher::new(None, 500); let column = Column::builder() .push(padded_logo) .push(fade_switcher) .with_cross_axis_alignment(crate::CrossAxisAlignment::Center); let content = Center::new(column); Self { content } } /// Clear content (back to startup mode - just logo) pub fn clear_content(&mut self) { self.content.child.children.1.switch_to(None); } /// Set to welcome mode (blank with welcome message) pub fn set_welcome(&mut self) { let blank_content = StandbyBlank::new(); self.content .child .children .1 .switch_to(Some(AnyOf::new(blank_content))); } /// Set to has-key mode with key information pub fn set_key(&mut self, device_name: impl Into<String>, held_share: HeldShare2) { let has_key_content = StandbyHasKey::new(device_name, held_share); self.content .child .children .1 .switch_to(Some(AnyOf::new(has_key_content))); } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/circle_button.rs
frostsnap_widgets/src/circle_button.rs
use crate::super_draw_target::SuperDrawTarget; use crate::{checkmark::Checkmark, palette::PALETTE, prelude::*}; use embedded_graphics::{ draw_target::DrawTarget, geometry::{Point, Size}, image::Image, pixelcolor::Rgb565, prelude::*, primitives::{Circle, PrimitiveStyleBuilder}, }; use embedded_iconoir::{icons::size48px::gestures::OpenSelectHandGesture, prelude::IconoirNewIcon}; // Circle dimensions const CIRCLE_RADIUS: u32 = 50; const CIRCLE_DIAMETER: u32 = CIRCLE_RADIUS * 2; #[derive(Debug, Clone, Copy, PartialEq)] pub enum CircleButtonState { Idle, Pressed, ShowingCheckmark, } /// A circular button that shows a hand icon when idle/pressed and transitions to a checkmark pub struct CircleButton { state: CircleButtonState, checkmark: Center<Checkmark<Rgb565>>, last_drawn_state: Option<CircleButtonState>, } impl Default for CircleButton { fn default() -> Self { Self::new() } } impl CircleButton { pub fn new() -> Self { // Use a checkmark that fits nicely within the circle let checkmark = Center::new(Checkmark::new(50, PALETTE.on_tertiary_container)); Self { state: CircleButtonState::Idle, checkmark, last_drawn_state: None, } } /// Set the button state pub fn set_state(&mut self, state: CircleButtonState) { self.state = state; } /// Get the current state pub fn state(&self) -> CircleButtonState { self.state } pub fn checkmark(&self) -> &Checkmark<Rgb565> { &self.checkmark.child } pub fn checkmark_mut(&mut self) -> &mut Checkmark<Rgb565> { &mut self.checkmark.child } /// Reset the button to idle state pub fn reset(&mut self) { self.state = CircleButtonState::Idle; self.checkmark.child.reset(); self.last_drawn_state = None; } /// Check if a point is within the circle pub fn contains_point(&self, point: Point) -> bool { let center = Point::new(CIRCLE_RADIUS as i32, CIRCLE_RADIUS as i32); let distance_squared = (point.x - center.x).pow(2) + (point.y - center.y).pow(2); distance_squared <= (CIRCLE_RADIUS as i32).pow(2) } } impl crate::DynWidget for CircleButton { fn set_constraints(&mut self, _max_size: Size) { // CircleButton has a fixed size, but we need to set constraints on the checkmark // Give the checkmark the full circle area to work with self.checkmark .set_constraints(Size::new(CIRCLE_DIAMETER, CIRCLE_DIAMETER)); } fn sizing(&self) -> crate::Sizing { Size::new(CIRCLE_DIAMETER, CIRCLE_DIAMETER).into() } fn handle_touch( &mut self, point: Point, _current_time: Instant, is_release: bool, ) -> Option<crate::KeyTouch> { if self.state == CircleButtonState::ShowingCheckmark { // Don't handle touches when showing checkmark return None; } if is_release { // Release - go back to idle if self.state == CircleButtonState::Pressed { self.state = CircleButtonState::Idle; } } else if self.contains_point(point) { // Press within button - set to pressed self.state = CircleButtonState::Pressed; } None } fn handle_vertical_drag(&mut self, _prev_y: Option<u32>, _new_y: u32, _is_release: bool) {} fn force_full_redraw(&mut self) { self.last_drawn_state = None; self.checkmark.force_full_redraw(); } } impl Widget for CircleButton { type Color = Rgb565; fn draw<D>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, current_time: crate::Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { let center = Point::new(CIRCLE_RADIUS as i32, CIRCLE_RADIUS as i32); // Only redraw the circle if state changed let should_redraw = self.last_drawn_state != Some(self.state); if should_redraw { match self.state { CircleButtonState::Idle => { let circle_style = PrimitiveStyleBuilder::new() .fill_color(PALETTE.surface_variant) .stroke_color(PALETTE.confirm_progress) .stroke_width(2) .build(); Circle::with_center(center, CIRCLE_DIAMETER - 4) .into_styled(circle_style) .draw(target)?; let icon = OpenSelectHandGesture::new(PALETTE.on_surface_variant); Image::with_center(&icon, center).draw(target)?; } CircleButtonState::Pressed => { let circle_style = PrimitiveStyleBuilder::new() .fill_color(PALETTE.tertiary_container) .stroke_color(PALETTE.confirm_progress) .stroke_width(2) .build(); Circle::with_center(center, CIRCLE_DIAMETER - 4) .into_styled(circle_style) .draw(target)?; let icon = OpenSelectHandGesture::new(PALETTE.on_tertiary_container); Image::with_center(&icon, center).draw(target)?; } CircleButtonState::ShowingCheckmark => { // Draw solid green circle (both fill and border are green) let circle_style = PrimitiveStyleBuilder::new() .fill_color(PALETTE.tertiary_container) .stroke_color(PALETTE.tertiary_container) .stroke_width(2) .build(); Circle::with_center(center, CIRCLE_DIAMETER - 4) .into_styled(circle_style) .draw(target)?; } } self.last_drawn_state = Some(self.state); } // Draw checkmark animation when in ShowingCheckmark state if self.state == CircleButtonState::ShowingCheckmark { self.checkmark.draw(target, current_time)?; } Ok(()) } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/scroll_bar.rs
frostsnap_widgets/src/scroll_bar.rs
use crate::super_draw_target::SuperDrawTarget; use crate::{palette::PALETTE, Frac, Rat, Widget}; use embedded_graphics::{ pixelcolor::Rgb565, prelude::*, primitives::{PrimitiveStyleBuilder, Rectangle, RoundedRectangle}, }; pub const SCROLLBAR_WIDTH: u32 = 4; const MIN_INDICATOR_HEIGHT: u32 = 20; #[derive(Debug, PartialEq)] pub struct ScrollBar { last_scroll_position: Option<Rat>, thumb_size: Frac, scroll_position: Rat, height: Option<u32>, } impl ScrollBar { pub fn new(thumb_size: Frac) -> Self { Self { last_scroll_position: None, thumb_size, scroll_position: Rat::ZERO, height: None, } } pub fn set_scroll_position(&mut self, position: Rat) { self.scroll_position = position; } pub fn draw<D: DrawTarget<Color = Rgb565>>(&mut self, target: &mut D) { if self.thumb_size >= Frac::ONE { // Everything is visible, no need for scrollbar return; } if self.last_scroll_position == Some(self.scroll_position) { return; } let bounds = target.bounding_box(); let track_rect = Rectangle::new(bounds.top_left, bounds.size); let thumb_height = (self.thumb_size * track_rect.size.height) .max(Rat::from_int(MIN_INDICATOR_HEIGHT as _)); let available_track_height = track_rect.size.height - thumb_height; let thumb_y = track_rect.top_left.y + (self.scroll_position * available_track_height).round() as i32; let thumb_rect = Rectangle::new( Point::new(track_rect.top_left.x, thumb_y), Size::new(track_rect.size.width, thumb_height.round()), ); // Always draw the track background let track = RoundedRectangle::with_equal_corners(track_rect, Size::new(2, 2)); let _ = track .into_styled( PrimitiveStyleBuilder::new() .fill_color(PALETTE.surface_variant) .build(), ) .draw(target); // Draw the thumb let thumb = RoundedRectangle::with_equal_corners(thumb_rect, Size::new(2, 2)); let _ = thumb .into_styled( PrimitiveStyleBuilder::new() .fill_color(PALETTE.on_surface_variant) .build(), ) .draw(target); self.last_scroll_position = Some(self.scroll_position); } } impl crate::DynWidget for ScrollBar { fn sizing(&self) -> crate::Sizing { crate::Sizing { width: SCROLLBAR_WIDTH, height: self .height .expect("ScrollBar::sizing called before set_constraints"), ..Default::default() } } fn set_constraints(&mut self, max_size: Size) { self.height = Some(max_size.height); } fn force_full_redraw(&mut self) { self.last_scroll_position = None; } } impl Widget for ScrollBar { type Color = Rgb565; fn draw<D: DrawTarget<Color = Self::Color>>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, _current_time: crate::Instant, ) -> Result<(), D::Error> { self.draw(target); Ok(()) } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/progress_bars.rs
frostsnap_widgets/src/progress_bars.rs
use crate::{palette::PALETTE, prelude::*}; use alloc::vec::Vec; use embedded_graphics::prelude::*; use frostsnap_macros::Widget; #[derive(Widget)] pub struct ProgressBars { #[widget_delegate] row: Row<Vec<Container<()>>>, } impl core::fmt::Debug for ProgressBars { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("ProgressBars") .field("bar_count", &self.row.children.len()) .finish() } } impl ProgressBars { pub fn new(total_bar_number: usize) -> Self { // Create containers for each bar let mut bars = Vec::with_capacity(total_bar_number); let flex_scores = vec![1; total_bar_number]; for _ in 0..total_bar_number { // Create container with the "off" color (surface_variant gray) // Fixed height of 8px, width will be determined by flex let container = Container::with_size((), Size::new(u32::MAX, 8)).with_fill(PALETTE.surface_variant); bars.push(container); } // Create the row let mut row = Row::new(bars).with_main_axis_alignment(MainAxisAlignment::Center); // Set flex scores row.flex_scores = flex_scores; // Set uniform 2px gap between bars row.set_uniform_gap(2); Self { row } } pub fn progress(&mut self, new_progress: usize) { // Clamp progress to valid range let new_progress = new_progress.min(self.row.children.len()); // Iterate over all containers and set their color based on the progress for (i, container) in self.row.children.iter_mut().enumerate() { if i < new_progress { // This bar should be "on" - set to green if container.fill_color() != Some(PALETTE.tertiary) { container.set_fill(PALETTE.tertiary); } } else { // This bar should be "off" - set to gray if container.fill_color() != Some(PALETTE.surface_variant) { container.set_fill(PALETTE.surface_variant); } } } } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/icons.rs
frostsnap_widgets/src/icons.rs
use crate::super_draw_target::SuperDrawTarget; use core::marker::PhantomData; use embedded_graphics::{geometry::Size, image::Image, pixelcolor::Rgb565, prelude::*}; use embedded_iconoir::{ icons::size24px::actions::Check, prelude::{IconoirIcon, IconoirNewIcon}, size32px::navigation::NavArrowLeft, }; #[derive(Debug, Clone, PartialEq)] pub struct Icon<I> { icon: PhantomData<I>, color: Rgb565, center: Option<Point>, } impl<I> Default for Icon<I> { fn default() -> Self { Self { icon: Default::default(), color: Default::default(), center: Default::default(), } } } impl<I: IconoirNewIcon<Rgb565>> Icon<I> { pub fn with_color(mut self, color: Rgb565) -> Self { self.color = color; self } pub fn with_center(mut self, center: Point) -> Self { self.center = Some(center); self } pub fn draw(&self, target: &mut impl DrawTarget<Color = Rgb565>) { let center = self.center.unwrap_or_else(|| { let size = target.bounding_box().size; Point::new(size.width as i32 / 2, size.height as i32 / 2) }); let icon = I::new(self.color); let _ = Image::with_center(&icon, center).draw(target); } } pub fn backspace() -> Icon<NavArrowLeft> { Icon::default() } pub fn confirm() -> Icon<Check> { Icon::default() } /// Wrapper to make an icon into a widget pub struct IconWidget<I> { icon: I, constraints: Option<Size>, needs_redraw: bool, } impl<I: embedded_graphics::image::ImageDrawable<Color = Rgb565>> IconWidget<I> { pub fn new(icon: I) -> Self { Self { icon, constraints: None, needs_redraw: true, } } } impl<I: embedded_graphics::image::ImageDrawable<Color = Rgb565>> crate::DynWidget for IconWidget<I> { fn set_constraints(&mut self, max_size: Size) { self.constraints = Some(max_size); } fn sizing(&self) -> crate::Sizing { let size = self.icon.bounding_box().size; crate::Sizing { width: size.width, height: size.height, ..Default::default() } } fn force_full_redraw(&mut self) { self.needs_redraw = true; } } impl<I: embedded_graphics::image::ImageDrawable<Color = Rgb565>> crate::Widget for IconWidget<I> { type Color = Rgb565; fn draw<D: embedded_graphics::draw_target::DrawTarget<Color = Self::Color>>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, _current_time: crate::Instant, ) -> Result<(), D::Error> { if self.needs_redraw { Image::new(&self.icon, Point::zero()).draw(target)?; self.needs_redraw = false; } Ok(()) } } impl<I: IconoirIcon> IconWidget<embedded_iconoir::Icon<Rgb565, I>> { pub fn set_color(&mut self, color: Rgb565) { self.icon.set_color(color); self.needs_redraw = true; } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/sign_prompt.rs
frostsnap_widgets/src/sign_prompt.rs
use crate::DefaultTextStyle; use crate::{ address_display::AddressDisplay, any_of::AnyOf, bitcoin_amount_display::BitcoinAmountDisplay, icons::IconWidget, page_slider::PageSlider, palette::PALETTE, prelude::*, widget_list::WidgetList, HoldToConfirm, HOLD_TO_CONFIRM_TIME_MS, }; use alloc::{format, string::ToString}; use embedded_graphics::{ draw_target::DrawTarget, geometry::{Point, Size}, pixelcolor::Rgb565, }; use frostsnap_core::bitcoin_transaction::PromptSignBitcoinTx; /// Widget list that generates sign prompt pages pub struct SignPromptPageList { prompt: PromptSignBitcoinTx, total_pages: usize, } /// Page widget for displaying amount to send #[derive(frostsnap_macros::Widget)] pub struct AmountPage { #[widget_delegate] center: Center< Column<( Text, SizedBox<Rgb565>, BitcoinAmountDisplay, SizedBox<Rgb565>, Text, )>, >, } impl AmountPage { pub fn new(index: usize, amount_sats: u64) -> Self { let title = Text::new( format!("Send Amount #{}", index + 1), DefaultTextStyle::new(crate::FONT_MED, PALETTE.text_secondary), ); let spacer = SizedBox::<Rgb565>::new(Size::new(1, 15)); // 15px height spacing let amount_display = BitcoinAmountDisplay::new(amount_sats); let btc_spacer = SizedBox::<Rgb565>::new(Size::new(1, 10)); // 10px spacing before BTC let btc_text = Text::new( "BTC".to_string(), DefaultTextStyle::new(crate::FONT_MED, PALETTE.text_secondary), ); let column = Column::new((title, spacer, amount_display, btc_spacer, btc_text)) .with_main_axis_alignment(MainAxisAlignment::Center) .with_cross_axis_alignment(CrossAxisAlignment::Center); Self { center: Center::new(column), } } } // Trait implementations are now generated by the derive macro /// Page widget for displaying recipient address #[derive(frostsnap_macros::Widget)] pub struct AddressPage { #[widget_delegate] center: Center<Padding<Column<(Text, AddressDisplay)>>>, } impl AddressPage { fn new(index: usize, address: &bitcoin::Address) -> Self { let title = Text::new( format!("Address #{}", index + 1), DefaultTextStyle::new(crate::FONT_MED, PALETTE.text_secondary), ); // Use our AddressDisplay widget which handles all address types let address_display = AddressDisplay::new(address.clone()); let column = Column::new((title, address_display)) .with_main_axis_alignment(MainAxisAlignment::SpaceAround); let padded = Padding::only(column).top(8).bottom(40).build(); Self { center: Center::new(padded), } } } // Trait implementations are now generated by the derive macro /// Page widget for displaying network fee #[derive(frostsnap_macros::Widget)] pub struct FeePage { #[widget_delegate] center: Center<Column<(Text, BitcoinAmountDisplay, Text)>>, } impl FeePage { fn new(fee_sats: u64) -> Self { let title = Text::new( "Network Fee".to_string(), DefaultTextStyle::new(crate::FONT_MED, PALETTE.text_secondary), ); let fee_amount = BitcoinAmountDisplay::new(fee_sats); let fee_sats_text = Text::new( format!("{} sats", fee_sats), DefaultTextStyle::new(crate::FONT_SMALL, PALETTE.text_secondary), ); let column = Column::new((title, fee_amount, fee_sats_text)) .with_main_axis_alignment(MainAxisAlignment::SpaceEvenly); Self { center: Center::new(column), } } } // Trait implementations are now generated by the derive macro /// Page widget for high fee warning #[derive(frostsnap_macros::Widget)] pub struct WarningPage { #[widget_delegate] center: Center< Column<( IconWidget< embedded_iconoir::Icon< Rgb565, embedded_iconoir::icons::size48px::actions::WarningTriangle, >, >, Text, Text, )>, >, } impl WarningPage { fn new(fee_sats: u64, _total_sent: u64) -> Self { use embedded_iconoir::prelude::*; let warning_icon = IconWidget::new( embedded_iconoir::icons::size48px::actions::WarningTriangle::new(PALETTE.error), ); let caution_text = Text::new( "Caution".to_string(), DefaultTextStyle::new(crate::FONT_LARGE, PALETTE.error), ); let warning_msg = if fee_sats > 100_000 { "Fee exceeds\n0.001 BTC" } else { "Fee exceeds\n5% of amount" }; let warning_text = Text::new( warning_msg.to_string(), DefaultTextStyle::new(crate::FONT_MED, PALETTE.on_surface), ); let column = Column::new((warning_icon, caution_text, warning_text)) .with_main_axis_alignment(MainAxisAlignment::Center); Self { center: Center::new(column), } } } // Trait implementations are now generated by the derive macro /// Confirmation page with HoldToConfirm pub struct ConfirmationPage { hold_confirm: HoldToConfirm<Column<(Text, Text, BitcoinAmountDisplay, Text)>>, } impl ConfirmationPage { fn new(total_sats: u64) -> Self { let sign_text = Text::new( "Sign transaction?", DefaultTextStyle::new(crate::FONT_MED, PALETTE.on_background), ); let sending_text = Text::new( "sending", DefaultTextStyle::new(crate::FONT_SMALL, PALETTE.text_secondary), ); let amount_display = BitcoinAmountDisplay::new(total_sats); let btc_text = Text::new( "BTC", DefaultTextStyle::new(crate::FONT_SMALL, PALETTE.text_secondary), ); let confirm_content = Column::new((sign_text, sending_text, amount_display, btc_text)) .with_main_axis_alignment(MainAxisAlignment::Center); let hold_confirm = HoldToConfirm::new(HOLD_TO_CONFIRM_TIME_MS, confirm_content).with_faded_out_button(); Self { hold_confirm } } pub fn is_confirmed(&self) -> bool { self.hold_confirm.is_completed() } } impl DynWidget for ConfirmationPage { fn set_constraints(&mut self, max_size: Size) { self.hold_confirm.set_constraints(max_size); } fn sizing(&self) -> crate::Sizing { self.hold_confirm.sizing() } fn handle_touch( &mut self, point: Point, current_time: Instant, is_release: bool, ) -> Option<crate::KeyTouch> { self.hold_confirm .handle_touch(point, current_time, is_release) } fn handle_vertical_drag(&mut self, prev_y: Option<u32>, new_y: u32, is_release: bool) { self.hold_confirm .handle_vertical_drag(prev_y, new_y, is_release); } fn force_full_redraw(&mut self) { self.hold_confirm.force_full_redraw(); } } impl Widget for ConfirmationPage { type Color = Rgb565; fn draw<D>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, current_time: Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { self.hold_confirm.draw(target, current_time) } } /// Type alias for the different pages that can be displayed type SignPromptPage = AnyOf<( AmountPage, AddressPage, FeePage, WarningPage, ConfirmationPage, )>; impl SignPromptPageList { fn new(prompt: PromptSignBitcoinTx) -> Self { let num_recipients = prompt.foreign_recipients.len(); let has_warning = Self::has_high_fee(&prompt); // Each recipient has 2 pages (amount, address), plus fee page, plus optional warning, plus confirmation let total_pages = num_recipients * 2 + 1 + if has_warning { 1 } else { 0 } + 1; Self { prompt, total_pages, } } /// Check if the transaction has high fees that warrant a warning fn has_high_fee(prompt: &PromptSignBitcoinTx) -> bool { let fee_sats = prompt.fee.to_sat(); // High fee if > 0.001 BTC (100,000 sats) if fee_sats > 100_000 { return true; } // High fee if > 5% of total amount being sent let total_sent: u64 = prompt .foreign_recipients .iter() .map(|(_, amount)| amount.to_sat()) .sum(); if total_sent > 0 && fee_sats > total_sent / 20 { return true; } false } } impl WidgetList<SignPromptPage> for SignPromptPageList { fn len(&self) -> usize { self.total_pages } fn get(&self, index: usize) -> Option<SignPromptPage> { if index >= self.total_pages { return None; } let num_recipients = self.prompt.foreign_recipients.len(); let recipient_pages = num_recipients * 2; let has_warning = Self::has_high_fee(&self.prompt); let page = if index < recipient_pages { // It's either an amount or address page for a recipient let recipient_idx = index / 2; let is_amount = index.is_multiple_of(2); if is_amount { // Amount page let (_, amount) = &self.prompt.foreign_recipients[recipient_idx]; SignPromptPage::new(AmountPage::new(recipient_idx, amount.to_sat())) } else { // Address page let (address, _) = &self.prompt.foreign_recipients[recipient_idx]; SignPromptPage::new(AddressPage::new(recipient_idx, address)) } } else if index == recipient_pages { // Fee page SignPromptPage::new(FeePage::new(self.prompt.fee.to_sat())) } else if has_warning && index == recipient_pages + 1 { // Warning page (if applicable) let total_sent: u64 = self .prompt .foreign_recipients .iter() .map(|(_, amount)| amount.to_sat()) .sum(); SignPromptPage::new(WarningPage::new(self.prompt.fee.to_sat(), total_sent)) } else { // Confirmation page (last page) let total_sent: u64 = self .prompt .foreign_recipients .iter() .map(|(_, amount)| amount.to_sat()) .sum(); SignPromptPage::new(ConfirmationPage::new(total_sent)) }; Some(page) } fn can_go_prev(&self, from_index: usize, current_widget: &SignPromptPage) -> bool { // If we're on the last page (confirmation screen) if from_index == self.total_pages - 1 { // Check if the confirmation screen has been confirmed if let Some(confirmation_page) = current_widget.downcast_ref::<ConfirmationPage>() { // Don't allow going back if confirmed return !confirmation_page.is_confirmed(); } } true // Allow navigation for all other cases } } /// High-level widget that manages the complete sign prompt flow using PageSlider #[derive(frostsnap_macros::Widget)] pub struct SignTxPrompt { #[widget_delegate] page_slider: PageSlider<SignPromptPageList, SignPromptPage>, } impl SignTxPrompt { pub fn new(prompt: PromptSignBitcoinTx) -> Self { let page_list = SignPromptPageList::new(prompt); let page_slider = PageSlider::new(page_list, 40) .with_on_page_ready(|page| { // Try to downcast to ConfirmationPage if let Some(confirmation_page) = page.downcast_mut::<ConfirmationPage>() { // Fade in the button when the confirmation page is ready confirmation_page.hold_confirm.fade_in_button(); } }) .with_swipe_up_chevron(); Self { page_slider } } /// Check if the transaction has been confirmed pub fn is_confirmed(&mut self) -> bool { // Check if we're on the last page if self.page_slider.current_index() == self.page_slider.total_pages() - 1 { let current_widget = self.page_slider.current_widget(); if let Some(confirmation_page) = current_widget.downcast_ref::<ConfirmationPage>() { return confirmation_page.is_confirmed(); } } false } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/switcher.rs
frostsnap_widgets/src/switcher.rs
use crate::{FadeSwitcher, Widget}; use embedded_graphics::pixelcolor::Rgb565; /// A widget that switches between child widgets instantly without fading /// Uses FadeSwitcher internally but with 0 duration for instant switching #[derive(frostsnap_macros::Widget)] pub struct Switcher<W: Widget<Color = Rgb565>> { fade_switcher: FadeSwitcher<W>, } impl<W: Widget<Color = Rgb565>> Switcher<W> { /// Create a new Switcher with an initial widget pub fn new(initial: W) -> Self { Self { fade_switcher: FadeSwitcher::new(initial, 0), } } /// Configure the Switcher to shrink to fit the first child pub fn with_shrink_to_fit(mut self) -> Self { self.fade_switcher = self.fade_switcher.with_shrink_to_fit(); self } /// Switch to a new widget instantly pub fn switch_to(&mut self, widget: W) { // FadeSwitcher's switch_to only takes the widget self.fade_switcher.switch_to(widget); } /// Get a reference to the current widget pub fn current(&self) -> &W { self.fade_switcher.current() } /// Get a mutable reference to the current widget pub fn current_mut(&mut self) -> &mut W { self.fade_switcher.current_mut() } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/share_index.rs
frostsnap_widgets/src/share_index.rs
use crate::DefaultTextStyle; use crate::{ layout::{MainAxisAlignment, Row}, palette::PALETTE, text::Text, }; use frostsnap_fonts::Gray4Font; /// A widget that displays a share index with "#" in secondary color and the number in primary #[derive(frostsnap_macros::Widget)] pub struct ShareIndexWidget { #[widget_delegate] row: Row<(Text, Text)>, } impl ShareIndexWidget { pub fn new(share_index: u16, font: &'static Gray4Font) -> Self { let hash_text = Text::new("#", DefaultTextStyle::new(font, PALETTE.text_secondary)); let index_text = Text::new( format!("{}", share_index), DefaultTextStyle::new(font, PALETTE.primary), ); let row = Row::builder() .push(hash_text) .push(index_text) .with_main_axis_alignment(MainAxisAlignment::Center); Self { row } } /// Create with custom alignment pub fn with_alignment(mut self, alignment: MainAxisAlignment) -> Self { self.row.main_axis_alignment = alignment; self } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/text.rs
frostsnap_widgets/src/text.rs
use super::Widget; use crate::{super_draw_target::SuperDrawTarget, Instant}; use alloc::string::String; use embedded_graphics::{ draw_target::DrawTarget, geometry::{Dimensions, Point, Size}, pixelcolor::PixelColor, prelude::*, primitives::{Line, PrimitiveStyle}, text::{ renderer::{CharacterStyle, TextRenderer}, Alignment, Baseline, Text as EgText, TextStyle, TextStyleBuilder, }, Drawable, }; /// Distance in pixels between the bottom of the text and the underline const UNDERLINE_DISTANCE: i32 = 2; /// A simple text widget that renders text at a specific position #[derive(Clone)] pub struct Text<S: CharacterStyle = crate::DefaultTextStyle, T = String> { text: T, character_style: S, text_style: TextStyle, underline_color: Option<<S as CharacterStyle>::Color>, drawn: bool, cached_size: Size, } impl<S, C> Text<S, String> where C: PixelColor, S: CharacterStyle<Color = C> + TextRenderer<Color = C> + Clone, { pub fn new<U: Into<String>>(text: U, character_style: S) -> Self { let text = text.into(); let text_style = TextStyleBuilder::new().baseline(Baseline::Top).build(); // Calculate size once during creation let text_obj = EgText::with_text_style( text.as_ref(), Point::zero(), character_style.clone(), text_style, ); let bbox = text_obj.bounding_box(); let cached_size = bbox.size; Self { text, character_style, text_style, underline_color: None, drawn: false, cached_size, } } } impl<S, C, T> Text<S, T> where T: AsRef<str>, C: PixelColor, S: CharacterStyle<Color = C> + TextRenderer<Color = C> + Clone, { pub fn new_with(text: T, character_style: S) -> Self { let text_style = TextStyleBuilder::new().baseline(Baseline::Top).build(); // Calculate size once during creation let text_obj = EgText::with_text_style( text.as_ref(), Point::zero(), character_style.clone(), text_style, ); let bbox = text_obj.bounding_box(); let cached_size = bbox.size; Self { text, character_style, text_style, underline_color: None, drawn: false, cached_size, } } pub fn text(&self) -> &str { self.text.as_ref() } /// Create the EgText object at the given position fn create_eg_text(&self) -> EgText<'_, S> { EgText::with_text_style( self.text.as_ref(), Point::zero(), self.character_style.clone(), self.text_style, ) } pub fn with_alignment(mut self, alignment: Alignment) -> Self { self.text_style = TextStyleBuilder::from(&self.text_style) .alignment(alignment) .build(); // Recalculate size with new alignment let text_obj = self.create_eg_text(); let bbox = text_obj.bounding_box(); self.cached_size = bbox.size; self } pub fn with_underline(mut self, color: <S as CharacterStyle>::Color) -> Self { self.underline_color = Some(color); // Add space for underline to cached size self.cached_size.height += UNDERLINE_DISTANCE as u32 + 1; self } pub fn set_character_style(&mut self, character_style: S) { self.character_style = character_style; // Recalculate size with new character style let text_obj = self.create_eg_text(); let bbox = text_obj.bounding_box(); self.cached_size = bbox.size; if self.underline_color.is_some() { self.cached_size.height += UNDERLINE_DISTANCE as u32 + 1; } self.drawn = false; } } impl<S, C, T> crate::DynWidget for Text<S, T> where T: AsRef<str> + Clone, C: PixelColor, S: CharacterStyle<Color = C> + TextRenderer<Color = C> + Clone, { fn set_constraints(&mut self, _max_size: Size) { // intrinsic size } fn sizing(&self) -> crate::Sizing { self.cached_size.into() } fn handle_touch( &mut self, _point: Point, _current_time: Instant, _is_release: bool, ) -> Option<crate::KeyTouch> { None } fn force_full_redraw(&mut self) { self.drawn = false; } } impl<S, C, T> Widget for Text<S, T> where T: AsRef<str> + Clone, C: crate::WidgetColor, S: CharacterStyle<Color = C> + TextRenderer<Color = C> + Clone, { type Color = C; fn draw<D>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, _current_time: Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { if !self.drawn { // Set background color on character style for proper alpha blending self.character_style .set_background_color(Some(target.background_color())); let mut text_obj = self.create_eg_text(); if text_obj.bounding_box().top_left.x < 0 { text_obj.position.x += text_obj.bounding_box().top_left.x.abs(); } text_obj.draw(target)?; // Draw underline if enabled if let Some(underline_color) = self.underline_color { let text_bbox = text_obj.bounding_box(); let underline_y = text_bbox.bottom_right().unwrap().y + UNDERLINE_DISTANCE; Line::new( Point::new(text_bbox.top_left.x, underline_y), Point::new(text_bbox.bottom_right().unwrap().x, underline_y), ) .into_styled(PrimitiveStyle::with_stroke(underline_color, 1)) .draw(target)?; } self.drawn = true; } Ok(()) } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/debug.rs
frostsnap_widgets/src/debug.rs
use crate::{palette::PALETTE, prelude::*, string_ext::StringWrap, switcher::Switcher, Fps}; use alloc::collections::VecDeque; use alloc::string::String; use alloc::vec::Vec; use embedded_graphics::pixelcolor::Rgb565; #[cfg(target_arch = "riscv32")] use embedded_graphics::pixelcolor::RgbColor; use embedded_graphics::{ draw_target::DrawTarget, mono_font::{iso_8859_1::FONT_7X13, MonoTextStyle}, prelude::{Point, Size}, }; // ============================================================================ // Configuration // ============================================================================ /// Configuration for which debug overlays to enable #[derive(Clone, Copy, Debug, Default)] pub struct EnabledDebug { pub logs: bool, pub memory: bool, pub fps: bool, } impl EnabledDebug { pub const ALL: Self = Self { logs: true, memory: true, fps: true, }; pub const NONE: Self = Self { logs: false, memory: false, fps: false, }; } // ============================================================================ // Logging functionality // ============================================================================ static mut LOG_BUFFER: Option<VecDeque<String>> = None; static mut LOG_DIRTY: bool = false; static mut INITIAL_STACK_PTR: Option<usize> = None; /// Set the initial stack pointer (called by init_log_stack_pointer! macro) pub fn set_initial_stack_pointer(sp: usize) { unsafe { INITIAL_STACK_PTR = Some(sp); } } /// Get the initial stack pointer (used by log_stack! macro) pub fn get_initial_stack_pointer() -> Option<usize> { unsafe { INITIAL_STACK_PTR } } pub fn init_logging() { unsafe { LOG_BUFFER = Some(VecDeque::with_capacity(32)); LOG_DIRTY = false; } } pub fn log(msg: String) { unsafe { if let Some(ref mut buffer) = LOG_BUFFER { // Enforce capacity limit if buffer.len() == buffer.capacity() { buffer.pop_front(); } buffer.push_back(msg); LOG_DIRTY = true; } } } #[inline(never)] pub fn log_stack_usage(label: &str) { let stack_var = 0u32; let current_sp = &stack_var as *const _ as usize; unsafe { if let Some(initial_sp) = INITIAL_STACK_PTR { // Stack grows downward, so initial - current = bytes used let stack_used = initial_sp.saturating_sub(current_sp); log(alloc::format!("{}: {}", label, stack_used)); } } } // Font for logging - FONT_7X13 is monospace const FONT_HEIGHT: u32 = 13; const FONT_WIDTH: u32 = 7; pub struct DebugLogWidget { // Cache of formatted text widgets wrapped in expanded container display_cache: Container<Switcher<Column<Vec<Text<MonoTextStyle<'static, Rgb565>, StringWrap>>>>>, max_lines: usize, chars_per_line: usize, } impl Default for DebugLogWidget { fn default() -> Self { Self::new() } } impl DebugLogWidget { pub fn new() -> Self { // Create empty column let column = Column::new(Vec::new()); let switcher = Switcher::new(column); let container = Container::new(switcher).with_expanded(); Self { display_cache: container, max_lines: 0, chars_per_line: 0, } } fn rebuild_display(&mut self) { unsafe { if !LOG_DIRTY { return; } if let Some(ref mut buffer) = LOG_BUFFER { let mut text_widgets = Vec::new(); // Trim buffer to max_lines if needed if self.max_lines > 0 { while buffer.len() > self.max_lines { buffer.pop_front(); } } // Create text widgets for each log entry with line wrapping for msg in buffer.iter() { // Create StringWrap with line wrapping based on character width let wrapped = StringWrap::from_str(msg, self.chars_per_line); let text = Text::new_with( wrapped, MonoTextStyle::new(&FONT_7X13, PALETTE.text_secondary), ) .with_underline(PALETTE.on_background); text_widgets.push(text); } // Column with newest messages at bottom, aligned to left let column = Column::new(text_widgets) .with_main_axis_alignment(MainAxisAlignment::End) .with_cross_axis_alignment(CrossAxisAlignment::Start); self.display_cache.child.switch_to(column); LOG_DIRTY = false; } } } } impl Widget for DebugLogWidget { type Color = Rgb565; fn draw<D>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, current_time: Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { // Just delegate to the child - no screen clearing! self.rebuild_display(); self.display_cache.draw(target, current_time) } } impl DynWidget for DebugLogWidget { fn set_constraints(&mut self, max_size: Size) { // Calculate chars per line based on font width constant self.chars_per_line = (max_size.width / FONT_WIDTH) as usize; // Calculate max lines based on font height constant self.max_lines = (max_size.height / FONT_HEIGHT) as usize; // Update the display cache constraints self.display_cache.set_constraints(max_size); // Force rebuild with new constraints unsafe { LOG_DIRTY = true; } } fn sizing(&self) -> crate::Sizing { // Just return the display cache's sizing self.display_cache.sizing() } } // ============================================================================ // Memory indicator (only on RISC-V/ESP32) // ============================================================================ #[cfg(target_arch = "riscv32")] const MEM_TEXT_SIZE: usize = 13; // Size for "U:123456 F:123456" #[cfg(target_arch = "riscv32")] type MemText = Text<MonoTextStyle<'static, Rgb565>, crate::string_ext::StringFixed<MEM_TEXT_SIZE>>; /// Memory usage indicator component that polls esp_alloc directly #[cfg(target_arch = "riscv32")] pub struct MemoryIndicator { display: Container<Switcher<MemText>>, last_draw_time: Option<Instant>, } #[cfg(target_arch = "riscv32")] impl Default for MemoryIndicator { fn default() -> Self { Self::new() } } #[cfg(target_arch = "riscv32")] const MEM_TEXT_STYLE: MonoTextStyle<'static, Rgb565> = MonoTextStyle::new(&FONT_7X13, Rgb565::CYAN); #[cfg(target_arch = "riscv32")] impl MemoryIndicator { fn new() -> Self { let initial_text = Text::new_with( crate::string_ext::StringFixed::from_string("000000/000000"), MEM_TEXT_STYLE, ); let display = Container::new(Switcher::new(initial_text).with_shrink_to_fit()); Self { display, last_draw_time: None, } } } #[cfg(target_arch = "riscv32")] impl DynWidget for MemoryIndicator { fn set_constraints(&mut self, max_size: Size) { self.display.set_constraints(max_size); } fn sizing(&self) -> crate::Sizing { self.display.sizing() } fn force_full_redraw(&mut self) { self.display.force_full_redraw(); } fn handle_touch( &mut self, point: Point, current_time: Instant, is_release: bool, ) -> Option<crate::KeyTouch> { self.display.handle_touch(point, current_time, is_release) } fn handle_vertical_drag(&mut self, prev_y: Option<u32>, new_y: u32, is_release: bool) { self.display.handle_vertical_drag(prev_y, new_y, is_release); } } #[cfg(target_arch = "riscv32")] impl Widget for MemoryIndicator { type Color = Rgb565; fn draw<D: DrawTarget<Color = Self::Color>>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, current_time: Instant, ) -> Result<(), D::Error> { // Update every 500ms (same rate as FPS widget) let should_update = match self.last_draw_time { Some(last_time) => current_time.saturating_duration_since(last_time) >= 500, None => true, }; if should_update { self.last_draw_time = Some(current_time); // Get heap used and free from esp_alloc let used = esp_alloc::HEAP.used(); let free = esp_alloc::HEAP.free(); // Format the memory stats into StringBuffer use core::fmt::Write; let mut buf = crate::string_ext::StringFixed::<MEM_TEXT_SIZE>::new(); let _ = write!(&mut buf, "{}/{}", used, free); // Create a new text widget with the updated text let text_widget = Text::new_with(buf, MEM_TEXT_STYLE); self.display.child.switch_to(text_widget); } // Always draw the display (it handles its own dirty tracking) self.display.draw(target, current_time) } } // Stub type for when not on RISC-V #[cfg(not(target_arch = "riscv32"))] type MemoryIndicator = (); // ============================================================================ // OverlayDebug - Main overlay widget // ============================================================================ /// A widget that overlays debug info (stats and/or logging) on top of another widget pub struct OverlayDebug<W> where W: DynWidget, { // Outer stack with all the overlays outer_stack: Stack<( Stack<(W, Option<DebugLogWidget>)>, Option<Row<(Option<Fps>, Option<MemoryIndicator>)>>, )>, // Track current view index (0 = main, 1 = logs if enabled) current_index: usize, // Whether logs are enabled logs_enabled: bool, } impl<W> OverlayDebug<W> where W: Widget<Color = Rgb565>, { pub fn new(child: W, config: EnabledDebug) -> Self { // Create optional log widget let log_widget = if config.logs { init_logging(); Some(DebugLogWidget::new()) } else { None }; // Create indexed stack for main widget and optional log viewer let mut indexed_stack = Stack::builder().push(child).push(log_widget); indexed_stack.set_index(Some(0)); // Start showing main widget // Create optional FPS widget let fps_widget = if config.fps { Some(Fps::new(500)) } else { None }; // Create optional memory widget (only on RISC-V) #[cfg(target_arch = "riscv32")] let mem_widget = if config.memory { Some(MemoryIndicator::default()) } else { None }; #[cfg(not(target_arch = "riscv32"))] let mem_widget: Option<MemoryIndicator> = if config.memory { Some(()) } else { None }; // Create stats row if either FPS or memory is enabled let stats_row = if config.fps || config.memory { let row = Row::builder() .push(fps_widget) .gap(8) .push(mem_widget) .with_cross_axis_alignment(CrossAxisAlignment::Start) .with_main_axis_alignment(MainAxisAlignment::Center); Some(row) } else { None }; // Create outer stack with all overlays let outer_stack = Stack::builder() .push(indexed_stack) .push_aligned(stats_row, Alignment::TopLeft); Self { outer_stack, current_index: 0, logs_enabled: config.logs, } } /// Get mutable reference to the inner child widget pub fn inner_mut(&mut self) -> &mut W { &mut self.outer_stack.children.0.children.0 } /// Get reference to the inner child widget pub fn inner(&self) -> &W { &self.outer_stack.children.0.children.0 } /// Switch to showing the log view (no-op if logs not enabled) pub fn show_logs(&mut self) { if self.logs_enabled { self.current_index = 1; self.outer_stack.children.0.set_index(Some(1)); } } /// Switch to showing the main widget pub fn show_main(&mut self) { self.current_index = 0; self.outer_stack.children.0.set_index(Some(0)); } /// Toggle between main widget and log view (no-op if logs not enabled) pub fn toggle_view(&mut self) { if self.logs_enabled { if self.current_index == 0 { self.show_logs(); } else { self.show_main(); } } } } impl<W> DynWidget for OverlayDebug<W> where W: Widget<Color = Rgb565>, { fn set_constraints(&mut self, max_size: Size) { self.outer_stack.set_constraints(max_size); } fn sizing(&self) -> crate::Sizing { self.outer_stack.sizing() } fn handle_touch( &mut self, point: Point, current_time: Instant, is_release: bool, ) -> Option<crate::KeyTouch> { self.outer_stack .handle_touch(point, current_time, is_release) } fn handle_vertical_drag(&mut self, prev_y: Option<u32>, new_y: u32, is_release: bool) { self.outer_stack .handle_vertical_drag(prev_y, new_y, is_release) } fn force_full_redraw(&mut self) { self.outer_stack.force_full_redraw() } } impl<W> Widget for OverlayDebug<W> where W: Widget<Color = Rgb565>, { type Color = Rgb565; fn draw<D>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, current_time: Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { self.outer_stack.draw(target, current_time) } } // ============================================================================ // Macros for logging // ============================================================================ /// Initialize the stack pointer at the caller's location #[macro_export] macro_rules! init_log_stack_pointer { () => {{ // Capture stack pointer at the macro call site let stack_var = 0u32; let sp = &stack_var as *const _ as usize; $crate::debug::set_initial_stack_pointer(sp); }}; } /// Log current stack usage with file and line info #[macro_export] macro_rules! log_stack { (once) => {{ static mut LOGGED: bool = false; if unsafe { !LOGGED } { unsafe { LOGGED = true; } $crate::log_stack!(); } }}; () => { $crate::log!("{}:{}", file!().rsplit('/').next().unwrap_or(file!());, line!()) }; }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/bitcoin_amount_display.rs
frostsnap_widgets/src/bitcoin_amount_display.rs
use crate::DefaultTextStyle; use crate::{palette::PALETTE, prelude::*, rat::FatRat}; use alloc::string::ToString; use embedded_graphics::{geometry::Size, pixelcolor::Rgb565}; // Type alias to reduce complexity type BitcoinAmountRow = Row<( Text, // Whole part + decimal point Text, // First decimal digit Text, // Second decimal digit SizedBox<Rgb565>, // Half-width space Text, // Third decimal digit Text, // Fourth decimal digit Text, // Fifth decimal digit SizedBox<Rgb565>, // Half-width space Text, // Sixth decimal digit Text, // Seventh decimal digit Text, // Eighth decimal digit )>; /// A widget that displays a Bitcoin amount with proper formatting and coloring /// Displays in format: X.XX XXX XXX with half-width spaces between segments #[derive(frostsnap_macros::Widget)] pub struct BitcoinAmountDisplay { /// The row containing all elements - delegated by the derive macro #[widget_delegate] row: BitcoinAmountRow, /// Amount in satoshis (for reference) satoshis: u64, } impl BitcoinAmountDisplay { pub fn new(satoshis: u64) -> Self { let btc = FatRat::from_ratio(satoshis, 100_000_000); let amount_str = format!("{}.", btc.whole_part()); let mut color = PALETTE.text_disabled; if btc.whole_part() > 0 { color = PALETTE.primary; } let whole_text = Text::new(amount_str, DefaultTextStyle::new(crate::FONT_LARGE, color)); // Get decimal digits iterator (take only 8 for Bitcoin) let mut after_decimal = btc.decimal_digits().take(8).map(|digit| { if digit > 0 { color = PALETTE.primary; } Text::new( digit.to_string(), DefaultTextStyle::new(crate::FONT_LARGE, color), ) }); // Half-width spacers (approximately half the width of a digit) let spacer1 = SizedBox::<Rgb565>::new(Size::new(4, 1)); let spacer2 = SizedBox::<Rgb565>::new(Size::new(4, 1)); // Create row with all elements let row = Row::new(( whole_text, after_decimal.next().unwrap(), after_decimal.next().unwrap(), spacer1, after_decimal.next().unwrap(), after_decimal.next().unwrap(), after_decimal.next().unwrap(), spacer2, after_decimal.next().unwrap(), after_decimal.next().unwrap(), after_decimal.next().unwrap(), )); Self { row, satoshis } } pub fn satoshis(&self) -> u64 { self.satoshis } } // All trait implementations are now generated by the derive macro
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/hold_to_confirm.rs
frostsnap_widgets/src/hold_to_confirm.rs
use crate::{ circle_button::{CircleButton, CircleButtonState}, hold_to_confirm_border::HoldToConfirmBorder, palette::PALETTE, prelude::*, rat::Frac, Fader, }; use alloc::boxed::Box; use embedded_graphics::{ draw_target::DrawTarget, geometry::{Point, Size}, pixelcolor::Rgb565, }; /// A widget that combines HoldToConfirmBorder with a hand gesture icon and transitions to a checkmark pub struct HoldToConfirm<W> where W: Widget<Color = Rgb565>, { content: Box<HoldToConfirmBorder<Container<Center<Column<(W, Fader<CircleButton>)>>>, Rgb565>>, last_update: Option<crate::Instant>, hold_duration_ms: u32, completed: bool, } impl<W> HoldToConfirm<W> where W: Widget<Color = Rgb565>, { pub fn new(hold_duration_ms: u32, widget: W) -> Self { const BORDER_WIDTH: u32 = 5; // Create the circle button wrapped in a fader (starts visible by default) let button = CircleButton::new(); let faded_button = Fader::new(button); // Create column with the widget (flex) and faded button let column = Column::builder() .push(widget) .flex(1) .push(faded_button) .with_main_axis_alignment(MainAxisAlignment::SpaceBetween); // Center the column, then put it in an expanded container to fill available space let centered = Center::new(column); let content = Container::new(centered).with_expanded(); // Create the border with the actual content inside let border = Box::new(HoldToConfirmBorder::new( content, BORDER_WIDTH, PALETTE.confirm_progress, PALETTE.background, )); Self { content: border, last_update: None, hold_duration_ms, completed: false, } } /// Builder method to start with the button faded out pub fn with_faded_out_button(mut self) -> Self { self.button_fader_mut().set_faded_out(); self } /// Fade in the button pub fn fade_in_button(&mut self) { if self.button_fader_mut().is_faded_out() { self.button_fader_mut().start_fade_in(300); } } pub fn button_mut(&mut self) -> &mut CircleButton { &mut self.content.child.child.child.children.1.child } pub fn button(&self) -> &CircleButton { &self.content.child.child.child.children.1.child } fn button_fader_mut(&mut self) -> &mut Fader<CircleButton> { &mut self.content.child.child.child.children.1 } /// Get mutable access to the inner widget pub fn widget_mut(&mut self) -> &mut W { &mut self.content.child.child.child.children.0 } /// Get access to the inner widget pub fn widget(&self) -> &W { &self.content.child.child.child.children.0 } pub fn is_completed(&self) -> bool { self.button().state() == CircleButtonState::ShowingCheckmark } fn is_holding(&self) -> bool { self.button().state() == CircleButtonState::Pressed } fn update_progress(&mut self, current_time: crate::Instant) { let holding = self.is_holding(); let current_progress = self.content.get_progress(); // Early exit if not holding and no progress if !holding && current_progress == Frac::ZERO { self.last_update = None; // Clear last_update when fully released return; } if let Some(last_time) = self.last_update { let elapsed_ms = current_time.saturating_duration_since(last_time) as u32; if elapsed_ms == 0 { return; } if holding && !self.completed { let increment = Frac::from_ratio(elapsed_ms, self.hold_duration_ms); let new_progress = current_progress + increment; self.content.set_progress(new_progress); if new_progress >= Frac::ONE { self.completed = true; // Start fading out the border only self.content.start_fade_out(500); self.button_mut() .set_state(CircleButtonState::ShowingCheckmark); } } else if !holding && current_progress > Frac::ZERO && !self.completed { let decrement = Frac::from_ratio(elapsed_ms, 1000); let new_progress = current_progress - decrement; self.content.set_progress(new_progress); // If we've fully released, clear last_update if new_progress == Frac::ZERO { self.last_update = None; return; } } self.last_update = Some(current_time); } else if holding { // First frame of holding - just set the time, don't update progress yet self.last_update = Some(current_time); } } } impl<W> crate::DynWidget for HoldToConfirm<W> where W: Widget<Color = Rgb565>, { fn set_constraints(&mut self, max_size: Size) { self.content.set_constraints(max_size); } fn sizing(&self) -> crate::Sizing { self.content.sizing() } fn handle_touch( &mut self, point: Point, current_time: crate::Instant, is_release: bool, ) -> Option<crate::KeyTouch> { // Handle touch on the border (which will pass it to content) self.content.handle_touch(point, current_time, is_release) } fn handle_vertical_drag(&mut self, _prev_y: Option<u32>, _new_y: u32, _is_release: bool) {} fn force_full_redraw(&mut self) { self.content.force_full_redraw(); } } impl<W> Widget for HoldToConfirm<W> where W: Widget<Color = Rgb565>, { type Color = Rgb565; fn draw<D>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, current_time: crate::Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { if self.is_holding() || self.content.get_progress() > Frac::ZERO { self.update_progress(current_time); } // Draw the border (which includes the content) self.content.draw(target, current_time)?; if self.content.is_faded_out() && !self.button().checkmark().drawing_started() { self.button_mut().checkmark_mut().start_drawing() } Ok(()) } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/page_slider.rs
frostsnap_widgets/src/page_slider.rs
use crate::super_draw_target::SuperDrawTarget; use crate::{palette::PALETTE, prelude::*, Fader, SlideInTransition, SwipeUpChevron, WidgetList}; use alloc::boxed::Box; use embedded_graphics::{ draw_target::DrawTarget, geometry::{Point, Size}, pixelcolor::Rgb565, }; const ANIMATION_DURATION_MS: u64 = 750; const MIN_SWIPE_DISTANCE: u32 = 0; // Type aliases to reduce complexity type PageStack<T> = Stack<(SlideInTransition<T>, Option<Fader<SwipeUpChevron>>)>; type PageReadyCallback<T> = Box<dyn FnMut(&mut T)>; #[derive(Debug, Clone, Copy, PartialEq)] pub enum Direction { Up, Down, } /// A page slider that uses SlideInTransition for smooth page transitions pub struct PageSlider<L, T> where L: WidgetList<T>, T: Widget<Color = Rgb565>, { list: L, current_index: usize, stack: PageStack<T>, drag_start: Option<u32>, height: u32, on_page_ready: Option<PageReadyCallback<T>>, page_ready_triggered: bool, screen_size: Option<Size>, } impl<L, T> PageSlider<L, T> where L: WidgetList<T>, T: Widget<Color = Rgb565>, { pub fn new(list: L, height: u32) -> Self { // Get the initial widget (index 0) let initial_widget = list .get(0) .expect("PageSlider requires at least one widget in the list"); let transition = SlideInTransition::new( initial_widget, ANIMATION_DURATION_MS, Point::new(0, 0), // Start at rest position for initial widget PALETTE.background, ); // Build stack with transition and optional chevron aligned at bottom center let stack = Stack::builder() .push(transition) .push_aligned(None::<Fader<SwipeUpChevron>>, Alignment::BottomCenter); Self { list, current_index: 0, stack, drag_start: None, height, on_page_ready: None, page_ready_triggered: false, screen_size: None, } } /// Builder method to set a callback that's called when a page is ready (animation complete) pub fn with_on_page_ready<F>(mut self, callback: F) -> Self where F: FnMut(&mut T) + 'static, { self.on_page_ready = Some(Box::new(callback)); self } /// Builder method to enable swipe up chevron indicator pub fn with_swipe_up_chevron(mut self) -> Self { // Create chevron let chevron = SwipeUpChevron::new(PALETTE.on_surface, PALETTE.background); let fader = Fader::new_faded_out(chevron); // Set the chevron in the stack (it's already positioned with BottomCenter alignment) self.stack.children.1 = Some(fader); self } pub fn current_index(&self) -> usize { self.current_index } pub fn total_pages(&self) -> usize { self.list.len() } pub fn has_next(&self) -> bool { self.current_index + 1 < self.list.len() } pub fn has_prev(&self) -> bool { self.current_index > 0 } /// Get a reference to the current widget pub fn current_widget(&mut self) -> &mut T { self.stack.children.0.current_widget_mut() } pub fn start_transition(&mut self, direction: Direction) { // First check if navigation is allowed based on the current widget let current_widget = self.stack.children.0.current_widget_mut(); let allowed = match direction { Direction::Up => self.list.can_go_next(self.current_index, current_widget), Direction::Down => self.list.can_go_prev(self.current_index, current_widget), }; if !allowed { return; // Navigation blocked by the widget list } // Instantly fade out the chevron when starting a transition if let Some(ref mut chevron) = &mut self.stack.children.1 { chevron.instant_fade(); } // Calculate target index let target_index = match direction { Direction::Up => { if self.has_next() { self.current_index + 1 } else { return; // Can't go forward } } Direction::Down => { if self.has_prev() { self.current_index - 1 } else { return; // Can't go back } } }; // Get the new widget if let Some(new_widget) = self.list.get(target_index) { // Set slide direction based on height let height = self.height as i32; let slide_from = match direction { Direction::Up => Point::new(0, height), // Slide from bottom Direction::Down => Point::new(0, -height), // Slide from top }; // Update the slide-from position and switch to the new widget let transition = &mut self.stack.children.0; transition.set_slide_from(slide_from); transition.switch_to(new_widget); self.current_index = target_index; // Reset the ready flag for the new page self.page_ready_triggered = false; } } } impl<L, T> DynWidget for PageSlider<L, T> where L: WidgetList<T>, T: Widget<Color = Rgb565>, { fn set_constraints(&mut self, max_size: Size) { self.screen_size = Some(max_size); // Just propagate to the stack - it handles all positioning self.stack.set_constraints(max_size); } fn sizing(&self) -> crate::Sizing { self.stack.sizing() } fn handle_touch( &mut self, point: Point, current_time: Instant, is_release: bool, ) -> Option<crate::KeyTouch> { // Pass through to stack self.stack.handle_touch(point, current_time, is_release) } fn handle_vertical_drag(&mut self, _prev_y: Option<u32>, new_y: u32, is_release: bool) { if is_release { if let Some(drag_start) = self.drag_start.take() { // Determine swipe direction based on drag distance if new_y > drag_start + MIN_SWIPE_DISTANCE { // Swiped down - go to previous page self.start_transition(Direction::Down); } else if drag_start > new_y + MIN_SWIPE_DISTANCE { // Swiped up - go to next page self.start_transition(Direction::Up); } } } else { // Start tracking drag if self.drag_start.is_none() { self.drag_start = Some(new_y); } } } fn force_full_redraw(&mut self) { self.stack.force_full_redraw(); } } impl<L, T> Widget for PageSlider<L, T> where L: WidgetList<T>, T: Widget<Color = Rgb565>, { type Color = Rgb565; fn draw<D>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, current_time: crate::Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { // Check if transition is complete and trigger callback if not already triggered if !self.page_ready_triggered && self.stack.children.0.is_transition_complete() { self.page_ready_triggered = true; // Call the on_page_ready callback if set if let Some(ref mut callback) = self.on_page_ready { // Get mutable access to the current widget let current_widget = self.stack.children.0.current_widget_mut(); callback(current_widget); } // Fade in the swipe chevron if present if let Some(ref mut chevron) = &mut self.stack.children.1 { let current_widget = self.stack.children.0.current_widget_mut(); if self.list.can_go_next(self.current_index, current_widget) { chevron.start_fade_in(400); } } } // Draw the stack (it handles drawing both transition and chevron overlay) self.stack.draw(target, current_time) } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/translate.rs
frostsnap_widgets/src/translate.rs
use crate::{ animation_speed::AnimationSpeed, vec_framebuffer::VecFramebuffer, Frac, Instant, Widget, }; use embedded_graphics::{ draw_target::DrawTarget, geometry::{Dimensions, Point, Size}, pixelcolor::BinaryColor, primitives::Rectangle, Pixel, }; /// Translation direction for the translate widget #[derive(Clone, PartialEq, Debug)] enum TranslationDirection { /// Animating between rest and offset Animating { /// The offset point (either from or to depending on from_offset) offset: Point, /// Duration of the animation duration: u64, /// When the animation started start_time: Option<Instant>, /// If true, animating from offset to rest. If false, from rest to offset. from_offset: bool, }, /// No animation - idle at a specific offset Idle { offset: Point }, } /// A widget that animates its child by translating it across the screen #[derive(Clone, PartialEq)] pub struct Translate<W: Widget> { pub child: W, /// Current offset from original position current_offset: Point, /// Current translation direction translation_direction: TranslationDirection, /// Whether to repeat the animation (reversing direction each time) repeat: bool, /// Animation speed curve animation_speed: AnimationSpeed, /// Background color for erasing background_color: W::Color, /// Bitmap tracking previous frame's pixels previous_bitmap: VecFramebuffer<BinaryColor>, /// Bitmap tracking current frame's pixels current_bitmap: VecFramebuffer<BinaryColor>, /// Cached constraints constraints: Option<Size>, /// Offset of the dirty rect within the child's full area dirty_rect_offset: Point, /// The child's dirty rect (cached from set_constraints) child_dirty_rect: Rectangle, } impl<W: Widget> Translate<W> where W::Color: Copy, { pub fn new(child: W, background_color: W::Color) -> Self { // We'll initialize bitmaps when we get constraints Self { previous_bitmap: VecFramebuffer::new(0, 0), current_bitmap: VecFramebuffer::new(0, 0), child, current_offset: Point::zero(), translation_direction: TranslationDirection::Idle { offset: Point::zero(), }, repeat: false, animation_speed: AnimationSpeed::Linear, background_color, constraints: None, dirty_rect_offset: Point::zero(), child_dirty_rect: Rectangle::zero(), } } /// Set the animation speed curve pub fn set_animation_speed(&mut self, speed: AnimationSpeed) { self.animation_speed = speed; } /// Animate from an offset to the rest position (entrance animation) pub fn animate_from(&mut self, from: Point, duration: u64) { self.translation_direction = TranslationDirection::Animating { offset: from, duration, start_time: None, from_offset: true, }; } /// Animate from rest position to an offset (exit animation) pub fn animate_to(&mut self, to: Point, duration: u64) { self.translation_direction = TranslationDirection::Animating { offset: to, duration, start_time: None, from_offset: false, }; } /// Legacy method for backwards compatibility pub fn translate(&mut self, movement: Point, duration: u64) { // Treat this as animating from current position by movement amount self.animate_to(movement, duration); } /// Enable or disable repeat mode (animation reverses direction each cycle) pub fn set_repeat(&mut self, repeat: bool) { self.repeat = repeat; } /// Check if animation is complete pub fn is_idle(&self) -> bool { matches!( self.translation_direction, TranslationDirection::Idle { .. } ) } /// Calculate the current offset based on translation direction fn calculate_offset(&mut self, current_time: Instant) -> Point { match self.translation_direction.clone() { TranslationDirection::Animating { offset, duration, start_time, from_offset, } => { // Initialize start time if needed let start = start_time.unwrap_or(current_time); if start_time.is_none() { self.translation_direction = TranslationDirection::Animating { offset, duration, start_time: Some(current_time), from_offset, }; } let elapsed_ms = current_time.saturating_duration_since(start) as u32; if elapsed_ms >= duration as u32 { // Animation complete let final_position = if from_offset { Point::zero() // Ended at rest } else { offset // Ended at offset }; if self.repeat { // Flip direction self.translation_direction = TranslationDirection::Animating { offset, duration, start_time: Some(current_time), from_offset: !from_offset, // Flip the direction }; final_position } else { // Stop at final position self.translation_direction = TranslationDirection::Idle { offset: final_position, }; final_position } } else { // Animation in progress let linear_progress = Frac::from_ratio(elapsed_ms, duration as u32); let progress = self.animation_speed.apply(linear_progress); if from_offset { // Animating from offset to rest offset * (Frac::ONE - progress) } else { // Animating from rest to offset offset * progress } } } TranslationDirection::Idle { offset } => offset, } } } impl<W: Widget> crate::DynWidget for Translate<W> where W::Color: Copy, { fn set_constraints(&mut self, max_size: Size) { self.constraints = Some(max_size); self.child.set_constraints(max_size); // Use the child's dirty_rect if available, otherwise fall back to full sizing let child_sizing = self.child.sizing(); let dirty_rect = child_sizing.dirty_rect(); let (buffer_size, offset) = (dirty_rect.size, dirty_rect.top_left); self.dirty_rect_offset = offset; self.child_dirty_rect = dirty_rect; self.previous_bitmap = VecFramebuffer::new(buffer_size.width as usize, buffer_size.height as usize); self.current_bitmap = VecFramebuffer::new(buffer_size.width as usize, buffer_size.height as usize); } fn sizing(&self) -> crate::Sizing { self.child.sizing() } fn handle_touch( &mut self, point: Point, current_time: Instant, is_release: bool, ) -> Option<crate::KeyTouch> { // Adjust touch point for current offset let adjusted_point = point - self.current_offset; self.child .handle_touch(adjusted_point, current_time, is_release) } fn force_full_redraw(&mut self) { self.child.force_full_redraw(); } } impl<W: Widget> Widget for Translate<W> where W::Color: Copy, { type Color = W::Color; fn draw<D: DrawTarget<Color = Self::Color>>( &mut self, target: &mut crate::SuperDrawTarget<D, Self::Color>, current_time: Instant, ) -> Result<(), D::Error> { self.constraints.unwrap(); // Calculate the current offset (will initialize start time if needed) let offset = self.calculate_offset(current_time); // Handle offset change and bitmap tracking if offset != self.current_offset { self.child.force_full_redraw(); // Clear current bitmap for reuse self.current_bitmap.clear(BinaryColor::Off); // Calculate offset difference let diff_offset = offset - self.current_offset; // Create a translated SuperDrawTarget for the animation offset only let translated_target = target.clone().translate(offset); // Wrap it in TranslatorDrawTarget for pixel tracking // The TranslatorDrawTarget will handle converting screen coords to bitmap coords let translator = TranslatorDrawTarget { inner: translated_target, current_bitmap: &mut self.current_bitmap, previous_bitmap: &mut self.previous_bitmap, diff_offset, dirty_rect_offset: self.dirty_rect_offset, dirty_rect: self.child_dirty_rect, }; // Wrap the TranslatorDrawTarget in another SuperDrawTarget let mut outer_target = crate::SuperDrawTarget::new(translator, self.background_color); // Draw the child self.child.draw(&mut outer_target, current_time)?; // Clear any remaining pixels from the previous bitmap let dirty_rect_offset = self.dirty_rect_offset; let clear_pixels = self.previous_bitmap.on_pixels().map(|point| { // Translate bitmap coordinates to screen coordinates // First add the dirty_rect offset, then the current animation offset let screen_point = point + dirty_rect_offset + self.current_offset; Pixel(screen_point, self.background_color) }); target.draw_iter(clear_pixels)?; // Swap bitmaps core::mem::swap(&mut self.previous_bitmap, &mut self.current_bitmap); self.current_offset = offset; } else { // No movement - just draw normally with animation offset let mut translated_target = target.clone().translate(offset); self.child.draw(&mut translated_target, current_time)?; } Ok(()) } } /// A DrawTarget wrapper that tracks pixels for the translate animation struct TranslatorDrawTarget<'a, D, C> where D: DrawTarget<Color = C>, C: crate::WidgetColor, { inner: crate::SuperDrawTarget<D, C>, current_bitmap: &'a mut VecFramebuffer<BinaryColor>, previous_bitmap: &'a mut VecFramebuffer<BinaryColor>, diff_offset: Point, dirty_rect_offset: Point, dirty_rect: Rectangle, } impl<'a, D, C> DrawTarget for TranslatorDrawTarget<'a, D, C> where D: DrawTarget<Color = C>, C: crate::WidgetColor, { type Color = C; type Error = D::Error; fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error> where I: IntoIterator<Item = Pixel<Self::Color>>, { let current_bitmap = &mut self.current_bitmap; let previous_bitmap = &mut self.previous_bitmap; let diff_offset = self.diff_offset; let dirty_rect_offset = self.dirty_rect_offset; let dirty_rect = self.dirty_rect; self.inner.draw_iter( pixels .into_iter() .filter(move |Pixel(point, _)| { // Only draw pixels that are within the dirty_rect dirty_rect.contains(*point) }) .inspect(|Pixel(point, _color)| { // Convert screen coordinates to bitmap coordinates let bitmap_point = *point - dirty_rect_offset; // Mark this pixel as drawn in the current bitmap VecFramebuffer::<BinaryColor>::set_pixel( current_bitmap, bitmap_point, BinaryColor::On, ); // Clear this pixel from the previous bitmap (offset by diff_offset) let prev_bitmap_point = bitmap_point + diff_offset; VecFramebuffer::<BinaryColor>::set_pixel( previous_bitmap, prev_bitmap_point, BinaryColor::Off, ); }), ) } } impl<'a, D, C> Dimensions for TranslatorDrawTarget<'a, D, C> where D: DrawTarget<Color = C>, C: crate::WidgetColor, { fn bounding_box(&self) -> Rectangle { self.inner.bounding_box() } } #[cfg(test)] mod tests { use super::*; use crate::layout::SizedBox; use embedded_graphics::pixelcolor::{Rgb565, RgbColor}; #[test] fn test_is_idle() { let widget = SizedBox::<Rgb565>::new(Size::new(10, 10)); let mut translate = Translate::new(widget, Rgb565::BLACK); // Should be idle initially assert!(translate.is_idle()); // Start animation from offset translate.animate_from(Point::new(10, 0), 1000); // After calling animate_from, no longer idle assert!(!translate.is_idle()); } #[test] fn test_animate_from_and_to() { let widget = SizedBox::<Rgb565>::new(Size::new(10, 10)); let mut translate = Translate::new(widget, Rgb565::BLACK); // Test animate_from translate.animate_from(Point::new(0, 100), 1000); assert!(!translate.is_idle()); // Test animate_to translate.animate_to(Point::new(0, -100), 1000); assert!(!translate.is_idle()); } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/progress.rs
frostsnap_widgets/src/progress.rs
use crate::super_draw_target::SuperDrawTarget; use crate::DefaultTextStyle; use crate::{palette::PALETTE, Column, Frac, Switcher, Text as TextWidget, Widget, FONT_SMALL}; use alloc::format; use embedded_graphics::{ draw_target::DrawTarget, geometry::{Point, Size}, pixelcolor::Rgb565, primitives::{Primitive, PrimitiveStyle, PrimitiveStyleBuilder, Rectangle, RoundedRectangle}, text::Alignment, Drawable, }; /// A progress bar widget with a rounded rectangle (no text) pub struct ProgressBar { /// The current progress as a fraction (0.0 to 1.0) progress: Frac, /// Height of the progress bar bar_height: u32, /// Corner radius for the rounded rectangles corner_radius: u32, /// Padding from edges bar_rect: Option<Rectangle>, /// Last drawn filled width to track changes last_filled_width: Option<u32>, /// Whether background has been drawn background_drawn: bool, } impl ProgressBar { /// Create a new progress bar pub fn new() -> Self { Self { progress: Frac::ZERO, bar_height: 20, corner_radius: 10, bar_rect: None, last_filled_width: None, background_drawn: false, } } /// Create a new progress bar with custom dimensions pub fn with_dimensions(bar_height: u32, corner_radius: u32) -> Self { Self { progress: Frac::ZERO, bar_height, corner_radius, bar_rect: None, last_filled_width: None, background_drawn: false, } } /// Set the progress (0.0 to 1.0) pub fn set_progress(&mut self, progress: Frac) { self.progress = progress; } /// Get the current progress pub fn progress(&self) -> Frac { self.progress } } impl Default for ProgressBar { fn default() -> Self { Self::new() } } impl crate::DynWidget for ProgressBar { fn sizing(&self) -> crate::Sizing { self.bar_rect .expect("ProgressBar::sizing called before set_constraints") .size .into() } fn set_constraints(&mut self, max_size: Size) { self.bar_rect = Some(Rectangle::new( Point::new(0, 0), Size::new(max_size.width, self.bar_height), )); // Reset drawing state when constraints change self.background_drawn = false; self.last_filled_width = None; } fn force_full_redraw(&mut self) { self.background_drawn = false; self.last_filled_width = None; } } impl Widget for ProgressBar { type Color = Rgb565; fn draw<D: DrawTarget<Color = Self::Color>>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, _current_time: crate::Instant, ) -> Result<(), D::Error> { let bar_rect = self .bar_rect .expect("ProgressBar::draw called before set_constraints"); // Draw the background/border only if not already drawn if !self.background_drawn { let background_rect = RoundedRectangle::with_equal_corners( bar_rect, Size::new(self.corner_radius, self.corner_radius), ); let background_style = PrimitiveStyleBuilder::new() .stroke_color(PALETTE.outline) .stroke_width(2) .build(); background_rect.into_styled(background_style).draw(target)?; } // Calculate the filled width based on progress let filled_width = (self.progress * bar_rect.size.width).round().max(1); // Only redraw if the filled width has changed if self.last_filled_width != Some(filled_width) { // Clear the inside of the bar first (in case progress decreased) if let Some(last_width) = self.last_filled_width { if filled_width < last_width { // Clear the area that was previously filled let clear_rect = Rectangle::new( Point::new( bar_rect.top_left.x + 2 + filled_width as i32, bar_rect.top_left.y + 2, ), Size::new(last_width - filled_width, self.bar_height - 4), ); let clear_style = PrimitiveStyle::with_fill(PALETTE.background); clear_rect.into_styled(clear_style).draw(target)?; } } // Draw the filled progress rectangle (if there's any progress) if self.progress > Frac::ZERO && filled_width > 2 { // Account for the border width let fill_rect = RoundedRectangle::with_equal_corners( Rectangle::new( Point::new(bar_rect.top_left.x + 2, bar_rect.top_left.y + 2), Size::new(filled_width.saturating_sub(4), self.bar_height - 4), ), Size::new( self.corner_radius.saturating_sub(2), self.corner_radius.saturating_sub(2), ), ); let fill_style = PrimitiveStyle::with_fill(PALETTE.primary); fill_rect.into_styled(fill_style).draw(target)?; } self.last_filled_width = Some(filled_width); } Ok(()) } } /// A progress indicator widget with a progress bar and percentage text #[derive(frostsnap_macros::Widget)] pub struct ProgressIndicator { /// Column containing the progress bar, spacer, and text switcher #[widget_delegate] column: Column<(ProgressBar, Switcher<TextWidget>)>, /// Last percentage to track changes last_percentage: u32, } impl Default for ProgressIndicator { fn default() -> Self { Self::new() } } impl ProgressIndicator { /// Create a new progress indicator pub fn new() -> Self { let progress_bar = ProgressBar::new(); let initial_text = TextWidget::new( "00%", DefaultTextStyle::new(FONT_SMALL, PALETTE.on_background), ) .with_alignment(Alignment::Center); let text_switcher = Switcher::new(initial_text).with_shrink_to_fit(); let column = Column::builder() .push(progress_bar) .gap(8) .push(text_switcher); Self { column, last_percentage: 0, } } /// Set the progress (0.0 to 1.0) pub fn set_progress(&mut self, progress: Frac) { // Update progress bar self.column.children.0.set_progress(progress); // Update text if percentage changed let percentage = (progress * 100u32).round(); if percentage != self.last_percentage { self.last_percentage = percentage; let percentage_text = format!("{:02}%", percentage); let new_text = TextWidget::new( percentage_text, DefaultTextStyle::new(FONT_SMALL, PALETTE.on_background), ) .with_alignment(Alignment::Center); self.column.children.1.switch_to(new_text); } } /// Get the current progress pub fn progress(&self) -> Frac { self.column.children.0.progress() } } // All trait implementations are now generated by the derive macro
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/sign_message.rs
frostsnap_widgets/src/sign_message.rs
use crate::{ palette::PALETTE, prelude::*, string_ext::StringWrap, HoldToConfirm, Padding, FONT_MED, }; use crate::{DefaultTextStyle, HOLD_TO_CONFIRM_TIME_SHORT_MS, LEGACY_FONT_SMALL}; use alloc::string::String; use embedded_graphics::pixelcolor::Rgb565; use embedded_graphics::{geometry::Size, text::Alignment}; use u8g2_fonts::U8g2TextStyle; /// Hold to confirm widget for signing messages #[derive(frostsnap_macros::Widget)] pub struct SignMessageConfirm { #[widget_delegate] hold_to_confirm: HoldToConfirm<Column<(Text, Container<Padding<Text<U8g2TextStyle<Rgb565>>>>)>>, } impl SignMessageConfirm { pub fn new(message: String) -> Self { let title = Text::new( "Sign message?", DefaultTextStyle::new(FONT_MED, PALETTE.on_background), ) .with_alignment(Alignment::Center); let wrapped_message = StringWrap::from_str(&message, 23); let message_text = Text::new( wrapped_message.as_str(), U8g2TextStyle::new(LEGACY_FONT_SMALL, PALETTE.on_surface), ) .with_alignment(Alignment::Center); let message_with_padding = Padding::all(8, message_text); let message_container = Container::new(message_with_padding) .with_border(PALETTE.outline, 2) .with_fill(PALETTE.surface) .with_corner_radius(Size::new(8, 8)) .with_expanded(); let content = Column::new((title, message_container)) .with_main_axis_alignment(MainAxisAlignment::SpaceEvenly); let hold_to_confirm = HoldToConfirm::new(HOLD_TO_CONFIRM_TIME_SHORT_MS, content); Self { hold_to_confirm } } /// Check if the confirmation is complete pub fn is_confirmed(&self) -> bool { self.hold_to_confirm.is_completed() } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/widget_list.rs
frostsnap_widgets/src/widget_list.rs
/// A trait for providing a list of widgets by index pub trait WidgetList<T> { /// Returns the number of widgets in the list fn len(&self) -> usize; /// Returns the widget at the given index, or None if out of bounds fn get(&self, index: usize) -> Option<T>; /// Returns true if the list is empty fn is_empty(&self) -> bool { self.len() == 0 } /// Returns true if navigation to the next page is allowed from the current page fn can_go_next(&self, from_index: usize, _current_widget: &T) -> bool { from_index + 1 < self.len() } /// Returns true if navigation to the previous page is allowed from the current page fn can_go_prev(&self, from_index: usize, _current_widget: &T) -> bool { from_index > 0 } } // Implementation for Vec<T> where T is Clone impl<T> WidgetList<T> for alloc::vec::Vec<T> where T: Clone, { fn len(&self) -> usize { self.len() } fn get(&self, index: usize) -> Option<T> { <[T]>::get(self, index).cloned() } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/fader.rs
frostsnap_widgets/src/fader.rs
use super::{Frac, Widget}; use crate::animation_speed::AnimationSpeed; use crate::super_draw_target::SuperDrawTarget; use crate::widget_color::ColorInterpolate; use embedded_graphics::{ draw_target::DrawTarget, geometry::{Dimensions, Point, Size}, pixelcolor::Rgb565, primitives::Rectangle, Pixel, }; /// The current state of the fader #[derive(Debug, PartialEq)] enum FadeState { /// Not fading, widget draws normally Idle, /// Currently fading out FadingOut { start_time: Option<crate::Instant>, duration_ms: u64, }, /// Currently fading in FadingIn { start_time: Option<crate::Instant>, duration_ms: u64, }, /// Faded out completely (for new_faded_out) FadedOut, } /// A widget that can fade its child to a target color #[derive(Debug, PartialEq)] pub struct Fader<W> { pub child: W, state: FadeState, animation_speed: AnimationSpeed, constraints: Option<Size>, } impl<W: Widget<Color = Rgb565>> Fader<W> { pub fn new(child: W) -> Self { Self { child, state: FadeState::Idle, animation_speed: AnimationSpeed::Linear, constraints: None, } } /// Create a new Fader that doesn't draw anything until start_fade_in is called pub fn new_faded_out(child: W) -> Self { Self { child, state: FadeState::FadedOut, animation_speed: AnimationSpeed::Linear, constraints: None, } } /// Set the animation speed curve pub fn set_animation_speed(&mut self, speed: AnimationSpeed) { self.animation_speed = speed; } /// Start fading out over the specified duration /// This function is monotonic - it can only make fades happen faster, never slower pub fn start_fade(&mut self, duration_ms: u64) { // If already faded out, do nothing if matches!(self.state, FadeState::FadedOut) { return; } // Check if we're already fading out with a start time if let FadeState::FadingOut { start_time: Some(_), duration_ms: current_duration, } = &mut self.state { if duration_ms < *current_duration { // Update to shorter duration, keeping the same start time *current_duration = duration_ms; } // Either updated to shorter duration or keeping existing (if new would be longer) return; } // Starting a new fade out (or switching from fade in/idle to fade out) self.state = FadeState::FadingOut { start_time: None, // Will be set on first draw duration_ms, }; } /// Start fading in over the specified duration /// This function is monotonic - it can only make fades happen faster, never slower pub fn start_fade_in(&mut self, duration_ms: u64) { // If already fully visible (Idle state), do nothing if matches!(self.state, FadeState::Idle) { return; } // Check if we're already fading in with a start time if let FadeState::FadingIn { start_time: Some(_), duration_ms: current_duration, } = &mut self.state { if duration_ms < *current_duration { // Update to shorter duration, keeping the same start time *current_duration = duration_ms; } // Either updated to shorter duration or keeping existing (if new would be longer) return; } // Starting a new fade in (or switching from fade out/idle to fade in) self.state = FadeState::FadingIn { start_time: None, // Will be set on first draw duration_ms, }; } /// Stop fading pub fn stop_fade(&mut self) { self.state = FadeState::Idle; } pub fn instant_fade(&mut self) { self.start_fade(0); } /// Check if fading is complete pub fn is_fade_complete(&self) -> bool { matches!(&self.state, FadeState::Idle | FadeState::FadedOut) } /// Check if the widget is currently faded out pub fn is_faded_out(&self) -> bool { matches!(self.state, FadeState::FadedOut) } /// Set the fader to faded out state pub fn set_faded_out(&mut self) { self.state = FadeState::FadedOut; } /// Check if the widget is showing (not faded out and not fading out) pub fn is_not_faded(&self) -> bool { matches!(self.state, FadeState::Idle) } pub fn is_visible(&self) -> bool { self.is_not_faded() || self.is_fading_in() } pub fn is_fading(&self) -> bool { matches!( self.state, FadeState::FadingIn { .. } | FadeState::FadingOut { .. } ) } pub fn is_fading_in(&self) -> bool { matches!(self.state, FadeState::FadingIn { .. }) } } /// A custom DrawTarget that intercepts pixel drawing and applies fade pub struct FadingDrawTarget<'a, D> { pub target: &'a mut D, pub fade_progress: Frac, pub target_color: Rgb565, } impl<'a, D: DrawTarget<Color = Rgb565>> DrawTarget for FadingDrawTarget<'a, D> { type Color = Rgb565; type Error = D::Error; fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error> where I: IntoIterator<Item = Pixel<Self::Color>>, { // Cache with invalidation based on source color let mut cache: Option<(Rgb565, Rgb565)> = None; // (source_color, faded_color) let faded_pixels = pixels.into_iter().map(|Pixel(point, color)| { let faded_color = match cache { Some((cached_source, cached_result)) if cached_source == color => { // Cache hit - same source color cached_result } _ => { // Cache miss or first calculation let calculated = color.interpolate(self.target_color, self.fade_progress); cache = Some((color, calculated)); calculated } }; Pixel(point, faded_color) }); self.target.draw_iter(faded_pixels) } } impl<'a, D: DrawTarget<Color = Rgb565>> Dimensions for FadingDrawTarget<'a, D> { fn bounding_box(&self) -> Rectangle { self.target.bounding_box() } } impl<W: Widget<Color = Rgb565>> crate::DynWidget for Fader<W> { fn set_constraints(&mut self, max_size: Size) { self.constraints = Some(max_size); self.child.set_constraints(max_size); } fn sizing(&self) -> crate::Sizing { self.child.sizing() } fn handle_touch( &mut self, point: Point, current_time: crate::Instant, lift_up: bool, ) -> Option<crate::KeyTouch> { if !self.is_not_faded() { return None; } self.child.handle_touch(point, current_time, lift_up) } fn handle_vertical_drag(&mut self, prev_y: Option<u32>, new_y: u32, _is_release: bool) { if !self.is_not_faded() { return; } self.child.handle_vertical_drag(prev_y, new_y, _is_release); } fn force_full_redraw(&mut self) { self.child.force_full_redraw(); } } impl<W: Widget<Color = Rgb565>> Widget for Fader<W> { type Color = Rgb565; fn draw<D>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, current_time: crate::Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { match &mut self.state { FadeState::FadedOut => Ok(()), FadeState::Idle => self.child.draw(target, current_time), state => { // Extract common fields based on state let (start_time, duration_ms, is_fade_in) = match state { FadeState::FadingOut { start_time, duration_ms, } => (start_time, *duration_ms, false), FadeState::FadingIn { start_time, duration_ms, } => (start_time, *duration_ms, true), _ => unreachable!(), }; // Set start time on first draw if start_time.is_none() { *start_time = Some(current_time); } let actual_start_time = start_time.unwrap(); // Calculate fade progress using Frac (automatically clamped to [0, 1]) let elapsed = current_time.saturating_duration_since(actual_start_time) as u32; let linear_progress = Frac::from_ratio(elapsed, duration_ms as u32); let eased_progress = self.animation_speed.apply(linear_progress); // For fade-in, reverse the progress (1.0 -> 0.0) let fade_progress = if is_fade_in { Frac::ONE - eased_progress } else { eased_progress }; self.child.force_full_redraw(); // Use SuperDrawTarget's opacity method for fading let mut fading_target = target.clone().opacity(Frac::ONE - fade_progress); self.child.draw(&mut fading_target, current_time)?; // Check if fade is complete let is_complete = if is_fade_in { fade_progress == Frac::ZERO } else { fade_progress == Frac::ONE }; if is_complete { self.state = if is_fade_in { FadeState::Idle } else { FadeState::FadedOut }; } Ok(()) } } } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/firmware_upgrade.rs
frostsnap_widgets/src/firmware_upgrade.rs
use crate::DefaultTextStyle; use crate::HOLD_TO_CONFIRM_TIME_SHORT_MS; use crate::{ palette::PALETTE, prelude::*, HoldToConfirm, Padding, ProgressIndicator, FONT_MED, FONT_SMALL, }; use alloc::{boxed::Box, format}; use embedded_graphics::{geometry::Size, text::Alignment}; /// Hold to confirm widget for firmware upgrades /// Displays the firmware hash and size #[derive(frostsnap_macros::Widget)] pub struct FirmwareUpgradeConfirm { #[widget_delegate] hold_to_confirm: HoldToConfirm< Column<( Text, Container<Padding<Column<(Text, Text, Text, Text)>>>, Text, )>, >, } impl FirmwareUpgradeConfirm { pub fn new(firmware_digest: [u8; 32], size_bytes: u32) -> Self { // Format the full hash as 4 lines of 16 hex chars each let hash_line1 = format!( "{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}", firmware_digest[0], firmware_digest[1], firmware_digest[2], firmware_digest[3], firmware_digest[4], firmware_digest[5], firmware_digest[6], firmware_digest[7] ); let hash_line2 = format!( "{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}", firmware_digest[8], firmware_digest[9], firmware_digest[10], firmware_digest[11], firmware_digest[12], firmware_digest[13], firmware_digest[14], firmware_digest[15] ); let hash_line3 = format!( "{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}", firmware_digest[16], firmware_digest[17], firmware_digest[18], firmware_digest[19], firmware_digest[20], firmware_digest[21], firmware_digest[22], firmware_digest[23] ); let hash_line4 = format!( "{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}", firmware_digest[24], firmware_digest[25], firmware_digest[26], firmware_digest[27], firmware_digest[28], firmware_digest[29], firmware_digest[30], firmware_digest[31] ); // Format size in KB or MB let size_text = if size_bytes < 1024 * 1024 { format!("{} KB", size_bytes / 1024) } else { format!("{:.1} MB", size_bytes as f32 / (1024.0 * 1024.0)) }; // Create the content with title, hash lines, and size let title = Text::new( "Upgrade firmware?", DefaultTextStyle::new(FONT_MED, PALETTE.on_background), ) .with_alignment(Alignment::Center); let hash1 = Text::new( hash_line1, DefaultTextStyle::new(FONT_SMALL, PALETTE.on_surface), ) .with_alignment(Alignment::Center); let hash2 = Text::new( hash_line2, DefaultTextStyle::new(FONT_SMALL, PALETTE.on_surface), ) .with_alignment(Alignment::Center); let hash3 = Text::new( hash_line3, DefaultTextStyle::new(FONT_SMALL, PALETTE.on_surface), ) .with_alignment(Alignment::Center); let hash4 = Text::new( hash_line4, DefaultTextStyle::new(FONT_SMALL, PALETTE.on_surface), ) .with_alignment(Alignment::Center); let size = Text::new( size_text, DefaultTextStyle::new(FONT_SMALL, PALETTE.on_surface_variant), ) .with_alignment(Alignment::Center); // Put just the hash lines in a container with rounded border, fill, and padding let hash_column = Column::new((hash1, hash2, hash3, hash4)); let hash_with_padding = Padding::all(5, hash_column); let hash_container = Container::new(hash_with_padding) .with_border(PALETTE.outline, 2) .with_fill(PALETTE.surface) .with_corner_radius(Size::new(10, 10)); // Create main column with title, container, and size let content = Column::builder() .push(title) .gap(8) .push(hash_container) .gap(8) .push(size) .with_main_axis_alignment(MainAxisAlignment::SpaceEvenly); // Create hold to confirm with 1 second hold time let hold_to_confirm = HoldToConfirm::new(HOLD_TO_CONFIRM_TIME_SHORT_MS, content); Self { hold_to_confirm } } /// Check if the confirmation is complete pub fn is_confirmed(&self) -> bool { self.hold_to_confirm.is_completed() } } /// Widget for showing firmware upgrade progress #[derive(frostsnap_macros::Widget)] pub enum FirmwareUpgradeProgress { /// Actively erasing or downloading with progress Active { widget: Box<Column<(Text, Padding<ProgressIndicator>)>>, }, /// Passive state - just show text Passive { widget: Center<Text> }, } impl FirmwareUpgradeProgress { /// Create a new firmware upgrade progress widget in erasing state pub fn erasing(progress: f32) -> Self { let title = Text::new( "Preparing for\nupgrade...", DefaultTextStyle::new(FONT_MED, PALETTE.on_background), ) .with_alignment(Alignment::Center); let mut progress_indicator = ProgressIndicator::new(); progress_indicator.set_progress(crate::Frac::from_ratio((progress * 100.0) as u32, 100)); // Add horizontal padding around the progress indicator let padded_progress = Padding::symmetric(20, 0, progress_indicator); let widget = Column::new((title, padded_progress)) .with_main_axis_alignment(MainAxisAlignment::SpaceEvenly); Self::Active { widget: Box::new(widget), } } /// Create a new firmware upgrade progress widget in downloading state pub fn downloading(progress: f32) -> Self { let title = Text::new( "Downloading\nupgrade...", DefaultTextStyle::new(FONT_MED, PALETTE.on_background), ) .with_alignment(Alignment::Center); let mut progress_indicator = ProgressIndicator::new(); progress_indicator.set_progress(crate::Frac::from_ratio((progress * 100.0) as u32, 100)); // Add horizontal padding around the progress indicator let padded_progress = Padding::symmetric(20, 0, progress_indicator); let widget = Column::new((title, padded_progress)) .with_main_axis_alignment(MainAxisAlignment::SpaceEvenly); Self::Active { widget: Box::new(widget), } } /// Create a new firmware upgrade progress widget in passive state pub fn passive() -> Self { // Show "Firmware Upgrade" text in passive state let text = Text::new( "Firmware\nUpgrade", DefaultTextStyle::new(FONT_MED, PALETTE.primary), ) .with_alignment(Alignment::Center); let widget = Center::new(text); Self::Passive { widget } } /// Update the progress for active states pub fn update_progress(&mut self, progress: f32) { if let Self::Active { widget } = self { // Update the progress indicator through the padding wrapper widget .children .1 .child .set_progress(crate::Frac::from_ratio((progress * 100.0) as u32, 100)); } } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/fps.rs
frostsnap_widgets/src/fps.rs
use crate::super_draw_target::SuperDrawTarget; use crate::{ string_ext::StringFixed, Container, DynWidget, Instant, Switcher, Text as TextWidget, Widget, }; use core::fmt::Write; use embedded_graphics::{ draw_target::DrawTarget, geometry::{Point, Size}, mono_font::{iso_8859_1::FONT_7X13, MonoTextStyle}, pixelcolor::{Rgb565, RgbColor}, }; // Constants for FPS text dimensions - "FPS: 999" is max 8 chars const FPS_MAX_CHARS: usize = 3; type FpsDisplay = Container<Switcher<TextWidget<MonoTextStyle<'static, Rgb565>>>>; /// A widget that displays frames per second using simple frame counting pub struct Fps { display: FpsDisplay, frame_count: u32, last_fps_time: Option<Instant>, last_display_update: Option<Instant>, current_fps: u32, update_interval_ms: u64, } impl Fps { /// Create a new FPS counter widget with green text pub fn new(update_interval_ms: u64) -> Self { let text_style = MonoTextStyle::new(&FONT_7X13, Rgb565::GREEN); let text = TextWidget::new("000", text_style); let switcher = Switcher::new(text).with_shrink_to_fit(); let display = Container::new(switcher).with_border(Rgb565::RED, 2); Self { display, frame_count: 0, update_interval_ms, last_fps_time: None, last_display_update: None, current_fps: 0, } } } impl DynWidget for Fps { fn set_constraints(&mut self, max_size: Size) { self.display.set_constraints(max_size); } fn sizing(&self) -> crate::Sizing { self.display.sizing() } fn handle_touch( &mut self, _point: Point, _current_time: Instant, _is_release: bool, ) -> Option<crate::KeyTouch> { None } fn force_full_redraw(&mut self) { self.display.force_full_redraw(); } } impl Widget for Fps { type Color = Rgb565; fn draw<D>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, current_time: Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { // Count frames self.frame_count += 1; // Calculate FPS every second let should_calculate = match self.last_fps_time { Some(last_time) => { let elapsed = current_time.saturating_duration_since(last_time); elapsed >= 1000 } None => true, }; if should_calculate { if let Some(last_time) = self.last_fps_time { let elapsed_ms = current_time.saturating_duration_since(last_time); if elapsed_ms > 0 { // Calculate FPS: frames * 1000 / elapsed_ms let fps = (self.frame_count as u64 * 1000) / elapsed_ms; self.current_fps = fps as u32; } } // Reset counter for next second self.frame_count = 0; self.last_fps_time = Some(current_time); } // Update display at the configured interval let should_update_display = match self.last_display_update { Some(last_update) => { current_time.saturating_duration_since(last_update) >= self.update_interval_ms } None => true, }; if should_update_display { // Format and update the display let mut buf = StringFixed::<FPS_MAX_CHARS>::new(); write!(&mut buf, "{}", self.current_fps).ok(); // Create new text widget with updated text let text_style = MonoTextStyle::new(&FONT_7X13, Rgb565::GREEN); let text = TextWidget::new(buf.as_str(), text_style); self.display.child.switch_to(text); self.last_display_update = Some(current_time); } // Draw the display self.display.draw(target, current_time) } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/one_time_clear_hack.rs
frostsnap_widgets/src/one_time_clear_hack.rs
use crate::{ palette::PALETTE, DynWidget, Instant, KeyTouch, Sizing, SuperDrawTarget, Widget, WidgetColor, }; use core::ops::{Deref, DerefMut}; use embedded_graphics::{ draw_target::DrawTarget, geometry::{Point, Size}, pixelcolor::Rgb565, }; /// A temporary hack widget that clears the screen once before drawing its child #[derive(Debug)] pub struct OneTimeClearHack<W> { child: W, needs_clear: bool, } impl<W> OneTimeClearHack<W> { pub fn new(child: W) -> Self { Self { child, needs_clear: true, } } pub fn inner(&self) -> &W { &self.child } pub fn inner_mut(&mut self) -> &mut W { &mut self.child } } impl<W> Deref for OneTimeClearHack<W> { type Target = W; fn deref(&self) -> &Self::Target { &self.child } } impl<W> DerefMut for OneTimeClearHack<W> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.child } } impl<W> DynWidget for OneTimeClearHack<W> where W: DynWidget, { fn set_constraints(&mut self, max_size: Size) { self.child.set_constraints(max_size); } fn sizing(&self) -> Sizing { self.child.sizing() } fn handle_touch( &mut self, point: Point, current_time: Instant, is_release: bool, ) -> Option<KeyTouch> { self.child.handle_touch(point, current_time, is_release) } fn handle_vertical_drag(&mut self, start_y: Option<u32>, current_y: u32, is_release: bool) { self.child .handle_vertical_drag(start_y, current_y, is_release); } fn force_full_redraw(&mut self) { self.needs_clear = true; self.child.force_full_redraw(); } } impl<W> Widget for OneTimeClearHack<W> where W: Widget, W::Color: WidgetColor + From<Rgb565>, { type Color = W::Color; fn draw<D>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, current_time: Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { // Clear the screen once if needed if self.needs_clear { target.clear(PALETTE.background.into())?; self.needs_clear = false; } // Draw the child self.child.draw(target, current_time) } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/string_ext.rs
frostsnap_widgets/src/string_ext.rs
use alloc::string::String; use core::fmt::{self, Display, Write}; /// A fixed-size string that doesn't allocate /// Useful for formatting strings in no_std environments without allocations #[derive(Clone, Copy)] pub struct StringFixed<const N: usize> { buf: [u8; N], len: usize, characters_per_row: usize, last_newline: usize, } impl<const N: usize> StringFixed<N> { pub fn new() -> Self { Self { buf: [0; N], len: 0, characters_per_row: usize::MAX, last_newline: 0, } } pub fn with_wrap(characters_per_row: usize) -> Self { Self { buf: [0; N], len: 0, characters_per_row, last_newline: 0, } } pub fn from_string(s: &str) -> Self { let mut buffer = Self::new(); let _ = buffer.write_str(s); buffer } pub fn as_str(&self) -> &str { core::str::from_utf8(&self.buf[..self.len]).unwrap_or("") } pub fn clear(&mut self) { self.len = 0; self.last_newline = 0; } pub fn len(&self) -> usize { self.len } pub fn is_empty(&self) -> bool { self.len == 0 } pub fn add_char(&mut self, ch: u8) -> Option<()> { if self.last_newline >= self.characters_per_row && self.characters_per_row > 0 { *self.buf.get_mut(self.len)? = b'\n'; self.len += 1; self.last_newline = 0; } if self.len > 0 && self.buf[self.len - 1] == b'\n' { self.last_newline = 0; } *self.buf.get_mut(self.len)? = ch; self.len += 1; self.last_newline += 1; Some(()) } } impl<const N: usize> Write for StringFixed<N> { fn write_str(&mut self, s: &str) -> core::fmt::Result { for byte in s.as_bytes() { if self.add_char(*byte).is_none() { break; } } Ok(()) } fn write_char(&mut self, c: char) -> core::fmt::Result { if let Ok(ch) = c.try_into() { self.add_char(ch); } else { self.add_char(b'?'); } Ok(()) } } impl<const N: usize> Default for StringFixed<N> { fn default() -> Self { Self::new() } } impl<const N: usize> Display for StringFixed<N> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(self.as_str()) } } impl<const N: usize> AsRef<str> for StringFixed<N> { fn as_ref(&self) -> &str { self.as_str() } } impl<const N: usize> PartialEq for StringFixed<N> { fn eq(&self, other: &Self) -> bool { self.as_str() == other.as_str() } } impl<const N: usize> Eq for StringFixed<N> {} impl<const N: usize> PartialEq<str> for StringFixed<N> { fn eq(&self, other: &str) -> bool { self.as_str() == other } } impl<const N: usize> PartialEq<&str> for StringFixed<N> { fn eq(&self, other: &&str) -> bool { self.as_str() == *other } } /// A dynamic string with line wrapping support /// Unlike StringFixed, this allocates and can grow as needed #[derive(Clone)] pub struct StringWrap { buf: String, characters_per_row: usize, last_newline: usize, } impl Default for StringWrap { fn default() -> Self { Self::new() } } impl StringWrap { pub fn new() -> Self { Self { buf: String::new(), characters_per_row: usize::MAX, last_newline: 0, } } pub fn with_wrap(characters_per_row: usize) -> Self { Self { buf: String::new(), characters_per_row, last_newline: 0, } } pub fn from_str(s: &str, characters_per_row: usize) -> Self { let mut wrapped = Self::with_wrap(characters_per_row); let _ = wrapped.write_str(s); wrapped } pub fn as_str(&self) -> &str { &self.buf } pub fn clear(&mut self) { self.buf.clear(); self.last_newline = 0; } pub fn len(&self) -> usize { self.buf.len() } pub fn is_empty(&self) -> bool { self.buf.is_empty() } fn add_char(&mut self, ch: char) { // Add newline if we've reached the character limit for this row if self.last_newline >= self.characters_per_row && self.characters_per_row > 0 { self.buf.push('\n'); self.last_newline = 0; } // Reset newline counter if we just added a newline if !self.buf.is_empty() && self.buf.ends_with('\n') { self.last_newline = 0; } self.buf.push(ch); self.last_newline += 1; } } impl Write for StringWrap { fn write_str(&mut self, s: &str) -> core::fmt::Result { for ch in s.chars() { self.add_char(ch); } Ok(()) } } impl Display for StringWrap { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(self.as_str()) } } impl AsRef<str> for StringWrap { fn as_ref(&self) -> &str { self.as_str() } } impl From<StringWrap> for String { fn from(wrapped: StringWrap) -> Self { wrapped.buf } } impl From<&StringWrap> for String { fn from(wrapped: &StringWrap) -> Self { wrapped.buf.clone() } } impl<const N: usize> fmt::Debug for StringFixed<N> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "StringFixed(\"{}\")", self.as_str()) } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/slide_in_transition.rs
frostsnap_widgets/src/slide_in_transition.rs
use crate::super_draw_target::SuperDrawTarget; use crate::{ animation_speed::AnimationSpeed, fader::Fader, translate::Translate, DynWidget, Instant, Widget, }; use core::mem; use embedded_graphics::{ draw_target::DrawTarget, geometry::{Point, Size}, pixelcolor::Rgb565, }; /// A transition widget that slides in a new widget while fading in /// The previous widget is efficiently cleared by Translate's pixel tracking /// Currently only supports Rgb565 due to Fader limitations pub struct SlideInTransition<T: Widget<Color = Rgb565>> { current: Option<Fader<Translate<T>>>, old: Option<Fader<Translate<T>>>, // Keep old widget for one frame to fade out transition_duration_ms: u64, slide_from_position: Point, bg_color: Rgb565, constraints: Option<Size>, } impl<T: Widget<Color = Rgb565>> SlideInTransition<T> { /// Create a new slide-in transition /// - initial: The initial widget to display /// - transition_duration_ms: How long the transition takes /// - slide_from_position: Where the widget slides in FROM (e.g., Point::new(0, 100) to slide up from bottom) /// - bg_color: Background color to use when clearing previous widget pub fn new( initial: T, transition_duration_ms: u64, slide_from_position: Point, bg_color: Rgb565, ) -> Self { let mut self_ = Self { current: None, old: None, transition_duration_ms, slide_from_position, bg_color, constraints: None, }; self_.switch_to(initial); self_ } /// Set the slide-from position for the next transition pub fn set_slide_from(&mut self, position: Point) { self.slide_from_position = position; } /// Get mutable access to the current widget if available pub fn current_widget_mut(&mut self) -> &mut T { &mut self.current.as_mut().unwrap().child.child } /// Check if the transition animation is complete pub fn is_transition_complete(&self) -> bool { // Check if current widget exists and its animation is complete if let Some(ref current) = self.current { // The transition is complete when: // 1. The fader is visible (fade-in complete) // 2. The translate animation is idle (slide complete) if current.is_visible() { // Access the translate widget inside the fader current.child.is_idle() } else { false } } else { true // No transition in progress } } /// Switch to a new widget with slide-in transition pub fn switch_to(&mut self, widget: T) { // Create translate widget and start the slide animation from the offset let mut new_translate = Translate::new(widget, self.bg_color); new_translate.set_animation_speed(AnimationSpeed::EaseOut); new_translate.animate_from(self.slide_from_position, self.transition_duration_ms); // Create new fader with fade starting let mut new_fader = Fader::new_faded_out(new_translate); new_fader.set_animation_speed(AnimationSpeed::EaseOut); // If we have constraints, propagate them to the new widget if let Some(constraints) = self.constraints { new_fader.set_constraints(constraints); } // Use mem::replace to swap in the new widget and get the old one if let Some(old) = self.current.as_mut() { let mut old_fader = mem::replace(old, new_fader); // we don't want to write over self.old unless the current one has actually been drawn if old_fader.is_visible() { old_fader.instant_fade(); self.old = Some(old_fader); } } else { self.current = Some(new_fader); } } } impl<T: Widget<Color = Rgb565>> DynWidget for SlideInTransition<T> { fn set_constraints(&mut self, max_size: Size) { self.constraints = Some(max_size); // Propagate constraints to current and old widgets if let Some(ref mut current) = self.current { current.set_constraints(max_size); } if let Some(ref mut old) = self.old { old.set_constraints(max_size); } } fn sizing(&self) -> crate::Sizing { // Return the sizing of the current widget if available if let Some(ref current) = self.current { current.sizing() } else { // If no current widget, return the constraint size or zero self.constraints.unwrap_or(Size::zero()).into() } } fn handle_touch( &mut self, point: Point, current_time: Instant, is_release: bool, ) -> Option<crate::KeyTouch> { self.current .as_mut() .and_then(|w| w.handle_touch(point, current_time, is_release)) } fn handle_vertical_drag(&mut self, prev_y: Option<u32>, new_y: u32, is_release: bool) { if let Some(ref mut current) = self.current { current.handle_vertical_drag(prev_y, new_y, is_release); } } fn force_full_redraw(&mut self) { if let Some(ref mut current) = self.current { current.force_full_redraw(); } } } impl<T: Widget<Color = Rgb565>> Widget for SlideInTransition<T> { type Color = Rgb565; fn draw<D>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, current_time: crate::Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { self.constraints.unwrap(); // Draw old widget once to let it fade out (clear pixels) if let Some(ref mut old) = self.old { old.draw(target, current_time)?; if old.is_faded_out() { self.old = None; } else { // this should never happen but just in case return Ok(()); } } if let Some(ref mut current) = self.current { if current.is_faded_out() { current.start_fade_in(self.transition_duration_ms); } current.draw(target, current_time)?; } Ok(()) } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/super_draw_target.rs
frostsnap_widgets/src/super_draw_target.rs
use crate::Frac; use alloc::rc::Rc; use core::cell::{RefCell, RefMut}; use embedded_graphics::prelude::*; use embedded_graphics::primitives::Rectangle; pub struct SuperDrawTarget<D, C = <D as DrawTarget>::Color> where D: DrawTarget<Color = C>, C: crate::WidgetColor, { display: Rc<RefCell<D>>, crop_area: Rectangle, opacity: Frac, background_color: C, } impl<D, C> SuperDrawTarget<D, C> where D: DrawTarget<Color = C>, C: crate::WidgetColor, { pub fn new(display: D, background_color: C) -> Self { let crop_area = display.bounding_box(); Self { display: Rc::new(RefCell::new(display)), crop_area, opacity: Frac::ONE, background_color, } } pub fn from_shared(display: Rc<RefCell<D>>, background_color: C) -> Self { let crop_area = display.borrow().bounding_box(); Self { display, crop_area, opacity: Frac::ONE, background_color, } } pub fn crop(mut self, area: Rectangle) -> Self { // When applying a crop, we translate the area relative to existing crop let mut translated = area; translated.top_left += self.crop_area.top_left; self.crop_area = translated; self } pub fn opacity(mut self, opacity: Frac) -> Self { // Multiply opacities to correctly handle nested transparency. // If a parent widget has 0.5 opacity and a child has 0.5 opacity, // the child should appear at 0.25 opacity (0.5 * 0.5), not 0.5. self.opacity = self.opacity * opacity; self } pub fn translate(mut self, offset: Point) -> Self { self.crop_area.top_left += offset; self } pub fn inner_mut(&mut self) -> Option<RefMut<'_, D>> { // Only return mutable reference if we're the only holder if Rc::strong_count(&self.display) == 1 { Some(self.display.borrow_mut()) } else { None } } pub fn background_color(&self) -> C { self.background_color } pub fn with_background_color(mut self, new_background_color: C) -> Self { // Interpolate the new background toward the existing background based on opacity. // This ensures child widgets (e.g., Text with anti-aliased fonts) blend against // the correct effective background color after opacity is applied. // Without this, text would blend against the raw background color, but pixels // would then be faded toward a different background, causing visible artifacts. self.background_color = self .background_color .interpolate(new_background_color, self.opacity); self } /// Clear an area with the background color pub fn clear_area(&mut self, area: &Rectangle) -> Result<(), D::Error> { self.fill_solid(area, self.background_color) } } impl<D, C> Clone for SuperDrawTarget<D, C> where D: DrawTarget<Color = C>, C: crate::WidgetColor, { fn clone(&self) -> Self { Self { display: Rc::clone(&self.display), crop_area: self.crop_area, opacity: self.opacity, background_color: self.background_color, } } } impl<D, C> DrawTarget for SuperDrawTarget<D, C> where D: DrawTarget<Color = C>, C: crate::WidgetColor, { type Color = C; type Error = D::Error; fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error> where I: IntoIterator<Item = Pixel<Self::Color>>, { let mut display = self.display.borrow_mut(); let crop = self.crop_area; if self.opacity < Frac::ONE { // Cache with invalidation based on source color let mut cache: Option<(C, C)> = None; // (source_color, interpolated_color) let pixels = pixels.into_iter().map(|Pixel(point, color)| { let translated_point = point + crop.top_left; let final_color = match cache { Some((cached_source, cached_result)) if cached_source == color => { // Cache hit - same source color cached_result } _ => { // Cache miss or first calculation let calculated = self.background_color.interpolate(color, self.opacity); cache = Some((color, calculated)); calculated } }; Pixel(translated_point, final_color) }); display.draw_iter(pixels) } else { // Just translate points let pixels = pixels.into_iter().map(|Pixel(point, color)| { let translated_point = point + crop.top_left; Pixel(translated_point, color) }); display.draw_iter(pixels) } } fn fill_contiguous<I>(&mut self, area: &Rectangle, colors: I) -> Result<(), Self::Error> where I: IntoIterator<Item = Self::Color>, { let mut display = self.display.borrow_mut(); let mut translated_area = *area; translated_area.top_left += self.crop_area.top_left; if self.opacity < Frac::ONE { // Cache with invalidation based on source color let mut cache: Option<(C, C)> = None; // (source_color, interpolated_color) let colors = colors.into_iter().map(|color| { match cache { Some((cached_source, cached_result)) if cached_source == color => { // Cache hit - same source color cached_result } _ => { // Cache miss or first calculation let calculated = self.background_color.interpolate(color, self.opacity); cache = Some((color, calculated)); calculated } } }); display.fill_contiguous(&translated_area, colors) } else { display.fill_contiguous(&translated_area, colors) } } fn fill_solid(&mut self, area: &Rectangle, color: Self::Color) -> Result<(), Self::Error> { let mut display = self.display.borrow_mut(); let final_color = if self.opacity < Frac::ONE { self.background_color.interpolate(color, self.opacity) } else { color }; let mut translated_area = *area; translated_area.top_left += self.crop_area.top_left; display.fill_solid(&translated_area, final_color) } fn clear(&mut self, color: Self::Color) -> Result<(), Self::Error> { let mut display = self.display.borrow_mut(); let final_color = if self.opacity < Frac::ONE { self.background_color.interpolate(color, self.opacity) } else { color }; // When clearing with a crop, we fill the crop area display.fill_solid(&self.crop_area, final_color) } } impl<D, C> Dimensions for SuperDrawTarget<D, C> where D: DrawTarget<Color = C>, C: crate::WidgetColor, { fn bounding_box(&self) -> Rectangle { // Return the crop area but with top_left at origin since that's what the widget sees Rectangle::new(Point::zero(), self.crop_area.size) } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/touch_listener.rs
frostsnap_widgets/src/touch_listener.rs
use crate::{DynWidget, Instant, Key, KeyTouch, Sizing, SuperDrawTarget, Widget}; use embedded_graphics::{ draw_target::DrawTarget, geometry::{Point, Size}, primitives::Rectangle, }; /// A widget that listens for touch events and converts them to KeyTouch events pub struct TouchListener<W> { pub child: W, on_touch: fn(Point, Instant, bool, &mut W) -> Option<Key>, sizing: Option<Sizing>, } impl<W> TouchListener<W> { /// Create a new TouchListener that wraps a child widget pub fn new(child: W, on_touch: fn(Point, Instant, bool, &mut W) -> Option<Key>) -> Self { Self { child, on_touch, sizing: None, } } } impl<W> DynWidget for TouchListener<W> where W: DynWidget, { fn set_constraints(&mut self, max_size: Size) { self.child.set_constraints(max_size); self.sizing = Some(self.child.sizing()); } fn sizing(&self) -> Sizing { self.sizing .expect("set_constraints must be called before sizing") } fn handle_touch( &mut self, point: Point, current_time: Instant, is_release: bool, ) -> Option<KeyTouch> { // Call our handler with the child if let Some(key) = (self.on_touch)(point, current_time, is_release, &mut self.child) { // Create the KeyTouch with our bounds let bounds = Rectangle::new(Point::zero(), self.sizing.unwrap().into()); Some(KeyTouch::new(key, bounds)) } else { // Also pass through to child in case it has its own handling self.child.handle_touch(point, current_time, is_release) } } fn handle_vertical_drag(&mut self, start_y: Option<u32>, current_y: u32, is_release: bool) { self.child .handle_vertical_drag(start_y, current_y, is_release); } fn force_full_redraw(&mut self) { self.child.force_full_redraw(); } } impl<W> Widget for TouchListener<W> where W: Widget, { type Color = W::Color; fn draw<D>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, current_time: Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { self.child.draw(target, current_time) } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/swipe_up_chevron.rs
frostsnap_widgets/src/swipe_up_chevron.rs
use crate::DefaultTextStyle; use crate::{bobbing_carat::BobbingCarat, text::Text, Column, FONT_SMALL}; use embedded_graphics::pixelcolor::Rgb565; use frostsnap_macros::Widget; // Since Gray4TextStyle only works with Rgb565, we now specialize SwipeUpChevron for Rgb565 #[derive(Widget)] pub struct SwipeUpChevron { column: Column<(BobbingCarat<Rgb565>, Text)>, } impl SwipeUpChevron { pub fn new(color: Rgb565, background_color: Rgb565) -> Self { let bobbing_carat = BobbingCarat::new(color, background_color); let text = Text::new("Swipe up", DefaultTextStyle::new(FONT_SMALL, color)); let column = Column::new((bobbing_carat, text)); Self { column } } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/gray4_style.rs
frostsnap_widgets/src/gray4_style.rs
use embedded_graphics::{ draw_target::DrawTarget, geometry::{Point, Size}, pixelcolor::{GrayColor, Rgb565, RgbColor}, primitives::{Line, Primitive, PrimitiveStyle, Rectangle}, text::{ renderer::{CharacterStyle, TextMetrics, TextRenderer}, Baseline, DecorationColor, }, Drawable, Pixel, }; /// Gray4TextStyle - implements embedded_graphics TextRenderer for Gray4 fonts use frostsnap_fonts::{GlyphInfo, Gray4Font}; /// Pre-calculated color cache for all 16 gray levels #[derive(Clone, Copy, Debug, PartialEq)] struct ColorCache { colors: [Rgb565; 16], } impl ColorCache { /// Create a new color cache with pre-blended colors fn new(text_color: Rgb565, background_color: Rgb565) -> Self { let mut colors = [Rgb565::BLACK; 16]; for (i, color) in colors.iter_mut().enumerate() { *color = Self::blend_color(i as u8, text_color, background_color); } Self { colors } } /// Blend color with alpha for anti-aliasing fn blend_color(alpha: u8, text_color: Rgb565, background_color: Rgb565) -> Rgb565 { use crate::{ColorInterpolate, Frac}; // Convert alpha (0-15) to Frac (0.0-1.0) for interpolation let alpha_frac = Frac::from_ratio(alpha as u32, 15); // Interpolate from background to text color background_color.interpolate(text_color, alpha_frac) } } /// Text style for Gray4 fonts that implements TextRenderer #[derive(Clone)] pub struct Gray4TextStyle { /// The Gray4 font to use pub font: &'static Gray4Font, /// Pre-cached colors for all 16 gray levels color_cache: ColorCache, /// Background color used for alpha blending background_color: Rgb565, /// Text color (needed for CharacterStyle::set_text_color) text_color: Rgb565, /// Underline color and thickness underline_color: DecorationColor<Rgb565>, /// Strikethrough color and thickness strikethrough_color: DecorationColor<Rgb565>, } impl Gray4TextStyle { /// Create a new Gray4TextStyle with the given font and text color /// Defaults to black background for alpha blending pub fn new(font: &'static Gray4Font, text_color: Rgb565) -> Self { Self { font, color_cache: ColorCache::new(text_color, Rgb565::BLACK), background_color: Rgb565::BLACK, text_color, underline_color: DecorationColor::None, strikethrough_color: DecorationColor::None, } } /// Set the underline color pub fn with_underline_color(mut self, underline_color: DecorationColor<Rgb565>) -> Self { self.underline_color = underline_color; self } /// Draw a single glyph with anti-aliasing fn draw_glyph<D>( &self, position: Point, glyph: &GlyphInfo, target: &mut D, ) -> Result<(), D::Error> where D: DrawTarget<Color = Rgb565>, { // Calculate glyph position with bearing offsets let draw_x = position.x + glyph.x_offset as i32; let draw_y = position.y + glyph.y_offset as i32; // Get iterator of pixels and map Gray4 to Rgb565 with correct position let pixels = self.font.glyph_pixels(glyph).map(|Pixel(point, gray)| { let color = self.color_cache.colors[gray.luma() as usize]; Pixel(Point::new(draw_x + point.x, draw_y + point.y), color) }); // Draw all pixels in one call target.draw_iter(pixels) } } impl TextRenderer for Gray4TextStyle { type Color = Rgb565; fn draw_string<D>( &self, text: &str, position: Point, baseline: Baseline, target: &mut D, ) -> Result<Point, D::Error> where D: DrawTarget<Color = Self::Color>, { let y_offset = match baseline { Baseline::Top => 0, Baseline::Bottom => -(self.font.line_height as i32), Baseline::Middle => -(self.font.line_height as i32 / 2), Baseline::Alphabetic => -(self.font.baseline as i32), }; let mut x = position.x; let y = position.y + y_offset; for ch in text.chars() { if let Some(glyph) = self.font.get_glyph(ch) { self.draw_glyph(Point::new(x, y), glyph, target)?; x += glyph.x_advance as i32; } else if ch == ' ' { // Space character x += (self.font.line_height / 4) as i32; } else { // Unknown character - use placeholder width x += (self.font.line_height / 3) as i32; } } // Underline match self.underline_color { DecorationColor::None => {} DecorationColor::TextColor => { let underline_y = y + self.font.baseline as i32 + 2; Line::new( Point::new(position.x, underline_y), Point::new(x, underline_y), ) .into_styled(PrimitiveStyle::with_stroke(self.text_color, 1)) .draw(target)?; } DecorationColor::Custom(color) => { let underline_y = y + self.font.baseline as i32 + 2; Line::new( Point::new(position.x, underline_y), Point::new(x, underline_y), ) .into_styled(PrimitiveStyle::with_stroke(color, 1)) .draw(target)?; } } // Strikethrough match self.strikethrough_color { DecorationColor::None => {} DecorationColor::TextColor => { let strikethrough_y = y + (self.font.line_height as i32) / 2; Line::new( Point::new(position.x, strikethrough_y), Point::new(x, strikethrough_y), ) .into_styled(PrimitiveStyle::with_stroke(self.text_color, 1)) .draw(target)?; } DecorationColor::Custom(color) => { let strikethrough_y = y + (self.font.line_height as i32) / 2; Line::new( Point::new(position.x, strikethrough_y), Point::new(x, strikethrough_y), ) .into_styled(PrimitiveStyle::with_stroke(color, 1)) .draw(target)?; } } Ok(Point::new(x, position.y)) } fn draw_whitespace<D>( &self, width: u32, position: Point, _baseline: Baseline, _target: &mut D, ) -> Result<Point, D::Error> where D: DrawTarget<Color = Self::Color>, { // Just advance the position - no drawing needed for whitespace Ok(Point::new(position.x + width as i32, position.y)) } fn measure_string(&self, text: &str, position: Point, _baseline: Baseline) -> TextMetrics { let mut width = 0u32; for ch in text.chars() { if let Some(glyph) = self.font.get_glyph(ch) { width += glyph.x_advance as u32; } else if ch == ' ' { width += self.font.line_height / 4; } else { width += self.font.line_height / 3; } } TextMetrics { bounding_box: Rectangle::new(position, Size::new(width, self.font.line_height)), next_position: Point::new(position.x + width as i32, position.y), } } fn line_height(&self) -> u32 { self.font.line_height } } impl CharacterStyle for Gray4TextStyle { type Color = Rgb565; fn set_text_color(&mut self, text_color: Option<Self::Color>) { if let Some(color) = text_color { if self.text_color != color { self.text_color = color; // Rebuild cache with new text color self.color_cache = ColorCache::new(self.text_color, self.background_color); } } } fn set_background_color(&mut self, background_color: Option<Self::Color>) { let bg_color = background_color.unwrap_or(Rgb565::BLACK); // Only rebuild cache if background actually changed if self.background_color != bg_color { self.background_color = bg_color; self.color_cache = ColorCache::new(self.text_color, bg_color); } } fn set_underline_color(&mut self, underline_color: DecorationColor<Self::Color>) { self.underline_color = underline_color; } fn set_strikethrough_color(&mut self, strikethrough_color: DecorationColor<Self::Color>) { self.strikethrough_color = strikethrough_color; } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/demo_widget.rs
frostsnap_widgets/src/demo_widget.rs
/// Macro for selecting and running demo widgets #[macro_export] macro_rules! demo_widget { ($demo:expr, $run_macro:ident) => { // Common imports for all demos use $crate::{ palette::PALETTE, HoldToConfirm, FONT_SMALL, FONT_MED, FONT_LARGE, prelude::*, DefaultTextStyle, }; use embedded_graphics::{ prelude::*, pixelcolor::{Rgb565, BinaryColor}, }; use $crate::alloc::string::{String, ToString}; use $crate::HOLD_TO_CONFIRM_TIME_MS; // Shared test word indices for demos that need them const TEST_WORD_INDICES: [u16; 25] = [ 1337, // owner 432, // deny 1789, // survey 923, // journey 567, // embark 1456, // recall 234, // churn 1678, // spawn 890, // invest 345, // crater 1234, // neutral 678, // fiscal 1890, // thumb 456, // diamond 1567, // robot 789, // guitar 1345, // oyster 123, // badge 1789, // survey 567, // embark 1012, // lizard 1456, // recall 789, // guitar 1678, // spawn 234, // churn ]; match $demo.as_ref() { "hello_world" => { use $crate::text::Text; let widget = Text::new("Hello World!", DefaultTextStyle::new(FONT_LARGE, PALETTE.on_background)); $run_macro!(widget); } "bip39_entry" => { let mut widget = $crate::backup::EnterShareScreen::new(); if cfg!(feature = "prefill-words") { widget.prefill_test_words(); } $run_macro!(widget); } "log_touches" => { use $crate::{TouchListener, Center, Text, Key}; // Debug logging is now in device crate - this demo just shows touch listener // Create centered text with instructions let text = Text::new("Touch me!", DefaultTextStyle::new(FONT_LARGE, PALETTE.on_background)) .with_alignment(embedded_graphics::text::Alignment::Center); let centered = Center::new(text); // Wrap it with TouchListener (logging would happen in device crate if enabled) let touch_listener = TouchListener::new(centered, |_point, _time, _is_release, _widget| { None::<Key> }); $run_macro!(touch_listener); } "numeric_keyboard" => { let widget = $crate::backup::NumericKeyboard::new(); $run_macro!(widget); } "confirm_touch" | "hold_confirm" | "hold_checkmark" | "hold_to_confirm" => { use $crate::{text::Text, HoldToConfirm, palette::PALETTE}; use embedded_graphics::pixelcolor::BinaryColor; let prompt_text = Text::new("Confirm\ntransaction", DefaultTextStyle::new(FONT_MED, PALETTE.on_background)).with_alignment(embedded_graphics::text::Alignment::Center); let widget = HoldToConfirm::new(HOLD_TO_CONFIRM_TIME_MS, prompt_text); $run_macro!(widget); } "welcome" => { use $crate::Standby; let mut widget = Standby::new(); widget.set_welcome(); $run_macro!(widget); } "column_cross_axis" => { use $crate::{text::Text, Column, palette::PALETTE}; // First column with Start alignment (left-aligned) let text1 = Text::new("cross axis", DefaultTextStyle::new($crate::FONT_MED, PALETTE.on_background)); let text2 = Text::new("start", DefaultTextStyle::new($crate::FONT_MED, PALETTE.on_background)); let inner_column1 = Column::new((text1, text2)) .with_cross_axis_alignment($crate::CrossAxisAlignment::Start); // Second column with center cross-axis alignment let text3 = Text::new("cross axis", DefaultTextStyle::new($crate::FONT_MED, PALETTE.on_background)); let text4 = Text::new("center", DefaultTextStyle::new($crate::FONT_MED, PALETTE.on_background)); let inner_column2 = Column::new((text3, text4)) .with_cross_axis_alignment($crate::CrossAxisAlignment::Center); // Third column with End alignment (right-aligned) let text5 = Text::new("cross axis", DefaultTextStyle::new($crate::FONT_MED, PALETTE.on_background)); let text6 = Text::new("end", DefaultTextStyle::new($crate::FONT_MED, PALETTE.on_background)); let inner_column3 = Column::new((text5, text6)) .with_cross_axis_alignment($crate::CrossAxisAlignment::End); // Outer column containing all three inner columns (default center alignment) let widget = Column::new((inner_column1, inner_column2, inner_column3)); $run_macro!(widget); } "row_cross_axis" => { use $crate::{text::Text, Row, Column, Container, palette::PALETTE}; // First row with Start alignment (top-aligned) let text1 = Text::new("cross axis", DefaultTextStyle::new($crate::FONT_SMALL, PALETTE.on_background)); let text2 = Text::new("start", DefaultTextStyle::new($crate::FONT_SMALL, PALETTE.on_background)); let inner_row1 = Row::new((text1, text2)) .with_cross_axis_alignment($crate::CrossAxisAlignment::Start) .with_debug_borders(true); let container1 = Container::with_size(inner_row1, Size::new(240, 80)) .with_border(PALETTE.primary, 2); // Second row with center cross-axis alignment let text3 = Text::new("cross axis", DefaultTextStyle::new($crate::FONT_SMALL, PALETTE.on_background)); let text4 = Text::new("center", DefaultTextStyle::new($crate::FONT_SMALL, PALETTE.on_background)); let inner_row2 = Row::new((text3, text4)) .with_cross_axis_alignment($crate::CrossAxisAlignment::Center) .with_debug_borders(true); let container2 = Container::with_size(inner_row2, Size::new(240, 80)) .with_border(PALETTE.primary, 2); // Third row with End alignment (bottom-aligned) let text5 = Text::new("cross axis", DefaultTextStyle::new($crate::FONT_SMALL, PALETTE.on_background)); let text6 = Text::new("end", DefaultTextStyle::new($crate::FONT_SMALL, PALETTE.on_background)); let inner_row3 = Row::new((text5, text6)) .with_cross_axis_alignment($crate::CrossAxisAlignment::End) .with_debug_borders(true); let container3 = Container::with_size(inner_row3, Size::new(240, 80)) .with_border(PALETTE.primary, 2); // Outer column containing all three containers let widget = Column::new((container1, container2, container3)); $run_macro!(widget); } "row_center" => { use $crate::{text::Text, Row, Container, palette::PALETTE}; // First row with Start alignment let text_a = Text::new("A", DefaultTextStyle::new($crate::FONT_LARGE, PALETTE.on_background)); let text_b = Text::new("B", DefaultTextStyle::new($crate::FONT_LARGE, PALETTE.on_background)); let start_row = Row::new((text_a, text_b)) .with_main_axis_alignment($crate::MainAxisAlignment::Start) .with_debug_borders(true); let start_container = Container::new(start_row).with_border(PALETTE.primary, 2); // Second row with Center alignment let text_c = Text::new("C", DefaultTextStyle::new($crate::FONT_LARGE, PALETTE.on_background)); let text_d = Text::new("D", DefaultTextStyle::new($crate::FONT_LARGE, PALETTE.on_background)); let center_row = Row::new((text_c, text_d)) .with_main_axis_alignment($crate::MainAxisAlignment::Center) .with_debug_borders(true); let center_container = Container::new(center_row).with_border(PALETTE.primary, 2); // Outer row containing both containers let widget = Row::new((start_container, center_container)); $run_macro!(widget); } "column_center" => { use $crate::{text::Text, Column, Container, palette::PALETTE}; // First column with Start alignment let text1 = Text::new("main axis alignment", DefaultTextStyle::new($crate::FONT_MED, PALETTE.on_background)); let text2 = Text::new("start", DefaultTextStyle::new($crate::FONT_LARGE, PALETTE.on_background)); let start_column = Column::new((text1, text2)).with_debug_borders(true); let start_container = Container::new(start_column).with_border(PALETTE.primary, 2); // Second column with Center alignment let text3 = Text::new("main axis alignment", DefaultTextStyle::new($crate::FONT_MED, PALETTE.on_background)); let text4 = Text::new("center", DefaultTextStyle::new($crate::FONT_LARGE, PALETTE.on_background)); let center_column = Column::new((text3, text4)) .with_main_axis_alignment($crate::MainAxisAlignment::Center).with_debug_borders(true); let center_container = Container::new(center_column).with_border(PALETTE.primary, 2); // Outer column containing both containers let widget = Column::new((start_container, center_container)); $run_macro!(widget); } "bip39_backup" => { use $crate::backup::BackupDisplay; use embedded_graphics::prelude::*; let share_index = 42; // Create the backup display - it now uses PageSlider internally and outputs Rgb565 let widget = BackupDisplay::new(TEST_WORD_INDICES, share_index); $run_macro!(widget); } "fade_in" => { use $crate::{fader::Fader, text::Text, palette::PALETTE}; // Simple text widget that will fade in let text = Text::new("Fade Demo", DefaultTextStyle::new($crate::FONT_LARGE, PALETTE.on_background)); // Create a fader starting faded out let mut fader = Fader::new_faded_out(text); // Start the fade-in immediately fader.start_fade_in(1000); $run_macro!(fader); } "fade_switcher" => { use $crate::{FadeSwitcher, Container, Padding, palette::PALETTE}; use embedded_graphics::prelude::*; use embedded_graphics::pixelcolor::RgbColor; struct FadeSwitcherDemo { fade_switcher: FadeSwitcher<Center<Container<Padding<Text>>>>, last_switch_time: Option<Instant>, showing_a: bool, } impl FadeSwitcherDemo { fn new() -> Self { let text = Text::new( "Lorem ipsum\ndolor sit\namet,\nconsectetur\nadipiscing", DefaultTextStyle::new(FONT_SMALL, PALETTE.on_background) ); let padded = Padding::all(10, text); let widget_a = Container::new(padded) .with_fill(PALETTE.surface) .with_border(PALETTE.primary, 2); Self { fade_switcher: FadeSwitcher::new(Center::new(widget_a), 500), last_switch_time: None, showing_a: true, } } } impl $crate::DynWidget for FadeSwitcherDemo { fn set_constraints(&mut self, max_size: Size) { self.fade_switcher.set_constraints(max_size); } fn sizing(&self) -> $crate::Sizing { self.fade_switcher.sizing() } fn force_full_redraw(&mut self) { self.fade_switcher.force_full_redraw(); } } impl $crate::Widget for FadeSwitcherDemo { type Color = Rgb565; fn draw<D>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, current_time: Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { if self.last_switch_time.is_none() { self.last_switch_time = Some(current_time); } let elapsed = current_time.saturating_duration_since(self.last_switch_time.unwrap()); if elapsed >= 3000 { if self.showing_a { let pink = Rgb565::new(31, 20, 31); let text_b = Text::new("", DefaultTextStyle::new(FONT_SMALL, PALETTE.on_background)); let padded_b = Padding::all(0, text_b); let widget_b = Container::with_size(padded_b, Size::new(20, 20)) .with_fill(pink); self.fade_switcher.switch_to(Center::new(widget_b)); } else { let text = Text::new( "Lorem ipsum\ndolor sit\namet,\nconsectetur\nadipiscing", DefaultTextStyle::new(FONT_SMALL, PALETTE.on_background) ); let padded = Padding::all(10, text); let widget_a = Container::new(padded) .with_fill(PALETTE.surface) .with_border(PALETTE.primary, 2); self.fade_switcher.switch_to(Center::new(widget_a)); } self.showing_a = !self.showing_a; self.last_switch_time = Some(current_time); } self.fade_switcher.draw(target, current_time) } } let widget = FadeSwitcherDemo::new(); $run_macro!(widget); } "device_name" => { use $crate::DeviceNameScreen; // Create device name screen with a long name to test let mut device_name_screen = DeviceNameScreen::new("Frank L".into()); $run_macro!(device_name_screen); } "bobbing_icon" => { use $crate::bobbing_carat::BobbingCarat; // Create the bobbing carat widget with colors let bobbing_carat = BobbingCarat::new(PALETTE.on_background, PALETTE.background); // Center it on screen let centered = Center::new(bobbing_carat); $run_macro!(centered); } "swipe_up_chevron" => { use $crate::SwipeUpChevron; // Create swipe up chevron with bobbing animation let swipe_hint = SwipeUpChevron::new(PALETTE.on_surface, PALETTE.background); // Center it on screen let centered = Center::new(swipe_hint); $run_macro!(centered); } "keygen_check" => { use $crate::keygen_check::KeygenCheck; // Create mock data for demo purposes let t_of_n = (2, 3); // 2 of 3 threshold let security_check_code: [u8; 4] = [0xAB, 0xCD, 0xEF, 0x12]; let widget = KeygenCheck::new(t_of_n, security_check_code); $run_macro!(widget); } "sign_prompt" => { use $crate::sign_prompt::SignTxPrompt; use frostsnap_core::bitcoin_transaction::PromptSignBitcoinTx; use core::str::FromStr; // Create dummy transaction data with different address types // Segwit v0 address (starts with bc1q) // let segwit_address = bitcoin::Address::from_str("bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4") // .unwrap() // .assume_checked(); // Taproot address (starts with bc1p) let taproot_address = bitcoin::Address::from_str("bc1p5d7rjq7g6rdk2yhzks9smlaqtedr4dekq08ge8ztwac72sfr9rusxg3297") .unwrap() .assume_checked(); // Legacy P2PKH address (starts with 1) // let legacy_address = bitcoin::Address::from_str("1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa") // .unwrap() // .assume_checked(); let prompt = PromptSignBitcoinTx { foreign_recipients: $crate::alloc::vec![ (taproot_address, bitcoin::Amount::from_sat(500_001)), // 0.00500001 BTC // (segwit_address, bitcoin::Amount::from_sat(150_000)), // 0.0015 BTC // (legacy_address, bitcoin::Amount::from_sat(50_000)), // 0.0005 BTC ], fee: bitcoin::Amount::from_sat(125_000), // 0.00125 BTC (high fee for demo) }; // Create the sign prompt widget let widget = SignTxPrompt::new(prompt); $run_macro!(widget); } "bitcoin_amount" => { use $crate::{bitcoin_amount_display::BitcoinAmountDisplay, Column, MainAxisAlignment}; // Create a simple BitcoinAmountDisplay with 21 BTC let amount_display = BitcoinAmountDisplay::new(21_000_000); // 21 BTC // Put it in a Column with MainAxisAlignment::Center like in sign_prompt let widget = Column::new((amount_display,)) .with_main_axis_alignment(MainAxisAlignment::Center); $run_macro!(widget); } "slide_in" => { use $crate::{PageSlider, WidgetList}; use embedded_graphics::prelude::*; use embedded_graphics::pixelcolor::Rgb565; // Type aliases to simplify the complex nested types type StyledText = Text; type NumberRow = Row<(StyledText, StyledText)>; type ThreeRowColumn = Column<(NumberRow, NumberRow, NumberRow)>; type PageWidget = Center<Container<ThreeRowColumn>>; // Create a WidgetList that generates column widgets with rows on the fly struct InfiniteTextPages; impl WidgetList<PageWidget> for InfiniteTextPages { fn len(&self) -> usize { usize::MAX // Infinite pages! } fn get(&self, index: usize) -> Option<PageWidget> { let number_words = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty"]; let start_num = index * 3 + 1; // Each page has 3 items // Create three rows with number and word let row1 = Row::new(( Text::new( $crate::alloc::format!("{}.", start_num), DefaultTextStyle::new($crate::FONT_MED, PALETTE.text_secondary) ), Text::new( number_words.get(start_num).unwrap_or(&"many").to_string(), DefaultTextStyle::new($crate::FONT_LARGE, PALETTE.on_background) ) )); let row2 = Row::new(( Text::new( $crate::alloc::format!("{}.", start_num + 1), DefaultTextStyle::new($crate::FONT_MED, PALETTE.text_secondary) ), Text::new( number_words.get(start_num + 1).unwrap_or(&"many").to_string(), DefaultTextStyle::new($crate::FONT_LARGE, PALETTE.on_background) ) )); let row3 = Row::new(( Text::new( $crate::alloc::format!("{}.", start_num + 2), DefaultTextStyle::new($crate::FONT_MED, PALETTE.text_secondary) ), Text::new( number_words.get(start_num + 2).unwrap_or(&"many").to_string(), DefaultTextStyle::new($crate::FONT_LARGE, PALETTE.on_background) ) )); let column = Column::new((row1, row2, row3)); let container = Container::new(column) .with_border(PALETTE.primary, 2); Some(Center::new(container)) } } // Create the PageSlider with infinite text pages let page_slider = PageSlider::new(InfiniteTextPages, 100); let widget = page_slider; $run_macro!(widget); } "firmware_upgrade_progress" | "firmware_upgrade_download" => { use $crate::{ firmware_upgrade::FirmwareUpgradeProgress, Padding }; // Show downloading state at 65% progress let widget = FirmwareUpgradeProgress::downloading(0.65); $run_macro!(widget); } "firmware_upgrade_erase" => { use $crate::firmware_upgrade::FirmwareUpgradeProgress; // Show erasing state at 35% progress let widget = FirmwareUpgradeProgress::erasing(0.35); $run_macro!(widget); } "firmware_upgrade_passive" => { use $crate::firmware_upgrade::FirmwareUpgradeProgress; // Show passive state let widget = FirmwareUpgradeProgress::passive(); $run_macro!(widget); } "progress" => { use $crate::{ProgressIndicator, Widget, Instant}; use embedded_graphics::prelude::*; // Create a progress indicator that animates from 0 to 100% struct AnimatedProgress { indicator: ProgressIndicator, start_time: Option<Instant>, duration_ms: u64, } impl AnimatedProgress { fn new() -> Self { Self { indicator: ProgressIndicator::new(), start_time: None, duration_ms: 5000, // 5 seconds to complete } } } impl $crate::DynWidget for AnimatedProgress { fn set_constraints(&mut self, max_size: Size) { self.indicator.set_constraints(max_size); } fn sizing(&self) -> $crate::Sizing { self.indicator.sizing() } fn force_full_redraw(&mut self) { self.indicator.force_full_redraw() } } impl Widget for AnimatedProgress { type Color = Rgb565; fn draw<D>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, current_time: $crate::Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { // Initialize start time on first draw if self.start_time.is_none() { self.start_time = Some(current_time); } // Calculate progress based on elapsed time let elapsed = current_time.saturating_duration_since(self.start_time.unwrap()); let progress = $crate::Frac::from_ratio(elapsed as u32, self.duration_ms as u32); // Update the indicator's progress self.indicator.set_progress(progress); // Draw the indicator self.indicator.draw(target, current_time) } } let widget = AnimatedProgress::new(); $run_macro!(widget); } "firmware_upgrade" => { use $crate::FirmwareUpgradeConfirm; // Create a test firmware digest (SHA256 hash) let firmware_digest: [u8; 32] = [ 0xab, 0xcd, 0xef, 0x12, 0x34, 0x56, 0x78, 0x90, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0xba, 0xbe, ]; let size_bytes = 1_234_567; // ~1.2 MB let widget = FirmwareUpgradeConfirm::new(firmware_digest, size_bytes); $run_macro!(widget); } "sign_test_message" => { use $crate::SignMessageConfirm; let test_message = "This is a very long test message that will be wrapped across multiple lines to demonstrate the StringWrap functionality and visual clipping in the container box."; let widget = SignMessageConfirm::new(test_message.to_string()); $run_macro!(widget); } "all_words" => { use $crate::backup::AllWordsPage; // Use the actual AllWordsPage widget with test word indices let all_words_page = AllWordsPage::new(&TEST_WORD_INDICES, 42); $run_macro!(all_words_page); } "row_inside_column" => { use $crate::{text::Text, Column, Row, Container, palette::PALETTE}; // Create three rows with number and word let row1 = Row::new(( Text::new( "1.", DefaultTextStyle::new($crate::FONT_MED, PALETTE.text_secondary) ), Text::new( "one", DefaultTextStyle::new($crate::FONT_LARGE, PALETTE.on_background) ) )); let row2 = Row::new(( Text::new( "2.", DefaultTextStyle::new($crate::FONT_MED, PALETTE.text_secondary) ), Text::new( "two", DefaultTextStyle::new($crate::FONT_LARGE, PALETTE.on_background) ) )); let row3 = Row::new(( Text::new( "3.", DefaultTextStyle::new($crate::FONT_MED, PALETTE.text_secondary) ), Text::new( "three", DefaultTextStyle::new($crate::FONT_LARGE, PALETTE.on_background) ) )); let column = Column::new((row1, row2, row3)); let widget = Container::new(column) .with_border(PALETTE.primary, 2); $run_macro!(widget); } "stack" => { use $crate::{Stack, Alignment, Container, text::Text, palette::PALETTE}; use embedded_graphics::primitives::{Rectangle, PrimitiveStyle}; // Create a background container let background = Container::with_size( Text::new("Background", DefaultTextStyle::new(FONT_LARGE, PALETTE.surface_variant)), Size::new(200, 150) ) .with_fill(PALETTE.surface) .with_border(PALETTE.primary, 2); // Create some text to overlay let centered_text = Text::new( "Centered", DefaultTextStyle::new(FONT_MED, PALETTE.primary) ).with_alignment(embedded_graphics::text::Alignment::Center); // Create a small icon-like widget positioned at top-right let icon = Container::with_size( Text::new("!", DefaultTextStyle::new(FONT_SMALL, PALETTE.on_background)), Size::new(20, 20) ) .with_fill(PALETTE.error) .with_corner_radius(Size::new(10, 10)); // Build the stack let stack = Stack::builder() .push(background) .push(centered_text) // This will be centered .push_positioned(icon, 170, 10) // Position in top-right .with_alignment(Alignment::Center); let widget = Center::new(stack); $run_macro!(widget); } "array_column" => { use $crate::{text::Text, Column, palette::PALETTE}; use embedded_graphics::prelude::*; // Create a column from a fixed-size array let texts = [ Text::new("First", DefaultTextStyle::new(FONT_MED, PALETTE.on_background)), Text::new("Second", DefaultTextStyle::new(FONT_MED, PALETTE.tertiary)), Text::new("Third", DefaultTextStyle::new(FONT_MED, PALETTE.on_background)), Text::new("Fourth", DefaultTextStyle::new(FONT_MED, PALETTE.tertiary)), Text::new("Fifth", DefaultTextStyle::new(FONT_MED, PALETTE.on_background)), ]; let widget = Column::new(texts) .with_main_axis_alignment(MainAxisAlignment::SpaceEvenly) .with_cross_axis_alignment(CrossAxisAlignment::Center); $run_macro!(widget); } "word_selector" => { use $crate::backup::WordSelector; use frost_backup::bip39_words::words_with_prefix; // Get all words starting with "CAR" (BIP39 words are uppercase) let words = words_with_prefix("CAR"); let widget = WordSelector::new(words, "CAR"); $run_macro!(widget); } "vec_column" => { use $crate::{text::Text, Column, Switcher, palette::PALETTE, DynWidget, Widget}; use $crate::alloc::vec::Vec; use embedded_graphics::prelude::*; // Interactive demo that adds text widgets on touch struct VecColumnDemo { texts: Vec<Text>,
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
true
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/compressed_point.rs
frostsnap_widgets/src/compressed_point.rs
use embedded_graphics::prelude::*; /// Compressed point representation using 3 bytes instead of 8 #[derive(Debug, Clone, Copy, PartialEq)] pub struct CompressedPoint { pub x: u8, pub y: u16, } impl CompressedPoint { pub fn new(point: Point) -> Self { Self { x: point.x as u8, y: point.y as u16, } } pub fn to_point(self) -> Point { Point::new(self.x as i32, self.y as i32) } } impl From<CompressedPoint> for Point { fn from(cp: CompressedPoint) -> Self { cp.to_point() } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/key_touch.rs
frostsnap_widgets/src/key_touch.rs
use crate::palette::PALETTE; use crate::super_draw_target::SuperDrawTarget; use crate::{Container, DynWidget as _, Fader, SizedBox, Widget}; use embedded_graphics::{pixelcolor::Rgb565, prelude::*, primitives::Rectangle}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Key { Keyboard(char), WordSelector(&'static str), EditWord(usize), NavBack, NavForward, ShowEnteredWords, } pub struct KeyTouch { pub key: Key, rect: Rectangle, let_go: Option<crate::Instant>, finished: bool, cancel: bool, widget: Fader<Container<SizedBox<Rgb565>>>, } impl KeyTouch { pub fn translate(&mut self, point: Point) { self.rect.top_left += point; } pub fn new(key: Key, rect: Rectangle) -> Self { const CORNER_RADIUS: u32 = 8; let sized_box = SizedBox::new(rect.size); let mut container = Container::with_size(sized_box, rect.size) .with_border(PALETTE.primary, 2) .with_corner_radius(Size::new(CORNER_RADIUS, CORNER_RADIUS)); // HACK: the container is a fixed size so this doesn't matter container.set_constraints(Size { width: u32::MAX, height: u32::MAX, }); let widget = Fader::new(container); Self { key, rect, let_go: None, finished: false, cancel: false, widget, } } pub fn let_go(&mut self, current_time: crate::Instant) -> Option<Key> { if self.cancel || self.let_go.is_some() { return None; } self.let_go = Some(current_time); // Start fade out animation self.widget.start_fade(500); Some(self.key) } pub fn cancel(&mut self) { self.cancel = true; // Immediately fade to background for cancel self.widget.instant_fade(); } pub fn has_been_let_go(&self) -> bool { self.let_go.is_some() } pub fn draw<D: DrawTarget<Color = Rgb565>>( &mut self, target: &mut SuperDrawTarget<D, Rgb565>, current_time: crate::Instant, ) { if self.finished { return; } // Translate the target to draw at the correct position let mut translated = target.clone().translate(self.rect.top_left); // Let the widget handle all drawing let _ = self.widget.draw(&mut translated, current_time); // Check if fade is complete if self.widget.is_faded_out() { self.finished = true; } } pub fn is_finished(&self) -> bool { self.finished } } impl core::fmt::Debug for KeyTouch { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("KeyTouch") .field("key", &self.key) .field("rect", &self.rect) .field("let_go", &self.let_go) .field("finished", &self.finished) .field("cancel", &self.cancel) .finish() } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/checkmark.rs
frostsnap_widgets/src/checkmark.rs
use super::{pixel_recorder::PixelRecorder, Widget}; use crate::{ compressed_point::CompressedPoint, super_draw_target::SuperDrawTarget, Frac, Instant, Rat, }; use alloc::vec::Vec; use embedded_graphics::{ draw_target::DrawTarget, geometry::{Point, Size}, pixelcolor::{BinaryColor, PixelColor}, prelude::*, primitives::{Circle, Line, PrimitiveStyle}, }; #[derive(PartialEq)] pub struct Checkmark<C> { width: u32, color: C, check_pixels: Vec<CompressedPoint>, progress: Frac, last_drawn_check_progress: Option<Frac>, animation_state: AnimationState, enabled: bool, animation_start_time: Option<crate::Instant>, check_width: u32, check_height: u32, } #[derive(Debug, Clone, Copy, PartialEq)] enum AnimationState { Idle, Drawing, Complete, } impl<C: PixelColor> Checkmark<C> { pub fn new(width: u32, color: C) -> Self { let mut checkmark = Self { width, color, check_pixels: Vec::new(), progress: Frac::ZERO, last_drawn_check_progress: None, animation_state: AnimationState::Idle, enabled: false, animation_start_time: None, check_width: 0, check_height: 0, }; checkmark.record_pixels(); checkmark } pub fn start_drawing(&mut self) { self.enabled = true; self.progress = Frac::ZERO; self.last_drawn_check_progress = None; self.animation_state = AnimationState::Drawing; self.animation_start_time = None; // Will be set on first draw } pub fn reset(&mut self) { self.enabled = false; self.progress = Frac::ZERO; self.last_drawn_check_progress = None; self.animation_state = AnimationState::Idle; } pub fn is_complete(&self) -> bool { self.animation_state == AnimationState::Complete } pub fn drawing_started(&self) -> bool { matches!( self.animation_state, AnimationState::Complete | AnimationState::Drawing ) } fn record_pixels(&mut self) { let mut recorder = PixelRecorder::new(); // Define checkmark points for perfect right angle // Second segment is 2.2x the length of the first segment let width = self.width; // Calculate segment lengths to use full width // The checkmark total width = first_x + second_x // We want: (first_x + second_x) + margins = width // With stroke width 8, we need margin of 4 on each side let margin = 5i32; // Radius of cap circle + 1 let available_width = width - (2 * margin as u32); // For 45-degree angles, x and y components are length / sqrt(2) // sqrt(2) ≈ 1.414213562373095 // To avoid division, we multiply by inverse: 1/sqrt(2) ≈ 0.7071067811865476 // As a fraction: 7071/10000 let inv_sqrt_2 = Rat::from_ratio(7071, 10000); // With ratio of 2.2:1 for second:first segment // Total horizontal span = first_x + second_x = available_width // first_x = first_length * inv_sqrt_2 // second_x = second_length * inv_sqrt_2 = 2.2 * first_length * inv_sqrt_2 // So: first_length * inv_sqrt_2 * (1 + 2.2) = available_width // first_length * inv_sqrt_2 * 3.2 = available_width // first_length = available_width / (inv_sqrt_2 * 3.2) // Since inv_sqrt_2 ≈ 0.7071, inv_sqrt_2 * 3.2 ≈ 2.263 // So first_length ≈ available_width / 2.263 ≈ available_width * 0.442 let first_segment_length = (Rat::from_ratio(4420, 10000) * available_width).round(); let second_segment_length = (Rat::from_ratio(22, 10) * first_segment_length).round(); // First segment: 45 degrees down-right let first_x_offset = (inv_sqrt_2 * first_segment_length).round() as i32; let first_y_offset = (inv_sqrt_2 * first_segment_length).round() as i32; // Second segment: 45 degrees up-right (perpendicular to first) let second_x_offset = (inv_sqrt_2 * second_segment_length).round() as i32; let second_y_offset = (inv_sqrt_2 * second_segment_length).round() as i32; // Position the middle point with margin let middle = Point::new(first_x_offset + margin, second_y_offset + margin); // Calculate the other points based on the middle point let left_start = Point::new(middle.x - first_x_offset, middle.y - first_y_offset); let right_end = Point::new(middle.x + second_x_offset, middle.y - second_y_offset); // Draw with thicker lines for better visibility let stroke_width = 8; let style = PrimitiveStyle::with_stroke(BinaryColor::On, stroke_width); Line::new(left_start, middle) .into_styled(style) .draw(&mut recorder) .ok(); Line::new(middle, right_end) .into_styled(style) .draw(&mut recorder) .ok(); // Add rounded caps at the ends - matching stroke width for subtle rounding let cap_diameter = stroke_width; // Same as stroke width for natural rounding let cap_style = PrimitiveStyle::with_fill(BinaryColor::On); // Round cap at left start Circle::with_center(left_start, cap_diameter) .into_styled(cap_style) .draw(&mut recorder) .ok(); // Round cap at right end Circle::with_center(right_end - Point::new(1, 0), cap_diameter) .into_styled(cap_style) .draw(&mut recorder) .ok(); // Round cap at middle joint Circle::with_center(middle - Point::new(1, 1), cap_diameter) .into_styled(cap_style) .draw(&mut recorder) .ok(); self.check_pixels = recorder.pixels; self.check_pixels.sort_unstable_by_key(|cp| cp.x); // Find the actual bounds of the recorded pixels if !self.check_pixels.is_empty() { let max_x = self.check_pixels.iter().map(|cp| cp.x).max().unwrap_or(0); let max_y = self .check_pixels .iter() .map(|cp| cp.y as u32) .max() .unwrap_or(0); self.check_width = (max_x + 1) as u32; // +1 because coordinates are 0-based self.check_height = max_y + 1; } else { // Fallback to calculated values self.check_width = self.width; // Approximate height based on width self.check_height = (self.width * 2) / 3; } } fn update_animation(&mut self, current_time: crate::Instant) { if !self.enabled { return; } // Animation duration in milliseconds const CHECK_DURATION_MS: u64 = 800; if self.animation_start_time.is_none() { self.animation_start_time = Some(current_time); } match self.animation_state { AnimationState::Idle => {} AnimationState::Drawing => { let start = self.animation_start_time.unwrap(); let elapsed = current_time.saturating_duration_since(start) as u32; self.progress = Frac::from_ratio(elapsed, CHECK_DURATION_MS as u32); if self.progress >= Frac::ONE { self.progress = Frac::ONE; self.animation_state = AnimationState::Complete; } } AnimationState::Complete => {} } } } impl<C: PixelColor> crate::DynWidget for Checkmark<C> { fn set_constraints(&mut self, _max_size: Size) { // Checkmark has a fixed size based on check_width and check_height } fn sizing(&self) -> crate::Sizing { crate::Sizing { width: self.check_width, height: self.check_height, ..Default::default() } } fn handle_touch( &mut self, _point: Point, _current_time: crate::Instant, _is_release: bool, ) -> Option<crate::KeyTouch> { None } fn handle_vertical_drag(&mut self, _start_y: Option<u32>, _current_y: u32, _is_release: bool) {} fn force_full_redraw(&mut self) { self.last_drawn_check_progress = None; } } impl<C: crate::WidgetColor> Widget for Checkmark<C> { type Color = C; fn draw<D>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, current_time: Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { if self.enabled { self.update_animation(current_time); // Draw animation inline match self.animation_state { AnimationState::Idle => {} AnimationState::Drawing | AnimationState::Complete => { let check_progress = self.progress; let current_pixels = (check_progress * self.check_pixels.len() as u32).round() as usize; let last_pixels = if let Some(last_progress) = self.last_drawn_check_progress { (last_progress * self.check_pixels.len() as u32).round() as usize } else { 0 }; if current_pixels > last_pixels && current_pixels <= self.check_pixels.len() { target.draw_iter( self.check_pixels[last_pixels..current_pixels] .iter() .map(|cp| Pixel(cp.to_point(), self.color)), )?; } self.last_drawn_check_progress = Some(check_progress); } } } Ok(()) } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/p2tr_address_display.rs
frostsnap_widgets/src/p2tr_address_display.rs
use crate::{ palette::PALETTE, text::Text, Column, DefaultTextStyle, MainAxisAlignment, Row, FONT_HUGE_MONO, }; use alloc::{boxed::Box, string::String, vec::Vec}; use frostsnap_fonts::Gray4Font; // Font for displaying addresses - uses monospace for better readability const ADDRESS_FONT: &Gray4Font = FONT_HUGE_MONO; // Type alias for a row with three text chunks type AddressRow = Row<[Text; 3]>; /// A widget for displaying P2TR (Taproot) addresses in a specific format: /// - 1 row with the first chunk (grayed out) /// - 5 rows with 3 chunks each (4 chars per chunk) /// - Total: 62 characters displayed as 16 chunks #[derive(Clone, frostsnap_macros::Widget)] pub struct P2trAddressDisplay { #[widget_delegate] column: Column<Box<(Row<[Text; 1]>, Column<[AddressRow; 5]>)>>, } impl P2trAddressDisplay { pub fn new(address: &str) -> Self { // P2TR addresses are always 62 characters (ASCII) // Split into chunks of 4 characters, padding with spaces as needed let chunks: Vec<String> = (0..address.len()) .step_by(4) .map(|start| { let end = (start + 4).min(address.len()); let chunk = &address[start..end]; // Pad to 4 characters with spaces format!("{:4}", chunk) }) .collect(); // Use monospace font for the address text let text_style = DefaultTextStyle::new(ADDRESS_FONT, PALETTE.on_surface); // First chunk on its own row (grayed out) let type_indicator = Row::new([Text::new(chunks[0].clone(), text_style.clone())]); // Create rows of 3 chunks each let mut rows = Vec::new(); for row_chunks in chunks[1..].chunks(3) { // Pad with empty text if needed (last row might have fewer than 3) let mut texts = vec![]; for i in 0..3 { if i < row_chunks.len() { texts.push(Text::new(row_chunks[i].clone(), text_style.clone())); } else { texts.push(Text::new(String::new(), text_style.clone())); } } let row: AddressRow = Row::new([texts[0].clone(), texts[1].clone(), texts[2].clone()]) .with_main_axis_alignment(MainAxisAlignment::SpaceAround); rows.push(row); } // Convert Vec to array - we know we have exactly 5 rows let address_rows: [AddressRow; 5] = rows .try_into() .unwrap_or_else(|_| panic!("Expected exactly 5 rows for P2TR address")); let address_column = Column::new(address_rows); // Create main column with type indicator and address rows let column = Column::new(Box::new((type_indicator, address_column))); Self { column } } pub fn set_rand_highlight(&mut self, rand_highlight: u32) { // Calculate highlight indices let first_u16 = (rand_highlight & 0xFFFF) as u16; let second_u16 = ((rand_highlight >> 16) & 0xFFFF) as u16; let first_idx = (first_u16 % 14) as usize; let second_idx = (second_u16 % 13) as usize; // Adjust second index if it would collide with or be >= first let second_idx = if second_idx >= first_idx { second_idx + 1 } else { second_idx }; let highlight_style = DefaultTextStyle::new(ADDRESS_FONT, PALETTE.primary); // Access the address rows through the box (skip the type indicator) let address_column = &mut self.column.children.1; // Update the highlighted chunks for idx in [first_idx, second_idx] { let row = idx / 3; let col = idx % 3; // Access the specific text widget and update its style address_column.children[row].children[col].set_character_style(highlight_style.clone()); } } } // All trait implementations are now generated by the derive macro
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/bitmap.rs
frostsnap_widgets/src/bitmap.rs
use crate::vec_framebuffer::VecFramebuffer; use alloc::vec::Vec; use bincode::{Decode, Encode}; use embedded_graphics::{pixelcolor::BinaryColor, prelude::*}; #[derive(Debug, Clone, Copy, Encode, Decode)] enum ImageColor { Binary = 0x00, } #[derive(Debug, Encode, Decode)] pub struct EncodedImage { color: ImageColor, width: u32, pub bytes: Vec<u8>, // TODO: use Cow<'static, [u8]> } impl EncodedImage { /// Load an encoded image from binary data pub fn from_bytes(data: &[u8]) -> Result<Self, bincode::error::DecodeError> { bincode::decode_from_slice(data, bincode::config::standard()).map(|(image, _)| image) } /// Get the width of the image pub fn width(&self) -> u32 { self.width } /// Get the height of the image (calculated from bytes and width) pub fn height(&self) -> u32 { // Each byte contains 8 pixels for binary images let total_pixels = self.bytes.len() * 8; total_pixels as u32 / self.width } } impl From<EncodedImage> for VecFramebuffer<BinaryColor> { fn from(encoded: EncodedImage) -> Self { // Convert from row-by-row with padding to sequential storage let width = encoded.width as usize; let height = encoded.height() as usize; let mut framebuffer = VecFramebuffer::new(width, height); let bytes_per_row = width.div_ceil(8); for y in 0..height { for x in 0..width { let byte_index = y * bytes_per_row + x / 8; let bit_index = 7 - (x % 8); if byte_index < encoded.bytes.len() { let bit = (encoded.bytes[byte_index] >> bit_index) & 1; let color = if bit == 1 { BinaryColor::On } else { BinaryColor::Off }; VecFramebuffer::<BinaryColor>::set_pixel( &mut framebuffer, Point::new(x as i32, y as i32), color, ); } } } framebuffer } } impl From<&EncodedImage> for VecFramebuffer<BinaryColor> { fn from(encoded: &EncodedImage) -> Self { // Convert from row-by-row with padding to sequential storage let width = encoded.width as usize; let height = encoded.height() as usize; let mut framebuffer = VecFramebuffer::new(width, height); let bytes_per_row = width.div_ceil(8); for y in 0..height { for x in 0..width { let byte_index = y * bytes_per_row + x / 8; let bit_index = 7 - (x % 8); if byte_index < encoded.bytes.len() { let bit = (encoded.bytes[byte_index] >> bit_index) & 1; let color = if bit == 1 { BinaryColor::On } else { BinaryColor::Off }; VecFramebuffer::<BinaryColor>::set_pixel( &mut framebuffer, Point::new(x as i32, y as i32), color, ); } } } framebuffer } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/keygen_check.rs
frostsnap_widgets/src/keygen_check.rs
use super::{Column, Container, HoldToConfirm, Padding, Row, Text}; use crate::HOLD_TO_CONFIRM_TIME_MS; use crate::DefaultTextStyle; use crate::{palette::PALETTE, MainAxisAlignment}; use alloc::format; use embedded_graphics::geometry::Size; type CodeText = Text; type TofNText = Text; type CodeColumn = Column<(TofNText, CodeText)>; type PaddedCodeColumn = Padding<CodeColumn>; type CodeContainer = Container<PaddedCodeColumn>; type ConfirmText = Text; type OnAllDevicesRow = Row<(ConfirmText, ConfirmText)>; type PromptColumn = Column<(ConfirmText, CodeContainer, OnAllDevicesRow)>; /// Widget for checking and confirming key generation #[derive(frostsnap_macros::Widget)] pub struct KeygenCheck { /// The hold-to-confirm widget #[widget_delegate] hold_to_confirm: HoldToConfirm<PromptColumn>, } impl KeygenCheck { /// Create a new keygen check widget pub fn new(t_of_n: (u16, u16), security_check_code: [u8; 4]) -> Self { // Format the t of n string let t_of_n_text = format!("{} of {}", t_of_n.0, t_of_n.1); // Format the security check code as hex let hex_code = format!( "{:02x}{:02x} {:02x}{:02x}", security_check_code[0], security_check_code[1], security_check_code[2], security_check_code[3] ); // Create the t of n text widget let t_of_n_style = DefaultTextStyle::new(crate::FONT_MED, PALETTE.on_surface); let t_of_n_widget = Text::new(t_of_n_text.clone(), t_of_n_style.clone()); // Create the hex code text widget using FONT_LARGE let code_style = DefaultTextStyle::new(crate::FONT_HUGE_MONO, PALETTE.on_surface); let code_widget = Text::new(hex_code.clone(), code_style); // Create internal column with t_of_n and code let code_column = Column::new((t_of_n_widget, code_widget)); // Put the column in a container with a border let padded_code_column = Padding::all(10, code_column); let code_container = Container::new(padded_code_column) .with_border(PALETTE.outline, 2) .with_fill(PALETTE.surface) .with_corner_radius(Size::new(8, 8)); // Create the "confirm identical" text let confirm_style = DefaultTextStyle::new(crate::FONT_MED, PALETTE.on_background); let confirm_identical_widget = Text::new("Confirm identical:", confirm_style.clone()); // Create the "on all devices" text with underline let on_text = Text::new("on ", confirm_style.clone()); let all_devices_text = Text::new("all devices", confirm_style).with_underline(PALETTE.on_background); let on_all_devices_row = Row::new((on_text, all_devices_text)); // Create the prompt column with SpaceEvenly alignment let prompt_column = Column::new((confirm_identical_widget, code_container, on_all_devices_row)) .with_main_axis_alignment(MainAxisAlignment::SpaceEvenly); // Create the hold-to-confirm widget let hold_to_confirm = HoldToConfirm::new(HOLD_TO_CONFIRM_TIME_MS, prompt_column); Self { hold_to_confirm } } /// Check if the user has confirmed pub fn is_confirmed(&self) -> bool { self.hold_to_confirm.is_completed() } } // All trait implementations are now generated by the derive macro
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/pixel_recorder.rs
frostsnap_widgets/src/pixel_recorder.rs
use crate::compressed_point::CompressedPoint; use alloc::vec::Vec; use embedded_graphics::{draw_target::DrawTarget, pixelcolor::BinaryColor, prelude::*}; /// A DrawTarget implementation that records pixel positions instead of drawing them. /// Useful for pre-computing pixel locations for animations. pub struct PixelRecorder { pub pixels: Vec<CompressedPoint>, } impl Default for PixelRecorder { fn default() -> Self { Self::new() } } impl PixelRecorder { pub fn new() -> Self { Self { pixels: Vec::new() } } } impl DrawTarget for PixelRecorder { type Color = BinaryColor; type Error = core::convert::Infallible; fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error> where I: IntoIterator<Item = embedded_graphics::Pixel<Self::Color>>, { for pixel in pixels { self.pixels.push(CompressedPoint::new(pixel.0)); } Ok(()) } } impl OriginDimensions for PixelRecorder { fn size(&self) -> Size { // Return a large size to ensure all pixels are recorded Size::new(1000, 1000) } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/widget_color.rs
frostsnap_widgets/src/widget_color.rs
use crate::Frac; use embedded_graphics::pixelcolor::{ BinaryColor, Gray2, Gray4, GrayColor, PixelColor, Rgb565, RgbColor, }; /// Trait for colors that can be interpolated pub trait ColorInterpolate: PixelColor { /// Interpolate between two colors. Returns a color that is `frac` of the way from `self` to `other`. /// When frac is 0, returns self. When frac is 1, returns other. fn interpolate(&self, other: Self, frac: Frac) -> Self; } impl ColorInterpolate for Rgb565 { fn interpolate(&self, other: Self, frac: Frac) -> Self { if frac == Frac::ONE { return other; } if frac == Frac::ZERO { return *self; } // frac represents progress from self to other let frac_inv = Frac::ONE - frac; // For each color component, calculate: self * (1-frac) + other * frac let from_r = (frac_inv * self.r() as u32).round(); let from_g = (frac_inv * self.g() as u32).round(); let from_b = (frac_inv * self.b() as u32).round(); let to_r = (frac * other.r() as u32).round(); let to_g = (frac * other.g() as u32).round(); let to_b = (frac * other.b() as u32).round(); Rgb565::new( (from_r + to_r) as u8, (from_g + to_g) as u8, (from_b + to_b) as u8, ) } } impl ColorInterpolate for BinaryColor { fn interpolate(&self, other: Self, frac: Frac) -> Self { // For binary colors, use a threshold approach at 50% if frac > Frac::from_ratio(1, 2) { other } else { *self } } } impl ColorInterpolate for Gray2 { fn interpolate(&self, other: Self, frac: Frac) -> Self { if frac == Frac::ONE { return other; } if frac == Frac::ZERO { return *self; } let frac_inv = Frac::ONE - frac; let from_v = (frac_inv * self.luma() as u32).round(); let to_v = (frac * other.luma() as u32).round(); Gray2::new((from_v + to_v) as u8) } } impl ColorInterpolate for Gray4 { fn interpolate(&self, other: Self, frac: Frac) -> Self { if frac == Frac::ONE { return other; } if frac == Frac::ZERO { return *self; } let frac_inv = Frac::ONE - frac; let from_v = (frac_inv * self.luma() as u32).round(); let to_v = (frac * other.luma() as u32).round(); Gray4::new((from_v + to_v) as u8) } } /// Trait alias for colors that can be used with widgets pub trait WidgetColor: PixelColor + ColorInterpolate + core::fmt::Debug {} // Blanket implementation for any type that satisfies both bounds impl<C> WidgetColor for C where C: PixelColor + ColorInterpolate + core::fmt::Debug {}
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/layout/sized_box.rs
frostsnap_widgets/src/layout/sized_box.rs
use crate::super_draw_target::SuperDrawTarget; use crate::Widget; use embedded_graphics::{ draw_target::DrawTarget, pixelcolor::{PixelColor, Rgb565}, prelude::*, }; /// A simple widget that has a fixed size but no content #[derive(Debug, PartialEq)] pub struct SizedBox<C = Rgb565> { size: Size, _phantom: core::marker::PhantomData<C>, } impl<C> SizedBox<C> { pub fn new(size: Size) -> Self { Self { size, _phantom: core::marker::PhantomData, } } /// Create a SizedBox with only width set (height is 0) pub fn width(width: u32) -> Self { Self { size: Size::new(width, 0), _phantom: core::marker::PhantomData, } } /// Create a SizedBox with only height set (width is 0) pub fn height(height: u32) -> Self { Self { size: Size::new(0, height), _phantom: core::marker::PhantomData, } } } impl<C: PixelColor> crate::DynWidget for SizedBox<C> { fn set_constraints(&mut self, _max_size: Size) { // SizedBox has a fixed size, ignores constraints } fn sizing(&self) -> crate::Sizing { self.size.into() } fn handle_touch( &mut self, _point: Point, _current_time: crate::Instant, _lift_up: bool, ) -> Option<crate::KeyTouch> { None } fn handle_vertical_drag(&mut self, _prev_y: Option<u32>, _new_y: u32, _is_release: bool) { // No-op } } impl<C: crate::WidgetColor> Widget for SizedBox<C> { type Color = C; fn draw<D>( &mut self, _target: &mut SuperDrawTarget<D, Self::Color>, _current_time: crate::Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { // Don't draw anything - this is just a placeholder widget Ok(()) } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/layout/column.rs
frostsnap_widgets/src/layout/column.rs
use super::{AssociatedArray, CrossAxisAlignment, MainAxisAlignment, MainAxisSize}; use crate::super_draw_target::SuperDrawTarget; use crate::{Instant, Widget}; use alloc::vec::Vec; use embedded_graphics::{ draw_target::DrawTarget, geometry::{Point, Size}, primitives::Rectangle, }; /// A column widget that arranges its children vertically /// /// The Column widget takes a tuple of child widgets and arranges them vertically. /// You can control the distribution of children along the vertical axis using `MainAxisAlignment` /// and their horizontal alignment using `CrossAxisAlignment`. /// /// # Example /// ```ignore /// let column = Column::new((widget1, widget2, widget3)) /// .with_main_axis_alignment(MainAxisAlignment::SpaceBetween) /// .with_cross_axis_alignment(CrossAxisAlignment::Center); /// ``` #[derive(Clone)] pub struct Column<T: AssociatedArray> { pub children: T, pub cross_axis_alignment: CrossAxisAlignment, pub main_axis_alignment: MainAxisAlignment, pub main_axis_size: MainAxisSize, pub(crate) child_rects: T::Array<Rectangle>, pub(crate) debug_borders: bool, pub(crate) sizing: Option<crate::Sizing>, /// Spacing to add after each child (indexed by child position) pub(crate) spacing_after: T::Array<u32>, /// Flex scores for each child (0 means not flexible) pub(crate) flex_scores: T::Array<u32>, } /// Helper to start building a Column with no children impl Column<()> { pub fn builder() -> Self { Self::new(()) } } impl<T: AssociatedArray> Column<T> { pub fn with_cross_axis_alignment(mut self, alignment: CrossAxisAlignment) -> Self { self.cross_axis_alignment = alignment; self } pub fn with_main_axis_alignment(mut self, alignment: MainAxisAlignment) -> Self { self.main_axis_alignment = alignment; // Start alignment uses Min size by default, all others use Max if matches!(alignment, MainAxisAlignment::Start) { self.main_axis_size = MainAxisSize::Min; } else { self.main_axis_size = MainAxisSize::Max; } self } pub fn with_main_axis_size(mut self, size: MainAxisSize) -> Self { self.main_axis_size = size; self } pub fn with_debug_borders(mut self, enabled: bool) -> Self { self.debug_borders = enabled; self } } impl<T: AssociatedArray> Column<T> { pub fn new(children: T) -> Self { // Don't extract sizes here - wait for set_constraints to be called Self { child_rects: children.create_array_with(Rectangle::zero()), spacing_after: children.create_array_with(0), flex_scores: children.create_array_with(0), children, cross_axis_alignment: CrossAxisAlignment::Center, main_axis_alignment: MainAxisAlignment::Start, main_axis_size: MainAxisSize::Min, // Start alignment defaults to Min debug_borders: false, sizing: None, } } /// Set the gap after a specific child (in pixels) pub fn set_gap(&mut self, child_index: usize, gap: u32) { if child_index < self.spacing_after.as_ref().len() { self.spacing_after.as_mut()[child_index] = gap; } } /// Set the same gap after all children except the last pub fn set_uniform_gap(&mut self, gap: u32) { let spacing = self.spacing_after.as_mut(); let len = spacing.len(); if len > 0 { for space in spacing.iter_mut().take(len - 1) { *space = gap; } spacing[len - 1] = 0; // No gap after last child } } /// Set all children to have the same flex score pub fn set_all_flex(&mut self, flex: u32) { for score in self.flex_scores.as_mut() { *score = flex; } } /// Set a gap after the last added widget pub fn gap(mut self, gap: u32) -> Self { let len = self.children.len(); if len > 0 { self.spacing_after.as_mut()[len - 1] = gap; } self } /// Set the flex score for the last added widget pub fn flex(mut self, score: u32) -> Self { let len = self.children.len(); if len > 0 { self.flex_scores.as_mut()[len - 1] = score; } self } } impl<T: AssociatedArray> Column<T> { /// Add a widget to the column pub fn push<W>(self, widget: W) -> Column<<T as crate::layout::PushWidget<W>>::Output> where T: crate::layout::PushWidget<W>, W: crate::DynWidget, { if self.sizing.is_some() { panic!("Cannot push widgets after set_constraints has been called"); } let old_len = self.children.len(); let new_children = self.children.push_widget(widget); // Copy over existing values and add new ones let mut new_spacing = new_children.create_array_with(0); let old_spacing = self.spacing_after.as_ref(); new_spacing.as_mut()[..old_len].copy_from_slice(old_spacing); new_spacing.as_mut()[old_len] = 0; // Default gap is 0 let mut new_flex = new_children.create_array_with(0); let old_flex = self.flex_scores.as_ref(); new_flex.as_mut()[..old_len].copy_from_slice(old_flex); new_flex.as_mut()[old_len] = 0; // Default flex is 0 (not flexible) Column { child_rects: new_children.create_array_with(Rectangle::zero()), spacing_after: new_spacing, flex_scores: new_flex, children: new_children, cross_axis_alignment: self.cross_axis_alignment, main_axis_alignment: self.main_axis_alignment, main_axis_size: self.main_axis_size, debug_borders: self.debug_borders, sizing: None, } } } // Generic implementation for any type with AssociatedArray impl<T> crate::DynWidget for Column<T> where T: AssociatedArray, { fn set_constraints(&mut self, max_size: Size) { let len = self.children.len(); if len == 0 { self.sizing = Some(crate::Sizing { width: 0, height: 0, dirty_rect: None, }); return; } let mut remaining_height = max_size.height; let mut max_child_width = 0u32; // Account for all spacing in remaining height (but not after the last child) let spacing_after = self.spacing_after.as_ref(); let total_spacing: u32 = if len > 0 { spacing_after[..len - 1].iter().sum() } else { 0 }; remaining_height = remaining_height.saturating_sub(total_spacing); // Get flex scores and calculate total flex let flex_scores = self.flex_scores.as_ref(); let total_flex: u32 = flex_scores.iter().sum(); // Create dirty_rects array that we'll populate as we go let mut dirty_rects = self.child_rects.clone(); // First pass: set constraints on non-flex children for (i, &flex_score) in flex_scores.iter().enumerate() { if flex_score == 0 { if let Some(child) = self.children.get_dyn_child(i) { // Set constraints on non-flex child with remaining available height child.set_constraints(Size::new(max_size.width, remaining_height)); let sizing = child.sizing(); remaining_height = remaining_height.saturating_sub(sizing.height); max_child_width = max_child_width.max(sizing.width); self.child_rects.as_mut()[i].size = sizing.into(); // Set dirty rect based on child's actual dirty rect or full size if let Some(child_dirty) = sizing.dirty_rect { dirty_rects.as_mut()[i] = child_dirty; } else { dirty_rects.as_mut()[i] = self.child_rects.as_ref()[i]; } } } } let total_flex_height = remaining_height; // Second pass: set constraints on flex children and update cached rects with sizes for (i, &flex_score) in flex_scores.iter().enumerate() { if flex_score > 0 { if let Some(child) = self.children.get_dyn_child(i) { // Calculate height for this flex child based on its flex score let flex_height = (total_flex_height * flex_score) / total_flex; // Set constraints on flex child with calculated height child.set_constraints(Size::new(max_size.width, flex_height)); let sizing = child.sizing(); remaining_height = remaining_height.saturating_sub(sizing.height); max_child_width = max_child_width.max(sizing.width); self.child_rects.as_mut()[i].size = sizing.into(); // Set dirty rect based on child's actual dirty rect or full size if let Some(child_dirty) = sizing.dirty_rect { dirty_rects.as_mut()[i] = child_dirty; } else { dirty_rects.as_mut()[i] = self.child_rects.as_ref()[i]; } } } } // Now compute positions based on alignment let (mut y_offset, spacing) = match self.main_axis_alignment { MainAxisAlignment::Start => (0u32, 0u32), MainAxisAlignment::Center => (remaining_height / 2, 0), MainAxisAlignment::End => (remaining_height, 0), MainAxisAlignment::SpaceBetween => { if len > 1 { (0, remaining_height / (len as u32 - 1)) } else { (0, 0) } } MainAxisAlignment::SpaceAround => { let spacing = remaining_height / (len as u32); (spacing / 2, spacing) } MainAxisAlignment::SpaceEvenly => { let spacing = remaining_height / (len as u32 + 1); (spacing, spacing) } }; // Third pass: Set positions for all children and update dirty_rects positions let spacing_after = self.spacing_after.as_ref(); let child_rects = self.child_rects.as_mut(); for i in 0..len { let size = child_rects[i].size; let x_offset = match self.cross_axis_alignment { CrossAxisAlignment::Start => 0, CrossAxisAlignment::Center => { // Center within the column's actual width, not the constraint let available_width = max_child_width.saturating_sub(size.width); (available_width / 2) as i32 } CrossAxisAlignment::End => { // Align to the end of the column's actual width, not the constraint let available_width = max_child_width.saturating_sub(size.width); available_width as i32 } }; let position = Point::new(x_offset, y_offset as i32); child_rects[i].top_left = position; // Update the dirty rect position dirty_rects.as_mut()[i].top_left += position; // Add the child height y_offset = y_offset.saturating_add(size.height); // Add spacing after this child (but not after the last) if i < len - 1 { y_offset = y_offset.saturating_add(spacing_after[i]); } // Add alignment spacing y_offset = y_offset.saturating_add(spacing); } // Compute and store sizing based on MainAxisSize let height = match self.main_axis_size { MainAxisSize::Min => y_offset, // Only as tall as needed MainAxisSize::Max => max_size.height, // Take full available height }; // Compute the dirty rect - the actual area where children will draw let dirty_rect = super::bounding_rect(dirty_rects); self.sizing = Some(crate::Sizing { width: max_child_width, height, dirty_rect, }); } fn sizing(&self) -> crate::Sizing { self.sizing .expect("set_constraints must be called before sizing") } #[allow(clippy::needless_range_loop)] fn handle_touch( &mut self, point: Point, current_time: Instant, is_release: bool, ) -> Option<crate::KeyTouch> { let child_rects = self.child_rects.as_ref(); let len = self.children.len(); for i in 0..len { if let Some(child) = self.children.get_dyn_child(i) { let area = child_rects[i]; if area.contains(point) || is_release { let relative_point = Point::new(point.x - area.top_left.x, point.y - area.top_left.y); if let Some(mut key_touch) = child.handle_touch(relative_point, current_time, is_release) { // Translate the KeyTouch rectangle back to parent coordinates key_touch.translate(area.top_left); return Some(key_touch); } } } } None } #[allow(clippy::needless_range_loop)] fn handle_vertical_drag(&mut self, start_y: Option<u32>, current_y: u32, is_release: bool) { let len = self.children.len(); for i in 0..len { if let Some(child) = self.children.get_dyn_child(i) { child.handle_vertical_drag(start_y, current_y, is_release); } } } #[allow(clippy::needless_range_loop)] fn force_full_redraw(&mut self) { let len = self.children.len(); for i in 0..len { if let Some(child) = self.children.get_dyn_child(i) { child.force_full_redraw(); } } } } // Widget implementation for Column<Vec<W>> impl<W, C> Widget for Column<Vec<W>> where W: Widget<Color = C>, C: crate::WidgetColor, { type Color = C; fn draw<D>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, current_time: Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { self.sizing.unwrap(); // Draw each child in its pre-computed rectangle for (i, child) in self.children.iter_mut().enumerate() { child.draw(&mut target.clone().crop(self.child_rects[i]), current_time)?; // Draw debug border if enabled if self.debug_borders { super::draw_debug_rect(target, self.child_rects[i])?; } } Ok(()) } } // Widget implementation for Column<[W; N]> impl<W, C, const N: usize> Widget for Column<[W; N]> where W: Widget<Color = C>, C: crate::WidgetColor, { type Color = C; fn draw<D>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, current_time: Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { self.sizing.unwrap(); // Draw each child in its pre-computed rectangle for (i, child) in self.children.iter_mut().enumerate() { child.draw(&mut target.clone().crop(self.child_rects[i]), current_time)?; // Draw debug border if enabled if self.debug_borders { super::draw_debug_rect(target, self.child_rects[i])?; } } Ok(()) } } // Macro to implement Widget for Column with tuples of different sizes macro_rules! impl_column_for_tuple { ($len:literal, $($t:ident),+) => { // Implementation for tuple directly impl<$($t: Widget<Color = C>),+, C: crate::WidgetColor> Widget for Column<($($t,)+)> { type Color = C; #[allow(unused_assignments)] fn draw<D>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, current_time: Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { self.sizing.unwrap(); // Get mutable references to children #[allow(non_snake_case, unused_variables)] let ($(ref mut $t,)+) = self.children; // Draw each child in its pre-computed rectangle let mut child_index = 0; $( { $t.draw(&mut target.clone().crop(self.child_rects[child_index]), current_time)?; // Draw debug border if enabled if self.debug_borders { super::draw_debug_rect(target, self.child_rects[child_index])?; } child_index += 1; } )+ Ok(()) } } // Implementation for Box<tuple> impl<$($t: Widget<Color = C>),+, C: crate::WidgetColor> Widget for Column<alloc::boxed::Box<($($t,)+)>> { type Color = C; #[allow(unused_assignments)] fn draw<D>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, current_time: Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { self.sizing.unwrap(); // Get mutable references to children through dereferencing #[allow(non_snake_case, unused_variables)] let ($(ref mut $t,)+) = &mut *self.children; // Draw each child in its pre-computed rectangle let mut child_index = 0; $( { $t.draw(&mut target.clone().crop(self.child_rects[child_index]), current_time)?; // Draw debug border if enabled if self.debug_borders { super::draw_debug_rect(target, self.child_rects[child_index])?; } child_index += 1; } )+ Ok(()) } } }; } // Generate implementations for tuples up to 20 elements impl_column_for_tuple!(1, T1); impl_column_for_tuple!(2, T1, T2); impl_column_for_tuple!(3, T1, T2, T3); impl_column_for_tuple!(4, T1, T2, T3, T4); impl_column_for_tuple!(5, T1, T2, T3, T4, T5); impl_column_for_tuple!(6, T1, T2, T3, T4, T5, T6); impl_column_for_tuple!(7, T1, T2, T3, T4, T5, T6, T7); impl_column_for_tuple!(8, T1, T2, T3, T4, T5, T6, T7, T8); impl_column_for_tuple!(9, T1, T2, T3, T4, T5, T6, T7, T8, T9); impl_column_for_tuple!(10, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10); impl_column_for_tuple!(11, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11); impl_column_for_tuple!(12, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12); impl_column_for_tuple!(13, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13); impl_column_for_tuple!(14, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14); impl_column_for_tuple!(15, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15); impl_column_for_tuple!(16, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16); impl_column_for_tuple!( 17, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17 ); impl_column_for_tuple!( 18, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18 ); impl_column_for_tuple!( 19, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19 ); impl_column_for_tuple!( 20, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20 );
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false
frostsnap/frostsnap
https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/layout/row.rs
frostsnap_widgets/src/layout/row.rs
use super::{AssociatedArray, CrossAxisAlignment, MainAxisAlignment, MainAxisSize}; use crate::super_draw_target::SuperDrawTarget; use crate::{Instant, Widget}; use alloc::vec::Vec; use embedded_graphics::{ draw_target::DrawTarget, geometry::{Point, Size}, primitives::Rectangle, }; /// A row widget that arranges its children horizontally /// /// The Row widget takes a tuple of child widgets and arranges them horizontally. /// You can control the distribution of children along the horizontal axis using `MainAxisAlignment` /// and their vertical alignment using `CrossAxisAlignment`. /// /// # Example /// ```ignore /// let row = Row::new((widget1, widget2, widget3)) /// .with_main_axis_alignment(MainAxisAlignment::SpaceBetween) /// .with_cross_axis_alignment(CrossAxisAlignment::Center); /// ``` #[derive(PartialEq, Clone)] pub struct Row<T: AssociatedArray> { pub children: T, pub cross_axis_alignment: CrossAxisAlignment, pub main_axis_alignment: MainAxisAlignment, pub main_axis_size: MainAxisSize, pub(crate) child_rects: T::Array<Rectangle>, pub(crate) debug_borders: bool, pub(crate) sizing: Option<crate::Sizing>, /// Spacing to add after each child (indexed by child position) pub(crate) spacing_after: T::Array<u32>, /// Flex scores for each child (0 means not flexible) pub(crate) flex_scores: T::Array<u32>, } /// Helper to start building a Row with no children impl Row<()> { pub fn builder() -> Self { Self::new(()) } } impl<T: AssociatedArray> Row<T> { pub fn new(children: T) -> Self { // Don't extract sizes here - wait for set_constraints to be called Self { child_rects: children.create_array_with(Rectangle::zero()), spacing_after: children.create_array_with(0), flex_scores: children.create_array_with(0), children, cross_axis_alignment: CrossAxisAlignment::Center, main_axis_alignment: MainAxisAlignment::Start, main_axis_size: MainAxisSize::Min, // Start alignment defaults to Min debug_borders: false, sizing: None, } } /// Set the gap after a specific child (in pixels) pub fn set_gap(&mut self, child_index: usize, gap: u32) { if child_index < self.spacing_after.as_ref().len() { self.spacing_after.as_mut()[child_index] = gap; } } /// Set the same gap after all children except the last pub fn set_uniform_gap(&mut self, gap: u32) { let spacing = self.spacing_after.as_mut(); let len = spacing.len(); if len > 0 { for space in spacing.iter_mut().take(len - 1) { *space = gap; } spacing[len - 1] = 0; // No gap after last child } } /// Set all children to have the same flex score pub fn set_all_flex(&mut self, flex: u32) { for score in self.flex_scores.as_mut() { *score = flex; } } /// Set a gap after the last added widget pub fn gap(mut self, gap: u32) -> Self { let len = self.children.len(); if len > 0 { self.spacing_after.as_mut()[len - 1] = gap; } self } /// Set the flex score for the last added widget pub fn flex(mut self, score: u32) -> Self { let len = self.children.len(); if len > 0 { self.flex_scores.as_mut()[len - 1] = score; } self } pub fn with_cross_axis_alignment(mut self, alignment: CrossAxisAlignment) -> Self { self.cross_axis_alignment = alignment; self } pub fn with_main_axis_alignment(mut self, alignment: MainAxisAlignment) -> Self { self.main_axis_alignment = alignment; // Start alignment uses Min size by default, all others use Max if matches!(alignment, MainAxisAlignment::Start) { self.main_axis_size = MainAxisSize::Min; } else { self.main_axis_size = MainAxisSize::Max; } self } pub fn with_main_axis_size(mut self, size: MainAxisSize) -> Self { self.main_axis_size = size; self } pub fn with_debug_borders(mut self, enabled: bool) -> Self { self.debug_borders = enabled; self } } impl<T: AssociatedArray> Row<T> { /// Add a widget to the row pub fn push<W>(self, widget: W) -> Row<<T as crate::layout::PushWidget<W>>::Output> where T: crate::layout::PushWidget<W>, W: crate::DynWidget, { if self.sizing.is_some() { panic!("Cannot push widgets after set_constraints has been called"); } let old_len = self.children.len(); let new_children = self.children.push_widget(widget); // Copy over existing values and add new ones let mut new_spacing = new_children.create_array_with(0); let old_spacing = self.spacing_after.as_ref(); new_spacing.as_mut()[..old_len].copy_from_slice(old_spacing); new_spacing.as_mut()[old_len] = 0; // Default gap is 0 let mut new_flex = new_children.create_array_with(0); let old_flex = self.flex_scores.as_ref(); new_flex.as_mut()[..old_len].copy_from_slice(old_flex); new_flex.as_mut()[old_len] = 0; // Default flex is 0 (not flexible) Row { child_rects: new_children.create_array_with(Rectangle::zero()), spacing_after: new_spacing, flex_scores: new_flex, children: new_children, cross_axis_alignment: self.cross_axis_alignment, main_axis_alignment: self.main_axis_alignment, main_axis_size: self.main_axis_size, debug_borders: self.debug_borders, sizing: None, } } } // Macro to implement Widget for Row with tuples of different sizes macro_rules! impl_row_for_tuple { ($len:literal, $($t:ident),+) => { impl<$($t: Widget<Color = C>),+, C: crate::WidgetColor> Widget for Row<($($t,)+)> { type Color = C; #[allow(unused_assignments)] fn draw<D>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, current_time: Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { self.sizing.unwrap(); // Get mutable references to children #[allow(non_snake_case, unused_variables)] let ($(ref mut $t,)+) = self.children; // Draw each child in its pre-computed rectangle let mut child_index = 0; $( { $t.draw(&mut target.clone().crop(self.child_rects[child_index]), current_time)?; // Draw debug border if enabled if self.debug_borders { super::draw_debug_rect(target, self.child_rects[child_index])?; } child_index += 1; } )+ Ok(()) } } }; } // Generate implementations for tuples up to 20 elements impl_row_for_tuple!(1, T1); impl_row_for_tuple!(2, T1, T2); impl_row_for_tuple!(3, T1, T2, T3); impl_row_for_tuple!(4, T1, T2, T3, T4); impl_row_for_tuple!(5, T1, T2, T3, T4, T5); impl_row_for_tuple!(6, T1, T2, T3, T4, T5, T6); impl_row_for_tuple!(7, T1, T2, T3, T4, T5, T6, T7); impl_row_for_tuple!(8, T1, T2, T3, T4, T5, T6, T7, T8); impl_row_for_tuple!(9, T1, T2, T3, T4, T5, T6, T7, T8, T9); impl_row_for_tuple!(10, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10); impl_row_for_tuple!(11, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11); impl_row_for_tuple!(12, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12); impl_row_for_tuple!(13, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13); impl_row_for_tuple!(14, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14); impl_row_for_tuple!(15, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15); impl_row_for_tuple!(16, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16); impl_row_for_tuple!(17, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17); impl_row_for_tuple!( 18, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18 ); impl_row_for_tuple!( 19, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19 ); impl_row_for_tuple!( 20, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20 ); // Generic DynWidget implementation for Row impl<T> crate::DynWidget for Row<T> where T: AssociatedArray, { fn set_constraints(&mut self, max_size: Size) { let len = self.children.len(); if len == 0 { self.sizing = Some(Default::default()); return; } let mut remaining_width = max_size.width; let mut max_child_height = 0u32; // Account for all spacing in remaining width (but not after the last child) let spacing_after = self.spacing_after.as_ref(); let total_spacing: u32 = if len > 0 { spacing_after[..len - 1].iter().sum() } else { 0 }; remaining_width = remaining_width.saturating_sub(total_spacing); // Get flex scores and calculate total flex let flex_scores = self.flex_scores.as_ref(); let total_flex: u32 = flex_scores.iter().sum(); // Create dirty_rects array that we'll populate as we go let mut dirty_rects = self.child_rects.clone(); // First pass: set constraints on non-flex children for (i, &flex_score) in flex_scores.iter().enumerate() { if flex_score == 0 { if let Some(child) = self.children.get_dyn_child(i) { // Set constraints on non-flex child with remaining available width child.set_constraints(Size::new(remaining_width, max_size.height)); let sizing = child.sizing(); remaining_width = remaining_width.saturating_sub(sizing.width); max_child_height = max_child_height.max(sizing.height); self.child_rects.as_mut()[i].size = sizing.into(); // Set dirty rect based on child's actual dirty rect or full size if let Some(child_dirty) = sizing.dirty_rect { dirty_rects.as_mut()[i] = child_dirty; } else { dirty_rects.as_mut()[i] = self.child_rects.as_ref()[i]; } } } } let total_flex_width = remaining_width; // Second pass: set constraints on flex children and update cached rects with sizes for (i, &flex_score) in flex_scores.iter().enumerate().take(len) { if flex_score > 0 { if let Some(child) = self.children.get_dyn_child(i) { // Calculate width for this flex child based on its flex score let flex_width = (total_flex_width * flex_score) / total_flex; // Set constraints on flex child with calculated width child.set_constraints(Size::new(flex_width, max_size.height)); let sizing = child.sizing(); remaining_width = remaining_width.saturating_sub(sizing.width); max_child_height = max_child_height.max(sizing.height); self.child_rects.as_mut()[i].size = sizing.into(); // Set dirty rect based on child's actual dirty rect or full size if let Some(child_dirty) = sizing.dirty_rect { dirty_rects.as_mut()[i] = child_dirty; } else { dirty_rects.as_mut()[i] = self.child_rects.as_ref()[i]; } } } } // Now compute positions based on alignment let (mut x_offset, spacing) = match self.main_axis_alignment { MainAxisAlignment::Start => (0u32, 0u32), MainAxisAlignment::Center => (remaining_width / 2, 0), MainAxisAlignment::End => (remaining_width, 0), MainAxisAlignment::SpaceBetween => { if len > 1 { (0, remaining_width / (len as u32 - 1)) } else { (0, 0) } } MainAxisAlignment::SpaceAround => { let spacing = remaining_width / (len as u32); (spacing / 2, spacing) } MainAxisAlignment::SpaceEvenly => { let spacing = remaining_width / (len as u32 + 1); (spacing, spacing) } }; // Third pass: Set positions for all children and update dirty_rects positions let spacing_after = self.spacing_after.as_ref(); let child_rects = self.child_rects.as_mut(); for i in 0..len { let size = child_rects[i].size; let y_offset = match self.cross_axis_alignment { CrossAxisAlignment::Start => 0, CrossAxisAlignment::Center => { let available_height = max_child_height.saturating_sub(size.height); (available_height / 2) as i32 } CrossAxisAlignment::End => { let available_height = max_child_height.saturating_sub(size.height); available_height as i32 } }; let position = Point::new(x_offset as i32, y_offset); child_rects[i].top_left = position; // Update the dirty rect position dirty_rects.as_mut()[i].top_left += position; // Add the child width x_offset = x_offset.saturating_add(size.width); // Add spacing after this child (but not after the last) if i < len - 1 { x_offset = x_offset.saturating_add(spacing_after[i]); } // Add alignment spacing x_offset = x_offset.saturating_add(spacing); } // Compute and store sizing based on MainAxisSize let width = match self.main_axis_size { MainAxisSize::Min => x_offset, // Only as wide as needed MainAxisSize::Max => max_size.width, // Take full available width }; // Compute the dirty rect - the actual area where children will draw let dirty_rect = super::bounding_rect(dirty_rects); self.sizing = Some(crate::Sizing { width, height: max_child_height, dirty_rect, }); } fn sizing(&self) -> crate::Sizing { self.sizing .expect("set_constraints must be called before sizing") } #[allow(clippy::needless_range_loop)] fn handle_touch( &mut self, point: Point, current_time: Instant, is_release: bool, ) -> Option<crate::KeyTouch> { let child_rects = self.child_rects.as_ref(); let len = self.children.len(); for i in 0..len { let area = child_rects[i]; if let Some(child) = self.children.get_dyn_child(i) { if area.contains(point) || is_release { let relative_point = Point::new(point.x - area.top_left.x, point.y - area.top_left.y); if let Some(mut key_touch) = child.handle_touch(relative_point, current_time, is_release) { // Translate the KeyTouch rectangle back to parent coordinates key_touch.translate(area.top_left); return Some(key_touch); } } } } None } #[allow(clippy::needless_range_loop)] fn handle_vertical_drag(&mut self, start_y: Option<u32>, current_y: u32, is_release: bool) { let len = self.children.len(); for i in 0..len { if let Some(child) = self.children.get_dyn_child(i) { child.handle_vertical_drag(start_y, current_y, is_release); } } } #[allow(clippy::needless_range_loop)] fn force_full_redraw(&mut self) { let len = self.children.len(); for i in 0..len { if let Some(child) = self.children.get_dyn_child(i) { child.force_full_redraw(); } } } } // Widget implementation for Row<Vec<W>> impl<W, C> Widget for Row<Vec<W>> where W: Widget<Color = C>, C: crate::WidgetColor, { type Color = C; fn draw<D>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, current_time: Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { self.sizing.unwrap(); // Draw each child in its pre-computed rectangle for (i, child) in self.children.iter_mut().enumerate() { child.draw(&mut target.clone().crop(self.child_rects[i]), current_time)?; // Draw debug border if enabled if self.debug_borders { super::draw_debug_rect(target, self.child_rects[i])?; } } Ok(()) } } // Widget implementation for Row<[W; N]> impl<W, C, const N: usize> Widget for Row<[W; N]> where W: Widget<Color = C>, C: crate::WidgetColor, { type Color = C; fn draw<D>( &mut self, target: &mut SuperDrawTarget<D, Self::Color>, current_time: Instant, ) -> Result<(), D::Error> where D: DrawTarget<Color = Self::Color>, { self.sizing.unwrap(); // Draw each child in its pre-computed rectangle for (i, child) in self.children.iter_mut().enumerate() { child.draw(&mut target.clone().crop(self.child_rects[i]), current_time)?; // Draw debug border if enabled if self.debug_borders { super::draw_debug_rect(target, self.child_rects[i])?; } } Ok(()) } }
rust
MIT
961deb080a81c754f402aaea24286bd141178e9d
2026-01-04T20:21:09.467677Z
false