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/frostsnap_widgets/src/layout/container.rs | frostsnap_widgets/src/layout/container.rs | use crate::super_draw_target::SuperDrawTarget;
use crate::Widget;
use embedded_graphics::{
draw_target::DrawTarget,
prelude::*,
primitives::{Rectangle, RoundedRectangle, StrokeAlignment},
};
/// A container that can optionally draw a border around its child
#[derive(PartialEq)]
pub struct Container<W>
where
W: Widget,
{
pub child: W,
width: Option<u32>, // None = shrink-wrap, Some(width) = explicit width (including MAX for fill)
height: Option<u32>, // None = shrink-wrap, Some(height) = explicit height (including MAX for fill)
border_color: Option<W::Color>,
border_width: u32,
fill_color: Option<W::Color>,
corner_radius: Option<Size>,
border_needs_redraw: bool,
computed_sizing: Option<crate::Sizing>,
child_rect: Option<Rectangle>,
}
impl<W: Widget> Container<W> {
/// Create a container that inherits size from its child
pub fn new(child: W) -> Self {
Self {
child,
width: None,
height: None,
border_color: None,
border_width: 0,
fill_color: None,
corner_radius: None,
border_needs_redraw: true,
computed_sizing: None,
child_rect: None,
}
}
/// Create a container with an explicit size
pub fn with_size(child: W, size: Size) -> Self {
Self {
child,
width: Some(size.width),
height: Some(size.height),
border_color: None,
border_width: 0,
fill_color: None,
corner_radius: None,
border_needs_redraw: true,
computed_sizing: None,
child_rect: None,
}
}
/// Set the width of the container
pub fn with_width(mut self, width: u32) -> Self {
self.width = Some(width);
self
}
/// Set the height of the container
pub fn with_height(mut self, height: u32) -> Self {
self.height = Some(height);
self
}
/// Set the border with a color and width
pub fn with_border(mut self, color: W::Color, width: u32) -> Self {
self.border_color = Some(color);
self.border_width = width;
self
}
/// Set the fill color
pub fn with_fill(mut self, color: W::Color) -> Self {
self.fill_color = Some(color);
self
}
/// Get the current fill color
pub fn fill_color(&self) -> Option<W::Color> {
self.fill_color
}
/// Set the fill color (mutable reference)
pub fn set_fill(&mut self, color: W::Color) {
self.fill_color = Some(color);
self.border_needs_redraw = true;
self.child.force_full_redraw();
}
/// Set the corner radius for rounded borders
pub fn with_corner_radius(mut self, corner_radius: Size) -> Self {
self.corner_radius = Some(corner_radius);
self
}
/// Set the container to expanded mode - it will fill the available space
pub fn with_expanded(mut self) -> Self {
// Expanded means requesting u32::MAX size
self.width = Some(u32::MAX);
self.height = Some(u32::MAX);
self
}
}
impl<W: Widget> crate::DynWidget for Container<W> {
fn set_constraints(&mut self, max_size: Size) {
// Calculate child constraints based on our width and height settings
let container_width = self.width.unwrap_or(max_size.width).min(max_size.width);
let container_height = self.height.unwrap_or(max_size.height).min(max_size.height);
let child_max_size = Size::new(
container_width.saturating_sub(2 * self.border_width),
container_height.saturating_sub(2 * self.border_width),
);
self.child.set_constraints(child_max_size);
// Now compute and store the sizing
let child_sizing = self.child.sizing();
// Calculate width: use explicit width if set, otherwise shrink-wrap
let width = if let Some(requested_width) = self.width {
requested_width.min(max_size.width)
} else {
child_sizing.width + 2 * self.border_width
};
// Calculate height: use explicit height if set, otherwise shrink-wrap
let height = if let Some(requested_height) = self.height {
requested_height.min(max_size.height)
} else {
child_sizing.height + 2 * self.border_width
};
// If no border, use the child's dirty rect offset by where the child is positioned
// If there's a border, the whole container area is dirty
let dirty_rect = if self.border_width == 0 {
self.child.sizing().dirty_rect
} else {
// With a border, the whole container is the dirty rect
None
};
self.computed_sizing = Some(crate::Sizing {
width,
height,
dirty_rect,
});
// Also compute and store the child rectangle
self.child_rect = Some(Rectangle::new(
Point::new(self.border_width as i32, self.border_width as i32),
Size::new(
width.saturating_sub(2 * self.border_width),
height.saturating_sub(2 * self.border_width),
),
));
}
fn sizing(&self) -> crate::Sizing {
self.computed_sizing
.expect("set_constraints must be called before sizing")
}
fn handle_touch(
&mut self,
point: Point,
current_time: crate::Instant,
is_release: bool,
) -> Option<crate::KeyTouch> {
// Offset point by border width when passing to child
let child_point = Point::new(
point.x - self.border_width as i32,
point.y - self.border_width as i32,
);
if let Some(mut key_touch) = self
.child
.handle_touch(child_point, current_time, is_release)
{
// Translate the KeyTouch rectangle back to parent coordinates
key_touch.translate(Point::new(
self.border_width as i32,
self.border_width as i32,
));
Some(key_touch)
} else {
None
}
}
fn handle_vertical_drag(&mut self, prev_y: Option<u32>, new_y: u32, is_release: bool) {
self.child.handle_vertical_drag(prev_y, new_y, is_release);
}
fn force_full_redraw(&mut self) {
self.border_needs_redraw = true;
self.child.force_full_redraw();
}
}
impl<W: Widget> Widget for Container<W> {
type Color = W::Color;
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 child_area = self
.child_rect
.expect("set_constraints must be called before draw");
// Draw border if needed
if self.border_needs_redraw && (self.border_color.is_some() || self.fill_color.is_some()) {
let container_size = Size::from(
self.computed_sizing
.expect("set_constraints must be called before draw"),
);
let border_rect = Rectangle::new(Point::zero(), container_size);
// Build the primitive style with inside stroke alignment
let mut style_builder = embedded_graphics::primitives::PrimitiveStyleBuilder::new();
if let Some(fill_color) = self.fill_color {
style_builder = style_builder.fill_color(fill_color);
}
if let Some(border_color) = self.border_color {
style_builder = style_builder
.stroke_color(border_color)
.stroke_width(self.border_width)
.stroke_alignment(StrokeAlignment::Inside);
}
let style = style_builder.build();
if let Some(corner_radius) = self.corner_radius {
RoundedRectangle::with_equal_corners(border_rect, corner_radius)
.into_styled(style)
.draw(target)?;
} else {
border_rect.into_styled(style).draw(target)?;
}
self.border_needs_redraw = false;
}
// Draw child with proper offset and cropping
// If we have a fill color, set it as the background for the cropped area
let mut child_target = target.clone().crop(child_area);
if let Some(fill_color) = self.fill_color {
child_target = child_target.with_background_color(fill_color);
}
self.child.draw(&mut child_target, current_time)?;
Ok(())
}
}
impl<W: Widget> core::fmt::Debug for Container<W>
where
W: core::fmt::Debug,
{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Container")
.field("child", &self.child)
.field("width", &self.width)
.field("height", &self.height)
.field("has_border", &self.border_color.is_some())
.field("border_width", &self.border_width)
.finish()
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/layout/alignment.rs | frostsnap_widgets/src/layout/alignment.rs | use crate::Widget;
use crate::{super_draw_target::SuperDrawTarget, Instant};
use embedded_graphics::{
draw_target::DrawTarget,
geometry::{Point, Size},
primitives::Rectangle,
};
/// Alignment for positioning widgets
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub enum Alignment {
#[default]
TopLeft,
TopCenter,
TopRight,
CenterLeft,
Center,
CenterRight,
BottomLeft,
BottomCenter,
BottomRight,
}
impl Alignment {
/// Calculate the x offset for the given alignment
pub fn x_offset(&self, container_width: u32, child_width: u32) -> i32 {
match self {
Alignment::TopLeft | Alignment::CenterLeft | Alignment::BottomLeft => 0,
Alignment::TopCenter | Alignment::Center | Alignment::BottomCenter => {
((container_width.saturating_sub(child_width)) / 2) as i32
}
Alignment::TopRight | Alignment::CenterRight | Alignment::BottomRight => {
(container_width.saturating_sub(child_width)) as i32
}
}
}
/// Calculate the y offset for the given alignment
pub fn y_offset(&self, container_height: u32, child_height: u32) -> i32 {
match self {
Alignment::TopLeft | Alignment::TopCenter | Alignment::TopRight => 0,
Alignment::CenterLeft | Alignment::Center | Alignment::CenterRight => {
((container_height.saturating_sub(child_height)) / 2) as i32
}
Alignment::BottomLeft | Alignment::BottomCenter | Alignment::BottomRight => {
(container_height.saturating_sub(child_height)) as i32
}
}
}
/// Calculate both x and y offsets
pub fn offset(&self, container_size: Size, child_size: Size) -> Point {
Point::new(
self.x_offset(container_size.width, child_size.width),
self.y_offset(container_size.height, child_size.height),
)
}
}
/// Horizontal alignment options
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum HorizontalAlignment {
Left,
Center,
Right,
}
impl HorizontalAlignment {
pub fn x_offset(&self, container_width: u32, child_width: u32) -> i32 {
match self {
HorizontalAlignment::Left => 0,
HorizontalAlignment::Center => {
((container_width.saturating_sub(child_width)) / 2) as i32
}
HorizontalAlignment::Right => (container_width.saturating_sub(child_width)) as i32,
}
}
}
/// Vertical alignment options
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum VerticalAlignment {
Top,
Center,
Bottom,
}
impl VerticalAlignment {
pub fn y_offset(&self, container_height: u32, child_height: u32) -> i32 {
match self {
VerticalAlignment::Top => 0,
VerticalAlignment::Center => {
((container_height.saturating_sub(child_height)) / 2) as i32
}
VerticalAlignment::Bottom => (container_height.saturating_sub(child_height)) as i32,
}
}
}
/// A widget that aligns its child with customizable horizontal and vertical alignment
#[derive(PartialEq)]
pub struct Align<W> {
pub child: W,
pub horizontal: HorizontalAlignment,
pub vertical: VerticalAlignment,
constraints: Option<Size>,
child_rect: Rectangle,
}
impl<W> Align<W> {
/// Create an Align widget that expands to fill available space
pub fn new(child: W) -> Self {
Self {
child,
horizontal: HorizontalAlignment::Center,
vertical: VerticalAlignment::Center,
constraints: None,
child_rect: Rectangle::zero(),
}
}
/// Set horizontal alignment (consumes self for chaining)
pub fn horizontal(mut self, alignment: HorizontalAlignment) -> Self {
self.horizontal = alignment;
self
}
/// Set vertical alignment (consumes self for chaining)
pub fn vertical(mut self, alignment: VerticalAlignment) -> Self {
self.vertical = alignment;
self
}
/// Set alignment using the combined Alignment enum
pub fn alignment(mut self, alignment: Alignment) -> Self {
let (horizontal, vertical) = match alignment {
Alignment::TopLeft => (HorizontalAlignment::Left, VerticalAlignment::Top),
Alignment::TopCenter => (HorizontalAlignment::Center, VerticalAlignment::Top),
Alignment::TopRight => (HorizontalAlignment::Right, VerticalAlignment::Top),
Alignment::CenterLeft => (HorizontalAlignment::Left, VerticalAlignment::Center),
Alignment::Center => (HorizontalAlignment::Center, VerticalAlignment::Center),
Alignment::CenterRight => (HorizontalAlignment::Right, VerticalAlignment::Center),
Alignment::BottomLeft => (HorizontalAlignment::Left, VerticalAlignment::Bottom),
Alignment::BottomCenter => (HorizontalAlignment::Center, VerticalAlignment::Bottom),
Alignment::BottomRight => (HorizontalAlignment::Right, VerticalAlignment::Bottom),
};
self.horizontal = horizontal;
self.vertical = vertical;
self
}
}
impl<W: Widget> crate::DynWidget for Align<W> {
fn set_constraints(&mut self, max_size: Size) {
self.constraints = Some(max_size);
self.child.set_constraints(max_size);
let child_size: Size = self.child.sizing().into();
// Calculate position based on alignment settings
let x_offset = self.horizontal.x_offset(max_size.width, child_size.width);
let y_offset = self.vertical.y_offset(max_size.height, child_size.height);
self.child_rect = Rectangle::new(Point::new(x_offset, y_offset), child_size);
}
fn sizing(&self) -> crate::Sizing {
let constraints = self.constraints.unwrap();
let child_sizing = self.child.sizing();
// The dirty rect is where the child actually draws, offset by the alignment position
let mut child_dirty = child_sizing.dirty_rect();
child_dirty.top_left += self.child_rect.top_left;
let dirty_rect = Some(child_dirty);
// Only expand when alignment requires it
crate::Sizing {
width: match self.horizontal {
HorizontalAlignment::Left => child_sizing.width,
_ => constraints.width,
},
height: match self.vertical {
VerticalAlignment::Top => child_sizing.height,
_ => constraints.height,
},
dirty_rect,
}
}
fn handle_touch(
&mut self,
point: Point,
current_time: Instant,
is_release: bool,
) -> Option<crate::KeyTouch> {
// Check if the touch is within the child's bounds
if self.child_rect.contains(point) || is_release {
// Translate the touch point to the child's coordinate system
let translated_point = Point::new(
point.x - self.child_rect.top_left.x,
point.y - self.child_rect.top_left.y,
);
if let Some(mut key_touch) =
self.child
.handle_touch(translated_point, current_time, is_release)
{
// Translate the KeyTouch rectangle back to parent coordinates
key_touch.translate(self.child_rect.top_left);
Some(key_touch)
} else {
None
}
} else {
None
}
}
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> Widget for Align<W> {
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.constraints.unwrap();
self.child
.draw(&mut target.clone().crop(self.child_rect), 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/layout/center.rs | frostsnap_widgets/src/layout/center.rs | use crate::Widget;
use crate::{super_draw_target::SuperDrawTarget, Instant};
use embedded_graphics::{
draw_target::DrawTarget,
geometry::{Point, Size},
primitives::Rectangle,
};
/// A widget that centers its child both horizontally and vertically
#[derive(PartialEq)]
pub struct Center<W> {
pub child: W,
constraints: Option<Size>,
child_rect: Rectangle,
sizing: crate::Sizing,
}
impl<W> Center<W> {
pub fn new(child: W) -> Self {
Self {
child,
constraints: None,
child_rect: Rectangle::zero(),
sizing: crate::Sizing::default(),
}
}
}
impl<W: Widget> crate::DynWidget for Center<W> {
fn set_constraints(&mut self, max_size: Size) {
self.constraints = Some(max_size);
self.child.set_constraints(max_size);
// Calculate centered position for child
let child_sizing = self.child.sizing();
let child_size: Size = child_sizing.into();
let x_offset = ((max_size.width as i32 - child_size.width as i32) / 2).max(0);
let y_offset = ((max_size.height as i32 - child_size.height as i32) / 2).max(0);
self.child_rect = Rectangle::new(Point::new(x_offset, y_offset), child_size);
// Calculate our sizing with the child's dirty_rect offset by the centering position
let mut child_dirty = child_sizing.dirty_rect();
child_dirty.top_left += self.child_rect.top_left;
let dirty_rect = Some(child_dirty);
self.sizing = crate::Sizing {
width: max_size.width,
height: max_size.height,
dirty_rect,
};
}
fn sizing(&self) -> crate::Sizing {
self.sizing
}
fn handle_touch(
&mut self,
point: Point,
current_time: Instant,
is_release: bool,
) -> Option<crate::KeyTouch> {
// Check if the touch is within the child's bounds
if self.child_rect.contains(point) {
// Translate the touch point to the child's coordinate system
let translated_point = Point::new(
point.x - self.child_rect.top_left.x,
point.y - self.child_rect.top_left.y,
);
if let Some(mut key_touch) =
self.child
.handle_touch(translated_point, current_time, is_release)
{
// Translate the KeyTouch rectangle back to parent coordinates
key_touch.translate(self.child_rect.top_left);
Some(key_touch)
} else {
None
}
} else {
None
}
}
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> Widget for Center<W> {
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.constraints.unwrap();
self.child
.draw(&mut target.clone().crop(self.child_rect), 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/layout/collections.rs | frostsnap_widgets/src/layout/collections.rs | //! Implementations of AssociatedArray and PushWidget for various collection types
use super::{AssociatedArray, PushWidget};
use alloc::{boxed::Box, vec, vec::Vec};
// The empty tuple needs special handling since it has no widgets
// We implement DynWidget for it to make everything work
impl crate::DynWidget for () {
fn set_constraints(&mut self, _max_size: embedded_graphics::geometry::Size) {}
fn sizing(&self) -> crate::Sizing {
Default::default()
}
}
// Implementation of AssociatedArray for empty tuple
impl AssociatedArray for () {
type Array<T: Clone> = [T; 0];
fn create_array_with<T: Copy>(&self, _value: T) -> Self::Array<T> {
[]
}
fn get_dyn_child(&mut self, _index: usize) -> Option<&mut dyn crate::DynWidget> {
None
}
fn len(&self) -> usize {
0
}
}
// PushWidget implementation for empty tuple - can push any widget type
impl<W: crate::DynWidget> PushWidget<W> for () {
type Output = (W,);
fn push_widget(self, widget: W) -> Self::Output {
(widget,)
}
}
// Macro to implement both AssociatedArray and PushWidget for tuples
macro_rules! impl_widget_tuple {
($len:literal, $($t:ident),+) => {
impl<$($t: crate::DynWidget),+> AssociatedArray for ($($t,)+) {
type Array<T: Clone> = [T; $len];
fn create_array_with<T: Copy>(&self, value: T) -> Self::Array<T> {
[value; $len]
}
fn get_dyn_child(&mut self, index: usize) -> Option<&mut dyn crate::DynWidget> {
#[allow(non_snake_case, unused_assignments, unused_mut)]
let ($(ref mut $t,)+) = self;
#[allow(unused_mut, unused_assignments)]
let mut i = 0;
$(
if i == index {
return Some($t as &mut dyn crate::DynWidget);
}
#[allow(unused_assignments)]
{ i += 1; }
)+
None
}
fn len(&self) -> usize {
$len
}
}
// PushWidget implementation for tuples - can push any widget type
impl<$($t: crate::DynWidget,)+ W: crate::DynWidget> PushWidget<W> for ($($t,)+) {
type Output = ($($t,)+ W);
fn push_widget(self, widget: W) -> Self::Output {
#[allow(non_snake_case)]
let ($($t,)+) = self;
($($t,)+ widget)
}
}
// Box implementation for heap allocation
impl<$($t: crate::DynWidget),+> AssociatedArray for Box<($($t,)+)> {
type Array<T: Clone> = Box<[T]>;
fn create_array_with<T: Copy>(&self, value: T) -> Self::Array<T> {
vec![value; $len].into_boxed_slice()
}
fn get_dyn_child(&mut self, index: usize) -> Option<&mut dyn crate::DynWidget> {
#[allow(non_snake_case, unused_assignments, unused_mut)]
let ($(ref mut $t,)+) = &mut **self;
#[allow(unused_mut, unused_assignments)]
let mut i = 0;
$(
if i == index {
return Some($t as &mut dyn crate::DynWidget);
}
#[allow(unused_assignments)]
{ i += 1; }
)+
None
}
fn len(&self) -> usize {
$len
}
}
// PushWidget implementation for Box<tuple> - can push any widget type
impl<$($t: crate::DynWidget,)+ W: crate::DynWidget> PushWidget<W> for Box<($($t,)+)> {
type Output = Box<($($t,)+ W)>;
fn push_widget(self, widget: W) -> Self::Output {
#[allow(non_snake_case)]
let ($($t,)+) = *self;
Box::new(($($t,)+ widget))
}
}
};
}
// Special macro for the last tuple (20) that can't add more widgets
macro_rules! impl_last_widget_tuple {
($len:literal, $($t:ident),+) => {
impl<$($t: crate::DynWidget),+> AssociatedArray for ($($t,)+) {
type Array<T: Clone> = [T; $len];
fn create_array_with<T: Copy>(&self, value: T) -> Self::Array<T> {
[value; $len]
}
fn get_dyn_child(&mut self, index: usize) -> Option<&mut dyn crate::DynWidget> {
#[allow(non_snake_case, unused_assignments, unused_mut)]
let ($(ref mut $t,)+) = self;
#[allow(unused_mut, unused_assignments)]
let mut i = 0;
$(
if i == index {
return Some($t as &mut dyn crate::DynWidget);
}
#[allow(unused_assignments)]
{ i += 1; }
)+
None
}
fn len(&self) -> usize {
$len
}
}
// Note: No PushWidget implementation for the last tuple (can't add more widgets)
// Box implementation for heap allocation
impl<$($t: crate::DynWidget),+> AssociatedArray for Box<($($t,)+)> {
type Array<T: Clone> = Box<[T]>;
fn create_array_with<T: Copy>(&self, value: T) -> Self::Array<T> {
vec![value; $len].into_boxed_slice()
}
fn get_dyn_child(&mut self, index: usize) -> Option<&mut dyn crate::DynWidget> {
#[allow(non_snake_case, unused_assignments, unused_mut)]
let ($(ref mut $t,)+) = &mut **self;
#[allow(unused_mut, unused_assignments)]
let mut i = 0;
$(
if i == index {
return Some($t as &mut dyn crate::DynWidget);
}
#[allow(unused_assignments)]
{ i += 1; }
)+
None
}
fn len(&self) -> usize {
$len
}
}
// Note: No PushWidget implementation for Box<last_tuple> either
};
}
// Generate implementations for tuples up to 20 elements
impl_widget_tuple!(1, T1);
impl_widget_tuple!(2, T1, T2);
impl_widget_tuple!(3, T1, T2, T3);
impl_widget_tuple!(4, T1, T2, T3, T4);
impl_widget_tuple!(5, T1, T2, T3, T4, T5);
impl_widget_tuple!(6, T1, T2, T3, T4, T5, T6);
impl_widget_tuple!(7, T1, T2, T3, T4, T5, T6, T7);
impl_widget_tuple!(8, T1, T2, T3, T4, T5, T6, T7, T8);
impl_widget_tuple!(9, T1, T2, T3, T4, T5, T6, T7, T8, T9);
impl_widget_tuple!(10, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10);
impl_widget_tuple!(11, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11);
impl_widget_tuple!(12, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12);
impl_widget_tuple!(13, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13);
impl_widget_tuple!(14, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14);
impl_widget_tuple!(15, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15);
impl_widget_tuple!(16, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16);
impl_widget_tuple!(17, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17);
impl_widget_tuple!(
18, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18
);
impl_widget_tuple!(
19, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19
);
impl_last_widget_tuple!(
20, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20
);
/// Implementation of AssociatedArray for Vec<W> to enable dynamic collections
impl<W: crate::DynWidget> AssociatedArray for Vec<W> {
type Array<T: Clone> = Vec<T>;
fn create_array_with<T: Copy>(&self, value: T) -> Self::Array<T> {
vec![value; self.len()]
}
fn get_dyn_child(&mut self, index: usize) -> Option<&mut dyn crate::DynWidget> {
self.get_mut(index).map(|w| w as &mut dyn crate::DynWidget)
}
fn len(&self) -> usize {
self.len()
}
}
// PushWidget implementation for Vec - can only push the same type T
impl<T: crate::DynWidget> PushWidget<T> for Vec<T> {
type Output = Vec<T>;
fn push_widget(mut self, widget: T) -> Self::Output {
self.push(widget);
self
}
}
/// Implementation of AssociatedArray for fixed-size arrays
impl<W: crate::DynWidget, const N: usize> AssociatedArray for [W; N] {
type Array<T: Clone> = [T; N];
fn create_array_with<T: Copy>(&self, value: T) -> Self::Array<T> {
[value; N]
}
fn get_dyn_child(&mut self, index: usize) -> Option<&mut dyn crate::DynWidget> {
self.get_mut(index).map(|w| w as &mut dyn crate::DynWidget)
}
fn len(&self) -> usize {
N
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/layout/mod.rs | frostsnap_widgets/src/layout/mod.rs | mod alignment;
mod center;
mod collections;
mod column;
mod container;
mod padding;
mod row;
mod sized_box;
mod stack;
pub use alignment::{Align, Alignment, HorizontalAlignment, VerticalAlignment};
pub use center::Center;
pub use column::Column;
pub use container::Container;
pub use padding::Padding;
pub use row::Row;
pub use sized_box::SizedBox;
pub use stack::{Positioned, Positioning, Stack};
/// Trait for types that have an associated array type for storing auxiliary data
pub trait AssociatedArray {
/// Generic associated type for auxiliary arrays (for storing rectangles, spacing, etc)
type Array<T: Clone>: AsRef<[T]> + AsMut<[T]> + Clone + IntoIterator<Item = T>;
/// Create an array filled with a specific value, sized according to self
fn create_array_with<T: Copy>(&self, value: T) -> Self::Array<T>;
/// Get a child widget as a dyn DynWidget reference by index
fn get_dyn_child(&mut self, index: usize) -> Option<&mut dyn crate::DynWidget>;
/// Get the number of children
fn len(&self) -> usize;
/// Is the array empty
fn is_empty(&self) -> bool {
self.len() == 0
}
}
/// Trait for types that can have widgets pushed to them
pub trait PushWidget<W: crate::DynWidget>: AssociatedArray {
/// The resulting type after pushing a widget
type Output: AssociatedArray;
/// Push a widget to this collection
fn push_widget(self, widget: W) -> Self::Output;
}
/// Alignment options for the cross axis (horizontal for Column, vertical for Row)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CrossAxisAlignment {
/// Align children to the start (left/top) of the cross axis
Start,
/// Center children along the cross axis
Center,
/// Align children to the end (right/bottom) of the cross axis
End,
}
/// Defines how children are distributed along the main axis (vertical for Column, horizontal for Row)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MainAxisAlignment {
/// Place children at the start with no spacing between them
Start,
/// Center children with no spacing between them
Center,
/// Place children at the end with no spacing between them
End,
/// Place children with equal spacing between them, with no space before the first or after the last child
/// Example with 3 children: [Child1]--space--[Child2]--space--[Child3]
SpaceBetween,
/// Place children with equal spacing around them, with half spacing before the first and after the last child
/// Example with 3 children: -half-[Child1]-full-[Child2]-full-[Child3]-half-
SpaceAround,
/// Place children with equal spacing between and around them
/// Example with 3 children: --space--[Child1]--space--[Child2]--space--[Child3]--space--
SpaceEvenly,
}
/// Controls how much space the widget should take in its main axis
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MainAxisSize {
/// Take up as much space as possible in the main axis
Max,
/// Take up only as much space as needed by the children
Min,
}
/// Calculate the bounding rectangle of a collection of rectangles
/// Returns None if no rectangles have non-zero area
pub(crate) fn bounding_rect(
rects: impl IntoIterator<Item = embedded_graphics::primitives::Rectangle>,
) -> Option<embedded_graphics::primitives::Rectangle> {
use embedded_graphics::geometry::Point;
use embedded_graphics::primitives::Rectangle;
let mut min_top_left: Option<Point> = None;
let mut max_bottom_right: Option<Point> = None;
for rect in rects {
min_top_left = Some(match min_top_left {
None => rect.top_left,
Some(p) => p.component_min(rect.top_left),
});
match (&max_bottom_right, rect.bottom_right()) {
(Some(mbr), Some(br)) => {
max_bottom_right = Some(mbr.component_max(br));
}
(None, Some(br)) => {
max_bottom_right = Some(br);
}
_ => { /* do nothing */ }
}
}
match (min_top_left, max_bottom_right) {
(Some(tl), Some(br)) => Some(Rectangle::with_corners(tl, br)),
_ => None,
}
}
/// Helper function to draw debug borders around rectangles
/// Automatically determines the appropriate WHITE color based on the color type's bit depth
pub(crate) fn draw_debug_rect<D, C>(
target: &mut D,
rect: embedded_graphics::primitives::Rectangle,
) -> Result<(), D::Error>
where
D: embedded_graphics::draw_target::DrawTarget<Color = C>,
C: crate::WidgetColor,
{
use embedded_graphics::pixelcolor::raw::RawData;
use embedded_graphics::pixelcolor::{Gray2, Gray4, Rgb565};
use embedded_graphics::prelude::{GrayColor, RgbColor};
use embedded_graphics::primitives::{Primitive, PrimitiveStyle};
use embedded_graphics::Drawable;
let debug_color = match C::Raw::BITS_PER_PIXEL {
16 => {
// Assume Rgb565 for 16-bit
Some(unsafe { *(&Rgb565::WHITE as *const Rgb565 as *const C) })
}
4 => {
// Assume Gray4 for 4-bit
Some(unsafe { *(&Gray4::WHITE as *const Gray4 as *const C) })
}
2 => {
// Assume Gray2 for 2-bit
Some(unsafe { *(&Gray2::WHITE as *const Gray2 as *const C) })
}
_ => None,
};
if let Some(color) = debug_color {
rect.into_styled(PrimitiveStyle::with_stroke(color, 1))
.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/layout/stack.rs | frostsnap_widgets/src/layout/stack.rs | use super::{Alignment, AssociatedArray};
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,
};
/// Positioning mode for a child in the Stack
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Positioning {
/// Uses the Stack's default alignment
Default,
/// Positioned at absolute coordinates
Absolute(Point),
/// Positioned with a specific alignment
Aligned(Alignment),
}
/// A positioned wrapper for widgets in a Stack
pub struct Positioned<W> {
pub widget: W,
pub position: Point,
}
impl<W> Positioned<W> {
pub fn new(widget: W, x: i32, y: i32) -> Self {
Self {
widget,
position: Point::new(x, y),
}
}
}
/// A stack widget that layers its children on top of each other
///
/// The Stack widget allows you to overlay multiple widgets. Children can be:
/// - Non-positioned: aligned according to the stack's alignment setting
/// - Positioned: placed at specific coordinates
///
/// Children are drawn in order, so later children appear on top of earlier ones.
///
/// # Example
/// ```ignore
/// let stack = Stack::builder()
/// .push(background_widget)
/// .push_positioned(icon_widget, 10, 10)
/// .push(centered_text)
/// .with_alignment(Alignment::Center);
/// ```
#[derive(PartialEq)]
pub struct Stack<T: AssociatedArray> {
pub children: T,
pub alignment: Alignment,
/// Positioning information for each child
pub(crate) positioning: T::Array<Positioning>,
/// Cached rectangles for each child
pub(crate) child_rects: T::Array<Rectangle>,
pub(crate) sizing: Option<crate::Sizing>,
/// Optional index for showing only one child (IndexedStack behavior)
pub(crate) index: Option<usize>,
/// Track if we've cleared non-indexed children
pub(crate) cleared: bool,
}
/// Helper to start building a Stack with no children
impl Stack<()> {
pub fn builder() -> Self {
Self::new(())
}
}
impl<T: AssociatedArray> Stack<T> {
pub fn new(children: T) -> Self {
Self {
positioning: children.create_array_with(Positioning::Default),
child_rects: children.create_array_with(Rectangle::zero()),
children,
alignment: Alignment::default(),
sizing: None,
index: None,
cleared: false,
}
}
/// Set the index of the only child to show (None shows all children)
pub fn set_index(&mut self, new_index: Option<usize>) {
if self.index != new_index {
self.index = new_index;
self.cleared = false;
// Force redraw of the newly visible widget
if let Some(idx) = new_index {
if let Some(child) = self.children.get_dyn_child(idx) {
child.force_full_redraw();
}
} else {
// If switching back to showing all, force redraw all
let len = self.children.len();
for i in 0..len {
if let Some(child) = self.children.get_dyn_child(i) {
child.force_full_redraw();
}
}
}
}
}
pub fn with_alignment(mut self, alignment: Alignment) -> Self {
self.alignment = alignment;
self
}
}
impl<T: AssociatedArray> Stack<T> {
/// Add a non-positioned widget to the stack
pub fn push<W>(self, widget: W) -> Stack<<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 array and add new entry
let mut new_positioning = new_children.create_array_with(Positioning::Default);
new_positioning.as_mut()[..old_len].copy_from_slice(self.positioning.as_ref());
// New child uses default positioning
new_positioning.as_mut()[old_len] = Positioning::Default;
Stack {
positioning: new_positioning,
child_rects: new_children.create_array_with(Rectangle::zero()),
children: new_children,
alignment: self.alignment,
sizing: None,
index: self.index,
cleared: self.cleared,
}
}
/// Add a positioned widget to the stack at a specific location
pub fn push_positioned<W>(
self,
widget: W,
x: i32,
y: i32,
) -> Stack<<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 array and add new entry
let mut new_positioning = new_children.create_array_with(Positioning::Default);
new_positioning.as_mut()[..old_len].copy_from_slice(self.positioning.as_ref());
// New child is positioned at absolute coordinates
new_positioning.as_mut()[old_len] = Positioning::Absolute(Point::new(x, y));
Stack {
positioning: new_positioning,
child_rects: new_children.create_array_with(Rectangle::zero()),
children: new_children,
alignment: self.alignment,
sizing: None,
index: self.index,
cleared: self.cleared,
}
}
/// Add a widget with alignment-based positioning
/// The widget will be positioned according to the alignment within the Stack's bounds
pub fn push_aligned<W>(
self,
widget: W,
alignment: Alignment,
) -> Stack<<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 array and add new entry
let mut new_positioning = new_children.create_array_with(Positioning::Default);
new_positioning.as_mut()[..old_len].copy_from_slice(self.positioning.as_ref());
// New child is positioned with specific alignment
new_positioning.as_mut()[old_len] = Positioning::Aligned(alignment);
Stack {
positioning: new_positioning,
child_rects: new_children.create_array_with(Rectangle::zero()),
children: new_children,
alignment: self.alignment,
sizing: None,
index: self.index,
cleared: self.cleared,
}
}
}
// Macro to implement Widget for Stack with tuples of different sizes
macro_rules! impl_stack_for_tuple {
($len:literal, $($t:ident),+) => {
impl<$($t: Widget<Color = C>),+, C: crate::WidgetColor> Widget for Stack<($($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>,
{
let size = self.sizing.unwrap();
// Clear the entire stack area once when index changes
if self.index.is_some() && !self.cleared {
let stack_rect = Rectangle::new(Point::zero(), size.into());
target.clear_area(&stack_rect)?;
self.cleared = true;
}
// Get mutable references to children
#[allow(non_snake_case, unused_variables)]
let ($(ref mut $t,)+) = self.children;
// Draw each child in order (first to last, so later children appear on top)
let mut child_index = 0;
$(
{
let rect = self.child_rects[child_index];
if self.index.is_none() || self.index == Some(child_index) {
$t.draw(&mut target.clone().crop(rect), current_time)?;
}
child_index += 1;
}
)+
Ok(())
}
}
};
}
// Generate implementations for tuples up to 20 elements
impl_stack_for_tuple!(1, T1);
impl_stack_for_tuple!(2, T1, T2);
impl_stack_for_tuple!(3, T1, T2, T3);
impl_stack_for_tuple!(4, T1, T2, T3, T4);
impl_stack_for_tuple!(5, T1, T2, T3, T4, T5);
impl_stack_for_tuple!(6, T1, T2, T3, T4, T5, T6);
impl_stack_for_tuple!(7, T1, T2, T3, T4, T5, T6, T7);
impl_stack_for_tuple!(8, T1, T2, T3, T4, T5, T6, T7, T8);
impl_stack_for_tuple!(9, T1, T2, T3, T4, T5, T6, T7, T8, T9);
impl_stack_for_tuple!(10, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10);
impl_stack_for_tuple!(11, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11);
impl_stack_for_tuple!(12, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12);
impl_stack_for_tuple!(13, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13);
impl_stack_for_tuple!(14, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14);
impl_stack_for_tuple!(15, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15);
impl_stack_for_tuple!(16, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16);
impl_stack_for_tuple!(
17, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17
);
impl_stack_for_tuple!(
18, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18
);
impl_stack_for_tuple!(
19, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19
);
impl_stack_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 Stack
impl<T> crate::DynWidget for Stack<T>
where
T: AssociatedArray,
{
fn set_constraints(&mut self, max_size: Size) {
let len = self.children.len();
if len == 0 {
self.sizing = Some(Size::new(0, 0).into());
return;
}
let mut max_width = 0u32;
let mut max_height = 0u32;
let mut dirty_rects = self.child_rects.clone();
for i in 0..len {
if let Some(child) = self.children.get_dyn_child(i) {
// Set constraints on each child with full available size
child.set_constraints(max_size);
let sizing = child.sizing();
// Calculate position based on positioning mode
let position = match self.positioning.as_ref()[i] {
Positioning::Default => {
// Use the stack's default alignment
self.alignment.offset(max_size, sizing.into())
}
Positioning::Absolute(pos) => {
// Use the absolute position
pos
}
Positioning::Aligned(alignment) => {
// Use the specific alignment
alignment.offset(max_size, sizing.into())
}
};
let rect = Rectangle::new(position, sizing.into());
self.child_rects.as_mut()[i] = rect;
dirty_rects.as_mut()[i] = sizing.dirty_rect.unwrap_or(rect);
// Track maximum dimensions for the stack's sizing
let right = (position.x as u32).saturating_add(sizing.width);
let bottom = (position.y as u32).saturating_add(sizing.height);
max_width = max_width.max(right);
max_height = max_height.max(bottom);
}
}
let dirty_rect = super::bounding_rect(dirty_rects);
self.sizing = Some(crate::Sizing {
width: max_width.min(max_size.width),
height: max_height.min(max_size.height),
dirty_rect,
});
}
fn sizing(&self) -> crate::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<crate::KeyTouch> {
let child_rects = self.child_rects.as_ref();
let len = self.children.len();
// If index is set, only handle touch for that child
if let Some(idx) = self.index {
if idx < len {
if let Some(child) = self.children.get_dyn_child(idx) {
let area = child_rects[idx];
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);
}
}
}
}
} else {
// Handle touches in reverse order (top-most children first)
// Check from last to first since later children are drawn on top
for i in (0..len).rev() {
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 Stack<Vec<W>>
impl<W, C> Widget for Stack<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>,
{
let size = self.sizing.unwrap();
// Clear the entire stack area once when index changes
if self.index.is_some() && !self.cleared {
let stack_rect = Rectangle::new(Point::zero(), size.into());
target.clear_area(&stack_rect)?;
self.cleared = true;
}
// Draw each child in its pre-computed rectangle
// For stacks, we draw in order (bottom to top)
for (i, child) in self.children.iter_mut().enumerate() {
let rect = self.child_rects[i];
if self.index.is_none() || self.index == Some(i) {
child.draw(&mut target.clone().crop(rect), current_time)?;
}
}
Ok(())
}
}
// Widget implementation for Stack<[W; N]>
impl<W, C, const N: usize> Widget for Stack<[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>,
{
let size = self.sizing.unwrap();
// Clear the entire stack area once when index changes
if self.index.is_some() && !self.cleared {
let stack_rect = Rectangle::new(Point::zero(), size.into());
target.clear_area(&stack_rect)?;
self.cleared = true;
}
// Draw each child in its pre-computed rectangle
// For stacks, we draw in order (bottom to top)
for (i, child) in self.children.iter_mut().enumerate() {
let rect = self.child_rects[i];
if self.index.is_none() || self.index == Some(i) {
child.draw(&mut target.clone().crop(rect), 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/layout/padding.rs | frostsnap_widgets/src/layout/padding.rs | use crate::Widget;
use crate::{super_draw_target::SuperDrawTarget, Instant};
use core::ops::{Deref, DerefMut};
use embedded_graphics::{
draw_target::DrawTarget,
geometry::{Point, Size},
primitives::Rectangle,
};
/// A widget that adds padding around its child
#[derive(PartialEq)]
pub struct Padding<W: Widget> {
pub child: W,
pub top: u32,
pub bottom: u32,
pub left: u32,
pub right: u32,
sizing: Option<crate::Sizing>,
child_rect: Option<Rectangle>,
}
impl<W: Widget> Padding<W> {
/// Create padding with all sides having the same value
pub fn all(padding: u32, child: W) -> Self {
Self {
child,
top: padding,
bottom: padding,
left: padding,
right: padding,
sizing: None,
child_rect: None,
}
}
/// Create padding with symmetric values (vertical and horizontal)
pub fn symmetric(horizontal: u32, vertical: u32, child: W) -> Self {
Self {
child,
top: vertical,
bottom: vertical,
left: horizontal,
right: horizontal,
sizing: None,
child_rect: None,
}
}
/// Create padding with only specific sides
pub fn only(child: W) -> PaddingBuilder<W> {
PaddingBuilder {
child,
top: 0,
bottom: 0,
left: 0,
right: 0,
}
}
/// Create padding with all sides specified
pub fn new(top: u32, bottom: u32, left: u32, right: u32, child: W) -> Self {
Self {
child,
top,
bottom,
left,
right,
sizing: None,
child_rect: None,
}
}
}
/// Builder for creating padding with only specific sides
pub struct PaddingBuilder<W: Widget> {
child: W,
top: u32,
bottom: u32,
left: u32,
right: u32,
}
impl<W: Widget> PaddingBuilder<W> {
pub fn top(mut self, value: u32) -> Self {
self.top = value;
self
}
pub fn bottom(mut self, value: u32) -> Self {
self.bottom = value;
self
}
pub fn left(mut self, value: u32) -> Self {
self.left = value;
self
}
pub fn right(mut self, value: u32) -> Self {
self.right = value;
self
}
pub fn build(self) -> Padding<W> {
Padding {
child: self.child,
top: self.top,
bottom: self.bottom,
left: self.left,
right: self.right,
sizing: None,
child_rect: None,
}
}
}
impl<W: Widget> crate::DynWidget for Padding<W> {
fn set_constraints(&mut self, max_size: Size) {
// Reduce max size by padding
let padded_width = max_size.width.saturating_sub(self.left + self.right);
let padded_height = max_size.height.saturating_sub(self.top + self.bottom);
self.child
.set_constraints(Size::new(padded_width, padded_height));
// Get child sizing and compute our own sizing
let child_sizing = self.child.sizing();
// The dirty rect for padding is the area given to the child,
// offset by the padding amounts
let dirty_rect = if child_sizing.width > 0 && child_sizing.height > 0 {
Some(Rectangle::new(
Point::new(self.left as i32, self.top as i32),
Size::new(child_sizing.width, child_sizing.height),
))
} else {
None
};
self.sizing = Some(crate::Sizing {
width: child_sizing.width + self.left + self.right,
height: child_sizing.height + self.top + self.bottom,
dirty_rect,
});
// Cache the child rectangle
self.child_rect = Some(Rectangle::new(
Point::new(self.left as i32, self.top as i32),
Size::new(child_sizing.width, child_sizing.height),
));
}
fn sizing(&self) -> crate::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<crate::KeyTouch> {
if let Some(child_rect) = self.child_rect {
if child_rect.contains(point) || is_release {
let child_point = point - child_rect.top_left;
if let Some(mut key_touch) =
self.child
.handle_touch(child_point, current_time, is_release)
{
key_touch.translate(child_rect.top_left);
return Some(key_touch);
}
}
}
None
}
fn handle_vertical_drag(&mut self, prev_y: Option<u32>, new_y: u32, is_release: bool) {
// Pass vertical drag to child with adjusted y values
let adjusted_prev_y = prev_y.map(|y| y.saturating_sub(self.top));
let adjusted_new_y = new_y.saturating_sub(self.top);
self.child
.handle_vertical_drag(adjusted_prev_y, adjusted_new_y, is_release);
}
fn force_full_redraw(&mut self) {
self.child.force_full_redraw();
}
}
impl<W: Widget> Widget for Padding<W> {
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>,
{
// Use the cached child rectangle
let child_rect = self
.child_rect
.expect("set_constraints must be called before draw");
// Draw the child in the cached rectangle
let mut cropped_target = target.clone().crop(child_rect);
self.child.draw(&mut cropped_target, current_time)?;
Ok(())
}
}
impl<W: Widget> Deref for Padding<W> {
type Target = W;
fn deref(&self) -> &Self::Target {
&self.child
}
}
impl<W: Widget> DerefMut for Padding<W> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.child
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/backup/enter_share_screen.rs | frostsnap_widgets/src/backup/enter_share_screen.rs | //! important to understand this module was developed prior to the widget system
//! being fleshed out and so it's very half baked and error prone.
use super::{
AlphabeticKeyboard, BackupModel, EnteredWords, InputPreview, MainViewState, NumericKeyboard,
WordSelector,
};
use crate::super_draw_target::SuperDrawTarget;
use crate::OneTimeClearHack;
use crate::{DynWidget, Key, KeyTouch, Widget};
use alloc::{vec, vec::Vec};
use embedded_graphics::{pixelcolor::Rgb565, prelude::*, primitives::Rectangle};
// Test word sets for auto-fill feature
// 3 compatible shares from 2-of-3 scheme, plus 1 incompatible from different secret
const TEST_WORD_SETS: [[&str; 24]; 4] = [
// Share #1 (25th word: MOBILE)
[
"MUTUAL", "JEANS", "SNAP", "STING", "BLESS", "JOURNEY", "MORAL", "BREAD", "ROOM", "LIMIT",
"DOSE", "GRAVITY", "SORT", "DELIVER", "OUTDOOR", "RIPPLE", "DONKEY", "BLOUSE", "PLAY",
"CART", "CENTURY", "MAXIMUM", "MAKE", "LOCAL",
],
// Share #2 (25th word: BUSINESS)
[
"CASH", "TRASH", "FOIL", "PREFER", "BUTTER", "IDEA", "BRAVE", "BITTER", "ITEM", "WINK",
"DRIFT", "SMILE", "TOMATO", "LUNCH", "OPTION", "HERO", "THREE", "ENGINE", "BLESS",
"MANAGE", "HORSE", "JAR", "ADVICE", "SHERIFF",
],
// Share #3 (25th word: FINGER)
[
"REGION", "FINISH", "TRAVEL", "LAUNDRY", "CHEAP", "HAIR", "PLUNGE", "BANANA", "CRACK",
"INTEREST", "DURING", "COTTON", "PHONE", "DISAGREE", "CRUNCH", "AIRPORT", "CANCEL", "FOLD",
"LAUNDRY", "PONY", "LOBSTER", "LENS", "MAMMAL", "CLOTH",
],
// Share #4 - Incompatible (25th word: ZOO)
[
"MIRACLE", "KETCHUP", "SLIM", "MAZE", "GUESS", "FEBRUARY", "IDLE", "ENDORSE", "BARELY",
"POLAR", "AGAIN", "SIBLING", "CLARIFY", "SHELL", "EAGER", "FISCAL", "DISTANCE", "FEW",
"ABOVE", "SURE", "FRAME", "ENFORCE", "BUTTER", "MORNING",
],
];
pub struct EnterShareScreen {
model: BackupModel,
numeric_keyboard: Option<OneTimeClearHack<NumericKeyboard>>,
alphabetic_keyboard: AlphabeticKeyboard,
word_selector: Option<OneTimeClearHack<WordSelector>>,
entered_words: Option<EnteredWords>,
input_preview: InputPreview,
touches: Vec<KeyTouch>,
keyboard_rect: Rectangle,
needs_redraw: bool,
size: Size,
auto_fill_enabled: bool,
}
impl Default for EnterShareScreen {
fn default() -> Self {
Self::new()
}
}
impl EnterShareScreen {
pub fn new() -> Self {
let model = BackupModel::new();
let alphabetic_keyboard = AlphabeticKeyboard::new();
let input_preview = InputPreview::new();
Self {
model,
numeric_keyboard: None,
alphabetic_keyboard,
word_selector: None,
entered_words: None,
input_preview,
touches: vec![],
keyboard_rect: Rectangle::zero(),
needs_redraw: true,
size: Size::zero(),
auto_fill_enabled: false,
}
}
pub fn is_finished(&self) -> bool {
matches!(
self.model.view_state().main_view,
MainViewState::AllWordsEntered { .. }
)
}
pub fn get_backup(&self) -> Option<frost_backup::share_backup::ShareBackup> {
if let MainViewState::AllWordsEntered { success } = &self.model.view_state().main_view {
success.clone()
} else {
None
}
}
/// Testing method to enable auto-fill mode
/// When enabled, entering a share index (1-4) will automatically fill in test words:
/// - Indices 1, 2, 3: Compatible shares from a 2-of-3 scheme
/// - Index 4: Incompatible share from a different secret
pub fn prefill_test_words(&mut self) {
self.auto_fill_enabled = true;
}
pub fn handle_vertical_drag(&mut self, prev_y: Option<u32>, new_y: u32, _is_release: bool) {
// scrolling cancels the touch
if let Some(active_touch) = self.touches.last_mut() {
active_touch.cancel()
}
if let Some(ref mut entered_words) = self.entered_words {
// Handle drag for entered words view
entered_words.handle_vertical_drag(prev_y, new_y, _is_release);
} else if self.word_selector.is_none() {
// Only handle drag for keyboard, not word selector
self.alphabetic_keyboard
.handle_vertical_drag(prev_y, new_y, _is_release);
}
}
fn cancel_all_touches(&mut self) {
for touch in &mut self.touches {
touch.cancel();
}
}
fn update_from_model(&mut self) {
let view_state = self.model.view_state();
// Update the input preview based on view state
self.input_preview.update_from_view_state(&view_state);
// Update progress - use total completed rows (share index + words)
let completed_rows = self.model.num_completed_rows();
self.input_preview.update_progress(completed_rows);
// Update keyboard/UI based on main view state
match view_state.main_view {
MainViewState::AllWordsEntered { .. } => {
// Show the EnteredWords view - same as when user taps ShowEnteredWords
if self.entered_words.is_none() {
let framebuffer = self.input_preview.get_framebuffer();
let entered_words =
EnteredWords::new(framebuffer, self.size, view_state.clone());
self.entered_words = Some(entered_words);
}
// Hide keyboards and word selector
self.numeric_keyboard = None;
self.word_selector = None;
self.cancel_all_touches();
}
MainViewState::EnterShareIndex { ref current } => {
// Show numeric keyboard
if self.numeric_keyboard.is_none() {
let numeric_keyboard = NumericKeyboard::new();
let mut numeric_keyboard_with_clear = OneTimeClearHack::new(numeric_keyboard);
numeric_keyboard_with_clear.set_constraints(self.keyboard_rect.size);
self.numeric_keyboard = Some(numeric_keyboard_with_clear);
}
if let Some(numeric_keyboard) = &mut self.numeric_keyboard {
numeric_keyboard.set_bottom_buttons_enabled(!current.is_empty());
}
}
MainViewState::EnterWord { valid_letters } => {
if self.numeric_keyboard.is_some() || self.word_selector.is_some() {
self.numeric_keyboard = None;
self.word_selector = None;
self.cancel_all_touches();
}
// Update alphabetic keyboard
self.alphabetic_keyboard.set_valid_keys(valid_letters);
let word_index = view_state.row - 1; // -1 because row 0 is share index
self.alphabetic_keyboard.set_current_word_index(word_index);
}
MainViewState::WordSelect {
ref current,
possible_words,
} => {
// Show word selector if not already showing
if self.word_selector.is_none() {
let word_selector = WordSelector::new(possible_words, current);
let mut word_selector_with_clear = OneTimeClearHack::new(word_selector);
word_selector_with_clear.set_constraints(self.keyboard_rect.size);
self.word_selector = Some(word_selector_with_clear);
self.cancel_all_touches();
}
// Still update alphabetic keyboard for consistency
let word_index = view_state.row - 1; // -1 because row 0 is share index
self.alphabetic_keyboard.set_current_word_index(word_index);
}
}
}
}
impl Widget for EnterShareScreen {
type Color = Rgb565;
fn draw<D>(
&mut self,
target: &mut SuperDrawTarget<D, Rgb565>,
current_time: crate::Instant,
) -> Result<(), D::Error>
where
D: DrawTarget<Color = Self::Color>,
{
// Draw touches and clean up
// First draw all touches
for touch in &mut self.touches {
touch.draw(target, current_time);
}
// Then remove finished ones
self.touches.retain(|touch| !touch.is_finished());
let input_display_rect = Rectangle::new(
Point::zero(),
Size::new(target.bounding_box().size.width, 60),
);
if let Some(ref mut entered_words) = self.entered_words {
// Full-screen entered words view
entered_words.draw(target, current_time);
} else if let Some(ref mut numeric_keyboard) = self.numeric_keyboard {
self.input_preview
.draw(&mut target.clone().crop(input_display_rect), current_time)?;
// Draw BIP39 input preview
numeric_keyboard.draw(&mut target.clone().crop(self.keyboard_rect), current_time)?;
} else if let Some(ref mut word_selector) = self.word_selector {
// Draw input preview at top
let _ = self
.input_preview
.draw(&mut target.clone().crop(input_display_rect), current_time);
// Draw word selector in keyboard area
word_selector.draw(&mut target.clone().crop(self.keyboard_rect), current_time)?;
} else {
// Normal keyboard and input preview
self.alphabetic_keyboard
.draw(&mut target.clone().crop(self.keyboard_rect), current_time)?;
// Draw BIP39 input preview
let input_display_rect = Rectangle::new(
Point::zero(),
Size::new(target.bounding_box().size.width, 60),
);
self.input_preview
.draw(&mut target.clone().crop(input_display_rect), current_time)?;
}
Ok(())
}
}
impl crate::DynWidget for EnterShareScreen {
fn set_constraints(&mut self, max_size: Size) {
self.size = max_size;
// Calculate keyboard rect
let preview_height = 60;
self.keyboard_rect = Rectangle::new(
Point::new(0, preview_height),
Size::new(max_size.width, max_size.height - preview_height as u32),
);
// Update children constraints
self.input_preview
.set_constraints(Size::new(max_size.width, preview_height as u32));
self.alphabetic_keyboard
.set_constraints(self.keyboard_rect.size);
// Update numeric keyboard and word selector if they exist
if let Some(ref mut numeric_keyboard) = self.numeric_keyboard {
numeric_keyboard.set_constraints(self.keyboard_rect.size);
}
if let Some(ref mut word_selector) = self.word_selector {
word_selector.set_constraints(self.keyboard_rect.size);
}
// Update from model to ensure proper initial scroll position
self.update_from_model();
}
fn sizing(&self) -> crate::Sizing {
self.size.into()
}
fn handle_touch(
&mut self,
point: Point,
current_time: crate::Instant,
lift_up: bool,
) -> Option<KeyTouch> {
if lift_up {
// Otherwise process normal key release
// Find the last non-cancelled touch
if let Some(active_touch) = self.touches.iter_mut().rev().find(|t| !t.has_been_let_go())
{
if let Some(key) = active_touch.let_go(current_time) {
match key {
Key::Keyboard('⌫') => {
// Just pass to model, let it handle
let mutations = self.model.backspace();
self.input_preview.apply_mutations(&mutations);
self.update_from_model();
}
Key::Keyboard('✓') => {
// Get current state to know what to complete
let view_state = self.model.view_state();
if let MainViewState::EnterShareIndex { current } = view_state.main_view
{
let mutations = self.model.complete_row(¤t);
self.input_preview.apply_mutations(&mutations);
self.update_from_model();
// Auto-fill test words if enabled
if self.auto_fill_enabled {
if let Ok(index) = current.parse::<usize>() {
if (1..=4).contains(&index) {
let words = &TEST_WORD_SETS[index - 1];
for word in words {
let mutations = self.model.complete_row(word);
self.input_preview.apply_mutations(&mutations);
}
self.update_from_model();
}
}
}
}
}
Key::Keyboard(c) if c.is_alphabetic() || c.is_numeric() => {
// Just pass character to model
let mutations = self.model.add_character(c);
self.input_preview.apply_mutations(&mutations);
self.update_from_model();
// Check if we're complete
if self.model.is_complete() {
// TODO: Create EnteredWords view when needed
// For now just mark as complete
self.needs_redraw = true;
}
}
Key::WordSelector(word) => {
// Complete the current row with selected word
let mutations = self.model.complete_row(word);
self.input_preview.apply_mutations(&mutations);
self.update_from_model();
// Check if we're complete
if self.model.is_complete() {
// TODO: Show EnteredWords view
self.needs_redraw = true;
}
}
Key::ShowEnteredWords => {
// Only show EnteredWords if we're at the start of a new word
let view_state = self.model.view_state();
if view_state.can_show_entered_words() {
let framebuffer = self.input_preview.get_framebuffer();
let current_row = view_state.row;
let mut entered_words =
EnteredWords::new(framebuffer, self.size, view_state);
// Scroll to show current word
if current_row > 0 {
entered_words.scroll_to_word_at_top(current_row - 1);
}
self.entered_words = Some(entered_words);
// Cancel all touches when switching views
self.cancel_all_touches();
}
// Otherwise ignore the touch
}
Key::EditWord(word_index) => {
// word_index from EnteredWords is actually the row index (0 = share index, 1+ = words)
let mutations = self.model.edit_row(word_index);
self.input_preview.apply_mutations(&mutations);
self.input_preview.force_redraw();
self.update_from_model();
// Exit EnteredWords view if we're in it
if self.entered_words.is_some() {
self.entered_words = None;
// Cancel all touches when switching views
self.cancel_all_touches();
}
}
_ => {} // Ignore other keys
}
}
}
} else {
// Handle touch for different modes
let key_touch = if let Some(ref entered_words) = self.entered_words {
// EnteredWords is full-screen, handle its touches directly
entered_words.handle_touch(point)
} else if let Some(ref mut numeric_keyboard) = self.numeric_keyboard {
// Numeric keyboard is in keyboard area for share index entry
if self.keyboard_rect.contains(point) {
let translated_point = point - self.keyboard_rect.top_left;
numeric_keyboard
.handle_touch(translated_point, current_time, lift_up)
.map(|mut key_touch| {
key_touch.translate(self.keyboard_rect.top_left);
key_touch
})
} else {
// Check input preview area
self.input_preview
.handle_touch(point, current_time, lift_up)
}
} else if let Some(ref mut word_selector) = self.word_selector {
// Word selector is in keyboard area, input preview is visible
if self.keyboard_rect.contains(point) {
let translated_point = point - self.keyboard_rect.top_left;
word_selector
.handle_touch(translated_point, current_time, lift_up)
.map(|mut key_touch| {
key_touch.translate(self.keyboard_rect.top_left);
key_touch
})
} else {
// Check input preview area
self.input_preview
.handle_touch(point, current_time, lift_up)
}
} else {
// Normal mode: check input preview first, then keyboard
if let Some(key_touch) =
self.input_preview
.handle_touch(point, current_time, lift_up)
{
Some(key_touch)
} else if self.keyboard_rect.contains(point) {
let translated_point = point - self.keyboard_rect.top_left;
self.alphabetic_keyboard
.handle_touch(translated_point, current_time, lift_up)
.map(|mut key_touch| {
key_touch.translate(self.keyboard_rect.top_left);
key_touch
})
} else {
None
}
};
if let Some(key_touch) = key_touch {
// Fast forward any ongoing scrolling animation immediately
// This ensures the UI is responsive to new input
if matches!(key_touch.key, Key::Keyboard(_)) {
self.input_preview.fast_forward_scrolling();
}
if let Some(last) = self.touches.last_mut() {
if last.key == key_touch.key {
self.touches.pop();
} else {
last.cancel();
}
}
self.touches.push(key_touch);
}
}
None
}
fn handle_vertical_drag(&mut self, prev_y: Option<u32>, new_y: u32, _is_release: bool) {
// scrolling cancels the touch
if let Some(active_touch) = self.touches.last_mut() {
active_touch.cancel()
}
if let Some(ref mut entered_words) = self.entered_words {
// Handle drag for entered words view
entered_words.handle_vertical_drag(prev_y, new_y, _is_release);
} else if self.word_selector.is_none() {
// Only handle drag for keyboard, not word selector
self.alphabetic_keyboard
.handle_vertical_drag(prev_y, new_y, _is_release);
}
}
fn force_full_redraw(&mut self) {
self.needs_redraw = true;
self.input_preview.force_redraw();
self.alphabetic_keyboard.force_full_redraw();
self.word_selector.force_full_redraw();
self.numeric_keyboard.force_full_redraw();
if let Some(ref mut entered_words) = self.entered_words {
entered_words.force_full_redraw();
}
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/backup/numeric_keyboard.rs | frostsnap_widgets/src/backup/numeric_keyboard.rs | use crate::DefaultTextStyle;
use crate::{
icons::IconWidget, palette::PALETTE, prelude::*, touch_listener::TouchListener, Key, FONT_MED,
};
use alloc::string::String;
use embedded_graphics::{pixelcolor::Rgb565, prelude::*};
use embedded_iconoir::prelude::*;
use frostsnap_macros::Widget;
// Type alias to simplify the complex type
type StyledText = Text;
/// A button widget that displays a numeric key
#[derive(Widget)]
pub struct NumericButton {
key: char,
enabled: bool,
#[widget_delegate]
inner: Container<Align<Padding<StyledText>>>,
}
impl NumericButton {
fn new(key: char, enabled: bool) -> TouchListener<Self> {
// Create text for the button
let text_color = if enabled {
PALETTE.primary
} else {
PALETTE.text_disabled
};
let text = Text::new(
String::from(key),
DefaultTextStyle::new(FONT_MED, text_color),
);
let text = Padding::only(text).top(6).build();
// Center align the text
let aligned_text = Align::new(text);
// Wrap in a Container with button styling
let container_fill = if enabled {
PALETTE.surface
} else {
PALETTE.surface_variant
};
let container = Container::new(aligned_text)
.with_fill(container_fill)
.with_corner_radius(Size::new(8, 8));
let button = Self {
key,
enabled,
inner: container,
};
// Return a TouchListener that returns the key when pressed
TouchListener::new(button, move |_, _, is_release, child| {
if !child.enabled || is_release {
None
} else {
Some(Key::Keyboard(child.key))
}
})
}
fn set_enabled(&mut self, enabled: bool) {
if self.enabled != enabled {
self.enabled = enabled;
// Update text color
let text_color = if enabled {
PALETTE.primary
} else {
PALETTE.text_disabled
};
// Update container fill
let container_fill = if enabled {
PALETTE.surface
} else {
PALETTE.surface_variant
};
// Update the text character style
self.inner
.child
.child
.child
.set_character_style(DefaultTextStyle::new(FONT_MED, text_color));
// Update the container fill
self.inner.set_fill(container_fill);
}
}
}
/// A button widget that displays a checkmark
#[derive(Widget)]
pub struct CheckmarkButton {
enabled: bool,
#[widget_delegate]
inner: Container<
Align<
IconWidget<
embedded_iconoir::Icon<Rgb565, embedded_iconoir::icons::size24px::actions::Check>,
>,
>,
>,
}
impl CheckmarkButton {
fn new(enabled: bool) -> TouchListener<Self> {
// Use smaller size24px icon and set color based on enabled state
let icon_color = if enabled {
PALETTE.on_primary_container
} else {
PALETTE.text_disabled
};
let icon = IconWidget::new(embedded_iconoir::icons::size24px::actions::Check::new(
icon_color,
));
// Center align the icon
let aligned_icon = Align::new(icon);
// Wrap in a Container with button styling
let container_fill = if enabled {
PALETTE.primary_container
} else {
PALETTE.surface_variant
};
let container = Container::new(aligned_icon)
.with_height(50)
.with_fill(container_fill)
.with_corner_radius(Size::new(8, 8));
let button = Self {
enabled,
inner: container,
};
// Return a TouchListener that returns the confirm key when pressed
TouchListener::new(button, move |_, _, is_release, child| {
if !child.enabled || is_release {
None
} else {
Some(Key::Keyboard('✓'))
}
})
}
fn set_enabled(&mut self, enabled: bool) {
if self.enabled != enabled {
self.enabled = enabled;
// Update icon color
let icon_color = if enabled {
PALETTE.on_primary_container
} else {
PALETTE.text_disabled
};
// Update container fill
let container_fill = if enabled {
PALETTE.primary_container
} else {
PALETTE.surface_variant
};
// Update the icon color using set_color
self.inner.child.child.set_color(icon_color);
// Update the container fill
self.inner.set_fill(container_fill);
}
}
}
type NumericRow = Row<(
TouchListener<NumericButton>,
TouchListener<NumericButton>,
TouchListener<NumericButton>,
)>;
type BottomRow = Row<(
Container<()>,
TouchListener<NumericButton>,
TouchListener<CheckmarkButton>,
)>;
/// A widget that displays a numeric keyboard with digits 0-9 and a checkmark
#[derive(Widget)]
pub struct NumericKeyboard {
#[widget_delegate]
keyboard: Padding<Column<alloc::boxed::Box<(NumericRow, NumericRow, NumericRow, BottomRow)>>>,
}
impl NumericKeyboard {
pub fn new() -> Self {
// Create the keyboard layout:
// 1 2 3
// 4 5 6
// 7 8 9
// _ 0 ✓
let gap = 4;
let mut row1 = Row::new((
NumericButton::new('1', true),
NumericButton::new('2', true),
NumericButton::new('3', true),
));
row1.set_all_flex(1);
row1.set_uniform_gap(gap);
let mut row2 = Row::new((
NumericButton::new('4', true),
NumericButton::new('5', true),
NumericButton::new('6', true),
));
row2.set_all_flex(1);
row2.set_uniform_gap(gap);
let mut row3 = Row::new((
NumericButton::new('7', true),
NumericButton::new('8', true),
NumericButton::new('9', true),
));
row3.set_all_flex(1);
row3.set_uniform_gap(gap);
// Bottom row with empty space, 0, and checkmark
// Start with 0 and checkmark disabled (no digits entered yet)
let empty_button = Container::new(()).with_expanded(); // Placeholder button (always disabled)
let mut row4 = Row::new((
empty_button,
NumericButton::new('0', false), // Initially disabled
CheckmarkButton::new(false), // Initially disabled
));
row4.set_all_flex(1);
row4.set_uniform_gap(gap);
// Create the column with all rows (boxed to move to heap)
let mut keyboard = Column::new(alloc::boxed::Box::new((row1, row2, row3, row4)));
keyboard.set_all_flex(1);
keyboard.set_uniform_gap(gap);
let keyboard = Padding::all(gap, keyboard);
Self { keyboard }
}
/// Helper method to enable/disable the 0 button and checkmark based on whether any digits have been entered
pub fn set_bottom_buttons_enabled(&mut self, enabled: bool) {
// Access the bottom row (4th row in the column)
let column = &mut self.keyboard.child;
let bottom_row = &mut column.children.3;
// Update the 0 button (second item in bottom row)
bottom_row.children.1.child.set_enabled(enabled);
// Update the checkmark button (third item in bottom row)
bottom_row.children.2.child.set_enabled(enabled);
}
}
impl Default for NumericKeyboard {
fn default() -> Self {
Self::new()
}
}
impl core::fmt::Debug for NumericKeyboard {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("NumericKeyboard").finish()
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/backup/word_selector.rs | frostsnap_widgets/src/backup/word_selector.rs | use crate::{
palette::PALETTE, prelude::*, touch_listener::TouchListener, DefaultTextStyle, Key, FONT_MED,
};
use alloc::{string::String, vec::Vec};
use embedded_graphics::prelude::*;
use frostsnap_macros::Widget;
// Type aliases to simplify the complex type
/// A button widget that displays a BIP39 word with prefix highlighting
#[derive(Widget)]
pub struct WordButton {
word: &'static str,
#[widget_delegate]
inner: Container<Padding<Row<(Text, Text)>>>,
}
impl WordButton {
fn new(word: &'static str, prefix: &str) -> TouchListener<Self> {
// Split the word into prefix and suffix
let suffix = &word[prefix.len()..];
// Create two text widgets - prefix in secondary color, suffix in primary
let prefix_text = Text::new(
String::from(prefix),
DefaultTextStyle::new(FONT_MED, PALETTE.text_secondary),
);
let suffix_text = Text::new(
String::from(suffix),
DefaultTextStyle::new(FONT_MED, PALETTE.primary),
);
// Create a row with the text elements, centered vertically
let word_row = Row::new((prefix_text, suffix_text))
.with_main_axis_alignment(MainAxisAlignment::Center);
let word_row = Padding::only(word_row).top(15).bottom(8).build();
// Wrap in a Container with fixed width, rounded corners, and button styling
// Width of 110px should fit most BIP39 words comfortably
// Using surface_variant as the button background color (Material Design elevated button)
let container = Container::new(word_row)
.with_width(110)
.with_fill(PALETTE.surface)
.with_corner_radius(Size::new(8, 8));
let word_button = Self {
word,
inner: container,
};
// Return a TouchListener that can inspect the child to get the word
TouchListener::new(word_button, |_, _, is_release, child| {
if is_release {
None
} else {
Some(Key::WordSelector(child.word))
}
})
}
}
type WordColumn = Column<Vec<TouchListener<WordButton>>>;
/// A widget that displays BIP39 words in two columns for selection
#[derive(Widget)]
pub struct WordSelector {
words: &'static [&'static str],
// Two columns of words
#[widget_delegate]
columns: Row<(WordColumn, WordColumn)>,
}
impl WordSelector {
pub fn new(words: &'static [&'static str], prefix: &str) -> Self {
// Split words into two columns
let mut left_words = Vec::new();
let mut right_words = Vec::new();
for (i, &word) in words.iter().enumerate() {
// Create a WordButton widget for each word
let word_button = WordButton::new(word, prefix);
if i % 2 == 0 {
left_words.push(word_button);
} else {
right_words.push(word_button);
}
}
// Create columns with flex for each word
let left_column =
Column::new(left_words).with_main_axis_alignment(MainAxisAlignment::SpaceEvenly);
let right_column =
Column::new(right_words).with_main_axis_alignment(MainAxisAlignment::SpaceEvenly);
// Create a row with the two columns
let columns = Row::new((left_column, right_column))
.with_main_axis_alignment(MainAxisAlignment::SpaceEvenly);
Self { words, columns }
}
}
impl core::fmt::Debug for WordSelector {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("WordSelector")
.field("words", &self.words)
.finish()
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/backup/input_preview.rs | frostsnap_widgets/src/backup/input_preview.rs | use super::backup_model::{FramebufferMutation, MainViewState, ViewState};
use super::LEGACY_FONT_MED;
use crate::cursor::Cursor;
use crate::palette::PALETTE;
use crate::progress_bars::ProgressBars;
use crate::super_draw_target::SuperDrawTarget;
use crate::text::Text as TextWidget;
use crate::{
icons, Align, Alignment as WidgetAlignment, Container, DynWidget, FadeSwitcher, Key, KeyTouch,
Widget,
};
use crate::{U8g2TextStyle, LEGACY_FONT_LARGE};
use alloc::{
rc::Rc,
string::{String, ToString},
};
use core::cell::RefCell;
use embedded_graphics::{
framebuffer::{buffer_size, Framebuffer},
geometry::AnchorX,
iterator::raw::RawDataSlice,
pixelcolor::{
raw::{LittleEndian, RawU2},
Gray2, Rgb565,
},
prelude::*,
primitives::{PrimitiveStyleBuilder, Rectangle},
text::{Alignment, Baseline, Text, TextStyleBuilder},
};
use frost_backup::NUM_WORDS;
// Type alias for the placeholder text widget (boxed to reduce stack usage)
type PlaceholderText = alloc::boxed::Box<Container<Align<TextWidget<U8g2TextStyle<Rgb565>>>>>;
// Constants for vertical BIP39 word display
pub(super) const TOTAL_WORDS: usize = NUM_WORDS;
pub(super) const FONT_SIZE: Size = Size::new(16, 24);
pub(super) const VERTICAL_PAD: u32 = 12; // 6px top + 6px bottom padding per word
// 180 pixels width / 16 pixels per char = 11.25 chars total
// So we can fit 11 chars total
const INDEX_CHARS: usize = 2; // "25" (no dot)
const SPACE_BETWEEN: usize = 1;
const PREVIEW_LEFT_PAD: i32 = 4; // Left padding for preview rect
pub(super) const TOP_PADDING: u32 = 10; // Top padding before first word
pub(super) const FB_WIDTH: u32 = 176; // Divisible by 4 for Gray2 alignment
pub(super) const FB_HEIGHT: u32 =
TOP_PADDING + ((TOTAL_WORDS + 1) as u32 * (FONT_SIZE.height + VERTICAL_PAD)); // +1 for share index row
pub(super) type Fb = Framebuffer<
Gray2,
RawU2,
LittleEndian,
{ FB_WIDTH as usize },
{ FB_HEIGHT as usize },
{ buffer_size::<Gray2>(FB_WIDTH as usize, FB_HEIGHT as usize) },
>;
pub struct InputPreview {
pub(super) area: Rectangle,
preview_rect: Rectangle,
backspace_rect: Rectangle,
progress_rect: Rectangle,
progress: ProgressBars,
framebuf: Framebuf,
init_draw: bool,
cursor: Cursor,
hint_switcher: alloc::boxed::Box<FadeSwitcher<Option<PlaceholderText>>>,
placeholder_text: Option<PlaceholderText>,
current_view_state: Option<ViewState>,
}
impl Default for InputPreview {
fn default() -> Self {
Self::new()
}
}
impl InputPreview {
pub fn new() -> Self {
// Initialize with zero-sized rectangles - will be set in set_constraints
let backspace_rect = Rectangle::zero();
let preview_rect = Rectangle::zero();
let progress_rect = Rectangle::zero();
// 26 segments: 1 for share index + 25 words for Frostsnap backup
let progress = ProgressBars::new(NUM_WORDS + 1);
let framebuf = Framebuf::new();
// Use FadeSwitcher with 300ms fade-in, 0ms fade-out, starting with None
let hint_switcher = alloc::boxed::Box::new(FadeSwitcher::new(None, 300));
Self {
area: Rectangle::zero(),
preview_rect,
backspace_rect,
progress_rect,
progress,
framebuf,
init_draw: false,
cursor: Cursor::new(Point::zero()), // Will update position in draw
hint_switcher,
placeholder_text: None,
current_view_state: None,
}
}
pub fn apply_mutations(&mut self, mutations: &[FramebufferMutation]) {
self.framebuf.apply_mutations(mutations);
}
pub fn update_progress(&mut self, completed_words: usize) {
self.progress.progress(completed_words);
}
pub fn contains(&self, point: Point) -> bool {
self.preview_rect.contains(point)
}
pub fn get_framebuffer(&self) -> Rc<RefCell<Fb>> {
self.framebuf.framebuffer.clone()
}
/// Force redraw of the input preview (including progress bar)
pub fn force_redraw(&mut self) {
self.init_draw = false;
self.framebuf.redraw = true;
self.progress.force_full_redraw();
}
/// Fast forward any ongoing scrolling animation
pub fn fast_forward_scrolling(&mut self) {
self.framebuf.fast_forward_scrolling();
}
pub fn is_scrolling(&self) -> bool {
self.framebuf.is_scrolling()
}
pub fn update_from_view_state(&mut self, view_state: &ViewState) {
// Store the current view state
self.current_view_state = Some(view_state.clone());
// Update cursor position based on view state
let x = ((INDEX_CHARS + SPACE_BETWEEN) + view_state.cursor_pos) * FONT_SIZE.width as usize;
// Fixed Y position - cursor appears at bottom of text (centered vertically, then add font height)
let y = self.preview_rect.size.height as i32 / 2 - FONT_SIZE.height as i32 / 2
+ FONT_SIZE.height as i32
- 2;
self.cursor.set_position(Point::new(x as i32, y));
// Enable cursor when there's text but row isn't complete (not in word selection)
let cursor_enabled = match &view_state.main_view {
MainViewState::EnterShareIndex { current } => !current.is_empty(),
MainViewState::EnterWord { .. } => view_state.cursor_pos > 0,
MainViewState::WordSelect { .. } => false, // No cursor during word selection
MainViewState::AllWordsEntered { .. } => false, // No cursor when all words entered
};
self.cursor.enabled(cursor_enabled);
// Update scroll position to show the current row
self.framebuf
.update_scroll_position_for_row(view_state.row, false);
if self.is_scrolling() {
self.hint_switcher.instant_fade();
}
// Update placeholder text based on whether the current row is empty
let hint_text = match &view_state.main_view {
MainViewState::EnterShareIndex { current } if current.is_empty() => {
Some(String::from("enter\nkey number"))
}
MainViewState::EnterWord { .. } if view_state.cursor_pos == 0 => {
// view_state.row is 0 for share index, 1 for word 1, etc.
Some(format!("enter\nword {}", view_state.row))
}
MainViewState::AllWordsEntered { .. } => {
self.hint_switcher.instant_fade();
None
}
_ => {
self.hint_switcher.instant_fade();
None
}
};
self.placeholder_text = hint_text.map(|text| {
let text_widget = TextWidget::new(
text,
U8g2TextStyle::new(LEGACY_FONT_MED, PALETTE.surface_variant),
)
.with_alignment(Alignment::Center);
let aligned = Align::new(text_widget).alignment(WidgetAlignment::Center);
let container = Container::new(aligned).with_expanded();
alloc::boxed::Box::new(container)
});
}
fn draw_cursor<D: DrawTarget<Color = Rgb565>>(
&mut self,
target: &mut SuperDrawTarget<D, Rgb565>,
current_time: crate::Instant,
) -> Result<(), D::Error> {
// Let the cursor handle its own drawing and blinking
self.cursor.draw(target, current_time)?;
Ok(())
}
}
impl crate::DynWidget for InputPreview {
fn set_constraints(&mut self, max_size: Size) {
let progress_height = 4;
let backspace_width = max_size.width / 4;
self.backspace_rect = Rectangle::new(
Point::new(max_size.width as i32 - backspace_width as i32, 0),
Size {
width: backspace_width,
height: max_size.height - progress_height,
},
);
self.preview_rect = Rectangle::new(
Point::new(PREVIEW_LEFT_PAD, 0),
Size {
width: FB_WIDTH, // Must match framebuffer width exactly
height: max_size.height - progress_height,
},
);
self.progress_rect = Rectangle::new(
Point::new(0, max_size.height as i32 - progress_height as i32),
Size::new(max_size.width, progress_height),
);
// Calculate text area size for hint switcher
let text_offset = ((INDEX_CHARS + SPACE_BETWEEN) * FONT_SIZE.width as usize) as u32;
let text_area_size = Size::new(
self.preview_rect.size.width.saturating_sub(text_offset),
self.preview_rect.size.height,
);
self.progress.set_constraints(self.progress_rect.size);
self.framebuf.set_constraints(self.preview_rect.size);
self.hint_switcher.set_constraints(text_area_size);
self.area = Rectangle::new(Point::zero(), max_size);
}
fn sizing(&self) -> crate::Sizing {
self.area.size.into()
}
fn handle_touch(
&mut self,
point: Point,
_current_time: crate::Instant,
_lift_up: bool,
) -> Option<KeyTouch> {
if self.backspace_rect.contains(point) {
Some(KeyTouch::new(Key::Keyboard('⌫'), self.backspace_rect))
} else if self.preview_rect.contains(point) {
// Only allow showing entered words if the current state permits it
if let Some(ref view_state) = self.current_view_state {
if view_state.can_show_entered_words() {
Some(KeyTouch::new(Key::ShowEnteredWords, self.preview_rect))
} else {
None
}
} else {
None
}
} else {
None
}
}
}
impl Widget for InputPreview {
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 backspace icon on first draw
if !self.init_draw {
// Clear the entire area first
let clear_rect = Rectangle::new(Point::zero(), self.area.size);
let _ = clear_rect
.into_styled(
PrimitiveStyleBuilder::new()
.fill_color(PALETTE.background)
.build(),
)
.draw(target);
icons::backspace()
.with_color(PALETTE.error)
.with_center(
self.backspace_rect
.resized_width(self.backspace_rect.size.width / 2, AnchorX::Left)
.center(),
)
.draw(target);
self.init_draw = true;
}
let text_offset = ((INDEX_CHARS + SPACE_BETWEEN) * FONT_SIZE.width as usize) as i32;
let hint_rect = Rectangle::new(
Point::new(
self.preview_rect.top_left.x + text_offset,
self.preview_rect.top_left.y,
),
Size::new(
self.preview_rect
.size
.width
.saturating_sub(text_offset as u32),
self.preview_rect.size.height,
),
);
// Draw hint text overlay only when not scrolling
if !self.is_scrolling() {
// Switch to placeholder text if we have one, otherwise empty container
if let Some(placeholder) = self.placeholder_text.take() {
self.hint_switcher.switch_to(Some(placeholder));
}
}
// Draw hint text offset to alin with actual text entry area
self.hint_switcher
.draw(&mut target.clone().crop(hint_rect), current_time)?;
self.framebuf
.draw(&mut target.clone().crop(self.preview_rect), current_time)?;
// Draw cursor when enabled (text entered but row not complete)
let _ = self.draw_cursor(&mut target.clone().crop(self.preview_rect), current_time);
// Always draw progress bars (they have their own redraw logic)
self.progress
.draw(&mut target.clone().crop(self.progress_rect), current_time)?;
Ok(())
}
}
pub struct Framebuf {
framebuffer: Rc<RefCell<Fb>>,
current_position: u32, // Current vertical scroll position
current_time: Option<crate::Instant>,
target_position: u32, // Target vertical scroll position
animation_start_time: Option<crate::Instant>, // When current animation started
viewport_height: u32, // Height of the visible area
pub(super) redraw: bool,
}
impl Framebuf {
pub fn new() -> Self {
let fb = Rc::new(RefCell::new(Fb::new()));
// Clear the framebuffer
let _ = fb.borrow_mut().clear(Gray2::BLACK);
// Pre-render share index placeholder with '#' prefix
let share_y = TOP_PADDING as i32 + (VERTICAL_PAD / 2) as i32;
let _ = Text::with_text_style(
" #",
Point::new(0, share_y),
U8g2TextStyle::new(LEGACY_FONT_LARGE, Gray2::new(0x01)),
TextStyleBuilder::new()
.alignment(Alignment::Left)
.baseline(Baseline::Top)
.build(),
)
.draw(&mut *fb.borrow_mut());
// Pre-render word indices with aligned dots (starting from second position)
for i in 0..TOTAL_WORDS {
// Word i is at row i+1 (row 0 is share index)
let row = i + 1;
let y = TOP_PADDING as i32
+ (row as u32 * (FONT_SIZE.height + VERTICAL_PAD)) as i32
+ (VERTICAL_PAD / 2) as i32;
let number = (i + 1).to_string();
// Right-align numbers at 2 characters from left (no dots)
let number_right_edge = 32; // 2 * 16 pixels
// Calculate number position to right-align
let number_x = if i < 9 {
// Single digit: right-aligned at position
number_right_edge - FONT_SIZE.width as i32
} else {
// Double digit: starts at position 0
0
};
// Draw the number with a different gray level
let _ = Text::with_text_style(
&number,
Point::new(number_x, y),
U8g2TextStyle::new(LEGACY_FONT_LARGE, Gray2::new(0x01)),
TextStyleBuilder::new()
.alignment(Alignment::Left)
.baseline(Baseline::Top)
.build(),
)
.draw(&mut *fb.borrow_mut());
}
Self {
framebuffer: fb,
current_position: 0,
current_time: None,
target_position: 0,
animation_start_time: None,
viewport_height: 34, // Default viewport height
redraw: true,
}
}
pub fn apply_mutations(&mut self, mutations: &[FramebufferMutation]) {
let mut fb = self.framebuffer.borrow_mut();
for mutation in mutations {
match mutation {
FramebufferMutation::SetCharacter { row, pos, char: ch } => {
let x = ((INDEX_CHARS + SPACE_BETWEEN) + pos) * FONT_SIZE.width as usize;
let y = TOP_PADDING as usize
+ (*row as u32 * (FONT_SIZE.height + VERTICAL_PAD)) as usize
+ (VERTICAL_PAD / 2) as usize;
let mut char_frame = fb.cropped(&Rectangle::new(
Point::new(x as i32, y as i32),
Size::new(FONT_SIZE.width, FONT_SIZE.height),
));
let _ = char_frame.clear(Gray2::BLACK);
let _ = Text::with_text_style(
&ch.to_string(),
Point::zero(),
U8g2TextStyle::new(LEGACY_FONT_LARGE, Gray2::new(0x02)),
TextStyleBuilder::new()
.alignment(Alignment::Left)
.baseline(Baseline::Top)
.build(),
)
.draw(&mut char_frame);
}
FramebufferMutation::DelCharacter { row, pos } => {
let x = ((INDEX_CHARS + SPACE_BETWEEN) + pos) * FONT_SIZE.width as usize;
let y = TOP_PADDING as usize
+ (*row as u32 * (FONT_SIZE.height + VERTICAL_PAD)) as usize
+ (VERTICAL_PAD / 2) as usize;
let mut char_frame = fb.cropped(&Rectangle::new(
Point::new(x as i32, y as i32),
Size::new(FONT_SIZE.width, FONT_SIZE.height),
));
let _ = char_frame.clear(Gray2::BLACK);
}
}
self.redraw = true;
}
}
// Update scroll position for a specific row
pub fn update_scroll_position_for_row(&mut self, row: usize, skip_animation: bool) {
// Calculate position to center the row in the viewport
let row_height = FONT_SIZE.height + VERTICAL_PAD;
let row_position = TOP_PADDING + (row as u32 * row_height);
// To center the row vertically: we want the row to appear at viewport_height/2
// The row's center is at row_position + row_height/2
// So scroll position should be: (row_position + row_height/2) - viewport_height/2
let row_center = row_position + row_height / 2;
let new_target = row_center.saturating_sub(self.viewport_height / 2);
if new_target != self.target_position {
self.target_position = new_target;
if skip_animation {
self.current_position = new_target;
self.animation_start_time = None;
} else {
self.animation_start_time = self.current_time;
}
self.redraw = true;
}
}
/// Fast forward scrolling by jumping to target position
pub fn fast_forward_scrolling(&mut self) {
self.redraw = self.current_position != self.target_position;
self.current_position = self.target_position;
self.animation_start_time = None;
}
/// Check if the framebuffer is currently scrolling
pub fn is_scrolling(&self) -> bool {
self.current_position != self.target_position
}
}
impl crate::DynWidget for Framebuf {
fn set_constraints(&mut self, max_size: Size) {
// Update viewport height based on constraints
self.viewport_height = max_size.height;
}
fn sizing(&self) -> crate::Sizing {
// Return the actual framebuffer dimensions
crate::Sizing {
width: FB_WIDTH,
height: self.viewport_height,
..Default::default()
}
}
}
impl Widget for Framebuf {
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 bb = target.bounding_box();
// Assert that framebuffer width matches target width
assert_eq!(
FB_WIDTH, bb.size.width,
"Framebuffer width ({}) must match target width ({})",
FB_WIDTH, bb.size.width
);
// Check if this is the first draw
let is_first_draw = self.current_time.is_none();
// Assert that viewport height matches what was set in set_constraints
assert_eq!(
self.viewport_height, bb.size.height,
"Viewport height mismatch: expected {} from set_constraints, got {} in draw",
self.viewport_height, bb.size.height
);
// On first draw, jump to target position
if is_first_draw {
self.current_position = self.target_position;
}
// Animate scrolling using acceleration
let last_draw_time = self.current_time.get_or_insert(current_time);
if self.current_position != self.target_position {
// Calculate time since animation started
let animation_elapsed = if let Some(start_time) = self.animation_start_time {
current_time.duration_since(start_time).unwrap_or(0) as f32
} else {
self.animation_start_time = Some(current_time);
0.0
};
// Accelerating curve: starts slow, speeds up
// Using a quadratic function for smooth acceleration
const ACCELERATION: f32 = 0.00000005; // Acceleration factor (5x faster)
const MIN_VELOCITY: f32 = 0.0005; // Minimum velocity to ensure it starts moving
// Calculate current velocity based on time elapsed
let velocity = MIN_VELOCITY + (ACCELERATION * animation_elapsed * animation_elapsed);
// Calculate distance to move this frame
let frame_duration = current_time.duration_since(*last_draw_time).unwrap_or(0) as f32;
// For upward scrolling, we want positive distance to move up (decrease position)
// When velocity is negative, we actually want to move down briefly
// Manual rounding: add 0.5 and truncate for positive values
let raw_distance = frame_duration * velocity;
let distance = if raw_distance >= 0.0 {
(raw_distance + 0.5) as i32
} else {
(raw_distance - 0.5) as i32
};
// Only proceed if we're actually going to move
if distance != 0 {
*last_draw_time = current_time;
// Direction: negative means scrolling up (decreasing position)
let direction =
(self.target_position as i32 - self.current_position as i32).signum();
// Apply the velocity in the correct direction
// For upward scroll (direction < 0), positive velocity should decrease position
let position_change = if direction < 0 {
-distance // Upward scroll
} else {
distance // Downward scroll
};
let new_position = (self.current_position as i32 + position_change).max(0);
// Check if we've reached or passed the target
if (direction < 0 && new_position <= self.target_position as i32)
|| (direction > 0 && new_position >= self.target_position as i32)
|| direction == 0
{
self.current_position = self.target_position;
self.animation_start_time = None; // Animation complete
} else {
self.current_position = new_position as u32;
}
self.redraw = true; // Keep redrawing until animation completes
}
// If distance is 0, we don't update last_draw_time, allowing frame_duration to accumulate
} else {
*last_draw_time = current_time;
self.animation_start_time = None;
}
// Only redraw if needed
if !self.redraw {
return Ok(());
}
// Skip to the correct starting position in the framebuffer
// current_position is already in pixels (Y coordinate), so we need to skip
// that many rows worth of pixels in the framebuffer
let skip_rows = self.current_position as usize;
let skip_pixels = skip_rows * FB_WIDTH as usize;
let take_pixels = bb.size.height as usize * bb.size.width as usize;
{
let fb = self.framebuffer.try_borrow().unwrap();
let framebuffer_pixels = RawDataSlice::<RawU2, LittleEndian>::new(fb.data())
.into_iter()
.skip(skip_pixels)
.take(take_pixels)
.map(|pixel| match Gray2::from(pixel).luma() {
0x00 => PALETTE.background,
0x01 => PALETTE.outline, // Numbers in subtle outline color
0x02 => PALETTE.on_background, // Words in normal text color
0x03 => PALETTE.on_background, // Also words
_ => PALETTE.background,
});
target.fill_contiguous(&bb, framebuffer_pixels)?;
}
// Only clear redraw flag if animation is complete
if self.current_position == self.target_position {
self.redraw = false;
}
Ok(())
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/backup/backup_display.rs | frostsnap_widgets/src/backup/backup_display.rs | use crate::backup::LEGACY_FONT_SMALL;
use crate::DefaultTextStyle;
use crate::HOLD_TO_CONFIRM_TIME_MS;
use crate::{
icons::IconWidget, page_slider::PageSlider, palette::PALETTE, prelude::*,
share_index::ShareIndexWidget, widget_list::WidgetList, FadeSwitcher, HoldToConfirm,
U8g2TextStyle, FONT_HUGE_MONO, FONT_LARGE, FONT_MED,
};
use alloc::{format, string::String, vec::Vec};
use embedded_graphics::{geometry::Size, pixelcolor::Rgb565, prelude::*, text::Alignment};
use frost_backup::{bip39_words::BIP39_WORDS, NUM_WORDS};
const WORDS_PER_PAGE: usize = 3;
/// A single page showing the share index
#[derive(frostsnap_macros::Widget)]
pub struct ShareIndexPage {
#[widget_delegate]
center: Center<Column<(Text, ShareIndexWidget)>>,
}
impl ShareIndexPage {
fn new(share_index: u16) -> Self {
let label = Text::new(
"Key number",
DefaultTextStyle::new(FONT_MED, PALETTE.text_secondary),
);
let share_index_widget = ShareIndexWidget::new(share_index, FONT_HUGE_MONO);
let column = Column::builder()
.push(label)
.gap(8)
.push(share_index_widget)
.with_cross_axis_alignment(CrossAxisAlignment::Center);
let center = Center::new(column);
Self { center }
}
}
/// A row showing a word number and the word itself
#[derive(frostsnap_macros::Widget)]
pub struct WordRow {
#[widget_delegate]
row: Row<(Text, SizedBox<Rgb565>, Text)>,
}
impl WordRow {
fn new(word_number: usize, word: &str) -> Self {
let number_text = Text::new(
format!("{}.", word_number),
DefaultTextStyle::new(FONT_MED, PALETTE.text_secondary),
)
.with_alignment(Alignment::Left);
let word_text = Text::new(
String::from(word),
DefaultTextStyle::new(FONT_HUGE_MONO, PALETTE.primary),
)
.with_alignment(Alignment::Left);
let spacer = SizedBox::width(10); // 10 pixels of space between number and word
let row = Row::new((number_text, spacer, word_text));
Self { row }
}
}
/// Enum for different word page layouts
type WordsPageLayout = Center<
crate::any_of::AnyOf<(
Column<(WordRow,)>,
Column<(WordRow, WordRow)>,
Column<(WordRow, WordRow, WordRow)>,
)>,
>;
/// A page showing up to 3 words
#[derive(frostsnap_macros::Widget)]
pub struct WordsPage {
#[widget_delegate]
layout: WordsPageLayout,
}
impl WordsPage {
fn new(words: Vec<(usize, String)>) -> Self {
// Build the layout based on how many words we have
let layout = match words.len() {
1 => {
let row1 = WordRow::new(words[0].0, &words[0].1);
Center::new(crate::any_of::AnyOf::new(
Column::new((row1,)).with_cross_axis_alignment(CrossAxisAlignment::Start),
))
}
2 => {
let row1 = WordRow::new(words[0].0, &words[0].1);
let row2 = WordRow::new(words[1].0, &words[1].1);
Center::new(crate::any_of::AnyOf::new(
Column::builder()
.push(row1)
.gap(20)
.push(row2)
.with_cross_axis_alignment(CrossAxisAlignment::Start),
))
}
3 => {
let row1 = WordRow::new(words[0].0, &words[0].1);
let row2 = WordRow::new(words[1].0, &words[1].1);
let row3 = WordRow::new(words[2].0, &words[2].1);
Center::new(crate::any_of::AnyOf::new(
Column::builder()
.push(row1)
.gap(20)
.push(row2)
.gap(20)
.push(row3)
.with_cross_axis_alignment(CrossAxisAlignment::Start),
))
}
_ => {
// Should never happen but handle gracefully
let row1 = WordRow::new(1, "error");
Center::new(crate::any_of::AnyOf::new(
Column::new((row1,)).with_cross_axis_alignment(CrossAxisAlignment::Start),
))
}
};
Self { layout }
}
}
// Helper type for a single word entry (number + word)
type SingleWordRow = Row<(Text<U8g2TextStyle<Rgb565>>, Text<U8g2TextStyle<Rgb565>>)>;
/// A page showing all 25 words in a simple scrollable format
#[derive(frostsnap_macros::Widget)]
pub struct AllWordsPage {
#[widget_delegate]
content: Row<(Column<Vec<SingleWordRow>>, Column<Vec<SingleWordRow>>)>,
}
impl AllWordsPage {
pub fn new(word_indices: &[u16; 25], share_index: u16) -> Self {
// Helper to create a word row (word_idx is 0-based)
let make_word_row = |word_idx: usize| -> SingleWordRow {
Row::new((
Text::new(
format!("{:2}.", word_idx + 1),
U8g2TextStyle::new(LEGACY_FONT_SMALL, PALETTE.text_secondary),
),
Text::new(
format!("{:<8}", BIP39_WORDS[word_indices[word_idx] as usize]),
U8g2TextStyle::new(LEGACY_FONT_SMALL, PALETTE.primary),
),
))
.with_main_axis_alignment(MainAxisAlignment::Start)
};
// Create left column: Share index, then words 1-12
let left_column = {
// First row: share index
let share_row = Row::new((
Text::new(
" #.",
U8g2TextStyle::new(LEGACY_FONT_SMALL, PALETTE.text_secondary),
),
Text::new(
format!("{}", share_index),
U8g2TextStyle::new(LEGACY_FONT_SMALL, PALETTE.primary),
)
.with_underline(PALETTE.surface),
))
.with_main_axis_alignment(MainAxisAlignment::Start);
let mut rows = Vec::with_capacity(13);
rows.push(share_row);
for i in 0..12 {
rows.push(make_word_row(i));
}
Column::new(rows)
.with_main_axis_alignment(MainAxisAlignment::Center)
.with_cross_axis_alignment(CrossAxisAlignment::Start)
};
// Create right column: Words 13-25
let mut right_rows = Vec::with_capacity(13);
for i in 12..25 {
right_rows.push(make_word_row(i));
}
let right_column = Column::new(right_rows)
.with_main_axis_alignment(MainAxisAlignment::Center)
.with_cross_axis_alignment(CrossAxisAlignment::Start);
// Combine the two columns
let two_columns = Row::new((left_column, right_column))
.with_main_axis_alignment(MainAxisAlignment::SpaceEvenly);
let content = two_columns;
Self { content }
}
}
/// Type alias for the content that can be shown in the confirmation screen
type ConfirmationContent = crate::any_of::AnyOf<(ConfirmContent, SafetyReminder)>;
/// A confirmation screen that shows after backup and fades to a security reminder
pub struct BackupConfirmationScreen {
hold_confirm: HoldToConfirm<FadeSwitcher<Center<ConfirmationContent>>>,
fade_triggered: bool,
}
/// The initial confirmation content
#[derive(frostsnap_macros::Widget)]
pub struct ConfirmContent {
#[widget_delegate]
column: Column<(Text, Text)>,
}
/// The safety reminder that fades in after confirmation
#[derive(frostsnap_macros::Widget)]
pub struct SafetyReminder {
#[widget_delegate]
content: Column<(
IconWidget<
embedded_iconoir::Icon<Rgb565, embedded_iconoir::icons::size48px::security::Shield>,
>,
Text,
Text,
)>,
}
impl ConfirmContent {
fn new() -> Self {
let title = Text::new(
"Backup\nrecorded?",
DefaultTextStyle::new(FONT_LARGE, PALETTE.on_background),
)
.with_alignment(Alignment::Center);
let subtitle = Text::new(
"I've written down:\n - The key number\n - All 25 words",
DefaultTextStyle::new(FONT_MED, PALETTE.text_secondary),
);
let column = Column::builder()
.push(title)
.gap(10)
.push(subtitle)
.with_main_axis_alignment(crate::MainAxisAlignment::SpaceEvenly);
Self { column }
}
}
impl SafetyReminder {
fn new() -> Self {
use embedded_iconoir::prelude::*;
let shield_icon = IconWidget::new(
embedded_iconoir::icons::size48px::security::Shield::new(PALETTE.primary),
);
let title = Text::new(
"Keep it secret",
DefaultTextStyle::new(FONT_MED, PALETTE.on_surface),
)
.with_alignment(Alignment::Center);
let subtitle = Text::new(
"Keep it safe",
DefaultTextStyle::new(FONT_MED, PALETTE.text_secondary),
)
.with_alignment(Alignment::Center);
let column = Column::builder()
.push(shield_icon)
.push(title)
.gap(20)
.push(subtitle)
.with_main_axis_alignment(crate::MainAxisAlignment::SpaceEvenly);
Self { content: column }
}
}
impl BackupConfirmationScreen {
fn new() -> Self {
let confirm_content = ConfirmContent::new();
let initial_content = ConfirmationContent::new(confirm_content);
let centered_content = Center::new(initial_content);
let fade_switcher = FadeSwitcher::new(
centered_content,
500, // 500ms fade duration
);
let hold_confirm =
HoldToConfirm::new(HOLD_TO_CONFIRM_TIME_MS, fade_switcher).with_faded_out_button();
Self {
hold_confirm,
fade_triggered: false,
}
}
pub fn is_confirmed(&self) -> bool {
self.hold_confirm.is_completed()
}
}
impl crate::DynWidget for BackupConfirmationScreen {
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: crate::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 crate::Widget for BackupConfirmationScreen {
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> {
// Check if we should trigger the fade
if !self.fade_triggered && self.hold_confirm.is_completed() {
self.fade_triggered = true;
// Switch to the safety reminder
let safety_reminder = SafetyReminder::new();
let safety_content = ConfirmationContent::new(safety_reminder);
let centered_safety = Center::new(safety_content);
self.hold_confirm.widget_mut().switch_to(centered_safety);
}
self.hold_confirm.draw(target, current_time)
}
}
/// A type that can be either a ShareIndexPage, WordsPage, AllWordsPage, or BackupConfirmationScreen
type BackupPage = crate::any_of::AnyOf<(
ShareIndexPage,
WordsPage,
AllWordsPage,
BackupConfirmationScreen,
)>;
/// Widget list that generates backup pages
pub struct BackupPageList {
word_indices: [u16; 25],
share_index: u16,
total_pages: usize,
}
impl BackupPageList {
fn new(word_indices: [u16; 25], share_index: u16) -> Self {
// Calculate total pages: 1 share index page + word pages + 1 all words page + 1 hold to confirm page
let word_pages = NUM_WORDS.div_ceil(WORDS_PER_PAGE);
let total_pages = 1 + word_pages + 1 + 1; // share + word pages + all words + confirm
Self {
word_indices,
share_index,
total_pages,
}
}
}
impl WidgetList<BackupPage> for BackupPageList {
fn len(&self) -> usize {
self.total_pages
}
fn get(&self, index: usize) -> Option<BackupPage> {
if index >= self.total_pages {
return None;
}
let page = if index == 0 {
// Share index page
BackupPage::new(ShareIndexPage::new(self.share_index))
} else if index == self.total_pages - 1 {
// Last page - Backup confirmation screen
BackupPage::new(BackupConfirmationScreen::new())
} else if index == self.total_pages - 2 {
// Second to last page - All words summary
BackupPage::new(AllWordsPage::new(&self.word_indices, self.share_index))
} else {
// Words page
let word_start_index = (index - 1) * WORDS_PER_PAGE;
let mut words = Vec::new();
for i in 0..WORDS_PER_PAGE {
let word_index = word_start_index + i;
if word_index < NUM_WORDS {
let word_number = word_index + 1;
let word = BIP39_WORDS[self.word_indices[word_index] as usize];
words.push((word_number, String::from(word)));
}
}
BackupPage::new(WordsPage::new(words))
};
Some(page)
}
fn can_go_prev(&self, from_index: usize, current_widget: &BackupPage) -> 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_screen) =
current_widget.downcast_ref::<BackupConfirmationScreen>()
{
// Don't allow going back if confirmed
return !confirmation_screen.is_confirmed();
}
}
true // Allow navigation for all other cases
}
}
/// Main widget that displays backup words using PageSlider
#[derive(frostsnap_macros::Widget)]
pub struct BackupDisplay {
#[widget_delegate]
page_slider: PageSlider<BackupPageList, BackupPage>,
}
impl BackupDisplay {
pub fn new(word_indices: [u16; 25], share_index: u16) -> Self {
let page_list = BackupPageList::new(word_indices, share_index);
let page_slider = PageSlider::new(page_list, 40)
.with_on_page_ready(|page| {
// Try to downcast to BackupConfirmationScreen
if let Some(confirmation_screen) = page.downcast_mut::<BackupConfirmationScreen>() {
// Fade in the button when the confirmation page is ready
confirmation_screen.hold_confirm.fade_in_button();
}
})
.with_swipe_up_chevron();
Self { page_slider }
}
/// Check if the backup has been confirmed via the hold-to-confirm on the last page
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_screen) =
current_widget.downcast_ref::<BackupConfirmationScreen>()
{
return confirmation_screen.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/backup/backup_model.rs | frostsnap_widgets/src/backup/backup_model.rs | use alloc::borrow::Cow;
use alloc::boxed::Box;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use frost_backup::{
bip39_words::{self, ValidLetters},
share_backup::ShareBackup,
NUM_WORDS,
};
#[derive(Debug)]
pub struct BackupModel {
share_index: String,
share_index_confirmed: bool,
words: [Cow<'static, str>; NUM_WORDS],
}
#[derive(Debug)]
pub enum FramebufferMutation {
SetCharacter { row: usize, pos: usize, char: char },
DelCharacter { row: usize, pos: usize },
}
#[derive(Debug, Clone)]
pub struct ViewState {
pub row: usize, // Which row is being edited (0 = share index)
pub cursor_pos: usize, // Position within that row for cursor
pub completed_rows: usize, // Number of rows that are fully completed
pub main_view: MainViewState, // The actual view to show
}
impl ViewState {
/// Check if we can show the entered words screen
pub fn can_show_entered_words(&self) -> bool {
// we don't allow navigating to the entered words page.
false
// Can show entered words only when:
// 1. We're entering a NEW word (row > completed_rows)
// 2. The current word is empty (cursor_pos == 0)
// 3. OR all words are complete
// match &self.main_view {
// MainViewState::EnterWord { .. } => {
// // Only allow if we're on a new row (not editing existing)
// // and the word is empty
// self.row >= self.completed_rows && self.cursor_pos == 0
// }
// MainViewState::AllWordsEntered { .. } => true,
// _ => false,
// }
}
}
#[derive(Debug, Clone)]
pub enum MainViewState {
EnterShareIndex {
current: String,
},
EnterWord {
valid_letters: ValidLetters,
},
WordSelect {
current: String,
possible_words: &'static [&'static str],
},
AllWordsEntered {
success: Option<ShareBackup>,
},
}
impl Default for BackupModel {
fn default() -> Self {
Self::new()
}
}
impl BackupModel {
pub fn new() -> Self {
Self {
share_index: String::new(),
share_index_confirmed: false,
words: [const { Cow::Borrowed("") }; NUM_WORDS],
}
}
/// Get a mutable reference to the string currently being edited along with its row index
fn current_string(&mut self) -> (usize, &mut String) {
if !self.share_index_confirmed {
(0, &mut self.share_index)
} else {
// Find first incomplete word and ensure it's Owned
let idx = self
.words
.iter()
.position(|w| matches!(w, Cow::Owned(_)) || w.is_empty())
.unwrap_or(0);
// Convert to Owned if it's an empty Borrowed
if self.words[idx].is_empty() {
self.words[idx] = Cow::Owned(String::new());
}
// Now we can safely get a mutable reference to the String
let string_ref = match &mut self.words[idx] {
Cow::Owned(s) => s,
_ => unreachable!("Word should be Owned at this point"),
};
(idx + 1, string_ref) // +1 because row 0 is share index
}
}
pub fn add_character(&mut self, c: char) -> Vec<FramebufferMutation> {
let mut mutations = Vec::new();
let (row, current) = self.current_string();
// Add the character
current.push(c);
mutations.push(FramebufferMutation::SetCharacter {
row,
pos: current.len() - 1,
char: c,
});
// Word-specific logic
if row > 0 {
// Special case: if we just typed Q, automatically add U
if c == 'Q' {
current.push('U');
mutations.push(FramebufferMutation::SetCharacter {
row,
pos: current.len() - 1,
char: 'U',
});
}
// Check for autocomplete
let matches = bip39_words::words_with_prefix(current);
if matches.len() == 1 {
// Auto-complete using complete_row
let complete_mutations = self.complete_row(matches[0]);
mutations.extend(complete_mutations);
}
}
mutations
}
pub fn backspace(&mut self) -> Vec<FramebufferMutation> {
let mut mutations = Vec::new();
let (row, current) = self.current_string();
if current.is_empty() {
// Current string is empty, go back to previous row
if row == 0 {
// Already at share index, nothing to do
return mutations;
} else if row == 1 && self.share_index_confirmed {
// Go back from first word to share index
self.share_index_confirmed = false;
} else if row > 1 {
// Go back to previous word - make it editable
let prev_word_idx = row - 2; // -1 for 0-based, -1 for share index
if prev_word_idx < NUM_WORDS {
// Convert previous word to Owned (making it editable)
let prev_word = self.words[prev_word_idx].to_string();
self.words[prev_word_idx] = Cow::Owned(prev_word);
}
}
// Now call backspace again to actually delete from the previous row
return self.backspace();
}
// Delete characters until we have multiple possibilities
loop {
if current.pop().is_some() {
mutations.push(FramebufferMutation::DelCharacter {
row,
pos: current.len(),
});
// For share index (row 0), just delete one character
if row == 0 {
break;
}
// For words, check if we now have multiple possibilities
if current.is_empty() {
break;
}
let matches = bip39_words::words_with_prefix(current);
if matches.len() > 1 {
break;
}
} else {
break;
}
}
mutations
}
pub fn complete_row(&mut self, completion: &str) -> Vec<FramebufferMutation> {
let mut mutations = Vec::new();
let (row, current) = self.current_string();
let current_len = current.len();
// Handle the framebuffer mutations the same way for all rows
if completion.starts_with(current.as_str()) {
// Add only the remaining characters
for (i, ch) in completion[current_len..].chars().enumerate() {
mutations.push(FramebufferMutation::SetCharacter {
row,
pos: current_len + i,
char: ch,
});
}
} else {
// Replace everything
// Clear current content
for i in 0..current_len {
mutations.push(FramebufferMutation::DelCharacter {
row,
pos: current_len - 1 - i,
});
}
// Set new content
for (i, ch) in completion.chars().enumerate() {
mutations.push(FramebufferMutation::SetCharacter {
row,
pos: i,
char: ch,
});
}
}
// Update the model based on which row we're completing
if row == 0 {
self.share_index = completion.to_string();
self.share_index_confirmed = true;
} else {
// Word - store as Borrowed if it's a valid BIP39 word, otherwise Owned
let word_idx = row - 1;
if let Ok(idx) = bip39_words::BIP39_WORDS.binary_search(&completion) {
self.words[word_idx] = Cow::Borrowed(bip39_words::BIP39_WORDS[idx]);
} else {
self.words[word_idx] = Cow::Owned(completion.to_string());
}
}
mutations
}
pub fn edit_row(&mut self, row: usize) -> Vec<FramebufferMutation> {
let mut mutations = Vec::new();
let to_delete = if row == 0 {
let to_delete = self.share_index.len();
self.share_index.clear();
self.share_index_confirmed = false;
to_delete
} else {
let word_idx = row - 1;
let to_delete = self.words[word_idx].len();
self.words[word_idx] = Cow::Owned(String::new());
to_delete
};
for i in 0..to_delete {
mutations.push(FramebufferMutation::DelCharacter {
row,
pos: to_delete - 1 - i,
});
}
mutations
}
pub fn view_state(&self) -> ViewState {
let completed_rows = self.num_completed_rows();
if !self.share_index_confirmed {
ViewState {
row: 0,
cursor_pos: self.share_index.len(),
completed_rows,
main_view: MainViewState::EnterShareIndex {
current: self.share_index.clone(),
},
}
} else if let Some(words) = self.get_words_as_static() {
// All words are entered, try to create ShareBackup
let share_index = self.share_index.parse::<u32>().expect("must be int");
let words_array: [&'static str; NUM_WORDS] = *words;
// Try to create ShareBackup from the entered words
let success = ShareBackup::from_words(share_index, words_array).ok();
ViewState {
row: NUM_WORDS, // Last word row
cursor_pos: 0,
completed_rows,
main_view: MainViewState::AllWordsEntered { success },
}
} else {
// Find first incomplete word
let idx = self
.words
.iter()
.position(|w| matches!(w, Cow::Owned(_)) || w.is_empty())
.unwrap_or(0);
let current_word = match &self.words[idx] {
Cow::Borrowed("") => "",
Cow::Borrowed(s) => s,
Cow::Owned(s) => s.as_str(),
};
let row = idx + 1; // +1 because row 0 is share index
let cursor_pos = current_word.len();
let current = current_word.to_string();
let main_view = if current_word.is_empty() {
// Empty word, show keyboard with all valid starting letters
let valid_letters = bip39_words::get_valid_next_letters("");
MainViewState::EnterWord { valid_letters }
} else {
// Check how many words match current prefix
let matches = bip39_words::words_with_prefix(current_word);
if matches.len() > 1 && matches.len() <= 8 {
// Show word selector
MainViewState::WordSelect {
current,
possible_words: matches,
}
} else {
// Show keyboard with valid next letters
let valid_letters = bip39_words::get_valid_next_letters(current_word);
MainViewState::EnterWord { valid_letters }
}
};
ViewState {
row,
cursor_pos,
completed_rows,
main_view,
}
}
}
pub fn num_completed_rows(&self) -> usize {
// Count share index if confirmed
let share_rows = if self.share_index_confirmed { 1 } else { 0 };
// Count only completed words (Borrowed with content, not Owned which means editing)
let word_rows = self
.words
.iter()
.filter(|w| matches!(w, Cow::Borrowed(s) if !s.is_empty()))
.count();
share_rows + word_rows
}
pub fn is_complete(&self) -> bool {
self.share_index_confirmed && self.words.iter().all(|w| !w.is_empty())
}
fn get_words_as_static(&self) -> Option<Box<[&'static str; NUM_WORDS]>> {
// Only return if all words are valid BIP39 words (Borrowed variants)
if !self.is_complete() {
return None;
}
let mut static_words = [""; NUM_WORDS];
for (i, word) in self.words.iter().enumerate() {
match word {
Cow::Borrowed(s) if !s.is_empty() => static_words[i] = s,
_ => return None, // Not a valid static BIP39 word
}
}
Some(Box::new(static_words))
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/backup/t9_keyboard.rs | frostsnap_widgets/src/backup/t9_keyboard.rs | use crate::palette::PALETTE;
use crate::super_draw_target::SuperDrawTarget;
use crate::DefaultTextStyle;
use crate::{Key, KeyTouch, Widget, FONT_LARGE, FONT_SMALL};
use alloc::string::String;
use embedded_graphics::{
pixelcolor::Rgb565,
prelude::*,
primitives::{PrimitiveStyle, Rectangle, RoundedRectangle},
text::{Alignment, Baseline, Text, TextStyleBuilder},
};
use frost_backup::bip39_words::ValidLetters;
// T9 keyboard layout
const T9_KEYS: [[&str; 3]; 3] = [
["abc", "def", "ghi"],
["jkl", "mno", "pqr"],
["stu", "vwx", "yz"],
];
const KEY_MARGIN: u32 = 12;
const KEY_SPACING: u32 = 8;
const CORNER_RADIUS: u32 = 12;
const MULTI_TAP_TIMEOUT_MS: u64 = 800; // Time before committing a letter
#[derive(Debug, Clone, Copy, PartialEq)]
struct T9KeyPosition {
row: usize,
col: usize,
}
#[derive(Debug)]
struct MultiTapState {
key_pos: T9KeyPosition,
tap_count: usize,
last_tap_time: crate::Instant,
}
#[derive(Debug)]
pub struct T9Keyboard {
valid_keys: ValidLetters,
key_rects: [[Rectangle; 3]; 3],
bounds: Rectangle,
multi_tap_state: Option<MultiTapState>,
needs_redraw: bool,
}
impl T9Keyboard {
pub fn new(keyboard_height: u32) -> Self {
// Calculate key dimensions - 3x3 grid
let available_width = 240 - (2 * KEY_MARGIN);
let key_width = (available_width - (2 * KEY_SPACING)) / 3;
// Use full height for the grid
let grid_height = keyboard_height - (2 * KEY_MARGIN);
let key_height = (grid_height - (2 * KEY_SPACING)) / 3;
// Create key rectangles
let mut key_rects = [[Rectangle::zero(); 3]; 3];
for row in 0..3 {
for col in 0..3 {
let x = KEY_MARGIN + col * (key_width + KEY_SPACING);
let y = KEY_MARGIN + row * (key_height + KEY_SPACING);
key_rects[row as usize][col as usize] = Rectangle::new(
Point::new(x as i32, y as i32),
Size::new(key_width, key_height),
);
}
}
let bounds = Rectangle::new(Point::zero(), Size::new(240, keyboard_height));
Self {
valid_keys: ValidLetters::default(),
key_rects,
bounds,
multi_tap_state: None,
needs_redraw: true,
}
}
pub fn set_valid_keys(&mut self, valid_keys: ValidLetters) {
// ValidLetters doesn't implement PartialEq, so we'll just always mark as needing redraw
// This is called infrequently enough that it shouldn't matter
self.valid_keys = valid_keys;
self.needs_redraw = true;
}
/// Get the current pending character based on multi-tap state
pub fn get_pending_char(&self) -> Option<char> {
if let Some(ref state) = self.multi_tap_state {
let key_chars = T9_KEYS[state.key_pos.row][state.key_pos.col];
let valid_letters = self.get_valid_letters_for_key(key_chars);
if valid_letters.is_empty() {
None
} else {
valid_letters
.chars()
.nth(state.tap_count % valid_letters.len())
}
} else {
None
}
}
/// Check if multi-tap timeout has expired
pub fn check_timeout(&mut self, current_time: crate::Instant) -> Option<char> {
if let Some(ref state) = self.multi_tap_state {
let elapsed = current_time.saturating_duration_since(state.last_tap_time);
if elapsed > MULTI_TAP_TIMEOUT_MS {
// Timeout expired, commit the character
let char_to_commit = self.get_pending_char();
self.multi_tap_state = None;
self.needs_redraw = true;
return char_to_commit;
}
}
None
}
fn get_valid_letters_for_key(&self, key_chars: &str) -> String {
// Get only the valid letters from this T9 key
key_chars
.chars()
.filter(|&c| self.valid_keys.is_valid(c.to_ascii_uppercase()))
.collect()
}
fn get_key_position_at_point(&self, point: Point) -> Option<T9KeyPosition> {
for (row_idx, row) in self.key_rects.iter().enumerate() {
for (col_idx, rect) in row.iter().enumerate() {
if rect.contains(point) {
return Some(T9KeyPosition {
row: row_idx,
col: col_idx,
});
}
}
}
None
}
/// Handle a key press and return the character to output (if any)
pub fn handle_key_press(
&mut self,
point: Point,
current_time: crate::Instant,
) -> Option<(Key, Rectangle)> {
// Check if it's a T9 key
if let Some(key_pos) = self.get_key_position_at_point(point) {
let rect = self.key_rects[key_pos.row][key_pos.col];
// Check if this key has any valid letters
let key_chars = T9_KEYS[key_pos.row][key_pos.col];
let valid_letters = self.get_valid_letters_for_key(key_chars);
if valid_letters.is_empty() {
return None;
}
// Handle multi-tap logic
let mut char_to_output = None;
if let Some(ref mut state) = self.multi_tap_state {
if state.key_pos == key_pos {
// Same key pressed again - increment tap count
state.tap_count += 1;
state.last_tap_time = current_time;
self.needs_redraw = true;
} else {
// Different key pressed - commit previous character and start new
char_to_output = self.get_pending_char();
self.multi_tap_state = Some(MultiTapState {
key_pos,
tap_count: 0,
last_tap_time: current_time,
});
self.needs_redraw = true;
}
} else {
// No active multi-tap - start new
self.multi_tap_state = Some(MultiTapState {
key_pos,
tap_count: 0,
last_tap_time: current_time,
});
self.needs_redraw = true;
}
// Return the committed character if any
if let Some(ch) = char_to_output {
return Some((Key::Keyboard(ch), rect));
}
}
None
}
fn draw_key<D: DrawTarget<Color = Rgb565>>(
&self,
target: &mut SuperDrawTarget<D, Rgb565>,
rect: Rectangle,
text: &str,
is_valid: bool,
) -> Result<(), D::Error> {
let key_color = if is_valid {
PALETTE.surface_variant
} else {
PALETTE.surface
};
let text_color = if is_valid {
PALETTE.on_surface
} else {
PALETTE.outline
};
// Draw key background
RoundedRectangle::with_equal_corners(rect, Size::new(CORNER_RADIUS, CORNER_RADIUS))
.into_styled(PrimitiveStyle::with_fill(key_color))
.draw(target)?;
// Draw key text - larger font for T9 keys
if text.len() <= 3 {
Text::with_text_style(
text,
rect.center(),
DefaultTextStyle::new(FONT_LARGE, text_color),
TextStyleBuilder::new()
.alignment(Alignment::Center)
.baseline(Baseline::Middle)
.build(),
)
.draw(target)?;
} else {
Text::with_text_style(
text,
rect.center(),
DefaultTextStyle::new(FONT_SMALL, text_color),
TextStyleBuilder::new()
.alignment(Alignment::Center)
.baseline(Baseline::Middle)
.build(),
)
.draw(target)?;
}
Ok(())
}
}
impl crate::DynWidget for T9Keyboard {
fn set_constraints(&mut self, _max_size: Size) {
// T9Keyboard has fixed size based on its bounds
}
fn sizing(&self) -> crate::Sizing {
self.bounds.size.into()
}
fn handle_touch(
&mut self,
point: Point,
current_time: crate::Instant,
lift_up: bool,
) -> Option<KeyTouch> {
if !lift_up {
// Only handle key press on touch down
if let Some((key, rect)) = self.handle_key_press(point, current_time) {
return Some(KeyTouch::new(key, rect));
}
}
None
}
fn handle_vertical_drag(&mut self, _prev_y: Option<u32>, _new_y: u32, _is_release: bool) {
// No drag behavior for keyboard
}
fn force_full_redraw(&mut self) {
self.needs_redraw = true;
}
}
impl Widget for T9Keyboard {
type Color = Rgb565;
fn draw<D>(
&mut self,
target: &mut SuperDrawTarget<D, Rgb565>,
current_time: crate::Instant,
) -> Result<(), D::Error>
where
D: DrawTarget<Color = Self::Color>,
{
// Check for timeout before drawing
let timed_out = self.check_timeout(current_time).is_some();
// Only redraw if needed
if !self.needs_redraw && !timed_out {
return Ok(());
}
// Clear background
self.bounds
.into_styled(PrimitiveStyle::with_fill(PALETTE.background))
.draw(target)?;
// Draw T9 keys
for (row_idx, row) in self.key_rects.iter().enumerate() {
for (col_idx, rect) in row.iter().enumerate() {
let key_chars = T9_KEYS[row_idx][col_idx];
let valid_letters = self.get_valid_letters_for_key(key_chars);
// Skip drawing if no valid letters
if valid_letters.is_empty() {
continue;
}
// Check if this is the active multi-tap key
let is_active = self
.multi_tap_state
.as_ref()
.map(|state| state.key_pos.row == row_idx && state.key_pos.col == col_idx)
.unwrap_or(false);
if is_active {
// Draw with highlight to show it's active
RoundedRectangle::with_equal_corners(
*rect,
Size::new(CORNER_RADIUS, CORNER_RADIUS),
)
.into_styled(PrimitiveStyle::with_fill(PALETTE.primary_container))
.draw(target)?;
// Show the current character being selected
if let Some(pending_char) = self.get_pending_char() {
// Create a buffer for the single character
let mut char_buf = [0u8; 4];
let char_str = pending_char.encode_utf8(&mut char_buf);
Text::with_text_style(
char_str,
rect.center(),
DefaultTextStyle::new(FONT_LARGE, PALETTE.on_primary_container),
TextStyleBuilder::new()
.alignment(Alignment::Center)
.baseline(Baseline::Middle)
.build(),
)
.draw(target)?;
}
} else {
// Draw key with only valid letters
self.draw_key(target, *rect, &valid_letters, true)?;
}
}
}
self.needs_redraw = false;
Ok(())
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/backup/alphabetic_keyboard.rs | frostsnap_widgets/src/backup/alphabetic_keyboard.rs | use crate::{
palette::PALETTE, super_draw_target::SuperDrawTarget, U8g2TextStyle, Widget, LEGACY_FONT_LARGE,
};
use alloc::{boxed::Box, string::ToString};
use embedded_graphics::{
framebuffer::{buffer_size, Framebuffer},
image::Image,
iterator::raw::RawDataSlice,
pixelcolor::{
raw::{LittleEndian, RawU1},
BinaryColor, Rgb565,
},
prelude::*,
primitives::{PrimitiveStyleBuilder, Rectangle},
text::{Alignment, Baseline, Text, TextStyleBuilder},
};
use embedded_iconoir::{
prelude::IconoirNewIcon,
size32px::navigation::{NavArrowLeft, NavArrowRight},
};
use frost_backup::bip39_words::ValidLetters;
// Constants for framebuffer and keyboard dimensions
const FRAMEBUFFER_WIDTH: u32 = 240;
const TOTAL_COLS: usize = 4;
const KEY_WIDTH: u32 = FRAMEBUFFER_WIDTH / TOTAL_COLS as u32;
const KEY_HEIGHT: u32 = 50;
const TOTAL_ROWS: usize = 7;
const FRAMEBUFFER_HEIGHT: u32 = TOTAL_ROWS as u32 * KEY_HEIGHT;
// Remove this inline color - we'll use PALETTE.primary_container for keys
type Fb = Framebuffer<
BinaryColor,
RawU1,
LittleEndian,
{ FRAMEBUFFER_WIDTH as usize },
{ FRAMEBUFFER_HEIGHT as usize },
{ buffer_size::<BinaryColor>(FRAMEBUFFER_WIDTH as usize, FRAMEBUFFER_HEIGHT as usize) },
>;
#[derive(Debug)]
pub struct AlphabeticKeyboard {
scroll_position: i32, // Current scroll offset
framebuffer: Box<Fb>, // Boxed framebuffer
needs_redraw: bool, // Flag to trigger redraw
enabled_keys: ValidLetters, // Which keys are enabled
visible_height: u32,
current_word_index: usize, // Current word being edited (0-24 for 25 words)
}
impl Default for AlphabeticKeyboard {
fn default() -> Self {
Self::new()
}
}
impl AlphabeticKeyboard {
pub fn new() -> Self {
let mut keyboard = Self {
framebuffer: Box::new(Fb::new()),
scroll_position: 0,
needs_redraw: true,
enabled_keys: ValidLetters::default(),
visible_height: 0, // Will be set in set_constraints
current_word_index: 0,
};
// Initialize by rendering the keyboard
keyboard.render_compact_keyboard();
keyboard
}
pub fn scroll(&mut self, amount: i32) {
// Calculate the effective height based on what's rendered
let num_rendered = if self.enabled_keys.count_enabled() == 0 {
ValidLetters::all_valid().count_enabled()
} else {
self.enabled_keys.count_enabled()
};
let rows_needed = num_rendered.div_ceil(TOTAL_COLS);
let keyboard_buffer_height = rows_needed * KEY_HEIGHT as usize;
let max_scroll = keyboard_buffer_height.saturating_sub(self.visible_height as usize);
let new_scroll_position = (self.scroll_position - amount).clamp(0, max_scroll as i32);
self.needs_redraw = self.needs_redraw || new_scroll_position != self.scroll_position;
self.scroll_position = new_scroll_position;
}
pub fn reset_scroll(&mut self) {
if self.scroll_position != 0 {
self.scroll_position = 0;
self.needs_redraw = true;
}
}
fn render_compact_keyboard(&mut self) {
// Clear the framebuffer
let _ = self.framebuffer.clear(BinaryColor::Off);
// Use U8g2TextStyle for monochrome framebuffer
let character_style = U8g2TextStyle::new(LEGACY_FONT_LARGE, BinaryColor::On);
// Determine which keys to render
let keys_to_render = if self.enabled_keys.count_enabled() == 0 {
ValidLetters::all_valid()
} else {
self.enabled_keys
};
// Always render in compact layout
for (idx, c) in keys_to_render.iter_valid().enumerate() {
let row = idx / TOTAL_COLS;
let col = idx % TOTAL_COLS;
let x = col as i32 * KEY_WIDTH as i32;
let y = row as i32 * KEY_HEIGHT as i32;
let position = Point::new(x + (KEY_WIDTH as i32 / 2), y + (KEY_HEIGHT as i32 / 2));
let _ = Text::with_text_style(
&c.to_string(),
position,
character_style.clone(),
TextStyleBuilder::new()
.alignment(Alignment::Center)
.baseline(Baseline::Middle)
.build(),
)
.draw(&mut *self.framebuffer);
}
}
pub fn set_valid_keys(&mut self, valid_letters: ValidLetters) {
// Simply update the enabled keys
self.enabled_keys = valid_letters;
// Reset scroll position and redraw the framebuffer
self.scroll_position = 0;
self.render_compact_keyboard();
self.needs_redraw = true;
}
pub fn set_current_word_index(&mut self, index: usize) {
if self.current_word_index != index {
self.current_word_index = index;
self.needs_redraw = true;
}
}
}
impl crate::DynWidget for AlphabeticKeyboard {
fn set_constraints(&mut self, max_size: Size) {
self.visible_height = max_size.height;
}
fn sizing(&self) -> crate::Sizing {
crate::Sizing {
width: FRAMEBUFFER_WIDTH,
height: self.visible_height,
..Default::default()
}
}
fn handle_touch(
&mut self,
point: Point,
_current_time: crate::Instant,
_lift_up: bool,
) -> Option<crate::KeyTouch> {
use crate::{Key, KeyTouch};
if self.enabled_keys.count_enabled() == 0 {
// Handle navigation button touches
let screen_width = FRAMEBUFFER_WIDTH;
let screen_height = self.visible_height;
// Check back button area (left side) - only if we can go back
if point.x < (screen_width / 2) as i32 && self.current_word_index > 0 {
let rect =
Rectangle::new(Point::new(0, 0), Size::new(screen_width / 2, screen_height));
return Some(KeyTouch::new(Key::NavBack, rect));
}
// Check forward button area (right side) - only if we can go forward
else if point.x >= (screen_width / 2) as i32 && self.current_word_index < 24 {
// 0-24 for 25 words
let rect = Rectangle::new(
Point::new((screen_width / 2) as i32, 0),
Size::new(screen_width / 2, screen_height),
);
return Some(KeyTouch::new(Key::NavForward, rect));
}
}
// In compact layout, keys are positioned differently
let col = (point.x / KEY_WIDTH as i32) as usize;
let row = ((point.y + self.scroll_position) / KEY_HEIGHT as i32) as usize;
if col < TOTAL_COLS {
let idx = row * TOTAL_COLS + col;
// Use nth_enabled to get the key at this index
if let Some(key) = self.enabled_keys.nth_enabled(idx) {
// Calculate the screen position of the key in compact layout
let x = col as i32 * KEY_WIDTH as i32;
let y = row as i32 * KEY_HEIGHT as i32 - self.scroll_position;
let rect = Rectangle::new(Point::new(x, y), Size::new(KEY_WIDTH, KEY_HEIGHT));
return Some(KeyTouch::new(Key::Keyboard(key), rect));
}
}
None
}
fn handle_vertical_drag(&mut self, prev_y: Option<u32>, new_y: u32, _is_release: bool) {
let delta = prev_y.map_or(0, |p| new_y as i32 - p as i32);
self.scroll(delta);
}
fn force_full_redraw(&mut self) {
self.needs_redraw = true;
}
}
impl Widget for AlphabeticKeyboard {
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.needs_redraw {
return Ok(());
}
let bounds = target.bounding_box();
// Draw based on layout
if self.enabled_keys.count_enabled() == 0 {
// Draw navigation buttons when no keys are enabled
let left_arrow = NavArrowLeft::new(PALETTE.on_background);
let right_arrow = NavArrowRight::new(PALETTE.on_background);
let screen_width = bounds.size.width;
let screen_height = bounds.size.height;
let icon_size = 32;
let padding = 10;
// Clear the area first
Rectangle::new(Point::zero(), bounds.size)
.into_styled(
PrimitiveStyleBuilder::new()
.fill_color(PALETTE.background)
.build(),
)
.draw(target)?;
// Draw left arrow if not at the first word
if self.current_word_index > 0 {
let left_point = Point::new(padding, (screen_height / 2 - icon_size / 2) as i32);
Image::new(&left_arrow, left_point).draw(target)?;
}
// Draw right arrow if not at the last word
if self.current_word_index < 24 {
let right_point = Point::new(
(screen_width - icon_size - padding as u32) as i32,
(screen_height / 2 - icon_size / 2) as i32,
);
Image::new(&right_arrow, right_point).draw(target)?;
}
// Removed word number display - not needed with navigation buttons
} else {
// Draw the framebuffer for compact keyboard
let content_height = ((self.framebuffer.size().height as i32 - self.scroll_position)
.max(0) as u32)
.min(bounds.size.height);
if content_height > 0 {
let skip_pixels =
(self.scroll_position.max(0) as usize) * FRAMEBUFFER_WIDTH as usize;
// Draw the framebuffer content followed by background padding
let framebuffer_pixels =
RawDataSlice::<RawU1, LittleEndian>::new(self.framebuffer.data())
.into_iter()
.skip(skip_pixels)
.take(FRAMEBUFFER_WIDTH as usize * content_height as usize)
.map(|r| match BinaryColor::from(r) {
BinaryColor::Off => PALETTE.background,
BinaryColor::On => PALETTE.primary_container,
});
let padding_pixels = core::iter::repeat_n(
PALETTE.background,
FRAMEBUFFER_WIDTH as usize * (bounds.size.height - content_height) as usize,
);
target.fill_contiguous(
&Rectangle::new(Point::zero(), bounds.size),
framebuffer_pixels.chain(padding_pixels),
)?;
}
}
self.needs_redraw = false;
Ok(())
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/backup/mod.rs | frostsnap_widgets/src/backup/mod.rs | mod alphabetic_keyboard;
mod backup_display;
mod backup_model;
mod backup_status_bar;
mod enter_share_screen;
mod entered_words;
mod input_preview;
mod numeric_keyboard;
mod t9_keyboard;
mod word_selector;
pub use alphabetic_keyboard::AlphabeticKeyboard;
pub use backup_display::{AllWordsPage, BackupDisplay};
pub use backup_model::{BackupModel, FramebufferMutation, MainViewState, ViewState};
pub use enter_share_screen::EnterShareScreen;
pub use entered_words::EnteredWords;
pub use input_preview::InputPreview;
pub use numeric_keyboard::NumericKeyboard;
pub use t9_keyboard::T9Keyboard;
pub use word_selector::WordSelector;
use u8g2_fonts::fonts as u8g2;
pub(crate) const LEGACY_FONT_LARGE: u8g2::u8g2_font_profont29_mf = u8g2::u8g2_font_profont29_mf;
#[allow(unused)]
pub(crate) const LEGACY_FONT_MED: u8g2::u8g2_font_profont22_mf = u8g2::u8g2_font_profont22_mf;
#[allow(unused)]
pub(crate) const LEGACY_FONT_SMALL: u8g2::u8g2_font_profont17_mf = u8g2::u8g2_font_profont17_mf;
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/backup/backup_status_bar.rs | frostsnap_widgets/src/backup/backup_status_bar.rs | use crate::palette::PALETTE;
use crate::DefaultTextStyle;
use crate::{any_of::AnyOf, prelude::*, FONT_MED, FONT_SMALL};
use alloc::string::ToString;
use embedded_graphics::prelude::*;
use frost_backup::NUM_WORDS;
pub const STATUS_BAR_HEIGHT: u32 = 55;
const CORNER_RADIUS: Size = Size::new(40, 5);
#[derive(Debug, Clone)]
pub enum BackupStatus {
Incomplete { words_entered: usize },
InvalidChecksum,
Valid,
}
// Widget for incomplete status
type IncompleteWidget = Container<Center<Column<(Text, Text)>>>;
// Widget for invalid checksum status
type InvalidChecksumWidget = Container<Center<Column<(Text, Text)>>>;
// Widget for valid status
type ValidWidget = Container<Center<Text>>;
#[derive(frostsnap_macros::Widget)]
pub struct BackupStatusBar {
widget: AnyOf<(IncompleteWidget, InvalidChecksumWidget, ValidWidget)>,
}
impl BackupStatusBar {
pub fn new(status: BackupStatus) -> Self {
match status {
BackupStatus::Incomplete { words_entered } => {
let text = if words_entered == 0 {
"Enter backup words".to_string()
} else {
format!("{}/{} words entered", words_entered, NUM_WORDS)
};
let main_text = Text::new(
text,
DefaultTextStyle::new(FONT_MED, PALETTE.on_surface_variant),
)
.with_alignment(embedded_graphics::text::Alignment::Center);
let hint_text = Text::new(
"tap word to edit",
DefaultTextStyle::new(FONT_SMALL, PALETTE.on_surface_variant),
)
.with_alignment(embedded_graphics::text::Alignment::Center);
use crate::layout::MainAxisAlignment;
let column = Column::new((main_text, hint_text))
.with_main_axis_alignment(MainAxisAlignment::Center);
let center = Center::new(column);
let mut container = Container::new(center)
.with_corner_radius(CORNER_RADIUS)
.with_border(PALETTE.outline, 2);
container.set_fill(PALETTE.surface_variant);
Self {
widget: AnyOf::new(container),
}
}
BackupStatus::InvalidChecksum => {
// Create column with two text elements
let invalid_text = Text::new(
"Invalid backup",
DefaultTextStyle::new(FONT_MED, PALETTE.on_error),
)
.with_alignment(embedded_graphics::text::Alignment::Center);
let tap_text = Text::new(
"tap word to edit",
DefaultTextStyle::new(FONT_SMALL, PALETTE.on_error),
)
.with_alignment(embedded_graphics::text::Alignment::Center);
use crate::layout::MainAxisAlignment;
let column = Column::new((invalid_text, tap_text))
.with_main_axis_alignment(MainAxisAlignment::Center);
let center = Center::new(column);
let mut container = Container::new(center)
.with_corner_radius(CORNER_RADIUS)
.with_border(PALETTE.outline, 2);
container.set_fill(PALETTE.error);
Self {
widget: AnyOf::new(container),
}
}
BackupStatus::Valid => {
let text_style = DefaultTextStyle::new(FONT_MED, PALETTE.on_tertiary_container);
let text_widget = Text::new("Backup valid", text_style)
.with_alignment(embedded_graphics::text::Alignment::Center);
let center = Center::new(text_widget);
let mut container = Container::new(center)
.with_corner_radius(CORNER_RADIUS)
.with_border(PALETTE.outline, 2);
container.set_fill(PALETTE.tertiary_container);
Self {
widget: AnyOf::new(container),
}
}
}
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/src/backup/entered_words.rs | frostsnap_widgets/src/backup/entered_words.rs | use crate::palette::PALETTE;
use crate::{DynWidget as _, Key, KeyTouch};
use alloc::rc::Rc;
use core::cell::RefCell;
use embedded_graphics::{
iterator::raw::RawDataSlice,
pixelcolor::{
raw::{LittleEndian, RawU2},
Gray2, Rgb565,
},
prelude::*,
primitives::Rectangle,
};
use super::{
backup_status_bar::{BackupStatus, BackupStatusBar, STATUS_BAR_HEIGHT},
input_preview::{Fb, FB_WIDTH, FONT_SIZE, TOP_PADDING, TOTAL_WORDS, VERTICAL_PAD},
ViewState,
};
use crate::scroll_bar::{ScrollBar, SCROLLBAR_WIDTH};
const WORD_LIST_LEFT_PAD: i32 = 4; // Left padding for word list
pub struct EnteredWords {
framebuffer: Rc<RefCell<Fb>>,
view_state: ViewState,
scroll_position: i32,
visible_size: Size,
needs_redraw: bool,
status_bar: BackupStatusBar,
scroll_bar: ScrollBar,
first_draw: bool,
}
impl EnteredWords {
/// Calculate the actual content height based on n_completed
fn calculate_content_height(&self) -> u32 {
// Show all rows up to and including the one being edited
// view_state.row is the row currently being edited (0 = share index, 1+ = words)
let visible_rows = (self.view_state.row + 1).min(TOTAL_WORDS + 1); // +1 to include current row
TOP_PADDING + (visible_rows as u32 * (FONT_SIZE.height + VERTICAL_PAD))
}
pub fn new(framebuffer: Rc<RefCell<Fb>>, visible_size: Size, view_state: ViewState) -> Self {
// Get status based on view_state
use super::backup_model::MainViewState;
let status = match &view_state.main_view {
MainViewState::AllWordsEntered { success } => match success {
Some(_) => BackupStatus::Valid,
None => BackupStatus::InvalidChecksum,
},
_ => {
// row 0 is share index, so completed words = row - 1 when row > 0
let completed_words = if view_state.row > 0 {
view_state.row - 1
} else {
0
};
BackupStatus::Incomplete {
words_entered: completed_words,
}
}
};
let mut status_bar = BackupStatusBar::new(status);
use crate::DynWidget;
status_bar.set_constraints(Size::new(visible_size.width, STATUS_BAR_HEIGHT));
// Use a fixed thumb size for now
let thumb_size = crate::Frac::from_ratio(1, 4); // 25% of scrollbar height
let scroll_bar = ScrollBar::new(thumb_size);
Self {
framebuffer: framebuffer.clone(),
view_state,
scroll_position: 0,
visible_size,
needs_redraw: true,
status_bar,
scroll_bar,
first_draw: true,
}
}
pub fn scroll_to_word_at_top(&mut self, word_index: usize) {
// Get the actual number of visible rows up to and including current
let visible_rows = (self.view_state.row + 1).min(TOTAL_WORDS + 1);
// Clamp the word index to what's actually visible
let clamped_word_index = word_index.min(visible_rows.saturating_sub(1));
let row_height = FONT_SIZE.height + VERTICAL_PAD;
// Calculate scroll to show word at top of scrollable area
let desired_scroll = clamped_word_index as i32 * row_height as i32;
// Get dynamic content height
let content_height = self.calculate_content_height();
// Calculate max scroll based on dynamic content
let scrollable_height = self.visible_size.height as i32 - STATUS_BAR_HEIGHT as i32;
let max_scroll = (content_height as i32)
.saturating_sub(scrollable_height)
.max(0);
self.scroll_position = desired_scroll.clamp(0, max_scroll);
let fraction = if max_scroll > 0 {
crate::Rat::from_ratio(self.scroll_position as u32, max_scroll as u32)
} else {
crate::Rat::ZERO
};
self.scroll_bar.set_scroll_position(fraction);
self.needs_redraw = true;
}
pub fn draw<D: DrawTarget<Color = Rgb565>>(
&mut self,
target: &mut crate::SuperDrawTarget<D, Rgb565>,
current_time: crate::Instant,
) {
if !self.needs_redraw {
return;
}
let bounds = target.bounding_box();
// Clear entire screen on first draw
if self.first_draw {
let _ = target.clear(PALETTE.background);
}
// Create a cropped target that matches the framebuffer width, centered
let cropped_rect = Rectangle::new(
Point::new(WORD_LIST_LEFT_PAD, 0),
Size::new(FB_WIDTH, bounds.size.height),
);
let mut cropped_target = target.clone().crop(cropped_rect);
let cropped_bounds = cropped_target.bounding_box();
// Get dynamic content height
let content_height = self.calculate_content_height();
// Draw words framebuffer in scrollable area only
if self.scroll_position < content_height as i32 {
let scrollable_height = (self.visible_size.height - STATUS_BAR_HEIGHT) as i32;
let skip_pixels = (self.scroll_position.max(0) as usize) * FB_WIDTH as usize;
let words_visible_height =
(content_height as i32 - self.scroll_position).min(scrollable_height) as usize;
let take_pixels = words_visible_height * FB_WIDTH as usize;
{
let fb = self.framebuffer.try_borrow().unwrap();
let framebuffer_pixels = RawDataSlice::<RawU2, LittleEndian>::new(fb.data())
.into_iter()
.skip(skip_pixels)
.take(take_pixels)
.map(|pixel| match Gray2::from(pixel).luma() {
0x00 => PALETTE.background,
0x01 => PALETTE.outline, // Numbers
0x02 => PALETTE.on_background,
0x03 => PALETTE.on_background,
_ => PALETTE.background,
});
let words_rect = Rectangle::new(
Point::zero(),
Size::new(cropped_bounds.size.width, words_visible_height as u32),
);
let _ = cropped_target.fill_contiguous(&words_rect, framebuffer_pixels);
} // fb borrow is dropped here
}
// Calculate status bar position
let status_y = bounds.size.height as i32 - STATUS_BAR_HEIGHT as i32;
// Draw status bar at fixed position at bottom of screen (full width)
use crate::Widget;
let status_area = Rectangle::new(
Point::new(0, status_y),
Size::new(bounds.size.width, STATUS_BAR_HEIGHT),
);
let _ = self
.status_bar
.draw(&mut target.clone().crop(status_area), current_time);
// Draw scroll bar
const SCROLLBAR_MARGIN: u32 = 0; // No margin from right edge
const SCROLLBAR_TOP_MARGIN: u32 = 30; // Increased top margin
const SCROLLBAR_BOTTOM_MARGIN: u32 = 2; // Bottom margin
let scrollbar_x = bounds.size.width as i32 - (SCROLLBAR_WIDTH + SCROLLBAR_MARGIN) as i32;
let scrollbar_y = SCROLLBAR_TOP_MARGIN as i32;
let scrollbar_height = (bounds.size.height - STATUS_BAR_HEIGHT)
- SCROLLBAR_TOP_MARGIN
- SCROLLBAR_BOTTOM_MARGIN;
let scrollbar_area = Rectangle::new(
Point::new(scrollbar_x, scrollbar_y),
Size::new(SCROLLBAR_WIDTH, scrollbar_height),
);
self.scroll_bar
.draw(&mut target.clone().crop(scrollbar_area));
self.needs_redraw = false;
self.first_draw = false;
}
pub fn handle_touch(&self, point: Point) -> Option<KeyTouch> {
// Status bar is not interactive, so skip checking it
let status_y = self.visible_size.height as i32 - STATUS_BAR_HEIGHT as i32;
if point.y >= status_y {
return None; // Touch is in status bar area
}
if point.x < WORD_LIST_LEFT_PAD || point.x >= WORD_LIST_LEFT_PAD + FB_WIDTH as i32 {
return None; // Touch is outside content area
}
// Adjust point for content offset
let content_point =
Point::new(point.x - WORD_LIST_LEFT_PAD, point.y + self.scroll_position);
// Calculate which word was touched using row height with padding
// Account for TOP_PADDING in the framebuffer
let row_height = (FONT_SIZE.height + VERTICAL_PAD) as i32;
let adjusted_y = content_point.y - TOP_PADDING as i32;
if adjusted_y < 0 {
return None; // Touch is in the top padding area
}
let word_index = (adjusted_y / row_height) as usize;
// Get the number of visible rows up to and including current
let visible_rows = (self.view_state.row + 1).min(TOTAL_WORDS + 1);
if word_index >= visible_rows {
return None; // Word not visible
}
// Only completed rows and current row can be edited
if word_index > self.view_state.row {
return None;
}
// Create a rectangle for the touched word (includes padding)
// Add TOP_PADDING since words are offset in the framebuffer
let y = TOP_PADDING as i32 + (word_index as i32 * row_height) - self.scroll_position;
let status_y = self.visible_size.height as i32 - STATUS_BAR_HEIGHT as i32;
// Clip the rectangle height if it would extend into the status area
let max_height = (status_y - y).max(0) as u32;
let rect_height = (FONT_SIZE.height + VERTICAL_PAD).min(max_height);
// Only return a touch if the rectangle has some height
if rect_height > 0 {
// Calculate width excluding scrollbar area
let touch_width = self.visible_size.width - SCROLLBAR_WIDTH;
let rect = Rectangle::new(
Point::new(0, y), // x=0 as requested
Size::new(touch_width, rect_height),
);
Some(KeyTouch::new(Key::EditWord(word_index), rect))
} else {
None
}
}
pub fn handle_vertical_drag(&mut self, prev_y: Option<u32>, new_y: u32, _is_release: bool) {
let delta = prev_y.map_or(0, |p| new_y as i32 - p as i32);
// Only scroll if there's a meaningful delta
if delta.abs() > 0 {
self.scroll(delta);
}
}
fn scroll(&mut self, amount: i32) {
// Get dynamic content height
let content_height = self.calculate_content_height();
// Scrollable area is screen height minus status bar height
let scrollable_height = self.visible_size.height as i32 - STATUS_BAR_HEIGHT as i32;
let max_scroll = (content_height as i32)
.saturating_sub(scrollable_height)
.max(0);
let new_scroll_position = (self.scroll_position - amount).clamp(0, max_scroll);
// Only redraw if position actually changed
if new_scroll_position != self.scroll_position {
self.scroll_position = new_scroll_position;
let fraction = if max_scroll > 0 {
crate::Rat::from_ratio(self.scroll_position as u32, max_scroll as u32)
} else {
crate::Rat::ZERO
};
self.scroll_bar.set_scroll_position(fraction);
self.needs_redraw = true;
}
}
pub fn force_full_redraw(&mut self) {
self.needs_redraw = true;
self.scroll_bar.force_full_redraw();
self.status_bar.force_full_redraw();
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/tests/vec_framebuffer.rs | frostsnap_widgets/tests/vec_framebuffer.rs | //! Tests for VecFramebuffer
use embedded_graphics::{
geometry::{Point, Size},
pixelcolor::{BinaryColor, Gray8, Rgb565},
prelude::*,
primitives::{Circle, PrimitiveStyle, Rectangle},
};
use frostsnap_widgets::vec_framebuffer::VecFramebuffer;
#[test]
fn test_framebuffer_creation_rgb565() {
let fb: VecFramebuffer<Rgb565> = VecFramebuffer::new(240, 280);
assert_eq!(fb.width, 240);
assert_eq!(fb.height, 280);
assert_eq!(fb.data.len(), 240 * 280 * 2); // 2 bytes per pixel
}
#[test]
fn test_framebuffer_creation_gray8() {
let fb: VecFramebuffer<Gray8> = VecFramebuffer::new(100, 100);
assert_eq!(fb.width, 100);
assert_eq!(fb.height, 100);
assert_eq!(fb.data.len(), 100 * 100); // 1 byte per pixel
}
#[test]
fn test_framebuffer_creation_binary() {
let fb: VecFramebuffer<BinaryColor> = VecFramebuffer::new(128, 64);
assert_eq!(fb.width, 128);
assert_eq!(fb.height, 64);
assert_eq!(fb.data.len(), 128 * 64 / 8); // 1 bit per pixel
}
#[test]
fn test_pixel_setting_rgb565() {
let mut fb: VecFramebuffer<Rgb565> = VecFramebuffer::new(10, 10);
fb.set_pixel(Point::new(5, 5), Rgb565::RED);
// Verify the pixel was set
let color = fb.get_pixel(Point::new(5, 5));
assert_eq!(color, Some(Rgb565::RED));
}
#[test]
fn test_pixel_setting_gray8() {
let mut fb: VecFramebuffer<Gray8> = VecFramebuffer::new(10, 10);
let gray_val = Gray8::new(128);
fb.set_pixel(Point::new(3, 3), gray_val);
// Verify the pixel was set
let color = fb.get_pixel(Point::new(3, 3));
assert_eq!(color, Some(gray_val));
}
#[test]
fn test_bounds_checking() {
let mut fb: VecFramebuffer<Rgb565> = VecFramebuffer::new(10, 10);
// This should not panic
fb.set_pixel(Point::new(100, 100), Rgb565::RED);
// This should return None
let color = fb.get_pixel(Point::new(100, 100));
assert_eq!(color, None);
}
#[test]
fn test_negative_coordinates() {
let mut fb: VecFramebuffer<Rgb565> = VecFramebuffer::new(10, 10);
// This should not panic
fb.set_pixel(Point::new(-5, -5), Rgb565::BLUE);
// This should return None
let color = fb.get_pixel(Point::new(-5, -5));
assert_eq!(color, None);
}
#[test]
fn test_fill_rect() {
let mut fb: VecFramebuffer<Rgb565> = VecFramebuffer::new(20, 20);
let rect = Rectangle::new(Point::new(5, 5), Size::new(10, 10));
fb.fill_rect(rect, Rgb565::GREEN);
// Check that pixels inside the rect are green
assert_eq!(fb.get_pixel(Point::new(7, 7)), Some(Rgb565::GREEN));
assert_eq!(fb.get_pixel(Point::new(14, 14)), Some(Rgb565::GREEN));
// Check that pixels outside the rect are black (default)
assert_eq!(fb.get_pixel(Point::new(4, 4)), Some(Rgb565::BLACK));
assert_eq!(fb.get_pixel(Point::new(15, 15)), Some(Rgb565::BLACK));
}
#[test]
fn test_clear() {
let mut fb: VecFramebuffer<Rgb565> = VecFramebuffer::new(10, 10);
// Set some pixels
fb.set_pixel(Point::new(5, 5), Rgb565::RED);
fb.set_pixel(Point::new(7, 7), Rgb565::BLUE);
// Clear with green
fb.clear(Rgb565::GREEN);
// All pixels should be green
for y in 0..10 {
for x in 0..10 {
assert_eq!(fb.get_pixel(Point::new(x, y)), Some(Rgb565::GREEN));
}
}
}
#[test]
fn test_draw_target() {
let mut fb: VecFramebuffer<Rgb565> = VecFramebuffer::new(50, 50);
// Draw a filled circle
let circle =
Circle::new(Point::new(10, 10), 30).into_styled(PrimitiveStyle::with_fill(Rgb565::CYAN));
circle.draw(&mut fb).unwrap();
// Check that some pixels inside the circle are cyan
assert_eq!(fb.get_pixel(Point::new(25, 25)), Some(Rgb565::CYAN));
// Draw a rectangle
use embedded_graphics::primitives::Primitive;
let rect = Rectangle::new(Point::new(0, 0), Size::new(10, 10))
.into_styled(PrimitiveStyle::with_fill(Rgb565::RED));
rect.draw(&mut fb).unwrap();
// Check that pixels in the rectangle are red
assert_eq!(fb.get_pixel(Point::new(5, 5)), Some(Rgb565::RED));
// Check that the circle pixel is still cyan (wasn't overwritten)
assert_eq!(fb.get_pixel(Point::new(25, 25)), Some(Rgb565::CYAN));
}
#[test]
fn test_draw_target_binary() {
use embedded_graphics::primitives::{Line, Primitive};
let mut fb: VecFramebuffer<BinaryColor> = VecFramebuffer::new(20, 20);
// Draw a line
let line = Line::new(Point::new(0, 0), Point::new(19, 19))
.into_styled(PrimitiveStyle::with_stroke(BinaryColor::On, 1));
line.draw(&mut fb).unwrap();
// Check some points on the diagonal
assert_eq!(fb.get_pixel(Point::new(0, 0)), Some(BinaryColor::On));
assert_eq!(fb.get_pixel(Point::new(10, 10)), Some(BinaryColor::On));
assert_eq!(fb.get_pixel(Point::new(19, 19)), Some(BinaryColor::On));
// Check a point off the diagonal
assert_eq!(fb.get_pixel(Point::new(0, 1)), Some(BinaryColor::Off));
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/tests/rat.rs | frostsnap_widgets/tests/rat.rs | use frostsnap_widgets::rat::{Frac, Rat};
#[test]
fn test_rat_from_ratio() {
// Test basic ratios
let half = Rat::from_ratio(1, 2);
let quarter = Rat::from_ratio(1, 4);
let three_quarters = Rat::from_ratio(3, 4);
let two = Rat::from_ratio(2, 1);
// Can't access internal values directly anymore, so test via Display
assert_eq!(half.to_string(), "0.5");
assert_eq!(quarter.to_string(), "0.25");
assert_eq!(three_quarters.to_string(), "0.75");
assert_eq!(two.to_string(), "2");
// Test edge cases
let zero = Rat::from_ratio(0, 100);
assert_eq!(zero.to_string(), "0");
// Division by zero should give a very large value
let div_by_zero = Rat::from_ratio(1, 0);
assert!(div_by_zero > Rat::from_ratio(1000000, 1));
}
#[test]
fn test_rat_add() {
let half = Rat::from_ratio(1, 2);
let quarter = Rat::from_ratio(1, 4);
let three_quarters = half + quarter;
assert_eq!(three_quarters, Rat::from_ratio(3, 4));
}
#[test]
fn test_rat_sub() {
let three_quarters = Rat::from_ratio(3, 4);
let quarter = Rat::from_ratio(1, 4);
let half = three_quarters - quarter;
assert_eq!(half, Rat::from_ratio(1, 2));
// Test underflow protection
let small = Rat::from_ratio(1, 4);
let large = Rat::from_ratio(3, 4);
let result = small - large;
assert_eq!(result, Rat::ZERO);
}
#[test]
fn test_rat_mul_u32() {
let half = Rat::from_ratio(1, 2);
assert_eq!(half * 100, 50);
assert_eq!(100 * half, 50);
let quarter = Rat::from_ratio(1, 4);
assert_eq!(quarter * 100, 25);
assert_eq!(100 * quarter, 25);
}
#[test]
fn test_rat_mul_i32() {
let half = Rat::from_ratio(1, 2);
assert_eq!(half * -100, -50);
assert_eq!(-100 * half, -50);
let quarter = Rat::from_ratio(1, 4);
assert_eq!(quarter * -100, -25);
assert_eq!(-100 * quarter, -25);
}
#[test]
fn test_rat_mul_rat() {
let half = Rat::from_ratio(1, 2);
let quarter = Rat::from_ratio(1, 4);
let eighth = half * quarter;
assert_eq!(eighth, Rat::from_ratio(1, 8));
// Test identity
let one = Rat::ONE;
assert_eq!(half * one, half);
// Test zero
let zero = Rat::ZERO;
assert_eq!(half * zero, Rat::ZERO);
}
#[test]
fn test_rat_div() {
let half = Rat::from_ratio(1, 2);
assert_eq!(half / 2, 2_500); // Internal representation detail
let three_quarters = Rat::from_ratio(3, 4);
assert_eq!(three_quarters / 3, 2_500);
}
#[test]
fn test_rat_display() {
assert_eq!(Rat::from_ratio(1, 2).to_string(), "0.5");
assert_eq!(Rat::from_ratio(1, 4).to_string(), "0.25");
assert_eq!(Rat::from_ratio(3, 4).to_string(), "0.75");
assert_eq!(Rat::from_ratio(5, 4).to_string(), "1.25");
assert_eq!(Rat::from_ratio(2, 1).to_string(), "2");
assert_eq!(Rat::ZERO.to_string(), "0");
assert_eq!(Rat::ONE.to_string(), "1");
// Test a value with trailing zeros
assert_eq!(Rat::from_ratio(1, 10).to_string(), "0.1");
assert_eq!(Rat::from_ratio(1, 8).to_string(), "0.125");
}
#[test]
fn test_rat_debug() {
assert_eq!(format!("{:?}", Rat::from_ratio(1, 2)), "5000/10000");
assert_eq!(format!("{:?}", Rat::from_ratio(1, 4)), "2500/10000");
assert_eq!(format!("{:?}", Rat::ONE), "10000/10000");
}
#[test]
fn test_frac_clamping() {
// Test normal values
let half_rat = Rat::from_ratio(1, 2);
let half_frac = Frac::new(half_rat);
assert_eq!(half_frac.as_rat(), half_rat);
// Test clamping values > 1
let two = Rat::from_ratio(2, 1);
let clamped = Frac::new(two);
assert_eq!(clamped, Frac::ONE);
// Test from_ratio with values > 1
let over_one = Frac::from_ratio(3, 2);
assert_eq!(over_one, Frac::ONE);
}
#[test]
fn test_frac_add() {
let quarter = Frac::from_ratio(1, 4);
let half = Frac::from_ratio(1, 2);
let three_quarters = quarter + half;
assert_eq!(three_quarters, Frac::from_ratio(3, 4));
// Test clamping on overflow
let three_quarters = Frac::from_ratio(3, 4);
let half = Frac::from_ratio(1, 2);
let result = three_quarters + half;
assert_eq!(result, Frac::ONE);
}
#[test]
fn test_frac_sub() {
let three_quarters = Frac::from_ratio(3, 4);
let quarter = Frac::from_ratio(1, 4);
let half = three_quarters - quarter;
assert_eq!(half, Frac::from_ratio(1, 2));
// Test clamping at 0
let small = Frac::from_ratio(1, 4);
let large = Frac::from_ratio(3, 4);
let zero = small - large;
assert_eq!(zero, Frac::ZERO);
}
#[test]
fn test_frac_display() {
assert_eq!(Frac::from_ratio(1, 2).to_string(), "0.5");
assert_eq!(Frac::from_ratio(1, 4).to_string(), "0.25");
assert_eq!(Frac::from_ratio(3, 4).to_string(), "0.75");
assert_eq!(Frac::ONE.to_string(), "1");
assert_eq!(Frac::ZERO.to_string(), "0");
}
#[test]
fn test_frac_debug() {
assert_eq!(format!("{:?}", Frac::from_ratio(1, 2)), "Frac(5000/10000)");
assert_eq!(format!("{:?}", Frac::ONE), "Frac(10000/10000)");
}
#[test]
fn test_small_frac() {
let nn = Frac::from_ratio(99, 100);
let one = Frac::from_ratio(1, 100);
assert_eq!((nn * 5u32) + (one * 5u32), 5 * Frac::ONE);
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_widgets/tests/fader.rs | frostsnap_widgets/tests/fader.rs | use embedded_graphics::{
draw_target::DrawTarget,
geometry::{Point, Size},
pixelcolor::Rgb565,
primitives::{Primitive, PrimitiveStyle, Rectangle},
Drawable,
};
use frostsnap_widgets::{
palette::PALETTE, vec_framebuffer::VecFramebuffer, Container, DefaultTextStyle, DynWidget,
Fader, Frac, Instant, Padding, SuperDrawTarget, Text, Widget, FONT_SMALL,
};
use proptest::prelude::*;
/// A simple widget that draws a single pixel of a specific color
#[derive(Clone)]
struct SinglePixelWidget {
color: Rgb565,
}
impl SinglePixelWidget {
fn new(color: Rgb565) -> Self {
Self { color }
}
}
impl DynWidget for SinglePixelWidget {
fn set_constraints(&mut self, _max_size: Size) {
// Single pixel widget has fixed size
}
fn sizing(&self) -> frostsnap_widgets::Sizing {
Size {
width: 1,
height: 1,
}
.into()
}
fn handle_touch(
&mut self,
_point: Point,
_current_time: Instant,
_is_release: bool,
) -> Option<frostsnap_widgets::KeyTouch> {
None
}
fn handle_vertical_drag(&mut self, _prev_y: Option<u32>, _new_y: u32, _is_release: bool) {}
fn force_full_redraw(&mut self) {}
}
impl Widget for SinglePixelWidget {
type Color = Rgb565;
fn draw<D: DrawTarget<Color = Self::Color>>(
&mut self,
target: &mut SuperDrawTarget<D, Self::Color>,
_current_time: Instant,
) -> Result<(), D::Error> {
// Draw a single pixel at (0, 0)
Rectangle::new(Point::new(0, 0), Size::new(1, 1))
.into_styled(PrimitiveStyle::with_fill(self.color))
.draw(target)
}
}
/// A custom DrawTarget that captures the color of the pixel at (0, 0)
struct SinglePixelCapture {
captured_color: Option<Rgb565>,
}
impl SinglePixelCapture {
fn new() -> Self {
Self {
captured_color: None,
}
}
fn get_captured_color(&self) -> Option<Rgb565> {
self.captured_color
}
}
impl DrawTarget for SinglePixelCapture {
type Color = Rgb565;
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 {
if pixel.0 == Point::new(0, 0) {
self.captured_color = Some(pixel.1);
}
}
Ok(())
}
}
impl embedded_graphics::geometry::OriginDimensions for SinglePixelCapture {
fn size(&self) -> Size {
Size::new(240, 280)
}
}
proptest! {
#[test]
fn test_fader_transitions(
bg_color_raw: u16,
color_a_raw: u16,
f_val in 0u32..=10000u32,
fade_duration_ms in 100u64..=5000u64,
redraw_interval_ms in 10u64..=100u64,
) {
// Convert raw values to colors
let bg_color = Rgb565::from(embedded_graphics::pixelcolor::raw::RawU16::new(bg_color_raw));
let color_a = Rgb565::from(embedded_graphics::pixelcolor::raw::RawU16::new(color_a_raw));
// Convert f_val to Frac using from_ratio
let f = Frac::from_ratio(f_val, 10000);
// Create the widget to fade
let widget = SinglePixelWidget::new(color_a);
// Create the fader in faded-out state and start it fading in from bg_color
let mut fader = Fader::new_faded_out(widget);
fader.start_fade_in(fade_duration_ms);
// Test at t=0 (should draw bg_color exclusively when fading in from it)
let capture_t0 = SinglePixelCapture::new();
let mut target_t0 = SuperDrawTarget::new(capture_t0, bg_color);
let t0 = Instant::from_millis(0);
fader.draw(&mut target_t0, t0).unwrap();
let capture_t0 = target_t0.inner_mut().unwrap();
// At t=0 when fading in from bg_color, we should see the background color
let captured_t0 = capture_t0.get_captured_color().expect("Should have drawn a pixel at t=0");
prop_assert_eq!(
captured_t0,
bg_color,
"At t=0 when fading in, should draw from_color (background). Got {:?}, expected {:?}",
captured_t0,
bg_color
);
// Draw at t = f * fade_duration_ms
// This is an intermediate point, no need to assert
let capture_mid = SinglePixelCapture::new();
let mut target_mid = SuperDrawTarget::new(capture_mid, bg_color);
let t_mid_ms = (f * (fade_duration_ms as u32)).round() as u64;
let t_mid = Instant::from_millis(t_mid_ms);
fader.draw(&mut target_mid, t_mid).unwrap();
// Draw at t = fade_duration_ms (should be fully color_a and idle)
// But we need to respect redraw_interval_ms, so keep drawing until we get a pixel
let mut captured_end = None;
let mut t = fade_duration_ms;
for _ in 0..10 { // Try up to 10 times to respect redraw interval
let capture_end = SinglePixelCapture::new();
let mut target_end = SuperDrawTarget::new(capture_end, bg_color);
fader.draw(&mut target_end, Instant::from_millis(t)).unwrap();
let capture_end = target_end.inner_mut().unwrap();
if let Some(color) = capture_end.get_captured_color() {
captured_end = Some(color);
break;
}
t += redraw_interval_ms;
}
let captured_end = captured_end.expect("Should have drawn at fade end");
prop_assert_eq!(
captured_end,
color_a,
);
// Verify fader is idle (draw again at a later time, should still be color_a)
let capture_idle = SinglePixelCapture::new();
let mut target_idle = SuperDrawTarget::new(capture_idle, bg_color);
let t_idle = Instant::from_millis(fade_duration_ms + 1000);
fader.draw(&mut target_idle, t_idle).unwrap();
let capture_idle = target_idle.inner_mut().unwrap();
let captured_idle = capture_idle.get_captured_color().expect("Should have drawn a pixel when idle");
prop_assert_eq!(
captured_idle,
color_a,
"When idle, should continue drawing widget color. Got {:?}, expected {:?}",
captured_idle,
color_a
);
// Verify is_fade_complete returns true
prop_assert!(
fader.is_fade_complete(),
"After fade duration, is_fade_complete() should return true"
);
// Now test fading out back to bg_color
fader.start_fade(fade_duration_ms);
// Draw at t=0 relative to fade out start (should still show color_a)
let fade_out_start = fade_duration_ms + 1000;
let capture_fade_out_t0 = SinglePixelCapture::new();
let mut target_fade_out_t0 = SuperDrawTarget::new(capture_fade_out_t0, bg_color);
fader.draw(&mut target_fade_out_t0, Instant::from_millis(fade_out_start)).unwrap();
let capture_fade_out_t0 = target_fade_out_t0.inner_mut().unwrap();
let captured_fade_out_t0 = capture_fade_out_t0.get_captured_color().expect("Should have drawn at fade out start");
prop_assert_eq!(
captured_fade_out_t0,
color_a,
"At fade out start, should still show widget color. Got {:?}, expected {:?}",
captured_fade_out_t0,
color_a
);
// Draw at fade out complete (should be fully bg_color and FadedOut)
let mut captured_fade_out_end = None;
let mut t_fade_out = fade_out_start + fade_duration_ms;
for _ in 0..10 { // Try up to 10 times to respect redraw interval
let capture_fade_out_end = SinglePixelCapture::new();
let mut target_fade_out_end = SuperDrawTarget::new(capture_fade_out_end, bg_color);
fader.draw(&mut target_fade_out_end, Instant::from_millis(t_fade_out)).unwrap();
let capture_fade_out_end = target_fade_out_end.inner_mut().unwrap();
if let Some(color) = capture_fade_out_end.get_captured_color() {
captured_fade_out_end = Some(color);
break;
}
t_fade_out += redraw_interval_ms;
}
let captured_fade_out_end = captured_fade_out_end.expect("Should have drawn at fade out end");
prop_assert_eq!(
captured_fade_out_end,
bg_color,
"After fade out complete, should show target color. Got {:?}, expected {:?}",
captured_fade_out_end,
bg_color
);
// Verify fader is in FadedOut state
prop_assert!(
fader.is_fade_complete(),
"After fade out, is_fade_complete() should return true"
);
prop_assert!(
fader.is_faded_out(),
"After fade out, is_faded_out() should return true"
);
// Try to draw again - should draw nothing (FadedOut state)
let capture_faded_out = SinglePixelCapture::new();
let mut target_faded_out = SuperDrawTarget::new(capture_faded_out, bg_color);
fader.draw(&mut target_faded_out, Instant::from_millis(t_fade_out + 1000)).unwrap();
let capture_faded_out = target_faded_out.inner_mut().unwrap();
prop_assert_eq!(
capture_faded_out.get_captured_color(),
None,
"In FadedOut state, should not draw anything"
);
}
}
#[test]
fn test_container_with_text_fade_out() {
// Create the exact widget from the demo
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 = Container::new(padded)
.with_fill(PALETTE.surface)
.with_border(PALETTE.primary, 2);
let mut fader = Fader::new(widget);
// Set up a framebuffer
let size = Size::new(240, 280);
// Set constraints on the fader
fader.set_constraints(size);
// Start fading out
fader.start_fade(500);
let framebuffer: VecFramebuffer<Rgb565> = VecFramebuffer::new(240, 280);
let mut target = SuperDrawTarget::new(framebuffer, PALETTE.background);
// Draw in a loop to simulate time passing
for t in (0..=600).step_by(16) {
fader.draw(&mut target, Instant::from_millis(t)).unwrap();
}
// Check that all pixels are PALETTE.background
let framebuffer = target.inner_mut().unwrap();
let all_background = framebuffer
.contiguous_pixels()
.all(|color| color == PALETTE.background);
assert!(
all_background,
"All pixels should be background color after fade out completes"
);
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_embedded/src/nonce_slots.rs | frostsnap_embedded/src/nonce_slots.rs | use alloc::vec::Vec;
use embedded_storage::nor_flash::NorFlash;
use frostsnap_core::device_nonces::{AbSlots, NonceStreamSlot, SecretNonceSlot};
use frostsnap_core::Versioned;
use crate::{ab_write::AbSlot, FlashPartition};
#[derive(Clone, Debug)]
pub struct NonceAbSlot<'a, S>(AbSlot<'a, S>);
impl<'a, S: NorFlash> NonceAbSlot<'a, S> {
pub fn load_slots(mut partition: FlashPartition<'a, S>) -> AbSlots<Self> {
let mut slots = Vec::with_capacity(partition.n_sectors() as usize / 2);
while partition.n_sectors() >= 2 {
slots.push(NonceAbSlot(AbSlot::new(partition.split_off_front(2))));
}
AbSlots::new(slots)
}
}
impl<S: NorFlash> NonceStreamSlot for NonceAbSlot<'_, S> {
fn read_slot_versioned(&mut self) -> Option<Versioned<SecretNonceSlot>> {
self.0.read()
}
fn write_slot_versioned(&mut self, value: Versioned<&SecretNonceSlot>) {
self.0.write(&value)
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_embedded/src/test.rs | frostsnap_embedded/src/test.rs | use alloc::boxed::Box;
use embedded_storage::nor_flash;
pub struct TestNorFlash(pub Box<[u8; 4096 * 4]>);
const WORD_SIZE: u32 = 4;
impl Default for TestNorFlash {
fn default() -> Self {
Self::new()
}
}
impl TestNorFlash {
pub fn new() -> Self {
Self(Box::new([0xffu8; 4096 * 4]))
}
}
impl nor_flash::ErrorType for TestNorFlash {
type Error = core::convert::Infallible;
}
impl nor_flash::ReadNorFlash for TestNorFlash {
const READ_SIZE: usize = 1;
fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Self::Error> {
bytes.copy_from_slice(&self.0[offset as usize..offset as usize + bytes.len()]);
Ok(())
}
fn capacity(&self) -> usize {
4096 * 4
}
}
impl nor_flash::NorFlash for TestNorFlash {
const WRITE_SIZE: usize = WORD_SIZE as usize;
const ERASE_SIZE: usize = 4096;
fn erase(&mut self, _from: u32, _to: u32) -> Result<(), Self::Error> {
todo!("not doing erase test yet")
}
fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
assert!(offset.is_multiple_of(WORD_SIZE));
assert!(bytes.len().is_multiple_of(4));
self.0[offset as usize..offset as usize + bytes.len()].copy_from_slice(bytes);
Ok(())
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_embedded/src/lib.rs | frostsnap_embedded/src/lib.rs | #![no_std]
#[cfg(feature = "std")]
#[macro_use]
extern crate std;
#[macro_use]
extern crate alloc;
mod ab_write;
#[cfg(test)]
pub mod test;
pub use ab_write::*;
mod nor_flash_log;
pub use nor_flash_log::*;
mod partition;
pub use partition::*;
mod nonce_slots;
pub use nonce_slots::*;
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_embedded/src/partition.rs | frostsnap_embedded/src/partition.rs | use alloc::boxed::Box;
use core::cell::RefCell;
use embedded_storage::nor_flash::{NorFlash, NorFlashError, NorFlashErrorKind, ReadNorFlash};
use frostsnap_comms::firmware_reader::{FirmwareReader, SECTOR_SIZE as FIRMWARE_SECTOR_SIZE};
use crate::ABWRITE_BINCODE_CONFIG;
pub struct FlashPartition<'a, S> {
pub tag: &'static str,
offset_sector: u32,
n_sectors: u32,
flash: &'a RefCell<S>,
}
impl<S> core::fmt::Debug for FlashPartition<'_, S> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("FlashPartition")
.field("tag", &self.tag)
.field("offset_sector", &self.offset_sector)
.field("n_sectors", &self.n_sectors)
.finish()
}
}
// Clone won't derive for some reason
impl<S> Clone for FlashPartition<'_, S> {
fn clone(&self) -> Self {
*self
}
}
impl<S> Copy for FlashPartition<'_, S> {}
pub const SECTOR_SIZE: usize = 4096;
impl<'a, S: NorFlash> FlashPartition<'a, S> {
pub fn new(
flash: &'a RefCell<S>,
offset_sector: u32,
n_sectors: u32,
tag: &'static str,
) -> Self {
Self {
tag,
offset_sector,
n_sectors,
flash,
}
}
pub fn nor_write(&self, offset: u32, bytes: &[u8]) -> Result<(), NorFlashErrorKind> {
if offset.saturating_add(bytes.len() as u32) > self.n_sectors * SECTOR_SIZE as u32 {
return Err(NorFlashErrorKind::OutOfBounds);
}
let abs_offset = offset + self.offset_sector * SECTOR_SIZE as u32;
NorFlash::write(&mut *self.flash.borrow_mut(), abs_offset, bytes).map_err(|e| e.kind())?;
Ok(())
}
pub fn nor_write_sector(
&self,
sector: u32,
bytes: &[u8; SECTOR_SIZE],
) -> Result<(), NorFlashErrorKind> {
self.nor_write(sector * SECTOR_SIZE as u32, &bytes[..])
}
pub fn read(&self, offset: u32, bytes: &mut [u8]) -> Result<(), NorFlashErrorKind> {
if offset.saturating_add(bytes.len() as u32) > self.n_sectors * SECTOR_SIZE as u32 {
return Err(NorFlashErrorKind::OutOfBounds);
}
let abs_offset = offset + self.offset_sector * SECTOR_SIZE as u32;
ReadNorFlash::read(&mut *self.flash.borrow_mut(), abs_offset, bytes)
.map_err(|e| e.kind())?;
Ok(())
}
pub fn read_sector(&self, sector: u32) -> Result<Box<[u8; SECTOR_SIZE]>, NorFlashErrorKind> {
let mut ret = Box::new([0u8; SECTOR_SIZE]);
self.read(sector * SECTOR_SIZE as u32, &mut ret[..])?;
Ok(ret)
}
/// splits n_sectors off the end of the parition into a new parition
pub fn split_off_end(&mut self, n_sectors: u32) -> FlashPartition<'a, S> {
assert!(n_sectors <= self.n_sectors);
self.n_sectors -= n_sectors;
let new_offset_sector = self.offset_sector + self.n_sectors;
FlashPartition {
tag: self.tag,
offset_sector: new_offset_sector,
n_sectors,
flash: self.flash,
}
}
/// splits n_sectors off the front of the parition into a new partition
pub fn split_off_front(&mut self, n_sectors: u32) -> FlashPartition<'a, S> {
assert!(n_sectors <= self.n_sectors);
let mut end = self.split_off_end(self.n_sectors - n_sectors);
// make the end the front
core::mem::swap(self, &mut end);
end
}
pub fn erase_sector(&self, sector: u32) -> Result<(), NorFlashErrorKind> {
if sector >= self.n_sectors {
return Err(NorFlashErrorKind::OutOfBounds);
}
let sector = self.offset_sector + sector;
NorFlash::erase(
&mut *self.flash.borrow_mut(),
sector * SECTOR_SIZE as u32,
(sector + 1) * SECTOR_SIZE as u32,
)
.map_err(|e| e.kind())
}
pub fn erase_all(&self) -> Result<(), NorFlashErrorKind> {
let start = self.offset_sector * SECTOR_SIZE as u32;
NorFlash::erase(
&mut *self.flash.borrow_mut(),
start,
start + self.n_sectors * SECTOR_SIZE as u32,
)
.map_err(|e| e.kind())
}
pub fn is_empty(&self) -> Result<bool, NorFlashErrorKind> {
for sector in 0..self.n_sectors {
let data = self.read_sector(sector)?;
if data.iter().any(|byte| *byte != 0xff) {
return Ok(false);
}
}
Ok(true)
}
pub fn set_offset(&mut self, offset: u32) {
assert_eq!(offset % SECTOR_SIZE as u32, 0);
self.offset_sector = offset / SECTOR_SIZE as u32;
}
pub fn set_size(&mut self, size: u32) {
assert_eq!(size % SECTOR_SIZE as u32, 0);
self.n_sectors = size / SECTOR_SIZE as u32;
}
pub fn set_offset_and_size(&mut self, offset: u32, size: u32) {
self.set_size(size);
self.set_offset(offset);
}
pub fn n_sectors(&self) -> u32 {
self.n_sectors
}
/// size in bytes
pub fn size(&self) -> u32 {
self.n_sectors * SECTOR_SIZE as u32
}
pub fn bincode_reader(&self) -> BincodeFlashReader<'a, S> {
BincodeFlashReader {
flash: *self,
pos: 0,
}
}
pub fn bincode_writer_remember_to_flush<const BUFFER_SIZE: usize>(
&self,
) -> BincodeFlashWriter<'a, S, BUFFER_SIZE> {
assert_eq!(BUFFER_SIZE % S::WRITE_SIZE, 0);
assert_eq!(S::ERASE_SIZE % BUFFER_SIZE, 0);
BincodeFlashWriter {
flash: *self,
buf: [0xff; BUFFER_SIZE],
buf_index: 0,
word_pos: 0,
}
}
pub fn erase_and_write_this<const BUFFER_SIZE: usize>(
&mut self,
blob: impl bincode::Encode,
) -> Result<u32, NorFlashErrorKind> {
self.erase_all()?;
let mut writer = self.bincode_writer_remember_to_flush::<BUFFER_SIZE>();
// FIXME: it's a bit annoying no error message can be passed into this error kind
bincode::encode_into_writer(blob, &mut writer, ABWRITE_BINCODE_CONFIG)
.map_err(|_| NorFlashErrorKind::Other)?;
let bytes_written = writer.flush()?;
Ok(bytes_written)
}
}
impl<'a, S: NorFlash> FirmwareReader for FlashPartition<'a, S> {
type Error = NorFlashErrorKind;
fn read_sector(
&self,
sector: u32,
) -> Result<Box<[u8; FIRMWARE_SECTOR_SIZE]>, NorFlashErrorKind> {
FlashPartition::read_sector(self, sector)
}
fn n_sectors(&self) -> u32 {
FlashPartition::n_sectors(self)
}
}
pub struct BincodeFlashReader<'a, S> {
flash: FlashPartition<'a, S>,
pos: u32,
}
impl<S> BincodeFlashReader<'_, S> {
pub fn seek_byte(&mut self, pos: u32) {
self.pos = pos;
}
pub fn byte_pos(&self) -> u32 {
self.pos
}
}
impl<S: NorFlash> bincode::de::read::Reader for BincodeFlashReader<'_, S> {
fn read(&mut self, bytes: &mut [u8]) -> Result<(), bincode::error::DecodeError> {
// this only works because we're using the "bytewise-read" feature of esp-storage
self.flash.read(self.pos, bytes).map_err(|e| {
bincode::error::DecodeError::OtherString(format!("Flash read error {e:?}"))
})?;
self.pos += bytes.len() as u32;
Ok(())
}
}
#[derive(Clone, Debug)]
pub struct BincodeFlashWriter<'a, S, const BUFFER_SIZE: usize> {
flash: FlashPartition<'a, S>,
buf: [u8; BUFFER_SIZE],
buf_index: usize,
word_pos: u32,
}
impl<S: NorFlash, const BUFFER_SIZE: usize> BincodeFlashWriter<'_, S, BUFFER_SIZE> {
pub fn seek_word(&mut self, word: u32) {
self.word_pos = word;
}
pub fn curr_word(&self) -> u32 {
self.word_pos
}
pub fn flush(mut self) -> Result<u32, NorFlashErrorKind> {
if self.buf_index != 0 {
let aligned_index = self.buf_index
+ ((S::WRITE_SIZE - (self.buf_index % S::WRITE_SIZE)) % S::WRITE_SIZE);
self.buf[self.buf_index..aligned_index].fill(0xff);
// set to zero so we don't get the drop panic even if we fail
self.buf_index = 0;
self.flash
.nor_write(
self.word_pos * S::WRITE_SIZE as u32,
&self.buf[..aligned_index],
)
.map_err(|e| e.kind())?;
self.word_pos += aligned_index as u32 / S::WRITE_SIZE as u32;
}
Ok(self.word_pos)
}
}
impl<S: NorFlash, const BUFFER_SIZE: usize> bincode::enc::write::Writer
for BincodeFlashWriter<'_, S, BUFFER_SIZE>
{
fn write(&mut self, bytes: &[u8]) -> Result<(), bincode::error::EncodeError> {
let mut i = 0;
loop {
if i == bytes.len() {
break;
}
self.buf[self.buf_index] = bytes[i];
self.buf_index += 1;
if self.buf_index == BUFFER_SIZE {
self.flash
.nor_write(self.word_pos * S::WRITE_SIZE as u32, &self.buf[..])
.map_err(|e| bincode::error::EncodeError::OtherString(format!("{e:?}")))?;
self.buf_index = 0;
self.word_pos += (BUFFER_SIZE / S::WRITE_SIZE) as u32;
}
i += 1;
}
Ok(())
}
}
impl<S, const BUFFER_SIZE: usize> Drop for BincodeFlashWriter<'_, S, BUFFER_SIZE> {
fn drop(&mut self) {
assert_eq!(
self.buf_index, 0,
"BincodeFlashWriter must be empty when dropped"
);
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::test::TestNorFlash;
use core::cell::RefCell;
use proptest::{collection, prelude::*};
#[test]
fn split_off_front() {
let test = RefCell::new(TestNorFlash::new());
let mut partition = FlashPartition::new(&test, 1, 3, "test");
let new_from_front = partition.split_off_front(1);
new_from_front.nor_write(8, [42; 4].as_slice()).unwrap();
partition.nor_write(8, [84; 4].as_slice()).unwrap();
assert_eq!(&test.borrow().0[4096 + 8..4096 + 8 + 4], [42; 4].as_slice());
assert_eq!(
&test.borrow().0[4096 * 2 + 8..4096 * 2 + 8 + 4],
[84; 4].as_slice()
);
}
#[test]
fn split_off_end() {
let test = RefCell::new(TestNorFlash::new());
let mut partition = FlashPartition::new(&test, 1, 3, "test");
let new_from_back = partition.split_off_end(1);
new_from_back.nor_write(8, [42; 4].as_slice()).unwrap();
partition.nor_write(8, [84; 4].as_slice()).unwrap();
assert_eq!(
&test.borrow().0[4096 * 3 + 8..4096 * 3 + 8 + 4],
[42; 4].as_slice()
);
assert_eq!(&test.borrow().0[4096 + 8..4096 + 8 + 4], [84; 4].as_slice());
}
proptest! {
#[test]
fn bincode_writer(data in collection::vec(any::<u8>(), 0..1024)) {
let test = RefCell::new(TestNorFlash::new());
let partition = FlashPartition::new(&test, 1, 3, "test");
let mut writer = partition.bincode_writer_remember_to_flush::<32>();
bincode::encode_into_writer(data.clone(), &mut writer, bincode::config::legacy() /* for fixint */).unwrap();
let end = writer.flush().unwrap();
prop_assert_eq!(end as usize, data.len().div_ceil(TestNorFlash::WRITE_SIZE) + /*int length is 8 bytes*/ 8 / TestNorFlash::WRITE_SIZE);
prop_assert_eq!(&test.borrow().0[4096 + 8..4096 + 8 + data.len()], &data[..]);
}
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_embedded/src/nor_flash_log.rs | frostsnap_embedded/src/nor_flash_log.rs | use alloc::string::ToString;
use embedded_storage::nor_flash::NorFlash;
use crate::FlashPartition;
const WORD_SIZE: u32 = core::mem::size_of::<u32>() as u32;
// so we get some buffer exhaustion while writing if we're testing
pub const WRITE_BUF_SIZE: usize = if cfg!(debug_assertions) { 512 } else { 32 };
pub struct NorFlashLog<'a, S> {
flash: FlashPartition<'a, S>,
word_pos: u32,
}
impl<'a, S: NorFlash> NorFlashLog<'a, S> {
pub fn new(flash: FlashPartition<'a, S>) -> Self {
assert_eq!(WORD_SIZE, S::WRITE_SIZE as u32);
Self { flash, word_pos: 0 }
}
/// The layout of the entries are word aligned and length prefixed. So the first entry has a
/// four byte little endian entry length (in words), and then the main body of the item bincode
/// encoded. Bincode doesn't care if it doesn't use all the bytes so there's no need to know
/// exactly where it ends.
pub fn push<I: bincode::Encode>(&mut self, item: I) -> Result<(), bincode::error::EncodeError> {
let mut writer = self
.flash
.bincode_writer_remember_to_flush::<WRITE_BUF_SIZE>();
// skip the first word because that's where we'll write the length
let start_word = self.word_pos + 1;
writer.seek_word(start_word);
bincode::encode_into_writer(item, &mut writer, bincode::config::standard())?;
let final_word = writer
.flush()
.map_err(|e| bincode::error::EncodeError::OtherString(e.to_string()))?;
let written_word_length = final_word - start_word;
let length_bytes = written_word_length.to_le_bytes();
self.flash
.nor_write(self.word_pos * WORD_SIZE, &length_bytes)
.map_err(|e| bincode::error::EncodeError::OtherString(e.to_string()))?;
self.word_pos += written_word_length + /* the length word */1;
Ok(())
}
pub fn seek_iter<I: bincode::Decode<()>>(
&mut self,
) -> impl Iterator<Item = Result<I, bincode::error::DecodeError>> + use<'_, 'a, S, I> {
self.word_pos = 0;
core::iter::from_fn(move || {
let mut length_buf = [0u8; WORD_SIZE as usize];
let length_word_byte_pos = self.word_pos * WORD_SIZE;
if let Err(e) = self.flash.read(length_word_byte_pos, &mut length_buf[..]) {
return Some(Err(bincode::error::DecodeError::OtherString(format!(
"failed to read length byte at {length_word_byte_pos} ({:?}) from {:?}",
e, self.flash,
))));
}
if length_buf == [0xff; WORD_SIZE as usize] {
return None;
}
self.word_pos += 1;
let word_length = u32::from_le_bytes(length_buf);
let mut reader = self.flash.bincode_reader();
let body_byte_pos = self.word_pos * WORD_SIZE;
reader.seek_byte(body_byte_pos);
let result =
bincode::decode_from_reader::<I, _, _>(&mut reader, bincode::config::standard());
let expected_pos = body_byte_pos + word_length * WORD_SIZE;
assert!(reader.byte_pos() <= expected_pos);
self.word_pos += word_length;
Some(result)
})
}
}
#[cfg(test)]
#[cfg(feature = "std")]
mod test {
use crate::test::TestNorFlash;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::cell::RefCell;
use proptest::collection;
use proptest::prelude::*;
use crate::FlashPartition;
use super::NorFlashLog;
#[test]
fn append_strings() {
let test = RefCell::new(TestNorFlash::new());
let mut log = NorFlashLog::new(FlashPartition::new(&test, 1, 3, "test"));
log.push(["ab".to_string()]).unwrap();
assert_eq!(
log.seek_iter::<String>()
.collect::<Result<Vec<_>, _>>()
.unwrap(),
vec!["ab".to_string()]
);
log.push(["cde".to_string()]).unwrap();
assert_eq!(
log.seek_iter::<String>()
.collect::<Result<Vec<_>, _>>()
.unwrap(),
vec!["ab".to_string(), "cde".to_string()]
);
log.push([String::new()]).unwrap();
assert_eq!(
log.seek_iter::<String>()
.collect::<Result<Vec<_>, _>>()
.unwrap(),
vec!["ab".to_string(), "cde".to_string(), "".to_string()]
);
}
proptest! {
#[test]
fn proptest_push(byte_vecs in collection::vec(collection::vec(any::<u8>(), 0..100), 0..100)) {
let test = RefCell::new(TestNorFlash::new());
let mut log = NorFlashLog::new(FlashPartition::new(&test, 1, 3, "test"));
for byte_vec in byte_vecs.clone() {
log.push(byte_vec).unwrap();
}
let got_byte_vecs = log.seek_iter::<Vec<u8>>().collect::<Result<Vec<_>, _>>().unwrap();
prop_assert_eq!(byte_vecs, got_byte_vecs);
}
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_embedded/src/ab_write.rs | frostsnap_embedded/src/ab_write.rs | use crate::FlashPartition;
use embedded_storage::nor_flash::NorFlash;
pub const ABWRITE_BINCODE_CONFIG: bincode::config::Configuration<
bincode::config::LittleEndian,
bincode::config::Fixint,
bincode::config::NoLimit,
> = bincode::config::standard().with_fixed_int_encoding();
/// Manages two writable sectors of persistent storage such that we make sure the state of the system we're managing is never lost.
/// The new state is first written, if that succeeds we finally write over the previous state.
#[derive(Clone, Debug)]
pub struct AbSlot<'a, S> {
slots: [Slot<'a, S>; 2],
}
impl<'a, S: NorFlash> AbSlot<'a, S> {
pub fn new(mut partition: FlashPartition<'a, S>) -> Self {
assert!(partition.n_sectors() >= 2);
assert_eq!(
partition.n_sectors() % 2,
0,
"ab-write partition sector size must be divisible by 2"
);
let slot_size = partition.n_sectors() / 2;
let b_slot = Slot {
flash: partition.split_off_end(slot_size),
};
let a_slot = Slot { flash: partition };
Self {
slots: [a_slot, b_slot],
}
}
pub fn write<T>(&self, value: &T)
where
T: bincode::Encode,
{
let (next_slot, next_index) = match self.current_slot_and_index() {
Some((current_slot, current_index, _)) => {
let next_slot = (current_slot + 1) % 2;
let next_index = current_index + 1;
if next_index == u32::MAX {
panic!("slot has been written too many times");
}
(next_slot, next_index)
}
None => (0, 0),
};
let slot_value = SlotValue {
index: next_index,
value,
};
let other_slot = (next_slot + 1) % 2;
self.slots[next_slot].write(slot_value);
self.slots[other_slot].write(slot_value);
}
pub fn read<T: bincode::Decode<()>>(&self) -> Option<T> {
let current_slot = self.current_slot();
let slot_value = self.slots[current_slot].read();
slot_value.map(|slot_value| slot_value.value)
}
fn current_slot(&self) -> usize {
if self.slots[1].read_index() > self.slots[0].read_index() {
1
} else {
0
}
}
fn current_slot_and_index(&self) -> Option<(usize, u32, bool)> {
let a_index = self.slots[0].read_index()?;
let b_index = self.slots[0].read_index()?;
Some(if b_index > a_index {
(1, b_index, b_index == a_index)
} else {
(0, a_index, b_index == a_index)
})
}
pub fn current_index(&mut self) -> u32 {
self.slots[0]
.read_index()
.max(self.slots[1].read_index())
.unwrap_or(0)
}
}
#[derive(Clone, Debug)]
struct Slot<'a, S> {
flash: FlashPartition<'a, S>,
}
impl<S: NorFlash> Slot<'_, S> {
// TODO: justify no erorr type here
pub fn read<T: bincode::Decode<()>>(&self) -> Option<SlotValue<T>> {
let value = bincode::decode_from_reader::<SlotValue<T>, _, _>(
self.flash.bincode_reader(),
ABWRITE_BINCODE_CONFIG,
)
.ok()?;
if value.index == u32::MAX {
None
} else {
Some(value)
}
}
pub fn write<T: bincode::Encode>(&self, value: SlotValue<T>) {
self.flash.erase_all().expect("must erase");
let mut writer = self.flash.bincode_writer_remember_to_flush::<256>();
bincode::encode_into_writer(&value, &mut writer, ABWRITE_BINCODE_CONFIG)
.expect("will encode");
writer.flush().expect("will flush all writes");
}
fn read_index(&self) -> Option<u32> {
let index = bincode::decode_from_reader::<u32, _, _>(
self.flash.bincode_reader(),
ABWRITE_BINCODE_CONFIG,
)
.expect("should always be able to read an int");
if index == u32::MAX {
None
} else {
Some(index)
}
}
}
#[derive(Clone, Copy, Debug, bincode::Encode, bincode::Decode)]
struct SlotValue<T> {
// the Sector with the newest index is chosen
index: u32,
value: T,
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/macros/src/lib.rs | macros/src/lib.rs | use proc_macro::TokenStream;
use quote::quote;
use syn::{Data, DeriveInput, Fields, parse_macro_input};
#[proc_macro_derive(Kind, attributes(delegate_kind))]
pub fn derive_kind(input: TokenStream) -> TokenStream {
// Parse the input tokens into a syntax tree
let input = parse_macro_input!(input as DeriveInput);
let name = input.ident;
// Only allow enums
let data_enum = match input.data {
Data::Enum(data_enum) => data_enum,
_ => {
return syn::Error::new_spanned(name, "Kind can only be derived for enums")
.to_compile_error()
.into();
}
};
// Build a match arm for each variant of the enum.
let match_arms = data_enum.variants.into_iter().map(|variant| {
let variant_ident = variant.ident;
// Check if the variant has the attribute `#[delegate_kind]`
let has_delegate = variant.attrs.iter().any(|attr| attr.path.is_ident("delegate_kind"));
if has_delegate {
// Ensure it's a newtype variant (tuple variant with exactly one field)
match variant.fields {
Fields::Unnamed(ref fields) if fields.unnamed.len() == 1 => {
// Delegate the `kind` call to the inner type
quote! {
#name::#variant_ident(inner) => inner.kind(),
}
},
_ => {
// Generate an error if the attribute is applied to a variant that is not a newtype
syn::Error::new_spanned(
variant_ident,
"delegate_kind attribute can only be applied to newtype variants (tuple struct with exactly one field)"
)
.to_compile_error()
}
}
} else {
// Without the attribute, simply return the variant name as a string literal.
let variant_name = variant_ident.to_string();
match variant.fields {
Fields::Unit => quote! {
#name::#variant_ident => #variant_name,
},
Fields::Unnamed(_) => quote! {
#name::#variant_ident(..) => #variant_name,
},
Fields::Named(_) => quote! {
#name::#variant_ident { .. } => #variant_name,
},
}
}
});
// Generate the final implementation of the `Kind` trait for the enum
let expanded = quote! {
impl Kind for #name {
fn kind(&self) -> &'static str {
match self {
#(#match_arms)*
}
}
}
};
TokenStream::from(expanded)
}
#[proc_macro_derive(Widget, attributes(widget_delegate, widget_crate))]
pub fn derive_widget(input: TokenStream) -> TokenStream {
// Parse the input tokens into a syntax tree
let input = parse_macro_input!(input as DeriveInput);
let name = &input.ident;
let generics = &input.generics;
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
// Determine the crate path to use
let crate_path = get_crate_path(&input.attrs);
match &input.data {
Data::Enum(data_enum) => derive_widget_for_enum(
name,
&impl_generics,
&ty_generics,
&where_clause,
data_enum,
&crate_path,
),
Data::Struct(data_struct) => derive_widget_for_struct(
name,
&impl_generics,
&ty_generics,
&where_clause,
data_struct,
&input.attrs,
&crate_path,
),
_ => syn::Error::new_spanned(name, "Widget can only be derived for enums and structs")
.to_compile_error()
.into(),
}
}
fn get_crate_path(attrs: &[syn::Attribute]) -> proc_macro2::TokenStream {
// Check if there's a #[widget_crate(path)] attribute
for attr in attrs {
if attr.path.is_ident("widget_crate")
&& let Ok(syn::Meta::List(meta_list)) = attr.parse_meta()
&& let Some(syn::NestedMeta::Meta(syn::Meta::Path(path))) = meta_list.nested.first()
{
return quote!(#path);
}
}
// Default: try to detect if we're in frostsnap_widgets itself
// by using crate:: which will work within the crate, and users outside
// can specify #[widget_crate(frostsnap_widgets)]
quote!(crate)
}
fn derive_widget_for_enum(
name: &syn::Ident,
impl_generics: &syn::ImplGenerics,
ty_generics: &syn::TypeGenerics,
where_clause: &Option<&syn::WhereClause>,
data_enum: &syn::DataEnum,
crate_path: &proc_macro2::TokenStream,
) -> TokenStream {
// Generate match arms for each method
let draw_arms = generate_match_arms(&data_enum.variants, quote!(draw(target, current_time)));
let set_constraints_arms =
generate_match_arms(&data_enum.variants, quote!(set_constraints(max_size)));
let sizing_arms = generate_match_arms(&data_enum.variants, quote!(sizing()));
let handle_touch_arms = generate_match_arms(
&data_enum.variants,
quote!(handle_touch(point, current_time, is_release)),
);
let handle_vertical_drag_arms = generate_match_arms(
&data_enum.variants,
quote!(handle_vertical_drag(prev_y, new_y, is_release)),
);
let force_full_redraw_arms =
generate_match_arms(&data_enum.variants, quote!(force_full_redraw()));
// Generate match arms for widget_name
let widget_name_arms = data_enum.variants.iter().map(|variant| {
let variant_ident = &variant.ident;
let variant_name = variant_ident.to_string();
match &variant.fields {
Fields::Unit => quote! {
Self::#variant_ident => #variant_name,
},
Fields::Unnamed(_) => quote! {
Self::#variant_ident(..) => #variant_name,
},
Fields::Named(_) => quote! {
Self::#variant_ident { .. } => #variant_name,
},
}
});
// Generate both DynWidget and Widget trait implementations
let expanded = quote! {
impl #impl_generics #name #ty_generics #where_clause {
/// Returns the name of the current widget variant
pub fn widget_name(&self) -> &'static str {
match self {
#(#widget_name_arms)*
}
}
}
impl #impl_generics #crate_path::DynWidget for #name #ty_generics #where_clause {
fn set_constraints(&mut self, max_size: embedded_graphics::geometry::Size) {
match self {
#(#set_constraints_arms)*
}
}
fn sizing(&self) -> #crate_path::Sizing {
match self {
#(#sizing_arms)*
}
}
fn handle_touch(
&mut self,
point: embedded_graphics::geometry::Point,
current_time: #crate_path::Instant,
is_release: bool,
) -> Option<#crate_path::KeyTouch> {
match self {
#(#handle_touch_arms)*
}
}
fn handle_vertical_drag(&mut self, prev_y: Option<u32>, new_y: u32, is_release: bool) {
match self {
#(#handle_vertical_drag_arms)*
}
}
fn force_full_redraw(&mut self) {
match self {
#(#force_full_redraw_arms)*
}
}
}
impl #impl_generics #crate_path::Widget for #name #ty_generics #where_clause {
type Color = embedded_graphics::pixelcolor::Rgb565;
fn draw<D>(
&mut self,
target: &mut #crate_path::SuperDrawTarget<D, Self::Color>,
current_time: #crate_path::Instant,
) -> Result<(), D::Error>
where
D: embedded_graphics::draw_target::DrawTarget<Color = Self::Color>,
{
match self {
#(#draw_arms)*
}
}
}
};
TokenStream::from(expanded)
}
fn derive_widget_for_struct(
name: &syn::Ident,
impl_generics: &syn::ImplGenerics,
ty_generics: &syn::TypeGenerics,
where_clause: &Option<&syn::WhereClause>,
data_struct: &syn::DataStruct,
attrs: &[syn::Attribute],
crate_path: &proc_macro2::TokenStream,
) -> TokenStream {
// Find the field to delegate to
let (delegate_field, field_type) =
match find_delegate_field_with_type(&data_struct.fields, attrs) {
Some(result) => result,
None => {
return syn::Error::new_spanned(
name,
"Struct must have either:\n\
- Exactly one field (for automatic delegation), or\n\
- A field marked with #[widget_delegate], or\n\
- The struct itself marked with #[widget_delegate(field_name)]",
)
.to_compile_error()
.into();
}
};
// Generate both DynWidget and Widget trait implementations
let expanded = quote! {
impl #impl_generics #crate_path::DynWidget for #name #ty_generics #where_clause {
fn set_constraints(&mut self, max_size: embedded_graphics::geometry::Size) {
self.#delegate_field.set_constraints(max_size)
}
fn sizing(&self) -> #crate_path::Sizing {
self.#delegate_field.sizing()
}
fn handle_touch(
&mut self,
point: embedded_graphics::geometry::Point,
current_time: #crate_path::Instant,
is_release: bool,
) -> Option<#crate_path::KeyTouch> {
self.#delegate_field.handle_touch(point, current_time, is_release)
}
fn handle_vertical_drag(&mut self, prev_y: Option<u32>, new_y: u32, is_release: bool) {
self.#delegate_field.handle_vertical_drag(prev_y, new_y, is_release)
}
fn force_full_redraw(&mut self) {
self.#delegate_field.force_full_redraw()
}
}
impl #impl_generics #crate_path::Widget for #name #ty_generics #where_clause {
type Color = <#field_type as #crate_path::Widget>::Color;
fn draw<D>(
&mut self,
target: &mut #crate_path::SuperDrawTarget<D, Self::Color>,
current_time: #crate_path::Instant,
) -> Result<(), D::Error>
where
D: embedded_graphics::draw_target::DrawTarget<Color = Self::Color>,
{
self.#delegate_field.draw(target, current_time)
}
}
};
TokenStream::from(expanded)
}
fn find_delegate_field_with_type(
fields: &syn::Fields,
struct_attrs: &[syn::Attribute],
) -> Option<(proc_macro2::TokenStream, syn::Type)> {
// First check if the struct has #[widget_delegate(field_name)]
for attr in struct_attrs {
if attr.path.is_ident("widget_delegate")
&& let Ok(syn::Meta::List(meta_list)) = attr.parse_meta()
&& let Some(syn::NestedMeta::Meta(syn::Meta::Path(path))) = meta_list.nested.first()
&& let Some(ident) = path.get_ident()
{
// Find the field with this name to get its type
if let Fields::Named(fields) = fields {
for field in &fields.named {
if field.ident.as_ref() == Some(ident) {
return Some((quote!(#ident), field.ty.clone()));
}
}
}
}
}
match fields {
Fields::Named(fields) => {
// Check if any field has #[widget_delegate] attribute
for field in &fields.named {
for attr in &field.attrs {
if attr.path.is_ident("widget_delegate")
&& let Some(field_name) = &field.ident
{
return Some((quote!(#field_name), field.ty.clone()));
}
}
}
// If there's only one field, use it
if fields.named.len() == 1
&& let Some(field) = fields.named.first()
&& let Some(field_name) = &field.ident
{
return Some((quote!(#field_name), field.ty.clone()));
}
}
Fields::Unnamed(fields) => {
// For tuple structs, use the first field if there's only one
if fields.unnamed.len() == 1
&& let Some(field) = fields.unnamed.first()
{
return Some((quote!(0), field.ty.clone()));
}
}
Fields::Unit => {}
}
None
}
fn generate_match_arms(
variants: &syn::punctuated::Punctuated<syn::Variant, syn::token::Comma>,
method_call: proc_macro2::TokenStream,
) -> Vec<proc_macro2::TokenStream> {
variants
.iter()
.map(|variant| {
let variant_ident = &variant.ident;
match &variant.fields {
Fields::Unit => {
// For unit variants, we can't delegate, so panic or return default
quote! {
Self::#variant_ident => panic!("Unit variant {} cannot delegate Widget methods", stringify!(#variant_ident)),
}
}
Fields::Unnamed(fields) => {
if fields.unnamed.len() == 1 {
// Single field tuple variant - delegate to inner widget
quote! {
Self::#variant_ident(widget) => widget.#method_call,
}
} else {
// Multiple fields - assume first field is the widget
quote! {
Self::#variant_ident(widget, ..) => widget.#method_call,
}
}
}
Fields::Named(fields) => {
// Check if any field has #[widget_delegate] attribute
let delegate_field = fields.named.iter().find_map(|field| {
for attr in &field.attrs {
if attr.path.is_ident("widget_delegate") {
return field.ident.as_ref();
}
}
None
});
if let Some(field_name) = delegate_field {
// Use the field marked with #[widget_delegate]
quote! {
Self::#variant_ident { #field_name, .. } => #field_name.#method_call,
}
} else {
// Fall back to looking for a field named 'widget'
quote! {
Self::#variant_ident { widget, .. } => widget.#method_call,
}
}
}
}
})
.collect()
}
#[proc_macro]
pub fn hex(input: TokenStream) -> TokenStream {
let input_str = parse_macro_input!(input as syn::LitStr);
let hex_str = input_str.value();
let hex_str = hex_str.trim();
if hex_str.len() % 2 != 0 {
return syn::Error::new_spanned(
input_str,
format!(
"hex string must have even length, got {} characters",
hex_str.len()
),
)
.to_compile_error()
.into();
}
let mut bytes = Vec::new();
for i in (0..hex_str.len()).step_by(2) {
let byte_str = &hex_str[i..i + 2];
match u8::from_str_radix(byte_str, 16) {
Ok(byte) => bytes.push(byte),
Err(_) => {
return syn::Error::new_spanned(
input_str,
format!("invalid hex digit in '{}'", byte_str),
)
.to_compile_error()
.into();
}
}
}
let byte_literals = bytes.iter().map(|b| quote!(#b));
let expanded = quote! {
[#(#byte_literals),*]
};
TokenStream::from(expanded)
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/macros/tests/hex_test.rs | macros/tests/hex_test.rs | use frostsnap_macros::hex;
#[test]
fn test_hex_basic() {
let bytes: [u8; 4] = hex!("deadbeef");
assert_eq!(bytes, [0xde, 0xad, 0xbe, 0xef]);
}
#[test]
fn test_hex_empty() {
let bytes: [u8; 0] = hex!("");
assert_eq!(bytes, []);
}
#[test]
fn test_hex_single_byte() {
let bytes: [u8; 1] = hex!("ff");
assert_eq!(bytes, [0xff]);
}
#[test]
fn test_hex_with_whitespace() {
let bytes: [u8; 4] = hex!(" deadbeef ");
assert_eq!(bytes, [0xde, 0xad, 0xbe, 0xef]);
}
#[test]
fn test_hex_uppercase() {
let bytes: [u8; 4] = hex!("DEADBEEF");
assert_eq!(bytes, [0xde, 0xad, 0xbe, 0xef]);
}
#[test]
fn test_hex_mixed_case() {
let bytes: [u8; 4] = hex!("DeAdBeEf");
assert_eq!(bytes, [0xde, 0xad, 0xbe, 0xef]);
}
#[test]
fn test_hex_sha256() {
let bytes: [u8; 32] = hex!("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
assert_eq!(bytes.len(), 32);
assert_eq!(bytes[0], 0xe3);
assert_eq!(bytes[31], 0x55);
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frost_backup/src/lib.rs | frost_backup/src/lib.rs | #![no_std]
#[cfg(feature = "std")]
#[macro_use]
extern crate std;
#[allow(unused_imports)]
#[macro_use]
extern crate alloc;
pub mod bip39_words;
pub mod recovery;
pub mod share_backup;
mod error;
pub use error::*;
pub use schnorr_fun::frost::Fingerprint;
pub use share_backup::*;
/// The default fingerprint used for share generation in production
pub const FINGERPRINT: Fingerprint = Fingerprint::FROST_V0;
/// Generate an xpriv from a secret scalar
///
/// This creates an xpriv with the standard initial values that can be used
/// for BIP32 derivation.
#[cfg(feature = "std")]
pub fn generate_xpriv(
secret: &schnorr_fun::fun::Scalar,
network: bitcoin::NetworkKind,
) -> bitcoin::bip32::Xpriv {
let secret_key = bitcoin::secp256k1::SecretKey::from_slice(&secret.to_bytes()).unwrap();
let chaincode = [0u8; 32];
bitcoin::bip32::Xpriv {
network,
depth: 0,
parent_fingerprint: [0u8; 4].into(),
child_number: bitcoin::bip32::ChildNumber::from_normal_idx(0).unwrap(),
private_key: secret_key,
chain_code: chaincode.into(),
}
}
/// Generate a descriptor string from a secret scalar
///
/// This creates a taproot descriptor with the standard derivation path
/// that can be imported into a wallet. The path includes an extra /0
/// at the beginning to match frostsnap_core's rootkey_to_master_appkey
/// derivation.
#[cfg(feature = "std")]
pub fn generate_descriptor(
secret: &schnorr_fun::fun::Scalar,
network: bitcoin::NetworkKind,
) -> alloc::string::String {
use alloc::format;
let xpriv = generate_xpriv(secret, network);
// Include the rootkey_to_master_appkey [0] derivation in the path
format!("tr({}/0/0/0/0/<0;1>/*)", xpriv)
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frost_backup/src/share_backup.rs | frost_backup/src/share_backup.rs | use crate::bip39_words::{word_to_index, BIP39_WORDS, BITS_PER_WORD};
use crate::error::ShareBackupError;
use alloc::{string::ToString, vec::Vec};
use core::{
fmt,
ops::{BitOrAssign, Shl},
str::FromStr,
};
use schnorr_fun::{
frost::{Fingerprint, SecretShare, ShareImage, ShareIndex, SharedKey},
fun::{hash::HashAdd, poly, prelude::*},
};
use sha2::{Digest, Sha256};
/// Number of words in a share backup
pub const NUM_WORDS: usize = 25;
/// Number of bits used for the scalar/secret share (32 bytes)
pub const SCALAR_BITS: usize = 256;
/// Number of bits used for polynomial checksum
pub const POLY_CHECKSUM_BITS: u8 = 8;
/// Number of bits used for words checksum
pub const WORDS_CHECKSUM_BITS: u8 = 11;
/// Start bit position for polynomial checksum (after scalar)
const POLY_CHECKSUM_START: usize = SCALAR_BITS;
/// Start bit position for words checksum (after scalar and poly checksum)
const WORDS_CHECKSUM_START: usize = SCALAR_BITS + POLY_CHECKSUM_BITS as usize;
/// Total number of bits in the backup (must equal NUM_WORDS * BITS_PER_WORD)
const TOTAL_BITS: usize = SCALAR_BITS + POLY_CHECKSUM_BITS as usize + WORDS_CHECKSUM_BITS as usize;
/// A Shamir secret share with checksum for BIP39 word encoding
///
/// Contains a secret share and its polynomial checksum for FROST compatibility.
/// For safety, you can't access the secret share until you've provided the
/// correct polynomial (i.e. [`SharedKey`]). You can however access the *share
/// image* which can allow you to produce the `SharedKey`. See *polynomial
/// checksum* in the README.
///
/// [`SharedKey`]: schnorr_fun::frost::SharedKey
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "bincode", derive(bincode::Encode, bincode::Decode))]
pub struct ShareBackup {
share: SecretShare,
poly_checksum: u16,
}
fn set_bit<T: BitOrAssign + Shl<u8, Output = T> + From<u8>>(target: &mut T, len: u8, index: u8) {
*target |= T::from(1) << ((len - 1) - index)
}
impl ShareBackup {
/// Returns the share index (x-coordinate in Shamir's scheme)
pub fn index(&self) -> ShareIndex {
self.share.index
}
/// Creates a ShareBackup with polynomial checksum for FROST compatibility
pub fn from_secret_share_and_shared_key(
secret_share: SecretShare,
shared_key: &SharedKey,
) -> Self {
let poly_checksum =
Self::compute_poly_checksum(secret_share.index, secret_share.share, shared_key);
ShareBackup {
share: secret_share,
poly_checksum,
}
}
/// Decodes a ShareBackup from index and 25 BIP39 words, validating checksums
pub fn from_words(index: u32, words: [&str; NUM_WORDS]) -> Result<Self, ShareBackupError> {
// First, convert each word to its BITS_PER_WORD-bit index
let mut word_indices = [0u16; NUM_WORDS];
for (i, word) in words.iter().enumerate() {
word_indices[i] =
word_to_index(word).ok_or_else(|| ShareBackupError::InvalidBip39Word {
word_index: i,
word: word.to_string(),
})? as u16;
}
let mut scalar_bytes = [0u8; 32];
let mut poly_checksum = 0u16;
let mut words_checksum = 0u16;
let mut total_bits_processed = 0;
for &word_idx in &word_indices {
for bit_offset in (0..BITS_PER_WORD).rev() {
let bit = (word_idx >> bit_offset) & 1;
if bit != 0 {
if total_bits_processed < SCALAR_BITS {
// Scalar bytes
let byte_index = total_bits_processed / 8;
let bit_in_byte = total_bits_processed % 8;
set_bit(&mut scalar_bytes[byte_index], 8, bit_in_byte as _);
} else if total_bits_processed < WORDS_CHECKSUM_START {
let checksum_bit = total_bits_processed - POLY_CHECKSUM_START;
set_bit(&mut poly_checksum, POLY_CHECKSUM_BITS, checksum_bit as _);
} else if total_bits_processed < TOTAL_BITS {
let checksum_bit = total_bits_processed - WORDS_CHECKSUM_START;
set_bit(&mut words_checksum, WORDS_CHECKSUM_BITS, checksum_bit as _);
}
}
total_bits_processed += 1;
}
}
let scalar = Scalar::from_bytes_mod_order(scalar_bytes);
// Verify words checksum before creating the share
let expected_words_checksum = Self::compute_words_checksum(index, scalar, poly_checksum);
if expected_words_checksum != words_checksum {
return Err(ShareBackupError::WordsChecksumFailed);
}
// Convert u32 to ShareIndex (Scalar<Public, NonZero>)
let index_scalar = Scalar::<Secret, Zero>::from(index)
.non_zero()
.ok_or(ShareBackupError::InvalidShareIndex)?
.public();
let share = SecretShare {
index: index_scalar,
share: scalar,
};
Ok(ShareBackup {
share,
poly_checksum,
})
}
/// Encodes share as 25 word indices (11-bit each) in constant time
pub fn to_word_indices(&self) -> [u16; NUM_WORDS] {
let scalar_bytes = self.share.share.to_bytes();
// Get index as u32
let index_u32: u32 = self
.index()
.try_into()
.expect("Share index should fit in u32");
// Calculate words checksum for encoding
let words_checksum =
Self::compute_words_checksum(index_u32, self.share.share, self.poly_checksum);
let mut word_indices = [0u16; NUM_WORDS];
let mut word_idx = 0;
let mut accumulator: u32 = 0;
let mut bits_in_acc = 0;
// Process the 32 scalar bytes
for &byte in &scalar_bytes {
accumulator = (accumulator << 8) | (byte as u32);
bits_in_acc += 8;
// Extract 11-bit words while we have enough bits
while bits_in_acc >= BITS_PER_WORD as u32 && word_idx < NUM_WORDS {
let shift = bits_in_acc - BITS_PER_WORD as u32;
word_indices[word_idx] = (accumulator >> shift) as u16;
accumulator &= (1u32 << shift) - 1;
bits_in_acc = shift;
word_idx += 1;
}
}
// After scalar bytes, we have some bits left in accumulator
// Add poly_checksum (8 bits) to complete the current word
accumulator = (accumulator << 8) | (self.poly_checksum as u32);
word_indices[23] = accumulator as u16;
word_indices[24] = words_checksum;
word_indices
}
/// Converts share to 25 BIP39 words for display/backup
pub fn to_words(&self) -> [&'static str; NUM_WORDS] {
let word_indices = self.to_word_indices();
let mut words = [""; NUM_WORDS];
for (i, &word_idx) in word_indices.iter().enumerate() {
words[i] = BIP39_WORDS[word_idx as usize];
}
words
}
/// Extracts the secret share after validating polynomial checksum
pub fn extract_secret<Z: ZeroChoice>(
self,
shared_key: &SharedKey<Normal, Z>,
) -> Result<SecretShare, ShareBackupError> {
// Verify polynomial checksum against the shared key
let poly_checksum = Self::compute_poly_checksum(self.index(), self.share.share, shared_key);
if poly_checksum != self.poly_checksum {
return Err(ShareBackupError::PolyChecksumFailed);
}
Ok(self.share)
}
/// Returns the public share image (index and commitment)
pub fn share_image(&self) -> ShareImage {
self.share.share_image()
}
fn compute_poly_checksum<Z: ZeroChoice>(
index: ShareIndex,
scalar: Scalar<Secret, Zero>,
shared_key: &SharedKey<Normal, Z>,
) -> u16 {
let hash = Sha256::new()
.add(index.to_bytes())
.add(scalar)
.add(shared_key.point_polynomial())
.finalize();
u16::from_be_bytes([hash[0], hash[1]]) >> (16 - POLY_CHECKSUM_BITS)
}
fn compute_words_checksum(index: u32, scalar: Scalar<Secret, Zero>, poly_checksum: u16) -> u16 {
let hash = Sha256::new()
.add(index.to_be_bytes())
.add(scalar)
.add(poly_checksum.to_be_bytes())
.finalize();
u16::from_be_bytes([hash[0], hash[1]]) >> (16 - WORDS_CHECKSUM_BITS)
}
/// Generates threshold shares with fingerprint grinding for FROST
pub fn generate_shares<R: rand_core::RngCore>(
secret: Scalar<Secret, NonZero>,
threshold: usize,
n_shares: usize,
fingerprint: Fingerprint,
rng: &mut R,
) -> (Vec<ShareBackup>, SharedKey) {
let poly = poly::scalar::generate_shamir_sharing_poly(secret, threshold, rng);
let point_poly = poly::scalar::to_point_poly(&poly);
let mut shared_key =
SharedKey::from_non_zero_poly(point_poly[0], point_poly[1..].iter().copied());
let tweak_poly = shared_key.grind_fingerprint::<sha2::Sha256>(fingerprint);
let poly = poly::scalar::add(poly, tweak_poly).collect::<Vec<_>>();
// Generate shares by evaluating the polynomial at indices 1..=n_shares
let shares: Vec<ShareBackup> = (1u32..=n_shares as _)
.map(|i| {
let index = Scalar::<Public, _>::from(i)
.non_zero()
.expect("starts at 1");
let share_scalar = poly::scalar::eval(&poly, index);
let poly_checksum = Self::compute_poly_checksum(index, share_scalar, &shared_key);
let share = SecretShare {
index,
share: share_scalar,
};
ShareBackup {
share,
poly_checksum,
}
})
.collect();
(shares, shared_key)
}
}
impl fmt::Display for ShareBackup {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let words = self.to_words();
let index_u32: u32 = self
.index()
.try_into()
.expect("Share index should fit in u32");
write!(f, "#{} ", index_u32)?;
for (i, word) in words.iter().enumerate() {
if i > 0 {
write!(f, " ")?;
}
write!(f, "{}", word)?;
}
Ok(())
}
}
impl FromStr for ShareBackup {
type Err = ShareBackupError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut parts = s.split_whitespace();
// Get the index
let index_str = parts
.next()
.ok_or(ShareBackupError::ShareIndexParseError)?
.trim_start_matches('#');
let index = index_str
.parse::<u32>()
.map_err(|_| ShareBackupError::ShareIndexParseError)?;
// Get the NUM_WORDS words
let mut words = [""; NUM_WORDS];
for word in &mut words {
*word = parts.next().ok_or(ShareBackupError::NotEnoughWords)?;
}
// Check there are no extra words
if parts.next().is_some() {
return Err(ShareBackupError::TooManyWords);
}
ShareBackup::from_words(index, words)
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frost_backup/src/bip39_words.rs | frost_backup/src/bip39_words.rs | //\! BIP39 English word list
/// Number of bits per BIP39 word
pub const BITS_PER_WORD: usize = 11;
/// Get the index of a word in the BIP39 word list using binary search
/// Returns None if the word is not in the list
pub fn word_to_index(word: &str) -> Option<usize> {
BIP39_WORDS.binary_search(&word).ok()
}
/// Check if a word is in the BIP39 word list using binary search
pub fn is_valid_bip39_word(word: &str) -> bool {
word_to_index(word).is_some()
}
/// Get all words that start with the given prefix
pub fn words_with_prefix(prefix: &str) -> &'static [&'static str] {
if prefix.is_empty() {
return &BIP39_WORDS;
}
let start = BIP39_WORDS.partition_point(|w| w < &prefix);
// Find the end of the matching words
let mut end = start;
while end < BIP39_WORDS.len() && BIP39_WORDS[end].starts_with(prefix) {
end += 1;
}
&BIP39_WORDS[start..end]
}
/// Returns which next letters are possible after `prefix` in the BIP39 list.
pub fn get_valid_next_letters(prefix: &str) -> ValidLetters {
if prefix.is_empty() {
// For empty prefix, return the default which has all letters except X
return ValidLetters::default();
}
// 1) Lower bound: first index where word >= prefix
let start = BIP39_WORDS.partition_point(|w| &w[..prefix.len().min(w.len())] < prefix);
let mut valid = ValidLetters::all_false();
// 2) Walk forward, strip off the prefix, and collect the very next char
for &word in &BIP39_WORDS[start..] {
if let Some(rest) = word.strip_prefix(prefix) {
if let Some(ch) = rest.chars().next() {
valid.set(ch);
}
} else {
// as soon as strip_prefix fails, we’re past the matching block
break;
}
}
valid
}
/// Represents which letters (A-Z) are valid next characters
#[derive(Debug, Clone, Copy)]
pub struct ValidLetters {
letters: [bool; 26],
count: u8, // Cache the count of enabled letters
}
const DEFAULT_VALID_LETTERS: [bool; 26] = [
true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, false, /* no letter starts with x */
true, true,
];
impl Default for ValidLetters {
fn default() -> Self {
let count = DEFAULT_VALID_LETTERS.iter().filter(|&&b| b).count() as u8;
Self {
letters: DEFAULT_VALID_LETTERS,
count,
}
}
}
impl ValidLetters {
/// Create a new ValidLetters with all letters invalid
pub fn all_false() -> Self {
Self {
letters: [false; 26],
count: 0,
}
}
/// Create a new ValidLetters with all letters valid
pub fn all_valid() -> Self {
Self {
letters: [true; 26],
count: 26,
}
}
/// Set a letter as valid (letter should be uppercase A-Z)
pub fn set(&mut self, letter: char) {
if let Some(idx) = Self::letter_to_index(letter) {
if !self.letters[idx] {
self.letters[idx] = true;
self.count += 1;
}
}
}
/// Check if a letter is valid
pub fn is_valid(&self, letter: char) -> bool {
Self::letter_to_index(letter)
.map(|idx| self.letters[idx])
.unwrap_or(false)
}
/// Get the nth enabled letter (returns None if index is out of bounds)
pub fn nth_enabled(&self, n: usize) -> Option<char> {
let mut count = 0;
for (idx, &is_valid) in self.letters.iter().enumerate() {
if is_valid {
if count == n {
return Some((b'A' + idx as u8) as char);
}
count += 1;
}
}
None
}
/// Count the number of enabled letters (cached)
pub fn count_enabled(&self) -> usize {
self.count as usize
}
/// Returns an iterator over all valid letters
pub fn iter_valid(&self) -> impl Iterator<Item = char> + '_ {
self.letters
.iter()
.enumerate()
.filter_map(|(idx, &is_valid)| {
if is_valid {
Some((b'A' + idx as u8) as char)
} else {
None
}
})
}
fn letter_to_index(letter: char) -> Option<usize> {
match letter {
'A'..='Z' => Some((letter as u8 - b'A') as usize),
_ => None,
}
}
}
/// The complete BIP39 English word list (2048 words)
pub static BIP39_WORDS: [&str; 2048] = [
"ABANDON", "ABILITY", "ABLE", "ABOUT", "ABOVE", "ABSENT", "ABSORB", "ABSTRACT", "ABSURD",
"ABUSE", "ACCESS", "ACCIDENT", "ACCOUNT", "ACCUSE", "ACHIEVE", "ACID", "ACOUSTIC", "ACQUIRE",
"ACROSS", "ACT", "ACTION", "ACTOR", "ACTRESS", "ACTUAL", "ADAPT", "ADD", "ADDICT", "ADDRESS",
"ADJUST", "ADMIT", "ADULT", "ADVANCE", "ADVICE", "AEROBIC", "AFFAIR", "AFFORD", "AFRAID",
"AGAIN", "AGE", "AGENT", "AGREE", "AHEAD", "AIM", "AIR", "AIRPORT", "AISLE", "ALARM", "ALBUM",
"ALCOHOL", "ALERT", "ALIEN", "ALL", "ALLEY", "ALLOW", "ALMOST", "ALONE", "ALPHA", "ALREADY",
"ALSO", "ALTER", "ALWAYS", "AMATEUR", "AMAZING", "AMONG", "AMOUNT", "AMUSED", "ANALYST",
"ANCHOR", "ANCIENT", "ANGER", "ANGLE", "ANGRY", "ANIMAL", "ANKLE", "ANNOUNCE", "ANNUAL",
"ANOTHER", "ANSWER", "ANTENNA", "ANTIQUE", "ANXIETY", "ANY", "APART", "APOLOGY", "APPEAR",
"APPLE", "APPROVE", "APRIL", "ARCH", "ARCTIC", "AREA", "ARENA", "ARGUE", "ARM", "ARMED",
"ARMOR", "ARMY", "AROUND", "ARRANGE", "ARREST", "ARRIVE", "ARROW", "ART", "ARTEFACT", "ARTIST",
"ARTWORK", "ASK", "ASPECT", "ASSAULT", "ASSET", "ASSIST", "ASSUME", "ASTHMA", "ATHLETE",
"ATOM", "ATTACK", "ATTEND", "ATTITUDE", "ATTRACT", "AUCTION", "AUDIT", "AUGUST", "AUNT",
"AUTHOR", "AUTO", "AUTUMN", "AVERAGE", "AVOCADO", "AVOID", "AWAKE", "AWARE", "AWAY", "AWESOME",
"AWFUL", "AWKWARD", "AXIS", "BABY", "BACHELOR", "BACON", "BADGE", "BAG", "BALANCE", "BALCONY",
"BALL", "BAMBOO", "BANANA", "BANNER", "BAR", "BARELY", "BARGAIN", "BARREL", "BASE", "BASIC",
"BASKET", "BATTLE", "BEACH", "BEAN", "BEAUTY", "BECAUSE", "BECOME", "BEEF", "BEFORE", "BEGIN",
"BEHAVE", "BEHIND", "BELIEVE", "BELOW", "BELT", "BENCH", "BENEFIT", "BEST", "BETRAY", "BETTER",
"BETWEEN", "BEYOND", "BICYCLE", "BID", "BIKE", "BIND", "BIOLOGY", "BIRD", "BIRTH", "BITTER",
"BLACK", "BLADE", "BLAME", "BLANKET", "BLAST", "BLEAK", "BLESS", "BLIND", "BLOOD", "BLOSSOM",
"BLOUSE", "BLUE", "BLUR", "BLUSH", "BOARD", "BOAT", "BODY", "BOIL", "BOMB", "BONE", "BONUS",
"BOOK", "BOOST", "BORDER", "BORING", "BORROW", "BOSS", "BOTTOM", "BOUNCE", "BOX", "BOY",
"BRACKET", "BRAIN", "BRAND", "BRASS", "BRAVE", "BREAD", "BREEZE", "BRICK", "BRIDGE", "BRIEF",
"BRIGHT", "BRING", "BRISK", "BROCCOLI", "BROKEN", "BRONZE", "BROOM", "BROTHER", "BROWN",
"BRUSH", "BUBBLE", "BUDDY", "BUDGET", "BUFFALO", "BUILD", "BULB", "BULK", "BULLET", "BUNDLE",
"BUNKER", "BURDEN", "BURGER", "BURST", "BUS", "BUSINESS", "BUSY", "BUTTER", "BUYER", "BUZZ",
"CABBAGE", "CABIN", "CABLE", "CACTUS", "CAGE", "CAKE", "CALL", "CALM", "CAMERA", "CAMP", "CAN",
"CANAL", "CANCEL", "CANDY", "CANNON", "CANOE", "CANVAS", "CANYON", "CAPABLE", "CAPITAL",
"CAPTAIN", "CAR", "CARBON", "CARD", "CARGO", "CARPET", "CARRY", "CART", "CASE", "CASH",
"CASINO", "CASTLE", "CASUAL", "CAT", "CATALOG", "CATCH", "CATEGORY", "CATTLE", "CAUGHT",
"CAUSE", "CAUTION", "CAVE", "CEILING", "CELERY", "CEMENT", "CENSUS", "CENTURY", "CEREAL",
"CERTAIN", "CHAIR", "CHALK", "CHAMPION", "CHANGE", "CHAOS", "CHAPTER", "CHARGE", "CHASE",
"CHAT", "CHEAP", "CHECK", "CHEESE", "CHEF", "CHERRY", "CHEST", "CHICKEN", "CHIEF", "CHILD",
"CHIMNEY", "CHOICE", "CHOOSE", "CHRONIC", "CHUCKLE", "CHUNK", "CHURN", "CIGAR", "CINNAMON",
"CIRCLE", "CITIZEN", "CITY", "CIVIL", "CLAIM", "CLAP", "CLARIFY", "CLAW", "CLAY", "CLEAN",
"CLERK", "CLEVER", "CLICK", "CLIENT", "CLIFF", "CLIMB", "CLINIC", "CLIP", "CLOCK", "CLOG",
"CLOSE", "CLOTH", "CLOUD", "CLOWN", "CLUB", "CLUMP", "CLUSTER", "CLUTCH", "COACH", "COAST",
"COCONUT", "CODE", "COFFEE", "COIL", "COIN", "COLLECT", "COLOR", "COLUMN", "COMBINE", "COME",
"COMFORT", "COMIC", "COMMON", "COMPANY", "CONCERT", "CONDUCT", "CONFIRM", "CONGRESS",
"CONNECT", "CONSIDER", "CONTROL", "CONVINCE", "COOK", "COOL", "COPPER", "COPY", "CORAL",
"CORE", "CORN", "CORRECT", "COST", "COTTON", "COUCH", "COUNTRY", "COUPLE", "COURSE", "COUSIN",
"COVER", "COYOTE", "CRACK", "CRADLE", "CRAFT", "CRAM", "CRANE", "CRASH", "CRATER", "CRAWL",
"CRAZY", "CREAM", "CREDIT", "CREEK", "CREW", "CRICKET", "CRIME", "CRISP", "CRITIC", "CROP",
"CROSS", "CROUCH", "CROWD", "CRUCIAL", "CRUEL", "CRUISE", "CRUMBLE", "CRUNCH", "CRUSH", "CRY",
"CRYSTAL", "CUBE", "CULTURE", "CUP", "CUPBOARD", "CURIOUS", "CURRENT", "CURTAIN", "CURVE",
"CUSHION", "CUSTOM", "CUTE", "CYCLE", "DAD", "DAMAGE", "DAMP", "DANCE", "DANGER", "DARING",
"DASH", "DAUGHTER", "DAWN", "DAY", "DEAL", "DEBATE", "DEBRIS", "DECADE", "DECEMBER", "DECIDE",
"DECLINE", "DECORATE", "DECREASE", "DEER", "DEFENSE", "DEFINE", "DEFY", "DEGREE", "DELAY",
"DELIVER", "DEMAND", "DEMISE", "DENIAL", "DENTIST", "DENY", "DEPART", "DEPEND", "DEPOSIT",
"DEPTH", "DEPUTY", "DERIVE", "DESCRIBE", "DESERT", "DESIGN", "DESK", "DESPAIR", "DESTROY",
"DETAIL", "DETECT", "DEVELOP", "DEVICE", "DEVOTE", "DIAGRAM", "DIAL", "DIAMOND", "DIARY",
"DICE", "DIESEL", "DIET", "DIFFER", "DIGITAL", "DIGNITY", "DILEMMA", "DINNER", "DINOSAUR",
"DIRECT", "DIRT", "DISAGREE", "DISCOVER", "DISEASE", "DISH", "DISMISS", "DISORDER", "DISPLAY",
"DISTANCE", "DIVERT", "DIVIDE", "DIVORCE", "DIZZY", "DOCTOR", "DOCUMENT", "DOG", "DOLL",
"DOLPHIN", "DOMAIN", "DONATE", "DONKEY", "DONOR", "DOOR", "DOSE", "DOUBLE", "DOVE", "DRAFT",
"DRAGON", "DRAMA", "DRASTIC", "DRAW", "DREAM", "DRESS", "DRIFT", "DRILL", "DRINK", "DRIP",
"DRIVE", "DROP", "DRUM", "DRY", "DUCK", "DUMB", "DUNE", "DURING", "DUST", "DUTCH", "DUTY",
"DWARF", "DYNAMIC", "EAGER", "EAGLE", "EARLY", "EARN", "EARTH", "EASILY", "EAST", "EASY",
"ECHO", "ECOLOGY", "ECONOMY", "EDGE", "EDIT", "EDUCATE", "EFFORT", "EGG", "EIGHT", "EITHER",
"ELBOW", "ELDER", "ELECTRIC", "ELEGANT", "ELEMENT", "ELEPHANT", "ELEVATOR", "ELITE", "ELSE",
"EMBARK", "EMBODY", "EMBRACE", "EMERGE", "EMOTION", "EMPLOY", "EMPOWER", "EMPTY", "ENABLE",
"ENACT", "END", "ENDLESS", "ENDORSE", "ENEMY", "ENERGY", "ENFORCE", "ENGAGE", "ENGINE",
"ENHANCE", "ENJOY", "ENLIST", "ENOUGH", "ENRICH", "ENROLL", "ENSURE", "ENTER", "ENTIRE",
"ENTRY", "ENVELOPE", "EPISODE", "EQUAL", "EQUIP", "ERA", "ERASE", "ERODE", "EROSION", "ERROR",
"ERUPT", "ESCAPE", "ESSAY", "ESSENCE", "ESTATE", "ETERNAL", "ETHICS", "EVIDENCE", "EVIL",
"EVOKE", "EVOLVE", "EXACT", "EXAMPLE", "EXCESS", "EXCHANGE", "EXCITE", "EXCLUDE", "EXCUSE",
"EXECUTE", "EXERCISE", "EXHAUST", "EXHIBIT", "EXILE", "EXIST", "EXIT", "EXOTIC", "EXPAND",
"EXPECT", "EXPIRE", "EXPLAIN", "EXPOSE", "EXPRESS", "EXTEND", "EXTRA", "EYE", "EYEBROW",
"FABRIC", "FACE", "FACULTY", "FADE", "FAINT", "FAITH", "FALL", "FALSE", "FAME", "FAMILY",
"FAMOUS", "FAN", "FANCY", "FANTASY", "FARM", "FASHION", "FAT", "FATAL", "FATHER", "FATIGUE",
"FAULT", "FAVORITE", "FEATURE", "FEBRUARY", "FEDERAL", "FEE", "FEED", "FEEL", "FEMALE",
"FENCE", "FESTIVAL", "FETCH", "FEVER", "FEW", "FIBER", "FICTION", "FIELD", "FIGURE", "FILE",
"FILM", "FILTER", "FINAL", "FIND", "FINE", "FINGER", "FINISH", "FIRE", "FIRM", "FIRST",
"FISCAL", "FISH", "FIT", "FITNESS", "FIX", "FLAG", "FLAME", "FLASH", "FLAT", "FLAVOR", "FLEE",
"FLIGHT", "FLIP", "FLOAT", "FLOCK", "FLOOR", "FLOWER", "FLUID", "FLUSH", "FLY", "FOAM",
"FOCUS", "FOG", "FOIL", "FOLD", "FOLLOW", "FOOD", "FOOT", "FORCE", "FOREST", "FORGET", "FORK",
"FORTUNE", "FORUM", "FORWARD", "FOSSIL", "FOSTER", "FOUND", "FOX", "FRAGILE", "FRAME",
"FREQUENT", "FRESH", "FRIEND", "FRINGE", "FROG", "FRONT", "FROST", "FROWN", "FROZEN", "FRUIT",
"FUEL", "FUN", "FUNNY", "FURNACE", "FURY", "FUTURE", "GADGET", "GAIN", "GALAXY", "GALLERY",
"GAME", "GAP", "GARAGE", "GARBAGE", "GARDEN", "GARLIC", "GARMENT", "GAS", "GASP", "GATE",
"GATHER", "GAUGE", "GAZE", "GENERAL", "GENIUS", "GENRE", "GENTLE", "GENUINE", "GESTURE",
"GHOST", "GIANT", "GIFT", "GIGGLE", "GINGER", "GIRAFFE", "GIRL", "GIVE", "GLAD", "GLANCE",
"GLARE", "GLASS", "GLIDE", "GLIMPSE", "GLOBE", "GLOOM", "GLORY", "GLOVE", "GLOW", "GLUE",
"GOAT", "GODDESS", "GOLD", "GOOD", "GOOSE", "GORILLA", "GOSPEL", "GOSSIP", "GOVERN", "GOWN",
"GRAB", "GRACE", "GRAIN", "GRANT", "GRAPE", "GRASS", "GRAVITY", "GREAT", "GREEN", "GRID",
"GRIEF", "GRIT", "GROCERY", "GROUP", "GROW", "GRUNT", "GUARD", "GUESS", "GUIDE", "GUILT",
"GUITAR", "GUN", "GYM", "HABIT", "HAIR", "HALF", "HAMMER", "HAMSTER", "HAND", "HAPPY",
"HARBOR", "HARD", "HARSH", "HARVEST", "HAT", "HAVE", "HAWK", "HAZARD", "HEAD", "HEALTH",
"HEART", "HEAVY", "HEDGEHOG", "HEIGHT", "HELLO", "HELMET", "HELP", "HEN", "HERO", "HIDDEN",
"HIGH", "HILL", "HINT", "HIP", "HIRE", "HISTORY", "HOBBY", "HOCKEY", "HOLD", "HOLE", "HOLIDAY",
"HOLLOW", "HOME", "HONEY", "HOOD", "HOPE", "HORN", "HORROR", "HORSE", "HOSPITAL", "HOST",
"HOTEL", "HOUR", "HOVER", "HUB", "HUGE", "HUMAN", "HUMBLE", "HUMOR", "HUNDRED", "HUNGRY",
"HUNT", "HURDLE", "HURRY", "HURT", "HUSBAND", "HYBRID", "ICE", "ICON", "IDEA", "IDENTIFY",
"IDLE", "IGNORE", "ILL", "ILLEGAL", "ILLNESS", "IMAGE", "IMITATE", "IMMENSE", "IMMUNE",
"IMPACT", "IMPOSE", "IMPROVE", "IMPULSE", "INCH", "INCLUDE", "INCOME", "INCREASE", "INDEX",
"INDICATE", "INDOOR", "INDUSTRY", "INFANT", "INFLICT", "INFORM", "INHALE", "INHERIT",
"INITIAL", "INJECT", "INJURY", "INMATE", "INNER", "INNOCENT", "INPUT", "INQUIRY", "INSANE",
"INSECT", "INSIDE", "INSPIRE", "INSTALL", "INTACT", "INTEREST", "INTO", "INVEST", "INVITE",
"INVOLVE", "IRON", "ISLAND", "ISOLATE", "ISSUE", "ITEM", "IVORY", "JACKET", "JAGUAR", "JAR",
"JAZZ", "JEALOUS", "JEANS", "JELLY", "JEWEL", "JOB", "JOIN", "JOKE", "JOURNEY", "JOY", "JUDGE",
"JUICE", "JUMP", "JUNGLE", "JUNIOR", "JUNK", "JUST", "KANGAROO", "KEEN", "KEEP", "KETCHUP",
"KEY", "KICK", "KID", "KIDNEY", "KIND", "KINGDOM", "KISS", "KIT", "KITCHEN", "KITE", "KITTEN",
"KIWI", "KNEE", "KNIFE", "KNOCK", "KNOW", "LAB", "LABEL", "LABOR", "LADDER", "LADY", "LAKE",
"LAMP", "LANGUAGE", "LAPTOP", "LARGE", "LATER", "LATIN", "LAUGH", "LAUNDRY", "LAVA", "LAW",
"LAWN", "LAWSUIT", "LAYER", "LAZY", "LEADER", "LEAF", "LEARN", "LEAVE", "LECTURE", "LEFT",
"LEG", "LEGAL", "LEGEND", "LEISURE", "LEMON", "LEND", "LENGTH", "LENS", "LEOPARD", "LESSON",
"LETTER", "LEVEL", "LIAR", "LIBERTY", "LIBRARY", "LICENSE", "LIFE", "LIFT", "LIGHT", "LIKE",
"LIMB", "LIMIT", "LINK", "LION", "LIQUID", "LIST", "LITTLE", "LIVE", "LIZARD", "LOAD", "LOAN",
"LOBSTER", "LOCAL", "LOCK", "LOGIC", "LONELY", "LONG", "LOOP", "LOTTERY", "LOUD", "LOUNGE",
"LOVE", "LOYAL", "LUCKY", "LUGGAGE", "LUMBER", "LUNAR", "LUNCH", "LUXURY", "LYRICS", "MACHINE",
"MAD", "MAGIC", "MAGNET", "MAID", "MAIL", "MAIN", "MAJOR", "MAKE", "MAMMAL", "MAN", "MANAGE",
"MANDATE", "MANGO", "MANSION", "MANUAL", "MAPLE", "MARBLE", "MARCH", "MARGIN", "MARINE",
"MARKET", "MARRIAGE", "MASK", "MASS", "MASTER", "MATCH", "MATERIAL", "MATH", "MATRIX",
"MATTER", "MAXIMUM", "MAZE", "MEADOW", "MEAN", "MEASURE", "MEAT", "MECHANIC", "MEDAL", "MEDIA",
"MELODY", "MELT", "MEMBER", "MEMORY", "MENTION", "MENU", "MERCY", "MERGE", "MERIT", "MERRY",
"MESH", "MESSAGE", "METAL", "METHOD", "MIDDLE", "MIDNIGHT", "MILK", "MILLION", "MIMIC", "MIND",
"MINIMUM", "MINOR", "MINUTE", "MIRACLE", "MIRROR", "MISERY", "MISS", "MISTAKE", "MIX", "MIXED",
"MIXTURE", "MOBILE", "MODEL", "MODIFY", "MOM", "MOMENT", "MONITOR", "MONKEY", "MONSTER",
"MONTH", "MOON", "MORAL", "MORE", "MORNING", "MOSQUITO", "MOTHER", "MOTION", "MOTOR",
"MOUNTAIN", "MOUSE", "MOVE", "MOVIE", "MUCH", "MUFFIN", "MULE", "MULTIPLY", "MUSCLE", "MUSEUM",
"MUSHROOM", "MUSIC", "MUST", "MUTUAL", "MYSELF", "MYSTERY", "MYTH", "NAIVE", "NAME", "NAPKIN",
"NARROW", "NASTY", "NATION", "NATURE", "NEAR", "NECK", "NEED", "NEGATIVE", "NEGLECT",
"NEITHER", "NEPHEW", "NERVE", "NEST", "NET", "NETWORK", "NEUTRAL", "NEVER", "NEWS", "NEXT",
"NICE", "NIGHT", "NOBLE", "NOISE", "NOMINEE", "NOODLE", "NORMAL", "NORTH", "NOSE", "NOTABLE",
"NOTE", "NOTHING", "NOTICE", "NOVEL", "NOW", "NUCLEAR", "NUMBER", "NURSE", "NUT", "OAK",
"OBEY", "OBJECT", "OBLIGE", "OBSCURE", "OBSERVE", "OBTAIN", "OBVIOUS", "OCCUR", "OCEAN",
"OCTOBER", "ODOR", "OFF", "OFFER", "OFFICE", "OFTEN", "OIL", "OKAY", "OLD", "OLIVE", "OLYMPIC",
"OMIT", "ONCE", "ONE", "ONION", "ONLINE", "ONLY", "OPEN", "OPERA", "OPINION", "OPPOSE",
"OPTION", "ORANGE", "ORBIT", "ORCHARD", "ORDER", "ORDINARY", "ORGAN", "ORIENT", "ORIGINAL",
"ORPHAN", "OSTRICH", "OTHER", "OUTDOOR", "OUTER", "OUTPUT", "OUTSIDE", "OVAL", "OVEN", "OVER",
"OWN", "OWNER", "OXYGEN", "OYSTER", "OZONE", "PACT", "PADDLE", "PAGE", "PAIR", "PALACE",
"PALM", "PANDA", "PANEL", "PANIC", "PANTHER", "PAPER", "PARADE", "PARENT", "PARK", "PARROT",
"PARTY", "PASS", "PATCH", "PATH", "PATIENT", "PATROL", "PATTERN", "PAUSE", "PAVE", "PAYMENT",
"PEACE", "PEANUT", "PEAR", "PEASANT", "PELICAN", "PEN", "PENALTY", "PENCIL", "PEOPLE",
"PEPPER", "PERFECT", "PERMIT", "PERSON", "PET", "PHONE", "PHOTO", "PHRASE", "PHYSICAL",
"PIANO", "PICNIC", "PICTURE", "PIECE", "PIG", "PIGEON", "PILL", "PILOT", "PINK", "PIONEER",
"PIPE", "PISTOL", "PITCH", "PIZZA", "PLACE", "PLANET", "PLASTIC", "PLATE", "PLAY", "PLEASE",
"PLEDGE", "PLUCK", "PLUG", "PLUNGE", "POEM", "POET", "POINT", "POLAR", "POLE", "POLICE",
"POND", "PONY", "POOL", "POPULAR", "PORTION", "POSITION", "POSSIBLE", "POST", "POTATO",
"POTTERY", "POVERTY", "POWDER", "POWER", "PRACTICE", "PRAISE", "PREDICT", "PREFER", "PREPARE",
"PRESENT", "PRETTY", "PREVENT", "PRICE", "PRIDE", "PRIMARY", "PRINT", "PRIORITY", "PRISON",
"PRIVATE", "PRIZE", "PROBLEM", "PROCESS", "PRODUCE", "PROFIT", "PROGRAM", "PROJECT", "PROMOTE",
"PROOF", "PROPERTY", "PROSPER", "PROTECT", "PROUD", "PROVIDE", "PUBLIC", "PUDDING", "PULL",
"PULP", "PULSE", "PUMPKIN", "PUNCH", "PUPIL", "PUPPY", "PURCHASE", "PURITY", "PURPOSE",
"PURSE", "PUSH", "PUT", "PUZZLE", "PYRAMID", "QUALITY", "QUANTUM", "QUARTER", "QUESTION",
"QUICK", "QUIT", "QUIZ", "QUOTE", "RABBIT", "RACCOON", "RACE", "RACK", "RADAR", "RADIO",
"RAIL", "RAIN", "RAISE", "RALLY", "RAMP", "RANCH", "RANDOM", "RANGE", "RAPID", "RARE", "RATE",
"RATHER", "RAVEN", "RAW", "RAZOR", "READY", "REAL", "REASON", "REBEL", "REBUILD", "RECALL",
"RECEIVE", "RECIPE", "RECORD", "RECYCLE", "REDUCE", "REFLECT", "REFORM", "REFUSE", "REGION",
"REGRET", "REGULAR", "REJECT", "RELAX", "RELEASE", "RELIEF", "RELY", "REMAIN", "REMEMBER",
"REMIND", "REMOVE", "RENDER", "RENEW", "RENT", "REOPEN", "REPAIR", "REPEAT", "REPLACE",
"REPORT", "REQUIRE", "RESCUE", "RESEMBLE", "RESIST", "RESOURCE", "RESPONSE", "RESULT",
"RETIRE", "RETREAT", "RETURN", "REUNION", "REVEAL", "REVIEW", "REWARD", "RHYTHM", "RIB",
"RIBBON", "RICE", "RICH", "RIDE", "RIDGE", "RIFLE", "RIGHT", "RIGID", "RING", "RIOT", "RIPPLE",
"RISK", "RITUAL", "RIVAL", "RIVER", "ROAD", "ROAST", "ROBOT", "ROBUST", "ROCKET", "ROMANCE",
"ROOF", "ROOKIE", "ROOM", "ROSE", "ROTATE", "ROUGH", "ROUND", "ROUTE", "ROYAL", "RUBBER",
"RUDE", "RUG", "RULE", "RUN", "RUNWAY", "RURAL", "SAD", "SADDLE", "SADNESS", "SAFE", "SAIL",
"SALAD", "SALMON", "SALON", "SALT", "SALUTE", "SAME", "SAMPLE", "SAND", "SATISFY", "SATOSHI",
"SAUCE", "SAUSAGE", "SAVE", "SAY", "SCALE", "SCAN", "SCARE", "SCATTER", "SCENE", "SCHEME",
"SCHOOL", "SCIENCE", "SCISSORS", "SCORPION", "SCOUT", "SCRAP", "SCREEN", "SCRIPT", "SCRUB",
"SEA", "SEARCH", "SEASON", "SEAT", "SECOND", "SECRET", "SECTION", "SECURITY", "SEED", "SEEK",
"SEGMENT", "SELECT", "SELL", "SEMINAR", "SENIOR", "SENSE", "SENTENCE", "SERIES", "SERVICE",
"SESSION", "SETTLE", "SETUP", "SEVEN", "SHADOW", "SHAFT", "SHALLOW", "SHARE", "SHED", "SHELL",
"SHERIFF", "SHIELD", "SHIFT", "SHINE", "SHIP", "SHIVER", "SHOCK", "SHOE", "SHOOT", "SHOP",
"SHORT", "SHOULDER", "SHOVE", "SHRIMP", "SHRUG", "SHUFFLE", "SHY", "SIBLING", "SICK", "SIDE",
"SIEGE", "SIGHT", "SIGN", "SILENT", "SILK", "SILLY", "SILVER", "SIMILAR", "SIMPLE", "SINCE",
"SING", "SIREN", "SISTER", "SITUATE", "SIX", "SIZE", "SKATE", "SKETCH", "SKI", "SKILL", "SKIN",
"SKIRT", "SKULL", "SLAB", "SLAM", "SLEEP", "SLENDER", "SLICE", "SLIDE", "SLIGHT", "SLIM",
"SLOGAN", "SLOT", "SLOW", "SLUSH", "SMALL", "SMART", "SMILE", "SMOKE", "SMOOTH", "SNACK",
"SNAKE", "SNAP", "SNIFF", "SNOW", "SOAP", "SOCCER", "SOCIAL", "SOCK", "SODA", "SOFT", "SOLAR",
"SOLDIER", "SOLID", "SOLUTION", "SOLVE", "SOMEONE", "SONG", "SOON", "SORRY", "SORT", "SOUL",
"SOUND", "SOUP", "SOURCE", "SOUTH", "SPACE", "SPARE", "SPATIAL", "SPAWN", "SPEAK", "SPECIAL",
"SPEED", "SPELL", "SPEND", "SPHERE", "SPICE", "SPIDER", "SPIKE", "SPIN", "SPIRIT", "SPLIT",
"SPOIL", "SPONSOR", "SPOON", "SPORT", "SPOT", "SPRAY", "SPREAD", "SPRING", "SPY", "SQUARE",
"SQUEEZE", "SQUIRREL", "STABLE", "STADIUM", "STAFF", "STAGE", "STAIRS", "STAMP", "STAND",
"START", "STATE", "STAY", "STEAK", "STEEL", "STEM", "STEP", "STEREO", "STICK", "STILL",
"STING", "STOCK", "STOMACH", "STONE", "STOOL", "STORY", "STOVE", "STRATEGY", "STREET",
"STRIKE", "STRONG", "STRUGGLE", "STUDENT", "STUFF", "STUMBLE", "STYLE", "SUBJECT", "SUBMIT",
"SUBWAY", "SUCCESS", "SUCH", "SUDDEN", "SUFFER", "SUGAR", "SUGGEST", "SUIT", "SUMMER", "SUN",
"SUNNY", "SUNSET", "SUPER", "SUPPLY", "SUPREME", "SURE", "SURFACE", "SURGE", "SURPRISE",
"SURROUND", "SURVEY", "SUSPECT", "SUSTAIN", "SWALLOW", "SWAMP", "SWAP", "SWARM", "SWEAR",
"SWEET", "SWIFT", "SWIM", "SWING", "SWITCH", "SWORD", "SYMBOL", "SYMPTOM", "SYRUP", "SYSTEM",
"TABLE", "TACKLE", "TAG", "TAIL", "TALENT", "TALK", "TANK", "TAPE", "TARGET", "TASK", "TASTE",
"TATTOO", "TAXI", "TEACH", "TEAM", "TELL", "TEN", "TENANT", "TENNIS", "TENT", "TERM", "TEST",
"TEXT", "THANK", "THAT", "THEME", "THEN", "THEORY", "THERE", "THEY", "THING", "THIS",
"THOUGHT", "THREE", "THRIVE", "THROW", "THUMB", "THUNDER", "TICKET", "TIDE", "TIGER", "TILT",
"TIMBER", "TIME", "TINY", "TIP", "TIRED", "TISSUE", "TITLE", "TOAST", "TOBACCO", "TODAY",
"TODDLER", "TOE", "TOGETHER", "TOILET", "TOKEN", "TOMATO", "TOMORROW", "TONE", "TONGUE",
"TONIGHT", "TOOL", "TOOTH", "TOP", "TOPIC", "TOPPLE", "TORCH", "TORNADO", "TORTOISE", "TOSS",
"TOTAL", "TOURIST", "TOWARD", "TOWER", "TOWN", "TOY", "TRACK", "TRADE", "TRAFFIC", "TRAGIC",
"TRAIN", "TRANSFER", "TRAP", "TRASH", "TRAVEL", "TRAY", "TREAT", "TREE", "TREND", "TRIAL",
"TRIBE", "TRICK", "TRIGGER", "TRIM", "TRIP", "TROPHY", "TROUBLE", "TRUCK", "TRUE", "TRULY",
"TRUMPET", "TRUST", "TRUTH", "TRY", "TUBE", "TUITION", "TUMBLE", "TUNA", "TUNNEL", "TURKEY",
"TURN", "TURTLE", "TWELVE", "TWENTY", "TWICE", "TWIN", "TWIST", "TWO", "TYPE", "TYPICAL",
"UGLY", "UMBRELLA", "UNABLE", "UNAWARE", "UNCLE", "UNCOVER", "UNDER", "UNDO", "UNFAIR",
"UNFOLD", "UNHAPPY", "UNIFORM", "UNIQUE", "UNIT", "UNIVERSE", "UNKNOWN", "UNLOCK", "UNTIL",
"UNUSUAL", "UNVEIL", "UPDATE", "UPGRADE", "UPHOLD", "UPON", "UPPER", "UPSET", "URBAN", "URGE",
"USAGE", "USE", "USED", "USEFUL", "USELESS", "USUAL", "UTILITY", "VACANT", "VACUUM", "VAGUE",
"VALID", "VALLEY", "VALVE", "VAN", "VANISH", "VAPOR", "VARIOUS", "VAST", "VAULT", "VEHICLE",
"VELVET", "VENDOR", "VENTURE", "VENUE", "VERB", "VERIFY", "VERSION", "VERY", "VESSEL",
"VETERAN", "VIABLE", "VIBRANT", "VICIOUS", "VICTORY", "VIDEO", "VIEW", "VILLAGE", "VINTAGE",
"VIOLIN", "VIRTUAL", "VIRUS", "VISA", "VISIT", "VISUAL", "VITAL", "VIVID", "VOCAL", "VOICE",
"VOID", "VOLCANO", "VOLUME", "VOTE", "VOYAGE", "WAGE", "WAGON", "WAIT", "WALK", "WALL",
"WALNUT", "WANT", "WARFARE", "WARM", "WARRIOR", "WASH", "WASP", "WASTE", "WATER", "WAVE",
"WAY", "WEALTH", "WEAPON", "WEAR", "WEASEL", "WEATHER", "WEB", "WEDDING", "WEEKEND", "WEIRD",
"WELCOME", "WEST", "WET", "WHALE", "WHAT", "WHEAT", "WHEEL", "WHEN", "WHERE", "WHIP",
"WHISPER", "WIDE", "WIDTH", "WIFE", "WILD", "WILL", "WIN", "WINDOW", "WINE", "WING", "WINK",
"WINNER", "WINTER", "WIRE", "WISDOM", "WISE", "WISH", "WITNESS", "WOLF", "WOMAN", "WONDER",
"WOOD", "WOOL", "WORD", "WORK", "WORLD", "WORRY", "WORTH", "WRAP", "WRECK", "WRESTLE", "WRIST",
"WRITE", "WRONG", "YARD", "YEAR", "YELLOW", "YOU", "YOUNG", "YOUTH", "ZEBRA", "ZERO", "ZONE",
"ZOO",
];
#[cfg(all(test, feature = "std"))]
mod tests {
use super::*;
use secp256kfun::hex;
use sha2::{digest::Digest, Sha256};
use std::string::String;
use std::vec::Vec;
#[test]
fn find_max_prefix_matches() {
let mut curr_count = 0;
let mut curr_prefix = "";
let mut max = 0;
let mut max_is_a_word = 0;
// Count occurrences of each 3-letter prefix
for word in &BIP39_WORDS {
let prefix = &word[..3];
if prefix != curr_prefix {
if curr_count > max {
max = curr_count;
}
if is_valid_bip39_word(curr_prefix) && curr_count > max_is_a_word {
max_is_a_word = curr_count;
}
curr_prefix = prefix;
curr_count = 0;
}
curr_count += 1;
}
assert_eq!(max, 13, "most popular 3 letter prefix");
assert_eq!(
max_is_a_word, 8,
"most popular 3 letter prefix where it's a word"
);
}
#[test]
fn test_bip39_wordlist_hash() {
// The official BIP39 English wordlist from:
// https://github.com/bitcoin/bips/blob/master/bip-0039/english.txt
// has this SHA256 hash when words are lowercase and joined with newlines
const EXPECTED_HASH: &str =
"2f5eed53a4727b4bf8880d8f3f199efc90e58503646d9ff8eff3a2ed3b24dbda";
// Convert our uppercase words to lowercase and join with newlines
let wordlist_string: String = BIP39_WORDS
.iter()
.map(|word| word.to_lowercase())
.collect::<Vec<_>>()
.join("\n");
// Calculate SHA256 hash
let mut hasher = Sha256::new();
hasher.update(wordlist_string.as_bytes());
hasher.update(b"\n");
let result = hasher.finalize();
let hash_hex = hex::encode(&result);
assert_eq!(
hash_hex, EXPECTED_HASH,
"BIP39 wordlist hash mismatch! The wordlist may have been modified."
);
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frost_backup/src/error.rs | frost_backup/src/error.rs | //! Error types for frost_backup
use alloc::string::String;
use core::fmt;
#[derive(Debug, Clone, PartialEq)]
pub enum ShareBackupError {
/// A word at a specific position is not in the BIP39 word list
InvalidBip39Word {
/// The word index (0 = share index, 1-25 = words)
word_index: usize,
/// The invalid word that was provided
word: String,
},
/// The share index cannot be zero
InvalidShareIndex,
/// The share index could not be parsed as a number
ShareIndexParseError,
/// The words checksum verification failed
WordsChecksumFailed,
/// The polynomial checksum verification failed
PolyChecksumFailed,
/// Not enough words were provided (expected 25)
NotEnoughWords,
/// Too many words were provided (expected 25)
TooManyWords,
}
impl fmt::Display for ShareBackupError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ShareBackupError::InvalidBip39Word { word_index, word } => {
write!(
f,
"Word at position {} '{}' is not in BIP39 word list",
word_index, word
)
}
ShareBackupError::InvalidShareIndex => {
write!(f, "Share index cannot be zero")
}
ShareBackupError::ShareIndexParseError => {
write!(f, "Invalid share index format")
}
ShareBackupError::WordsChecksumFailed => {
write!(f, "Words checksum verification failed")
}
ShareBackupError::PolyChecksumFailed => {
write!(f, "Polynomial checksum verification failed")
}
ShareBackupError::NotEnoughWords => {
write!(f, "Not enough words in share")
}
ShareBackupError::TooManyWords => {
write!(f, "Too many words in share")
}
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for ShareBackupError {}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frost_backup/src/recovery.rs | frost_backup/src/recovery.rs | use crate::ShareBackup;
use alloc::collections::{BTreeMap, BTreeSet};
use alloc::vec::Vec;
use schnorr_fun::{
frost::{Fingerprint, SecretShare, ShareImage, ShareIndex, SharedKey},
fun::prelude::*,
};
/// Errors that can occur during secret recovery.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RecoveryError {
/// No shares were provided
NoSharesProvided,
/// The polynomial checksum verification failed
PolynomialChecksumFailed,
/// Failed to extract secret from a share
SecretExtractionFailed,
}
impl core::fmt::Display for RecoveryError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
RecoveryError::NoSharesProvided => write!(f, "No shares provided"),
RecoveryError::PolynomialChecksumFailed => {
write!(f, "Polynomial checksum verification failed")
}
RecoveryError::SecretExtractionFailed => {
write!(f, "Failed to extract secret from share")
}
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for RecoveryError {}
/// The result of recovering a secret from shares.
#[derive(Debug, Clone)]
pub struct RecoveredSecret {
/// The recovered secret scalar
pub secret: Scalar<Secret, Zero>,
/// The shares that were compatible with the recovered shared_key
pub compatible_shares: Vec<ShareBackup>,
/// The shared key reconstructed from the shares
pub shared_key: SharedKey<Normal, Zero>,
}
/// Recovers the original secret from a threshold number of shares.
///
/// The shares must have been generated with the same fingerprint. Note that all
/// shares must be compatible with each other for this to succeed (or you put in
/// a NONE fingerprint).
pub fn recover_secret(
shares: &[ShareBackup],
fingerprint: Fingerprint,
) -> Result<RecoveredSecret, RecoveryError> {
if shares.is_empty() {
return Err(RecoveryError::NoSharesProvided);
}
// Reconstruct the SharedKey from share images
let share_images: Vec<_> = shares.iter().map(|backup| backup.share_image()).collect();
let shared_key = SharedKey::from_share_images(share_images);
// Verify the fingerprint matches
if shared_key
.check_fingerprint::<sha2::Sha256>(fingerprint)
.is_none()
{
return Err(RecoveryError::PolynomialChecksumFailed);
}
// Extract and verify the secret shares against the reconstructed key
let mut secret_shares = Vec::with_capacity(shares.len());
for share in shares {
let secret_share = share
.clone()
.extract_secret(&shared_key)
.map_err(|_| RecoveryError::SecretExtractionFailed)?;
secret_shares.push(secret_share);
}
// Reconstruct the secret
let reconstructed = SecretShare::recover_secret(&secret_shares);
Ok(RecoveredSecret {
secret: reconstructed,
compatible_shares: shares.to_vec(),
shared_key,
})
}
/// Recovers the secret from a collection of shares by automatically discovering compatible subsets.
///
/// This function searches through the provided shares to find a valid subset that can reconstruct
/// a SharedKey matching the given fingerprint. It's useful when you have a collection of shares
/// that may include duplicates, shares from different DKG sessions, or corrupted shares.
///
/// # Arguments
/// * `shares` - A slice of ShareBackup instances to search through
/// * `fingerprint` - The fingerprint that was used when generating the shares
///
/// # Returns
/// * `Some(RecoveredSecret)` - The recovered secret, shares used, and shared key
/// * `None` - If no valid subset is found
///
/// # Example
/// ```no_run
/// # use frost_backup::{ShareBackup, recovery::recover_secret_fuzzy, Fingerprint};
/// # let mixed_shares: Vec<ShareBackup> = vec![];
/// if let Some(recovered) = recover_secret_fuzzy(&mixed_shares, Fingerprint::default(), None) {
/// println!("Recovered secret using {} shares", recovered.compatible_shares.len());
/// }
/// ```
pub fn recover_secret_fuzzy(
shares: &[ShareBackup],
fingerprint: Fingerprint,
known_threshold: Option<usize>,
) -> Option<RecoveredSecret> {
// Get share images from all shares
let share_images: Vec<ShareImage> = shares.iter().map(|s| s.share_image()).collect();
// Try to find a valid subset of shares
let (compatible_images, shared_key) =
find_valid_subset(&share_images, fingerprint, known_threshold)?;
// Find the ShareBackups that correspond to the compatible images
let mut compatible_shares = Vec::new();
for image in &compatible_images {
// Find the first share that has this image
if let Some(share) = shares.iter().find(|s| &s.share_image() == image) {
compatible_shares.push(share.clone());
} else {
// This shouldn't happen since we got the images from the shares
return None;
}
}
// Extract secret shares
let mut secret_shares = Vec::with_capacity(compatible_shares.len());
for share in &compatible_shares {
let secret_share = share.clone().extract_secret(&shared_key).ok()?;
secret_shares.push(secret_share);
}
// Reconstruct the secret
let reconstructed = SecretShare::recover_secret(&secret_shares);
Some(RecoveredSecret {
secret: reconstructed,
compatible_shares,
shared_key,
})
}
/// Finds a valid subset of ShareImages that can reconstruct a SharedKey matching the given fingerprint.
///
/// This function tries different combinations of shares to find a valid subset, starting with all shares
/// and progressively trying smaller subsets. It handles duplicate shares at the same index by trying all
/// alternatives when that index is included.
///
/// Note this finds shares that are compatible with each other -- it doesn't
/// find shares that on their own were single share wallets.
///
/// # Arguments
/// * `images` - A slice of ShareImages to search through
/// * `fingerprint` - The fingerprint that the reconstructed SharedKey must match
///
/// # Returns
/// * `Some((share_subset, shared_key))` - A valid subset of shares and the reconstructed SharedKey
/// * `None` - If no valid subset is found
pub fn find_valid_subset(
images: &[ShareImage],
fingerprint: Fingerprint,
known_threshold: Option<usize>,
) -> Option<(BTreeSet<ShareImage>, SharedKey<Normal, Zero>)> {
// We need at least 2 images for the fingerprint to actually filter anything
// -- unless we know explicitly that it's the trivial 1-of-n case then we
// can just go ahead and choose one.
let min_shares_needed = known_threshold.unwrap_or(2);
if images.len() < min_shares_needed {
return None;
}
// Group shares by index to handle duplicates
let mut shares_by_index: BTreeMap<ShareIndex, Vec<ShareImage>> = BTreeMap::new();
for image in images {
shares_by_index
.entry(image.index)
.or_insert_with(Vec::new)
.push(*image);
}
// Get unique indices
let indices: Vec<ShareIndex> = shares_by_index.keys().copied().collect();
let n_indices = indices.len();
let sizes: Vec<_> = match known_threshold {
Some(known_threshold) => vec![known_threshold],
None => (2..=n_indices).collect(),
};
let mut best_match: Option<(SharedKey<Normal, Zero>, usize)> = None;
// Try subsets from largest to smallest (but at least 2 shares)
'outer: for subset_size in sizes {
// Generate all combinations of indices of the given size
for index_combo in generate_combinations(&indices, subset_size) {
// For this combination of indices, try all possible share selections
for share_combo in generate_share_combinations(&index_combo, &shares_by_index) {
// Try to reconstruct SharedKey from this combination
let shared_key = SharedKey::from_share_images(share_combo.clone());
// If threshold was specified, enforce strict matching. You
// might think that since we're only generating combinations of
// the right size that nothing can go wrong -- but it is
// possible to get a threshold 2 poly from a 3 shares if they
// lie on the right polynomial.
if let Some(expected_threshold) = known_threshold {
if shared_key.point_polynomial().len() != expected_threshold {
continue;
}
}
// Check how many fingerprint bits matched
if let Some(bits_matched) =
shared_key.check_fingerprint::<sha2::Sha256>(fingerprint)
{
// Only update if this is better than our current best
let is_better = match &best_match {
None => true,
Some((_, prev_bits)) => bits_matched > *prev_bits,
};
if is_better {
best_match = Some((shared_key, bits_matched));
// Early exit if we found a complete match
if bits_matched >= fingerprint.max_bits_total as usize {
break 'outer;
}
}
}
}
}
}
let shared_key = best_match.map(|(key, _)| key)?;
let compatible = images
.iter()
.cloned()
.filter(|image| shared_key.share_image(image.index) == *image)
.collect();
Some((compatible, shared_key))
}
/// Generate all combinations of k elements from a slice
fn generate_combinations<T: Clone>(elements: &[T], k: usize) -> impl Iterator<Item = Vec<T>> + '_ {
let n = elements.len();
// Use a vector to track which elements are included in the current combination
let mut indices = (0..k).collect::<Vec<usize>>();
let mut first = true;
core::iter::from_fn(move || {
if k > n || k == 0 {
return None;
}
if first {
first = false;
let combination: Vec<T> = indices.iter().map(|&i| elements[i].clone()).collect();
return Some(combination);
}
// Find the rightmost index that can be incremented
let mut i = k;
for j in (0..k).rev() {
if indices[j] != j + n - k {
i = j;
break;
}
}
// If no index can be incremented, we're done
if i == k {
return None;
}
// Increment the found index and reset all indices to its right
indices[i] += 1;
for j in (i + 1)..k {
indices[j] = indices[j - 1] + 1;
}
let combination: Vec<T> = indices.iter().map(|&i| elements[i].clone()).collect();
Some(combination)
})
}
/// Generate all possible share combinations for a given set of indices,
/// handling multiple shares at the same index
fn generate_share_combinations<'a>(
indices: &'a [ShareIndex],
shares_by_index: &'a BTreeMap<ShareIndex, Vec<ShareImage>>,
) -> impl Iterator<Item = Vec<ShareImage>> + 'a {
// Get the shares at each index (we know all indices exist in the map)
let shares_per_index: Vec<&Vec<ShareImage>> = indices
.iter()
.map(|index| {
shares_by_index
.get(index)
.expect("index should exist in map")
})
.collect();
let n = indices.len();
// Initialize indices for each position (all start at 0)
let mut current_indices = vec![0; n];
let mut first = true;
core::iter::from_fn(move || {
if n == 0 {
return None;
}
if first {
first = false;
// Build first combination
let combination: Vec<ShareImage> = current_indices
.iter()
.enumerate()
.map(|(i, &idx)| shares_per_index[i][idx])
.collect();
return Some(combination);
}
// Increment indices (like counting in mixed base)
let mut position = n - 1;
loop {
current_indices[position] += 1;
if current_indices[position] < shares_per_index[position].len() {
// Successfully incremented, build next combination
let combination: Vec<ShareImage> = current_indices
.iter()
.enumerate()
.map(|(i, &idx)| shares_per_index[i][idx])
.collect();
return Some(combination);
}
// Need to carry over
current_indices[position] = 0;
if position == 0 {
// We've generated all combinations
return None;
}
position -= 1;
}
})
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frost_backup/src/bin/frost_backup.rs | frost_backup/src/bin/frost_backup.rs | use clap::{Parser, Subcommand};
use core::convert::TryInto;
use frost_backup::*;
use schnorr_fun::fun::prelude::*;
use std::fs;
use std::str::FromStr;
fn print_derivation_path_explanation() {
eprintln!("🗺️ Derivation path explanation:");
eprintln!(" The descriptor uses the path: /0/0/0/0/<0;1>/*");
eprintln!(" │ │ │ │ │ └─ Address index (wildcard)");
eprintln!(" │ │ │ │ └─ Keychain (0=external, 1=internal)");
eprintln!(" │ │ │ └─ Account index (0=first account)");
eprintln!(" │ │ └─ Account type (0=segwit v1/taproot)");
eprintln!(" │ └─ App type (0=Bitcoin)");
eprintln!(" └─ Root to master (Frostsnap convention)");
}
#[derive(Parser)]
#[command(name = "frost_backup")]
#[command(about = "BIP39-based backup scheme for Shamir secret shares")]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
Generate {
#[arg(help = "Threshold of shares needed to reconstruct")]
threshold: usize,
#[arg(help = "Total number of shares to generate")]
number_of_shares: usize,
#[arg(help = "Secret as 32 bytes hex (optional - will generate random if not provided)")]
secret: Option<Scalar>,
#[arg(
short = 'o',
long = "output",
help = "Output file for all shares (use '-' for stdout, omit to print all shares to stdout)"
)]
output: Option<String>,
#[arg(
short = 'y',
long = "yes",
help = "Skip confirmation prompt (not recommended for production use)"
)]
yes: bool,
},
Reconstruct {
#[arg(
help = "Share files to reconstruct from (use '-' for stdin with EOF (Ctrl+D) to finish)",
required = true,
num_args = 1..
)]
files: Vec<String>,
#[arg(
short = 't',
long = "threshold",
help = "Threshold of shares needed to reconstruct (optional - will try to discover if not provided)"
)]
threshold: Option<usize>,
#[arg(
help = "Network for the descriptor output",
default_value = "main",
short,
long,
value_parser = ["main", "test"]
)]
network: String,
#[arg(
long = "no-check-fingerprint",
help = "Skip fingerprint checking (uses 0-bit fingerprint). Requires --threshold to be specified"
)]
no_check_fingerprint: bool,
},
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let cli = Cli::parse();
match cli.command {
Commands::Generate {
threshold,
number_of_shares,
secret,
output,
yes,
} => {
if !yes {
eprintln!("⚠️ WARNING: Local Key Generation Not Recommended");
eprintln!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
eprintln!("📱 This command is intended primarily for testing and");
eprintln!(" advanced users who understand the security implications.");
eprintln!();
eprintln!("🔒 Real keys used to protect funds should be generated using");
eprintln!(" Frostsnap devices through a truly 'Distributed'-DKG process.");
eprintln!();
eprint!("Continue with local key generation? [y/N]: ");
use std::io::{self, Write};
io::stdout().flush()?;
let mut input = String::new();
io::stdin().read_line(&mut input)?;
match input.trim().to_lowercase().as_str() {
"y" | "yes" => {
eprintln!("Proceeding with local generation...");
}
_ => {
eprintln!("Aborted. Use Frostsnap devices for secure key generation.");
return Ok(());
}
}
}
// Validate parameters
if threshold > number_of_shares {
return Err("Threshold cannot be greater than number of shares".into());
}
if threshold == 0 {
return Err("Threshold must be at least 1".into());
}
// Use provided secret or generate a random one
let mut rng = rand::thread_rng();
let secret_scalar = match secret {
Some(s) => s,
None => Scalar::random(&mut rng),
};
// Generate shares with randomness
let (shares, shared_key) = ShareBackup::generate_shares(
secret_scalar,
threshold,
number_of_shares,
frost_backup::FINGERPRINT,
&mut rng,
);
// Print metadata to stderr so stdout can be used for shares
if secret.is_none() {
eprintln!("🎲 Generated random secret:");
eprintln!(" {}", secret_scalar);
}
eprintln!("🔑 Root Public key: {}", shared_key.public_key());
// Generate taproot descriptor
let descriptor = generate_descriptor(&secret_scalar, bitcoin::NetworkKind::Main);
eprintln!("📜 Bitcoin descriptor:");
eprintln!(" {}", descriptor);
// Print derivation path explanation
print_derivation_path_explanation();
// Always show critical backup instructions
eprintln!();
eprintln!("⚠️ ⚠️ ⚠️ CRITICAL BACKUP INSTRUCTIONS ⚠️ ⚠️ ⚠️");
eprintln!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
eprintln!("🔥 WRITE EACH SHARE DOWN IN A SEPARATE, SECURE PLACE");
eprintln!("📍 INCLUDE THE SHARE NUMBER (e.g., #1, #2, #3)");
eprintln!(
"🔐 ANY {} OUT OF {} SHARES WILL RESTORE YOUR WALLET",
threshold, number_of_shares
);
eprintln!(
"💀 LOSING MORE THAN {} SHARES MEANS LOSING YOUR FUNDS FOREVER",
number_of_shares - threshold
);
eprintln!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
match output {
Some(out) if out == "-" => {
// Output all shares to stdout
for share in &shares {
println!("{}", share);
}
}
Some(out) => {
// Check if file already exists
if std::path::Path::new(&out).exists() {
return Err(format!(
"File '{}' already exists. Please use a different filename or remove the existing file.",
out
).into());
}
// Output all shares to file
let mut content = String::new();
for share in &shares {
content.push_str(&share.to_string());
content.push('\n');
}
fs::write(&out, content)?;
eprintln!();
eprintln!("💾 Saved all {} shares to {}", number_of_shares, out);
}
None => {
// Output all shares to stdout with formatting
for (i, share) in shares.iter().enumerate() {
eprintln!("════════════════════════════════════════════════");
eprintln!("SHARE #{} - STORE THIS SEPARATELY:", i + 1);
eprintln!("════════════════════════════════════════════════");
println!("{}", share);
eprintln!();
}
}
}
eprintln!();
eprintln!(
"✅ Successfully generated {} shares with threshold {}",
number_of_shares, threshold
);
eprintln!("🚨 REMINDER: Store each share in a different physical location!");
eprintln!(" Examples: safety deposit boxes, trusted family members, secure safes");
}
Commands::Reconstruct {
files,
threshold,
network,
no_check_fingerprint,
} => {
// Validate that threshold is provided when using --no-check-fingerprint
if no_check_fingerprint && threshold.is_none() {
return Err("Threshold must be specified when using --no-check-fingerprint".into());
}
let mut shares = Vec::new();
// Read shares from specified files
for file in files {
if file == "-" {
// Read multiple shares from stdin, one per line
use std::io::{self, BufRead, BufReader};
let stdin = io::stdin();
let reader = BufReader::new(stdin);
for line in reader.lines() {
let line = line?;
let line = line.trim();
// Skip empty lines
if line.is_empty() {
continue;
}
match ShareBackup::from_str(line) {
Ok(share) => {
let index_u32: u32 = share.index().try_into().unwrap();
eprintln!("📥 Loaded share #{} from stdin", index_u32);
shares.push(share);
}
Err(e) => {
return Err(
format!("Failed to parse share from stdin: {}", e).into()
);
}
}
}
} else {
// Read from file
let content = fs::read_to_string(&file)?;
match ShareBackup::from_str(content.trim()) {
Ok(share) => {
let index_u32: u32 = share.index().try_into().unwrap();
eprintln!("📁 Loaded share #{} from {}", index_u32, file);
shares.push(share);
}
Err(e) => {
return Err(
format!("Failed to parse share from {}: {}", file, e).into()
);
}
}
}
}
// Reconstruct the secret
let fingerprint = if no_check_fingerprint {
eprintln!();
eprintln!("⚠️ Warning: Skipping fingerprint check - accepting any valid {}-of-{} polynomial",
threshold.unwrap(), shares.len());
// Use 0-bit fingerprint (no checking)
schnorr_fun::frost::Fingerprint::NONE
} else {
frost_backup::FINGERPRINT
};
let recovered = recovery::recover_secret_fuzzy(&shares, fingerprint, threshold)
.ok_or("❌ Failed to find a valid subset of shares")?;
eprintln!();
eprintln!("🔓 Reconstructed secret:");
eprintln!(" {}", recovered.secret);
eprintln!("🔑 Public key: {}", recovered.shared_key.public_key());
// Show which share indices were used
let used_indices: Vec<String> = recovered
.compatible_shares
.iter()
.map(|idx| format!("#{}", idx))
.collect();
eprintln!("📊 Compatible shares found: {}", used_indices.join(", "));
// Check if the secret is zero (extremely unlikely but theoretically possible)
match recovered.secret.non_zero() {
Some(non_zero_secret) => {
// Generate taproot descriptor
let net = match network.as_str() {
"test" => bitcoin::NetworkKind::Test,
_ => bitcoin::NetworkKind::Main,
};
let descriptor = frost_backup::generate_descriptor(&non_zero_secret, net);
// Print the descriptor to stdout for piping
println!("{}", descriptor);
eprintln!("📜 Bitcoin descriptor:");
eprintln!(" {}", descriptor);
// Print derivation path explanation
print_derivation_path_explanation();
}
None => {
eprintln!();
eprintln!(
"⚠️ The recovered secret is zero - no valid descriptor can be generated."
);
return Ok(());
}
}
}
}
Ok(())
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frost_backup/tests/checksum_statistics.rs | frost_backup/tests/checksum_statistics.rs | use core::convert::TryInto;
use frost_backup::*;
use rand::Rng;
use secp256kfun::{
proptest::test_runner::{RngAlgorithm, TestRng},
s,
};
#[test]
fn test_checksum_false_positive_rate() {
// The words checksum uses WORDS_CHECKSUM_BITS bits
// So we expect about 1/(2^WORDS_CHECKSUM_BITS) false positives
let expected_false_positive_rate = 1.0 / (1 << share_backup::WORDS_CHECKSUM_BITS) as f64;
println!("Using {} checksum bits", share_backup::WORDS_CHECKSUM_BITS);
println!(
"Expected false positive rate: 1/{} ≈ {:.6}",
1 << share_backup::WORDS_CHECKSUM_BITS,
expected_false_positive_rate
);
let mut rng = TestRng::deterministic_rng(RngAlgorithm::ChaCha);
let secret = s!(42);
// Generate a valid share to corrupt (use small fingerprint for faster tests)
let fingerprint = schnorr_fun::frost::Fingerprint {
bits_per_coeff: 7,
max_bits_total: 14,
tag: "test",
};
let (shares, _) = ShareBackup::generate_shares(secret, 2, 3, fingerprint, &mut rng);
let share = &shares[0];
let mut false_positives = 0;
let mut total_corruptions = 0;
// Test corrupting each word position
for word_index in 0..25 {
let original_words = share.to_words();
// Try many different word substitutions
// BIP39 has 2048 words, so we'll try a good sample
for _corruption_attempt in 0..500 {
let mut corrupted_words = original_words;
// Pick a random different word
let original_word = original_words[word_index];
// Keep trying until we get a different word
let new_word = loop {
let new_word_index = rng.gen_range(0..2048);
let candidate = frost_backup::bip39_words::BIP39_WORDS[new_word_index];
if candidate != original_word {
break candidate;
}
};
corrupted_words[word_index] = new_word;
total_corruptions += 1;
// Check if the corrupted share passes validation
let index_u32: u32 = share.index().try_into().unwrap();
if ShareBackup::from_words(index_u32, corrupted_words).is_ok() {
false_positives += 1;
}
}
}
// Calculate the observed false positive rate
let observed_rate = false_positives as f64 / total_corruptions as f64;
let expected_rate = expected_false_positive_rate;
println!("Total corruptions tested: {}", total_corruptions);
println!("False positives: {}", false_positives);
println!("Observed false positive rate: {:.6}", observed_rate);
println!("Expected false positive rate: {:.6}", expected_rate);
// Allow some statistical variance - we expect the rate to be within reasonable bounds
// Using binomial distribution, the standard deviation is sqrt(n*p*(1-p))
// For ~12500 trials with p=1/2048, std dev ≈ 2.5, so 3 sigma ≈ 7.5
// This gives us a range of about (false_positives ± 7.5) / total_corruptions
let lower_bound = expected_rate * 0.5; // Very generous bounds to avoid flaky tests
let upper_bound = expected_rate * 2.0;
assert!(
observed_rate >= lower_bound && observed_rate <= upper_bound,
"False positive rate {:.6} is outside expected range [{:.6}, {:.6}]",
observed_rate,
lower_bound,
upper_bound
);
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frost_backup/tests/recovery_tests.rs | frost_backup/tests/recovery_tests.rs | mod common;
use frost_backup::{recovery, ShareBackup};
use rand::{rngs::StdRng, SeedableRng};
use schnorr_fun::frost::{ShareImage, SharedKey};
use secp256kfun::prelude::*;
const TEST_FINGERPRINT: schnorr_fun::frost::Fingerprint = schnorr_fun::frost::Fingerprint {
bits_per_coeff: 10,
max_bits_total: 20,
tag: "test",
};
#[test]
fn test_recover_secret() {
// Generate a test secret
let secret = s!(42);
// 🎲 deterministic for testing since some checksums only work probabilistically
let mut rng = StdRng::seed_from_u64(42);
let (shares, _) = ShareBackup::generate_shares(secret, 2, 3, TEST_FINGERPRINT, &mut rng);
// Test recovery with exact threshold
let recovered =
recovery::recover_secret(&shares[0..2], TEST_FINGERPRINT).expect("Recovery should succeed");
assert_eq!(recovered.secret.public(), secret.public());
// Test recovery with more than threshold
let recovered =
recovery::recover_secret(&shares, TEST_FINGERPRINT).expect("Recovery should succeed");
assert_eq!(recovered.secret.public(), secret.public());
// Test with wrong fingerprint (should fail)
let wrong_fingerprint = schnorr_fun::frost::Fingerprint {
bits_per_coeff: 10,
max_bits_total: 20,
tag: "wrong",
};
assert!(recovery::recover_secret(&shares[0..2], wrong_fingerprint).is_err());
// Test with single share (should fail)
assert!(recovery::recover_secret(&shares[0..1], TEST_FINGERPRINT).is_err());
// Test with no shares
assert!(recovery::recover_secret(&[], TEST_FINGERPRINT).is_err());
}
#[test]
fn test_find_valid_subset() {
// Tests the basic functionality of find_valid_subset:
// - Can find valid subsets when given all shares
// - Can find valid subsets with exactly threshold shares
// - Correctly rejects shares with wrong fingerprint
// - Correctly handles edge cases (single share, empty slice)
// Generate a test secret
let secret = s!(42);
// Generate shares (threshold=2, n=4)
let mut rng = rand::thread_rng();
let (shares, shared_key) =
ShareBackup::generate_shares(secret, 2, 4, TEST_FINGERPRINT, &mut rng);
// Get share images
let images: Vec<ShareImage> = shares.iter().map(|s| s.share_image()).collect();
// Test with all shares
let result = recovery::find_valid_subset(&images, TEST_FINGERPRINT, None);
assert!(result.is_some());
let (found_shares, found_key) = result.unwrap();
assert!(found_shares.len() >= 2);
assert_eq!(found_key.public_key(), shared_key.public_key());
// Test with minimum threshold shares
let result = recovery::find_valid_subset(&images[0..2], TEST_FINGERPRINT, None);
assert!(result.is_some());
// Test with wrong fingerprint
let wrong_fingerprint = schnorr_fun::frost::Fingerprint {
bits_per_coeff: 10,
max_bits_total: 20,
tag: "wrong",
};
let result = recovery::find_valid_subset(&images, wrong_fingerprint, None);
assert!(result.is_none());
// Test with single share (should fail)
let result = recovery::find_valid_subset(&images[0..1], TEST_FINGERPRINT, None);
assert!(result.is_none());
// Test with empty slice
let result = recovery::find_valid_subset(&[], TEST_FINGERPRINT, None);
assert!(result.is_none());
}
#[test]
fn test_find_valid_subset_with_conflicting_indices() {
// Tests that find_valid_subset can handle shares from two different sharings
// of the SAME secret. Even though both sharings are valid, shares from different
// sharings shouldn't be mixed together.
//
// This simulates a scenario where someone might generate shares multiple times for
// the same secret (e.g., to change the threshold or number of shares) and accidentally
// mix shares from the old and new sharings.
// Use the same secret for both sharings
let secret = s!(42);
// Generate first set of shares (threshold=3, n=5)
let mut rng = rand::thread_rng();
let (shares1, _shared_key1) =
ShareBackup::generate_shares(secret, 3, 5, TEST_FINGERPRINT, &mut rng);
// Generate second set of shares from the SAME secret (but different polynomial)
let (shares2, _shared_key2) =
ShareBackup::generate_shares(secret, 3, 5, TEST_FINGERPRINT, &mut rng);
// Create share images from the first sharing
let mut images: Vec<ShareImage> = shares1.iter().map(|s| s.share_image()).collect();
// Add a share from the second sharing at index 2 (same as shares1[1])
// This creates a conflict: two different shares both claiming to be at index 2
// Even though both are valid shares of the same secret, they're from different polynomials
images.push(shares2[1].share_image());
// Test discovery - should find valid subset from one of the sharings
let result = recovery::find_valid_subset(&images, TEST_FINGERPRINT, None);
assert!(result.is_some());
let (found_shares, found_key) = result.unwrap();
// Should have at least threshold shares
assert!(found_shares.len() >= 3);
// The found key should match the same secret (both sharings have the same secret)
assert_eq!(found_key.public_key(), g!(secret * G).normalize());
// Verify that the found shares can successfully recover the secret
// This implicitly verifies they're all from the same sharing (not mixed)
// because mixed shares wouldn't be able to recover the secret
// Count how many shares came from each sharing
let from_shares1 = found_shares
.iter()
.filter(|img| shares1.iter().any(|s| s.share_image() == **img))
.count();
let from_shares2 = found_shares
.iter()
.filter(|img| shares2.iter().any(|s| s.share_image() == **img))
.count();
// All shares should come from one sharing or the other, not mixed
assert!(
from_shares1 == 0 || from_shares2 == 0,
"Found shares should all be from the same sharing, but got {} from first and {} from second",
from_shares1, from_shares2
);
}
#[test]
fn test_find_valid_subset_mixed_different_secrets() {
// Tests that find_valid_subset can handle shares from different secrets
// mixed together. The algorithm should reject invalid combinations and find only
// the shares that belong to the same secret sharing.
//
// This simulates a scenario where someone might accidentally mix shares from
// completely different secrets (e.g., mixing up shares from different wallets).
// Test case where we have shares from different secrets mixed together
let secret1 = s!(42);
let secret2 = s!(123);
let mut rng = rand::thread_rng();
let (shares1, _) = ShareBackup::generate_shares(secret1, 2, 3, TEST_FINGERPRINT, &mut rng);
let (shares2, _) = ShareBackup::generate_shares(secret2, 2, 3, TEST_FINGERPRINT, &mut rng);
// Mix shares from both sharings
let mixed_images = vec![
shares1[0].share_image(),
shares1[1].share_image(),
shares2[0].share_image(),
shares2[1].share_image(),
];
// Should find a valid subset (from one of the sharings)
let result = recovery::find_valid_subset(&mixed_images, TEST_FINGERPRINT, None);
assert!(result.is_some());
let (found_shares, found_key) = result.unwrap();
assert!(found_shares.len() >= 2);
// The found key should correspond to either secret1 or secret2
let secret1_key = g!(secret1 * G).normalize();
let secret2_key = g!(secret2 * G).normalize();
assert!(
found_key.public_key() == secret1_key || found_key.public_key() == secret2_key,
"Found key should match one of the original secrets"
);
}
#[test]
fn test_recover_secret_fuzzy() {
// Tests that recover_secret_fuzzy can automatically find valid shares from a mixed collection
// Generate shares from two different secrets
let secret1 = s!(1337);
let secret2 = s!(9999);
let mut rng = rand::thread_rng();
let (shares1, _) = ShareBackup::generate_shares(secret1, 2, 3, TEST_FINGERPRINT, &mut rng);
let (shares2, _) = ShareBackup::generate_shares(secret2, 2, 3, TEST_FINGERPRINT, &mut rng);
// Mix shares from both sharings
let mut mixed_shares = vec![
shares1[0].clone(),
shares1[1].clone(),
shares2[0].clone(),
shares2[1].clone(),
];
// Add some duplicates
mixed_shares.push(shares1[0].clone());
mixed_shares.push(shares2[1].clone());
// Try fuzzy recovery - should find one valid set
let result = recovery::recover_secret_fuzzy(&mixed_shares, TEST_FINGERPRINT, None);
assert!(result.is_some());
let recovered = result.unwrap();
assert_eq!(recovered.compatible_shares.len(), 2); // Should use exactly threshold shares
// The recovered secret should match one of the originals
assert!(
recovered.secret == secret1 || recovered.secret == secret2,
"Recovered secret should match one of the original secrets"
);
// Verify the shared key matches the shares used
let share_images: Vec<_> = recovered
.compatible_shares
.iter()
.map(|s| s.share_image())
.collect();
let reconstructed_key = SharedKey::from_share_images(share_images);
assert_eq!(
reconstructed_key.public_key(),
recovered.shared_key.public_key()
);
}
#[test]
fn test_recover_secret_fuzzy_no_valid_shares() {
// Test that recover_secret_fuzzy returns None when no valid subset exists
let secret = s!(42);
let mut rng = rand::thread_rng();
let (shares, _) = ShareBackup::generate_shares(secret, 3, 5, TEST_FINGERPRINT, &mut rng);
// Only provide 2 shares when threshold is 3
let insufficient_shares = vec![shares[0].clone(), shares[1].clone()];
let result = recovery::recover_secret_fuzzy(&insufficient_shares, TEST_FINGERPRINT, None);
assert!(result.is_none());
}
#[test]
fn test_find_valid_subset_threshold_one() {
// Test that 1-of-1 shares work correctly when threshold is known
let secret = s!(42);
let mut rng = rand::thread_rng();
let (shares, shared_key) =
ShareBackup::generate_shares(secret, 1, 3, TEST_FINGERPRINT, &mut rng);
let share_images: Vec<ShareImage> = shares.iter().map(|s| s.share_image()).collect();
let result = recovery::find_valid_subset(&share_images, TEST_FINGERPRINT, Some(1));
assert!(
result.is_some(),
"Should be able to recover with 1-of-1 share when threshold is known"
);
let (found_shares, found_key) = result.unwrap();
assert_eq!(found_shares.len(), 3);
assert_eq!(found_key, shared_key);
}
#[test]
fn test_find_valid_subset_threshold_validation() {
// Test that find_valid_subset strictly validates threshold when specified.
//
// Use TEST_SHARES_2_OF_3 which are from a 2-of-3 wallet (threshold=2, poly length=2)
// but specify known_threshold=3. This should be rejected.
use crate::common::{TEST_SHARES_1_OF_1, TEST_SHARES_2_OF_3, TEST_SHARES_3_OF_5};
// Parse all 3 test shares from 2-of-3 wallet
let shares_2_of_3: Vec<ShareBackup> = TEST_SHARES_2_OF_3
.iter()
.map(|s| s.parse().expect("Should parse test share"))
.collect();
// Extract share images
let share_images_2_of_3: Vec<_> = shares_2_of_3.iter().map(|s| s.share_image()).collect();
// Try to find valid subset with known_threshold=3
// These shares are from a threshold-2 wallet, so this should return None
let result =
recovery::find_valid_subset(&share_images_2_of_3, frost_backup::FINGERPRINT, Some(3));
assert!(
result.is_none(),
"Should reject shares when discovered threshold (2) doesn't match specified threshold (3)"
);
// But it should succeed with the correct threshold
let result =
recovery::find_valid_subset(&share_images_2_of_3, frost_backup::FINGERPRINT, Some(2));
assert!(
result.is_some(),
"Should accept shares when threshold matches"
);
// Now test with threshold-3 shares
let shares_3_of_5: Vec<ShareBackup> = TEST_SHARES_3_OF_5
.iter()
.map(|s| s.parse().expect("Should parse test share"))
.collect();
// Test with only 2 shares from threshold-3 wallet - should fail
let share_images_insufficient: Vec<_> = shares_3_of_5[0..2]
.iter()
.map(|s| s.share_image())
.collect();
let result = recovery::find_valid_subset(
&share_images_insufficient,
frost_backup::FINGERPRINT,
Some(3),
);
assert!(
result.is_none(),
"Should fail with only 2 shares when threshold is 3"
);
// Test with exactly 3 shares from threshold-3 wallet - should succeed
let share_images_exact: Vec<_> = shares_3_of_5[0..3]
.iter()
.map(|s| s.share_image())
.collect();
let result =
recovery::find_valid_subset(&share_images_exact, frost_backup::FINGERPRINT, Some(3));
assert!(
result.is_some(),
"Should succeed with exactly 3 shares when threshold is 3"
);
// Test with all 5 shares from threshold-3 wallet - should succeed
let share_images_all: Vec<_> = shares_3_of_5.iter().map(|s| s.share_image()).collect();
let result = recovery::find_valid_subset(&share_images_all, frost_backup::FINGERPRINT, Some(3));
assert!(
result.is_some(),
"Should succeed with all 5 shares when threshold is 3"
);
// Test adding threshold-1 share to the mix - should still succeed (finds threshold-3 subset)
let share_1_of_1: ShareBackup = TEST_SHARES_1_OF_1[0]
.parse()
.expect("Should parse test share");
let mut share_images_mixed = share_images_all.clone();
share_images_mixed.push(share_1_of_1.share_image());
let result =
recovery::find_valid_subset(&share_images_mixed, frost_backup::FINGERPRINT, Some(3));
assert!(
result.is_some(),
"Should succeed finding threshold-3 subset even with threshold-1 share mixed in"
);
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frost_backup/tests/descriptor_match.rs | frost_backup/tests/descriptor_match.rs | use bitcoin::bip32::DerivationPath;
use bitcoin::secp256k1;
use bitcoin::{Address, Network};
use frost_backup::generate_xpriv;
use frostsnap_coordinator::bitcoin::{descriptor_for_account_keychain, wallet::KeychainId};
use frostsnap_core::{
tweak::{AccountKind, BitcoinAccount, BitcoinAccountKeychain, Keychain},
MasterAppkey,
};
use schnorr_fun::fun::prelude::*;
use std::str::FromStr;
#[test]
fn test_addresses_match() {
// Generate a test secret
let secret = Scalar::random(&mut rand::thread_rng());
let network = bitcoin::NetworkKind::Test;
// Path 1: Generate xpriv using frost_backup
let xpriv = generate_xpriv(&secret, network);
let secp = secp256k1::Secp256k1::new();
// Derive the frost_backup address at the expected path
// The full path is /0/0/0/0/0/0 (6 zeros total)
let path = DerivationPath::from_str("m/0/0/0/0/0/0").unwrap();
let derived = xpriv.derive_priv(&secp, &path).unwrap();
let pubkey = derived.to_keypair(&secp).x_only_public_key().0;
let frost_backup_address = Address::p2tr(&secp, pubkey, None, Network::Testnet);
// Path 2: Generate descriptor using frostsnap_core
// Convert secret to Point
let root_key: Point = g!(secret * G).normalize();
// Derive master appkey from rootkey
let master_appkey = MasterAppkey::derive_from_rootkey(root_key);
// Create a bitcoin account (0 hardened)
let account = BitcoinAccount {
kind: AccountKind::Segwitv1,
index: 0,
};
// Create keychain id for external chain (0)
let keychain_id: KeychainId = (
master_appkey,
BitcoinAccountKeychain {
account,
keychain: Keychain::External,
},
);
// Get descriptor from frostsnap_coordinator
let frostsnap_descriptor = descriptor_for_account_keychain(keychain_id, network);
// Get address from frostsnap descriptor
let frostsnap_address = frostsnap_descriptor
.at_derivation_index(0)
.expect("Valid derivation")
.address(Network::Testnet)
.expect("Valid address");
// Compare addresses
assert_eq!(
frost_backup_address, frostsnap_address,
"First address from frost_backup xpriv should match frostsnap_core descriptor"
);
// Also verify addresses at index 1
let path1 = DerivationPath::from_str("m/0/0/0/0/0/1").unwrap();
let derived1 = xpriv.derive_priv(&secp, &path1).unwrap();
let pubkey1 = derived1.to_keypair(&secp).x_only_public_key().0;
let frost_backup_address_1 = Address::p2tr(&secp, pubkey1, None, Network::Testnet);
let frostsnap_address_1 = frostsnap_descriptor
.at_derivation_index(1)
.expect("Valid derivation")
.address(Network::Testnet)
.expect("Valid address");
assert_eq!(
frost_backup_address_1, frostsnap_address_1,
"Second address from frost_backup xpriv should match frostsnap_core descriptor"
);
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frost_backup/tests/specification_tests.rs | frost_backup/tests/specification_tests.rs | use core::{convert::TryInto, str::FromStr};
use frost_backup::*;
use schnorr_fun::frost::SharedKey;
use secp256kfun::{marker::*, Scalar};
mod common;
use common::{INVALID_SHARE_CHECKSUM, TEST_SHARES_1_OF_1, TEST_SHARES_2_OF_3, TEST_SHARES_3_OF_5};
/// Iterator that generates all combinations of k elements from n elements
struct Combinations {
n: usize,
k: usize,
combo: Vec<usize>,
first: bool,
}
impl Combinations {
fn new(n: usize, k: usize) -> Self {
Combinations {
n,
k,
combo: (0..k).collect(),
first: true,
}
}
}
impl Iterator for Combinations {
type Item = Vec<usize>;
fn next(&mut self) -> Option<Self::Item> {
if self.k > self.n {
return None;
}
if self.first {
self.first = false;
return Some(self.combo.clone());
}
// Find the rightmost element that can be incremented
let mut i = self.k;
while i > 0 && (i == self.k || self.combo[i - 1] == self.n - self.k + i - 1) {
i -= 1;
}
if i == 0 {
return None;
}
// Increment and reset following elements
self.combo[i - 1] += 1;
for j in i..self.k {
self.combo[j] = self.combo[j - 1] + 1;
}
Some(self.combo.clone())
}
}
/// Test vectors for a 1-of-1 scheme
#[test]
fn test_specification_1_of_1() {
// Parse the share
let share: ShareBackup = TEST_SHARES_1_OF_1[0].parse().expect("Share should parse");
// Verify index
assert_eq!(TryInto::<u32>::try_into(share.index()).unwrap(), 1);
let expected_secret = Scalar::<Secret, Zero>::from_str(
"0101010101010101010101010101010101010101010101010101010101010101",
)
.unwrap();
// Test recovery with single share
let recovered = recovery::recover_secret(&[share], Fingerprint::default())
.expect("Recovery should succeed");
assert_eq!(
recovered.secret, expected_secret,
"Should recover the correct secret"
);
}
/// Test vectors with hardcoded shares for a 2-of-3 scheme
/// These were generated with a known secret and should always produce the same result
#[test]
fn test_specification_2_of_3() {
// Parse all shares
let shares: Vec<ShareBackup> = TEST_SHARES_2_OF_3
.iter()
.enumerate()
.map(|(i, share_str)| {
share_str
.parse()
.unwrap_or_else(|_| panic!("Share {} should parse", i + 1))
})
.collect();
// Verify indices
for (i, share) in shares.iter().enumerate() {
assert_eq!(
TryInto::<u32>::try_into(share.index()).unwrap(),
(i + 1) as u32
);
}
let expected_secret = Scalar::<Secret, Zero>::from_str(
"0101010101010101010101010101010101010101010101010101010101010101",
)
.unwrap();
// Test all possible combinations of 2 shares from 3
let mut first_polynomial = None;
for combo in Combinations::new(3, 2) {
let images: Vec<_> = combo.iter().map(|&i| shares[i].share_image()).collect();
let shared_key = SharedKey::from_share_images(images);
// Verify all combinations produce the same polynomial
match first_polynomial {
None => first_polynomial = Some(shared_key.point_polynomial().to_vec()),
Some(ref first) => assert_eq!(
first,
&shared_key.point_polynomial().to_vec(),
"All share combinations should produce the same polynomial"
),
}
// Test that this combination recovers the correct secret
let selected_shares: Vec<ShareBackup> = combo.iter().map(|&i| shares[i].clone()).collect();
let recovered = recovery::recover_secret(&selected_shares, Fingerprint::default())
.expect("Recovery should succeed");
assert_eq!(
recovered.secret, expected_secret,
"Combination {:?} should recover the correct secret",
combo
);
}
}
/// Test vectors for a 3-of-5 scheme
#[test]
fn test_specification_3_of_5() {
// Parse all shares
let shares: Vec<ShareBackup> = TEST_SHARES_3_OF_5
.iter()
.enumerate()
.map(|(i, share_str)| {
share_str
.parse()
.unwrap_or_else(|_| panic!("Share {} should parse", i + 1))
})
.collect();
// Verify indices
for (i, share) in shares.iter().enumerate() {
assert_eq!(
TryInto::<u32>::try_into(share.index()).unwrap(),
(i + 1) as u32
);
}
let expected_secret = Scalar::<Secret, Zero>::from_str(
"deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
)
.unwrap();
// Generate all possible combinations of 3 shares from 5
let mut first_polynomial = None;
for combo in Combinations::new(5, 3) {
let images: Vec<_> = combo.iter().map(|&i| shares[i].share_image()).collect();
let shared_key = SharedKey::from_share_images(images);
// Verify all combinations produce the same polynomial
match first_polynomial {
None => first_polynomial = Some(shared_key.point_polynomial().to_vec()),
Some(ref first) => assert_eq!(
first,
&shared_key.point_polynomial().to_vec(),
"All share combinations should produce the same polynomial"
),
}
// Test that this combination recovers the correct secret
let selected_shares: Vec<ShareBackup> = combo.iter().map(|&i| shares[i].clone()).collect();
let recovered = recovery::recover_secret(&selected_shares, Fingerprint::default())
.expect("Recovery should succeed");
assert_eq!(
recovered.secret,
expected_secret,
"Combination {:?} (shares {},{},{}) should recover the correct secret",
combo,
combo[0] + 1,
combo[1] + 1,
combo[2] + 1
);
}
}
/// Test that parsing and Display are inverses
#[test]
fn test_specification_roundtrip() {
// Use a valid share from the test vectors
let test_share = TEST_SHARES_2_OF_3[0];
let share: ShareBackup = test_share.parse().expect("Should parse");
let formatted = share.to_string();
// The formatted string should parse back to the same share
let reparsed: ShareBackup = formatted.parse().expect("Should parse formatted string");
assert_eq!(
TryInto::<u32>::try_into(share.index()).unwrap(),
TryInto::<u32>::try_into(reparsed.index()).unwrap()
);
assert_eq!(share.to_words(), reparsed.to_words());
}
/// Test that checksums are actually verified
#[test]
fn test_specification_checksum_validation() {
// Valid share from test vectors
let valid_share = TEST_SHARES_2_OF_3[0];
let valid = valid_share.parse::<ShareBackup>();
assert!(valid.is_ok(), "Valid share should parse");
let invalid = INVALID_SHARE_CHECKSUM.parse::<ShareBackup>();
assert!(invalid.is_err(), "Invalid checksum should fail");
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frost_backup/tests/error_handling.rs | frost_backup/tests/error_handling.rs | //! Test improved error handling for invalid BIP39 words
use frost_backup::{ShareBackup, ShareBackupError};
#[test]
fn test_invalid_word_error_message() {
// Test with an invalid word at position 5
let mut words = ["ABANDON"; 25];
words[4] = "INVALIDWORD"; // 5th word (0-indexed)
let result = ShareBackup::from_words(1, words);
assert!(result.is_err());
match result {
Err(ShareBackupError::InvalidBip39Word { word_index, word }) => {
assert_eq!(word_index, 4);
assert_eq!(word, "INVALIDWORD");
}
_ => panic!("Expected InvalidBip39Word error"),
}
}
#[test]
fn test_multiple_invalid_words() {
// Test that we get the error for the first invalid word
let mut words = ["ABANDON"; 25];
words[2] = "BADWORD1"; // 3rd word
words[7] = "BADWORD2"; // 8th word
let result = ShareBackup::from_words(1, words);
assert!(result.is_err());
match result {
Err(ShareBackupError::InvalidBip39Word { word_index, word }) => {
assert_eq!(word_index, 2); // Should report first invalid word
assert_eq!(word, "BADWORD1");
}
_ => panic!("Expected InvalidBip39Word error"),
}
}
#[test]
fn test_fromstr_error_handling() {
use std::str::FromStr;
// Test with invalid word
let invalid_share = "#1 ABANDON ABANDON ABANDON ABANDON INVALIDWORD ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON";
let result = ShareBackup::from_str(invalid_share);
assert!(matches!(
result,
Err(ShareBackupError::InvalidBip39Word { .. })
));
// Test missing words
let not_enough = "#1 ABANDON ABANDON";
let result = ShareBackup::from_str(not_enough);
assert!(matches!(result, Err(ShareBackupError::NotEnoughWords)));
// Test too many words
let too_many = "#1 ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON ABANDON EXTRA";
let result = ShareBackup::from_str(too_many);
assert!(matches!(result, Err(ShareBackupError::TooManyWords)));
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frost_backup/tests/proptest.rs | frost_backup/tests/proptest.rs | use core::convert::TryInto;
use frost_backup::*;
use proptest::prelude::*;
use rand::seq::SliceRandom;
use schnorr_fun::frost::ShareImage;
use secp256kfun::{
marker::*,
proptest::{
arbitrary::any,
strategy::{Just, Strategy},
test_runner::{RngAlgorithm, TestRng},
},
Point, Scalar,
};
mod common;
use common::TEST_SHARES_3_OF_5;
proptest! {
#![proptest_config(ProptestConfig::with_cases(100))]
#[test]
fn share_backup_end_to_end(
secret in any::<Scalar<Secret, NonZero>>(),
(n_parties, threshold) in (1usize..=10).prop_flat_map(|n| (Just(n), 1usize..=n)),
) {
// Use deterministic RNG for reproducibility
let mut rng = TestRng::deterministic_rng(RngAlgorithm::ChaCha);
// Generate shares using our backup scheme (use small fingerprint for faster tests)
let fingerprint = schnorr_fun::frost::Fingerprint {
bits_per_coeff: 7,
max_bits_total: 14,
tag: "test",
};
let (shares, _poly_commitment) = ShareBackup::generate_shares(
secret,
threshold,
n_parties,
fingerprint,
&mut rng
);
// Verify we got the right number of shares
prop_assert_eq!(shares.len(), n_parties);
// Verify share indices are sequential from 1
for (i, share) in shares.iter().enumerate() {
prop_assert_eq!(TryInto::<u32>::try_into(share.index()).unwrap(), (i + 1) as u32);
}
// Test encoding and decoding of each share
for share in &shares {
let words = share.to_words();
prop_assert_eq!(words.len(), 25);
// Test roundtrip through words
let index_u32: u32 = share.index().try_into().unwrap();
let decoded = ShareBackup::from_words(index_u32, words)
.expect("Should decode valid share");
// Test Display/FromStr roundtrip
let formatted = share.to_string();
let parsed: ShareBackup = formatted.parse()
.expect("Should parse formatted share");
let parsed_idx: u32 = parsed.index().try_into().unwrap();
let share_idx: u32 = share.index().try_into().unwrap();
prop_assert_eq!(parsed_idx, share_idx);
prop_assert_eq!(parsed.to_words(), share.to_words());
// Verify the decoded share matches
let decoded_idx: u32 = decoded.index().try_into().unwrap();
let share_idx2: u32 = share.index().try_into().unwrap();
prop_assert_eq!(decoded_idx, share_idx2);
prop_assert_eq!(decoded.to_words(), share.to_words());
}
// Test reconstruction with random threshold-sized subsets using recovery module
// Use a boolean mask to select which shares to use (like in frost_prop.rs)
let mut signer_mask = vec![true; threshold];
signer_mask.extend(vec![false; n_parties - threshold]);
// Test a few random combinations
for _ in 0..3.min(n_parties) { // Test up to 3 random combinations
signer_mask.shuffle(&mut rng);
let selected_shares: Vec<ShareBackup> = signer_mask
.iter()
.zip(shares.iter())
.filter(|(is_selected, _)| **is_selected)
.map(|(_, share)| share.clone())
.collect();
prop_assert_eq!(selected_shares.len(), threshold, "Should have exactly threshold shares");
let recovered = recovery::recover_secret(&selected_shares, fingerprint)
.expect("Recovery should succeed");
prop_assert_eq!(
recovered.secret.public(),
secret.public(),
"Failed to reconstruct secret with random selection of {} shares",
threshold
);
}
// Test that threshold-1 shares cannot reconstruct the correct secret
if threshold > 1 && shares.len() >= threshold {
let insufficient = &shares[0..threshold-1];
// This should fail because we don't have enough shares
let result = recovery::recover_secret(insufficient, fingerprint);
// We expect an error, but if it somehow succeeds, verify it's not the correct secret
if let Ok(recovered) = result {
prop_assert_ne!(
recovered.secret.public(),
secret.public(),
"Should not reconstruct correct secret with insufficient shares"
);
}
}
}
#[test]
fn find_valid_subset_with_noise(
(bogus_indices, bogus_points) in (0usize..10)
.prop_flat_map(|n| (
prop::collection::vec(1u32..6, n),
prop::collection::vec(any::<Point<Normal, Public, Zero>>(), n)
))
) {
// Parse all 5 shares
let all_valid_shares: Vec<ShareBackup> = TEST_SHARES_3_OF_5
.iter()
.map(|s| s.parse().expect("Valid share string"))
.collect();
// Randomly select 3 shares using TestRng
let mut rng = TestRng::deterministic_rng(RngAlgorithm::ChaCha);
// Get the selected shares
let valid_shares: Vec<ShareBackup> = all_valid_shares.choose_multiple(&mut rng, 3).cloned().collect();
// Get share images from valid shares
let valid_images: Vec<ShareImage> = valid_shares
.iter()
.map(|s| s.share_image())
.collect();
// Generate bogus share images
let mut all_images = valid_images.clone();
// Add bogus shares at random indices
for (idx, point) in bogus_indices.iter().zip(bogus_points.iter()) {
// Generate a bogus share using a pre-generated random point
let bogus_index = Scalar::<Public, _>::from(*idx).non_zero().expect("non-zero");
let bogus_image = ShareImage {
index: bogus_index,
image: *point,
};
all_images.push(bogus_image);
}
all_images.shuffle(&mut rng);
// Try to discover the valid shares
let result = recovery::find_valid_subset(&all_images, Fingerprint::default(), None);
// Should always find exactly the 3 valid shares
prop_assert!(result.is_some(), "Should find valid shares among noise");
let (found_shares, _) = result.unwrap();
prop_assert_eq!(found_shares.len(), 3, "Should find exactly 3 shares");
// Verify all found shares are from the valid set
for found in &found_shares {
prop_assert!(
valid_images.contains(found),
"Found share should be one of the valid shares"
);
}
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frost_backup/tests/common/mod.rs | frost_backup/tests/common/mod.rs | #![allow(unused)]
/// Shared test vectors for a 1-of-1 scheme
/// Secret used: 0x0101010101010101010101010101010101010101010101010101010101010101
/// Generated with fingerprint: 18-bit "frost-v0"
pub const TEST_SHARES_1_OF_1: &[&str] = &[
"#1 ABSURD AMOUNT DOCTOR ACOUSTIC AVOID LETTER ADVICE CAGE ABSURD AMOUNT DOCTOR ACOUSTIC AVOID LETTER ADVICE CAGE ABSURD AMOUNT DOCTOR ACOUSTIC AVOID LETTER ADVICE CURTAIN SOON",
];
/// Shared test vectors for a 2-of-3 scheme
/// Secret used: 0x0101010101010101010101010101010101010101010101010101010101010101
/// Generated with fingerprint: 18-bit "frost-v0"
pub const TEST_SHARES_2_OF_3: &[&str] = &[
"#1 MUTUAL JEANS SNAP STING BLESS JOURNEY MORAL BREAD ROOM LIMIT DOSE GRAVITY SORT DELIVER OUTDOOR RIPPLE DONKEY BLOUSE PLAY CART CENTURY MAXIMUM MAKE LOCAL MOBILE",
"#2 CASH TRASH FOIL PREFER BUTTER IDEA BRAVE BITTER ITEM WINK DRIFT SMILE TOMATO LUNCH OPTION HERO THREE ENGINE BLESS MANAGE HORSE JAR ADVICE SHERIFF BUSINESS",
"#3 REGION FINISH TRAVEL LAUNDRY CHEAP HAIR PLUNGE BANANA CRACK INTEREST DURING COTTON PHONE DISAGREE CRUNCH AIRPORT CANCEL FOLD LAUNDRY PONY LOBSTER LENS MAMMAL CLOTH FINGER",
];
/// Shared test vectors for a 3-of-5 scheme
/// Secret used: 0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef
/// Generated with fingerprint: 18-bit "frost-v0"
pub const TEST_SHARES_3_OF_5: &[&str] = &[
"#1 DUTCH GLAD TORCH EXACT PROGRAM GRASS CLUB SCRAP MUSCLE TUITION TISSUE CLERK SEA SUMMER SHIP VERY FREQUENT DIAL SYRUP MAMMAL SIMILAR MISERY PLAY RING ARM",
"#2 SUGAR GENERAL PARK VOYAGE CREEK FLY MOTOR ALWAYS WAVE SUNNY WARRIOR DIAMOND WAVE SUNSET ANY LEFT LIGHT FLOAT VAULT GENUINE ELBOW TENNIS BECOME TABLE CLAIM",
"#3 ORANGE HAMMER UNFOLD REFUSE IMMUNE FAVORITE POET MEDIA CARRY SEGMENT PULL BRUSH DAMAGE ADDRESS FILE PORTION UNFOLD BLAST ACCOUNT NATION TELL BELT DENY ABILITY FOOD",
"#4 MIRACLE KETCHUP SLIM MAZE GUESS FEBRUARY IDLE ENDORSE BARELY POLAR AGAIN SIBLING CLARIFY SHELL EAGER FISCAL DISTANCE FEW ABOVE SURE FRAME ENFORCE BUTTER MORNING ZOO",
"#5 PUMPKIN NEUTRAL DESTROY INSTALL BEHAVE FOLD UNDER EAST SHORT MAGNET WORLD DEVICE SPECIAL BUYER STONE MILLION JUNIOR BEAN UPON CRYSTAL SCENE LEARN SEARCH GALAXY SUMMER"
];
/// Invalid share for testing checksum validation
/// This is TEST_SHARES_2_OF_3[0] with the last word changed from "MOBILE" to "ABANDON"
pub const INVALID_SHARE_CHECKSUM: &str = "#1 MUTUAL JEANS SNAP STING BLESS JOURNEY MORAL BREAD ROOM LIMIT DOSE GRAVITY SORT DELIVER OUTDOOR RIPPLE DONKEY BLOUSE PLAY CART CENTURY MAXIMUM MAKE LOCAL ABANDON";
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/desktop_camera/src/lib.rs | frostsnapp/desktop_camera/src/lib.rs | pub mod common;
pub mod decode;
#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "linux")]
pub use linux::LinuxCamera as Camera;
#[cfg(target_os = "windows")]
mod windows;
#[cfg(target_os = "windows")]
pub use windows::WindowsCamera as Camera;
pub use common::{
CameraError, CameraSink, DeviceChange, DeviceInfo, Frame, FrameFormat, Resolution, Result,
};
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/desktop_camera/src/linux.rs | frostsnapp/desktop_camera/src/linux.rs | use crate::common::{
CameraError, CameraSink, CandidateFormat, DeviceInfo, Frame, FrameFormat, Resolution, Result,
};
use std::thread::{self, JoinHandle};
use v4l::Device;
use v4l::context::enum_devices;
use v4l::io::traits::CaptureStream as V4lCaptureStream;
use v4l::prelude::MmapStream;
use v4l::video::Capture;
pub struct LinuxCamera {
_thread: JoinHandle<()>,
}
impl LinuxCamera {
pub fn list_devices() -> Result<Vec<DeviceInfo>> {
Ok(enum_devices()
.into_iter()
.filter_map(|node| {
let index = node.index();
let dev = Device::new(index).ok()?;
let caps = dev.query_caps().ok()?;
let formats = dev.enum_formats().ok()?;
let candidates: Vec<_> = formats
.into_iter()
.filter_map(|f| fourcc_to_frame_format(f.fourcc).map(|fmt| (f.fourcc, fmt)))
.flat_map(|(fourcc, frame_format)| {
dev.enum_framesizes(fourcc)
.into_iter()
.flatten()
.map(move |fs| {
let (width, height) = match &fs.size {
v4l::framesize::FrameSizeEnum::Discrete(size) => {
(size.width, size.height)
}
v4l::framesize::FrameSizeEnum::Stepwise(stepwise) => {
(stepwise.max_width, stepwise.max_height)
}
};
CandidateFormat::new(frame_format, Resolution::new(width, height))
})
})
.collect();
let best = CandidateFormat::select_best(candidates)?;
Some(DeviceInfo {
id: format!("/dev/video{}", index),
index,
name: caps.card,
description: format!("{} ({})", caps.driver, caps.bus),
format: best.format,
resolution: best.resolution,
})
})
.collect())
}
pub fn open(device_info: &DeviceInfo, sink: impl CameraSink) -> Result<Self> {
let device = Device::new(device_info.index).map_err(|e| {
CameraError::OpenFailed(format!(
"Failed to open device {}: {}",
device_info.index, e
))
})?;
let mut fmt = device
.format()
.map_err(|e| CameraError::OpenFailed(format!("Failed to get format: {}", e)))?;
fmt.fourcc = frame_format_to_fourcc(device_info.format);
fmt.width = device_info.resolution.width;
fmt.height = device_info.resolution.height;
let actual_fmt = device
.set_format(&fmt)
.map_err(|e| CameraError::OpenFailed(format!("Failed to set format: {}", e)))?;
let format = device_info.format;
let width = actual_fmt.width;
let height = actual_fmt.height;
let thread = thread::spawn(move || {
let mut stream =
match MmapStream::with_buffers(&device, v4l::buffer::Type::VideoCapture, 4) {
Ok(s) => s,
Err(_) => return,
};
while let Ok((buf, _meta)) = stream.next() {
let jpeg_data = match crate::decode::raw_to_jpeg(buf, format, width, height) {
Ok(data) => data,
Err(_) => continue,
};
let frame = Frame {
data: jpeg_data,
width,
height,
};
if sink.send_frame(frame).is_err() {
break;
}
}
});
Ok(Self { _thread: thread })
}
}
fn fourcc_to_frame_format(fourcc: v4l::FourCC) -> Option<FrameFormat> {
let bytes = fourcc.repr;
match &bytes {
b"YUYV" => Some(FrameFormat::YUYV422),
b"MJPG" => Some(FrameFormat::MJPEG),
b"NV12" => Some(FrameFormat::NV12),
b"YU12" => Some(FrameFormat::YUV420),
b"RGB3" => Some(FrameFormat::RGB24),
_ => None,
}
}
fn frame_format_to_fourcc(format: FrameFormat) -> v4l::FourCC {
let bytes = match format {
FrameFormat::YUYV422 => *b"YUYV",
FrameFormat::MJPEG => *b"MJPG",
FrameFormat::NV12 => *b"NV12",
FrameFormat::YUV420 => *b"YU12",
FrameFormat::RGB24 => *b"RGB3",
};
v4l::FourCC { repr: bytes }
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/desktop_camera/src/decode.rs | frostsnapp/desktop_camera/src/decode.rs | use crate::common::{CameraError, FrameFormat, Result};
pub fn raw_to_jpeg(data: &[u8], format: FrameFormat, width: u32, height: u32) -> Result<Vec<u8>> {
match format {
FrameFormat::MJPEG => Ok(data.to_vec()),
FrameFormat::YUYV422 => {
let rgb = yuyv_to_rgb(data, width, height);
encode_rgb_to_jpeg(&rgb, width, height)
}
FrameFormat::NV12 => {
let rgb = nv12_to_rgb(data, width, height);
encode_rgb_to_jpeg(&rgb, width, height)
}
FrameFormat::YUV420 => {
let rgb = yuv420_to_rgb(data, width, height);
encode_rgb_to_jpeg(&rgb, width, height)
}
FrameFormat::RGB24 => encode_rgb_to_jpeg(data, width, height),
}
}
fn encode_rgb_to_jpeg(rgb_data: &[u8], width: u32, height: u32) -> Result<Vec<u8>> {
use image::ExtendedColorType;
use image::codecs::jpeg::JpegEncoder;
let mut jpeg_data = Vec::new();
let mut encoder = JpegEncoder::new_with_quality(&mut jpeg_data, 85);
encoder
.encode(rgb_data, width, height, ExtendedColorType::Rgb8)
.map_err(|e| CameraError::DecodeError(format!("JPEG encode failed: {:?}", e)))?;
Ok(jpeg_data)
}
fn yuyv_to_rgb(yuyv_data: &[u8], _width: u32, _height: u32) -> Vec<u8> {
let mut rgb = Vec::with_capacity((yuyv_data.len() / 2) * 3);
for chunk in yuyv_data.chunks_exact(4) {
let y0 = chunk[0] as i32;
let u = chunk[1] as i32 - 128;
let y1 = chunk[2] as i32;
let v = chunk[3] as i32 - 128;
for &y in &[y0, y1] {
let r = (y + ((359 * v) >> 8)).clamp(0, 255) as u8;
let g = (y - ((88 * u + 183 * v) >> 8)).clamp(0, 255) as u8;
let b = (y + ((454 * u) >> 8)).clamp(0, 255) as u8;
rgb.push(r);
rgb.push(g);
rgb.push(b);
}
}
rgb
}
fn nv12_to_rgb(data: &[u8], width: u32, height: u32) -> Vec<u8> {
let width = width as usize;
let height = height as usize;
let y_plane_size = width * height;
let mut rgb = Vec::with_capacity(width * height * 3);
let y_plane = &data[..y_plane_size];
let uv_plane = &data[y_plane_size..];
for row in 0..height {
for col in 0..width {
let y = y_plane[row * width + col] as i32;
let uv_row = row / 2;
let uv_col = (col / 2) * 2;
let uv_index = uv_row * width + uv_col;
let u = uv_plane.get(uv_index).copied().unwrap_or(128) as i32 - 128;
let v = uv_plane.get(uv_index + 1).copied().unwrap_or(128) as i32 - 128;
let r = (y + ((359 * v) >> 8)).clamp(0, 255) as u8;
let g = (y - ((88 * u + 183 * v) >> 8)).clamp(0, 255) as u8;
let b = (y + ((454 * u) >> 8)).clamp(0, 255) as u8;
rgb.push(r);
rgb.push(g);
rgb.push(b);
}
}
rgb
}
fn yuv420_to_rgb(data: &[u8], width: u32, height: u32) -> Vec<u8> {
let width = width as usize;
let height = height as usize;
let y_plane_size = width * height;
let u_plane_size = (width / 2) * (height / 2);
let mut rgb = Vec::with_capacity(width * height * 3);
let y_plane = &data[..y_plane_size];
let u_plane = &data[y_plane_size..y_plane_size + u_plane_size];
let v_plane = &data[y_plane_size + u_plane_size..];
for row in 0..height {
for col in 0..width {
let y = y_plane[row * width + col] as i32;
let uv_row = row / 2;
let uv_col = col / 2;
let uv_index = uv_row * (width / 2) + uv_col;
let u = u_plane.get(uv_index).copied().unwrap_or(128) as i32 - 128;
let v = v_plane.get(uv_index).copied().unwrap_or(128) as i32 - 128;
let r = (y + ((359 * v) >> 8)).clamp(0, 255) as u8;
let g = (y - ((88 * u + 183 * v) >> 8)).clamp(0, 255) as u8;
let b = (y + ((454 * u) >> 8)).clamp(0, 255) as u8;
rgb.push(r);
rgb.push(g);
rgb.push(b);
}
}
rgb
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/desktop_camera/src/windows.rs | frostsnapp/desktop_camera/src/windows.rs | use crate::common::{
CameraError, CameraSink, CandidateFormat, DeviceInfo, Frame, FrameFormat, Resolution, Result,
};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, LazyLock};
use std::thread::{self, JoinHandle};
use windows::Win32::Media::MediaFoundation::*;
use windows::Win32::System::Com::{COINIT, CoInitializeEx, CoUninitialize};
use windows::core::GUID;
static INITIALIZED: LazyLock<Arc<AtomicBool>> = LazyLock::new(|| Arc::new(AtomicBool::new(false)));
static CAMERA_REFCNT: LazyLock<Arc<AtomicUsize>> = LazyLock::new(|| Arc::new(AtomicUsize::new(0)));
const CO_INIT_APARTMENT_THREADED: COINIT = COINIT(0x2);
const CO_INIT_DISABLE_OLE1DDE: COINIT = COINIT(0x4);
const MF_VIDEO_FORMAT_YUY2: GUID = GUID::from_values(
0x32595559,
0x0000,
0x0010,
[0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71],
);
const MF_VIDEO_FORMAT_MJPEG: GUID = GUID::from_values(
0x47504A4D,
0x0000,
0x0010,
[0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71],
);
const MF_VIDEO_FORMAT_NV12: GUID = GUID::from_values(
0x3231564E,
0x0000,
0x0010,
[0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71],
);
const MF_VIDEO_FORMAT_RGB24: GUID = GUID::from_values(
0x00000014,
0x0000,
0x0010,
[0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71],
);
const MEDIA_FOUNDATION_FIRST_VIDEO_STREAM: u32 = 0xFFFFFFFC;
fn guid_to_frameformat(guid: GUID) -> Option<FrameFormat> {
match guid {
MF_VIDEO_FORMAT_NV12 => Some(FrameFormat::NV12),
MF_VIDEO_FORMAT_RGB24 => Some(FrameFormat::RGB24),
MF_VIDEO_FORMAT_YUY2 => Some(FrameFormat::YUYV422),
MF_VIDEO_FORMAT_MJPEG => Some(FrameFormat::MJPEG),
_ => None,
}
}
fn frameformat_to_guid(format: FrameFormat) -> GUID {
match format {
FrameFormat::NV12 => MF_VIDEO_FORMAT_NV12,
FrameFormat::RGB24 => MF_VIDEO_FORMAT_RGB24,
FrameFormat::YUYV422 => MF_VIDEO_FORMAT_YUY2,
FrameFormat::MJPEG => MF_VIDEO_FORMAT_MJPEG,
FrameFormat::YUV420 => MF_VIDEO_FORMAT_NV12,
}
}
fn initialize_mf() -> Result<()> {
if !INITIALIZED.load(Ordering::SeqCst) {
unsafe {
let hr = CoInitializeEx(None, CO_INIT_APARTMENT_THREADED | CO_INIT_DISABLE_OLE1DDE);
if hr.is_err() {
return Err(CameraError::OpenFailed("CoInitializeEx failed".to_string()));
}
let hr = MFStartup(MF_API_VERSION, MFSTARTUP_NOSOCKET);
if hr.is_err() {
CoUninitialize();
return Err(CameraError::OpenFailed("MFStartup failed".to_string()));
}
}
INITIALIZED.store(true, Ordering::SeqCst);
}
CAMERA_REFCNT.fetch_add(1, Ordering::SeqCst);
Ok(())
}
fn de_initialize_mf() {
if CAMERA_REFCNT.fetch_sub(1, Ordering::SeqCst) == 1 {
if INITIALIZED.load(Ordering::SeqCst) {
unsafe {
let _ = MFShutdown();
CoUninitialize();
}
INITIALIZED.store(false, Ordering::SeqCst);
}
}
}
pub struct WindowsCamera {
_thread: JoinHandle<()>,
}
impl WindowsCamera {
pub fn list_devices() -> Result<Vec<DeviceInfo>> {
initialize_mf()?;
let attributes = unsafe {
let mut attr = None;
MFCreateAttributes(&mut attr, 1).map_err(|e| {
CameraError::DeviceError(format!("MFCreateAttributes failed: {}", e))
})?;
attr.ok_or_else(|| CameraError::DeviceError("Failed to create attributes".to_string()))?
};
unsafe {
attributes
.SetGUID(
&MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,
&MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID,
)
.map_err(|e| CameraError::DeviceError(format!("SetGUID failed: {}", e)))?;
}
let mut count = 0_u32;
let mut devices_ptr: *mut Option<IMFActivate> = std::ptr::null_mut();
unsafe {
MFEnumDeviceSources(&attributes, &mut devices_ptr, &mut count).map_err(|e| {
CameraError::DeviceError(format!("MFEnumDeviceSources failed: {}", e))
})?;
}
if count == 0 {
de_initialize_mf();
return Ok(vec![]);
}
let devices = unsafe { std::slice::from_raw_parts(devices_ptr, count as usize) };
let mut device_list = Vec::new();
for (index, activate_opt) in devices.iter().enumerate() {
if let Some(activate) = activate_opt {
let name = unsafe {
let mut pwstr = windows::core::PWSTR::null();
let mut len = 0;
activate
.GetAllocatedString(
&MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME,
&mut pwstr,
&mut len,
)
.ok()
.and_then(|_| pwstr.to_string().ok())
.unwrap_or_else(|| format!("Camera {}", index))
};
let symlink = unsafe {
let mut pwstr = windows::core::PWSTR::null();
let mut len = 0;
activate
.GetAllocatedString(
&MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK,
&mut pwstr,
&mut len,
)
.ok()
.and_then(|_| pwstr.to_string().ok())
.unwrap_or_else(|| format!("device_{}", index))
};
if let Ok((format, resolution)) = get_preferred_format(activate) {
device_list.push(DeviceInfo {
id: symlink.clone(),
index,
name,
description: symlink,
format,
resolution,
});
}
}
}
de_initialize_mf();
Ok(device_list)
}
pub fn open(device_info: &DeviceInfo, sink: impl CameraSink) -> Result<Self> {
initialize_mf()?;
let format = device_info.format;
let width = device_info.resolution.width;
let height = device_info.resolution.height;
let index = device_info.index;
let thread = thread::spawn(move || {
if let Err(_) = capture_thread(index, format, width, height, sink) {
de_initialize_mf();
}
});
Ok(Self { _thread: thread })
}
}
impl Drop for WindowsCamera {
fn drop(&mut self) {
de_initialize_mf();
}
}
fn get_preferred_format(activate: &IMFActivate) -> Result<(FrameFormat, Resolution)> {
unsafe {
let media_source: IMFMediaSource = activate
.ActivateObject()
.map_err(|e| CameraError::OpenFailed(format!("ActivateObject failed: {}", e)))?;
let mut attr = None;
MFCreateAttributes(&mut attr, 1)
.map_err(|e| CameraError::OpenFailed(format!("MFCreateAttributes failed: {}", e)))?;
let attr =
attr.ok_or_else(|| CameraError::OpenFailed("Failed to create attributes".to_string()))?;
attr.SetUINT32(&MF_READWRITE_DISABLE_CONVERTERS, 1)
.map_err(|e| CameraError::OpenFailed(format!("SetUINT32 failed: {}", e)))?;
let source_reader: IMFSourceReader =
MFCreateSourceReaderFromMediaSource(&media_source, &attr).map_err(|e| {
CameraError::OpenFailed(format!(
"MFCreateSourceReaderFromMediaSource failed: {}",
e
))
})?;
let mut candidates = Vec::new();
let mut index = 0;
while let Ok(media_type) =
source_reader.GetNativeMediaType(MEDIA_FOUNDATION_FIRST_VIDEO_STREAM, index)
{
index += 1;
let fourcc = media_type.GetGUID(&MF_MT_SUBTYPE).ok();
let frame_format = fourcc.and_then(guid_to_frameformat);
if let Ok(res_u64) = media_type.GetUINT64(&MF_MT_FRAME_SIZE) {
let width = (res_u64 >> 32) as u32;
let height = res_u64 as u32;
if let Some(ff) = frame_format {
candidates.push(CandidateFormat::new(ff, Resolution::new(width, height)));
}
}
}
let best = CandidateFormat::select_best(candidates).ok_or_else(|| {
CameraError::UnsupportedFormat("No supported format found".to_string())
})?;
Ok((best.format, best.resolution))
}
}
fn capture_thread(
index: usize,
format: FrameFormat,
width: u32,
height: u32,
sink: impl CameraSink,
) -> Result<()> {
unsafe {
let attributes = {
let mut attr = None;
MFCreateAttributes(&mut attr, 1).map_err(|e| {
CameraError::DeviceError(format!("MFCreateAttributes failed: {}", e))
})?;
attr.ok_or_else(|| CameraError::DeviceError("Failed to create attributes".to_string()))?
};
attributes
.SetGUID(
&MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,
&MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID,
)
.map_err(|e| CameraError::DeviceError(format!("SetGUID failed: {}", e)))?;
let mut count = 0_u32;
let mut devices_ptr: *mut Option<IMFActivate> = std::ptr::null_mut();
MFEnumDeviceSources(&attributes, &mut devices_ptr, &mut count)
.map_err(|e| CameraError::DeviceError(format!("MFEnumDeviceSources failed: {}", e)))?;
if index >= count as usize {
return Err(CameraError::DeviceNotFound(format!(
"Device {} not found",
index
)));
}
let devices = std::slice::from_raw_parts(devices_ptr, count as usize);
let activate = devices[index]
.as_ref()
.ok_or_else(|| CameraError::DeviceNotFound(format!("Device {} is null", index)))?;
let media_source: IMFMediaSource = activate
.ActivateObject()
.map_err(|e| CameraError::OpenFailed(format!("ActivateObject failed: {}", e)))?;
let mut attr = None;
MFCreateAttributes(&mut attr, 1)
.map_err(|e| CameraError::OpenFailed(format!("MFCreateAttributes failed: {}", e)))?;
let attr =
attr.ok_or_else(|| CameraError::OpenFailed("Failed to create attributes".to_string()))?;
attr.SetUINT32(&MF_READWRITE_DISABLE_CONVERTERS, 1)
.map_err(|e| CameraError::OpenFailed(format!("SetUINT32 failed: {}", e)))?;
let source_reader: IMFSourceReader =
MFCreateSourceReaderFromMediaSource(&media_source, &attr).map_err(|e| {
CameraError::OpenFailed(format!(
"MFCreateSourceReaderFromMediaSource failed: {}",
e
))
})?;
// Find and set the matching format
let guid = frameformat_to_guid(format);
let mut index = 0;
let mut found = false;
while let Ok(media_type) =
source_reader.GetNativeMediaType(MEDIA_FOUNDATION_FIRST_VIDEO_STREAM, index)
{
index += 1;
if let (Ok(fourcc), Ok(res_u64)) = (
media_type.GetGUID(&MF_MT_SUBTYPE),
media_type.GetUINT64(&MF_MT_FRAME_SIZE),
) {
let type_width = (res_u64 >> 32) as u32;
let type_height = res_u64 as u32;
if fourcc == guid && type_width == width && type_height == height {
source_reader
.SetCurrentMediaType(MEDIA_FOUNDATION_FIRST_VIDEO_STREAM, None, &media_type)
.map_err(|e| {
CameraError::OpenFailed(format!("SetCurrentMediaType failed: {}", e))
})?;
found = true;
break;
}
}
}
if !found {
return Err(CameraError::UnsupportedFormat(
"Failed to set format".to_string(),
));
}
source_reader
.SetStreamSelection(MEDIA_FOUNDATION_FIRST_VIDEO_STREAM, true)
.map_err(|e| CameraError::CaptureFailed(format!("SetStreamSelection failed: {}", e)))?;
loop {
let mut sample_opt = None;
let mut stream_flags = 0;
loop {
source_reader
.ReadSample(
MEDIA_FOUNDATION_FIRST_VIDEO_STREAM,
0,
None,
Some(&mut stream_flags),
None,
Some(&mut sample_opt),
)
.map_err(|e| CameraError::CaptureFailed(format!("ReadSample failed: {}", e)))?;
if sample_opt.is_some() {
break;
}
}
let sample =
sample_opt.ok_or_else(|| CameraError::CaptureFailed("No sample".to_string()))?;
let buffer = sample.ConvertToContiguousBuffer().map_err(|e| {
CameraError::CaptureFailed(format!("ConvertToContiguousBuffer failed: {}", e))
})?;
let mut buffer_ptr = std::ptr::null_mut::<u8>();
let mut buffer_len = 0_u32;
buffer
.Lock(&mut buffer_ptr, None, Some(&mut buffer_len))
.map_err(|e| CameraError::CaptureFailed(format!("Lock failed: {}", e)))?;
if !buffer_ptr.is_null() && buffer_len > 0 {
let data = std::slice::from_raw_parts(buffer_ptr, buffer_len as usize).to_vec();
let jpeg_data = match crate::decode::raw_to_jpeg(&data, format, width, height) {
Ok(data) => data,
Err(_) => {
let _ = buffer.Unlock();
continue;
}
};
let frame = Frame {
data: jpeg_data,
width,
height,
};
if sink.send_frame(frame).is_err() {
break;
}
}
let _ = buffer.Unlock();
}
}
de_initialize_mf();
Ok(())
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/desktop_camera/src/common.rs | frostsnapp/desktop_camera/src/common.rs | use std::fmt;
/// Preferred pixel count for MJPEG (hardware decoded, can handle higher res)
pub const MJPEG_PREFERRED_PIXELS: u32 = 1920 * 1080;
/// Preferred pixel count for raw formats like NV12/YUYV (CPU decoded, prefer lower res)
pub const RAW_PREFERRED_PIXELS: u32 = 1280 * 720;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeviceInfo {
pub id: String,
pub index: usize,
pub name: String,
pub description: String,
pub format: FrameFormat,
pub resolution: Resolution,
}
impl fmt::Display for DeviceInfo {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} ({}): {}", self.name, self.id, self.description)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Resolution {
pub width: u32,
pub height: u32,
}
impl Resolution {
pub fn new(width: u32, height: u32) -> Self {
Self { width, height }
}
}
impl fmt::Display for Resolution {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}x{}", self.width, self.height)
}
}
impl Resolution {
pub fn pixels(&self) -> u32 {
self.width * self.height
}
/// Distance from the preferred pixel count for this format
pub fn distance_from_preferred(&self, format: FrameFormat) -> u32 {
let preferred = if format == FrameFormat::MJPEG {
MJPEG_PREFERRED_PIXELS
} else {
RAW_PREFERRED_PIXELS
};
self.pixels().abs_diff(preferred)
}
}
/// A camera format/resolution candidate.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CandidateFormat {
pub format: FrameFormat,
pub resolution: Resolution,
}
impl CandidateFormat {
pub fn new(format: FrameFormat, resolution: Resolution) -> Self {
Self { format, resolution }
}
/// Select the best candidate from a list.
/// Preference order: (1) MJPEG over raw, (2) closest to preferred pixel count
pub fn select_best(candidates: impl IntoIterator<Item = Self>) -> Option<Self> {
candidates.into_iter().max_by_key(|c| {
(
c.format == FrameFormat::MJPEG,
std::cmp::Reverse(c.resolution.distance_from_preferred(c.format)),
)
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FrameFormat {
YUYV422,
NV12,
YUV420,
MJPEG,
RGB24,
}
impl fmt::Display for FrameFormat {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
FrameFormat::YUYV422 => write!(f, "YUYV422"),
FrameFormat::NV12 => write!(f, "NV12"),
FrameFormat::YUV420 => write!(f, "YUV420"),
FrameFormat::MJPEG => write!(f, "MJPEG"),
FrameFormat::RGB24 => write!(f, "RGB24"),
}
}
}
pub struct Frame {
pub data: Vec<u8>,
pub width: u32,
pub height: u32,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DeviceChange {
Added(DeviceInfo),
Removed(String),
}
#[derive(Debug)]
pub enum CameraError {
DeviceNotFound(String),
OpenFailed(String),
CaptureFailed(String),
UnsupportedFormat(String),
InvalidParameter(String),
DecodeError(String),
IoError(std::io::Error),
DeviceError(String),
}
impl std::fmt::Display for CameraError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CameraError::DeviceNotFound(msg) => write!(f, "Device not found: {}", msg),
CameraError::OpenFailed(msg) => write!(f, "Failed to open device: {}", msg),
CameraError::CaptureFailed(msg) => write!(f, "Failed to start capture: {}", msg),
CameraError::UnsupportedFormat(msg) => write!(f, "Format not supported: {}", msg),
CameraError::InvalidParameter(msg) => write!(f, "Invalid parameter: {}", msg),
CameraError::DecodeError(msg) => write!(f, "Decode error: {}", msg),
CameraError::IoError(e) => write!(f, "IO error: {}", e),
CameraError::DeviceError(msg) => write!(f, "Device error: {}", msg),
}
}
}
impl std::error::Error for CameraError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
CameraError::IoError(e) => Some(e),
_ => None,
}
}
}
impl From<std::io::Error> for CameraError {
fn from(e: std::io::Error) -> Self {
CameraError::IoError(e)
}
}
pub type Result<T> = std::result::Result<T, CameraError>;
pub trait CameraSink: Send + 'static {
fn send_frame(&self, frame: Frame) -> Result<()>;
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/rust/build.rs | frostsnapp/rust/build.rs | use std::env;
use std::fs;
use std::path::Path;
fn main() {
println!("cargo::rustc-check-cfg=cfg(bundle_firmware)");
if env::var("BUNDLE_FIRMWARE").is_ok() {
println!("cargo:rustc-cfg=bundle_firmware");
let source_path =
Path::new("../../target/riscv32imc-unknown-none-elf/release/firmware.bin");
let out_dir = env::var("OUT_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("firmware.bin");
println!("cargo:rerun-if-changed={}", source_path.display());
if !source_path.exists() {
eprintln!(
"device firmware file doesn't exist at {}. Build before trying to build app.",
source_path.display()
);
} else {
fs::copy(source_path, dest_path).expect("Failed to copy firmware.bin to OUT_DIR");
}
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/rust/src/lib.rs | frostsnapp/rust/src/lib.rs | pub mod api;
mod coordinator;
mod device_list;
#[allow(clippy::all)]
mod frb_generated;
pub mod logger;
pub mod sink_wrap;
pub use bitcoin::Network;
use frostsnap_coordinator::FirmwareBin;
pub use frostsnap_core::device::KeyPurpose;
use frostsnap_core::SymmetricKey;
#[cfg(not(bundle_firmware))]
pub const FIRMWARE: Option<FirmwareBin> = None;
#[cfg(bundle_firmware)]
pub const FIRMWARE: Option<FirmwareBin> = Some(FirmwareBin::new(include_bytes!(concat!(
env!("OUT_DIR"),
"/firmware.bin"
))));
#[allow(unused)]
/// meant to be replaced by something that's actually secure from the phone's secure element.
const TEMP_KEY: SymmetricKey = SymmetricKey([42u8; 32]);
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/rust/src/logger.rs | frostsnapp/rust/src/logger.rs | use std::{io, sync::RwLock};
use crate::frb_generated::StreamSink;
use lazy_static::lazy_static;
use time::{
format_description::well_known::{iso8601::Config, Iso8601},
OffsetDateTime,
};
use tracing_subscriber::registry::LookupSpan;
lazy_static! {
static ref LOG_SINK: RwLock<Option<StreamSink<String>>> = Default::default();
}
#[derive(Clone)]
struct DartLogWriter;
impl io::Write for DartLogWriter {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let string = String::from_utf8_lossy(buf);
let newline_stripped = string.trim_end_matches('\n');
let sink_lock = LOG_SINK.read().unwrap();
let _ = sink_lock
.as_ref()
.unwrap()
.add(newline_stripped.to_string());
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
/// Set the global [`StreamSink`] used by [`dart_logger`].
///
/// Returns whether this is the first call.
pub fn set_dart_logger(sink: StreamSink<String>) -> bool {
let mut sink_lock = LOG_SINK.write().unwrap();
let is_new = sink_lock.is_none();
*sink_lock = Some(sink);
is_new
}
/// Obtain the Dart logger.
///
/// [`set_dart_logger`] must be called atleast once before calling this method.
pub fn dart_logger<S>() -> impl tracing_subscriber::layer::Layer<S>
where
S: tracing::Subscriber + for<'a> LookupSpan<'a>,
{
tracing_subscriber::fmt::layer()
.with_ansi(false)
.with_file(false)
.with_line_number(false)
.with_target(false)
.with_timer(TimeFormatter)
.with_writer(move || io::LineWriter::new(DartLogWriter))
}
struct TimeFormatter;
const ISO8601_CONFIG: Config = Config::DEFAULT.set_time_precision(
time::format_description::well_known::iso8601::TimePrecision::Second {
decimal_digits: None,
},
);
const TIME_FORMAT: Iso8601<{ ISO8601_CONFIG.encode() }> = Iso8601;
impl tracing_subscriber::fmt::time::FormatTime for TimeFormatter {
fn format_time(&self, w: &mut tracing_subscriber::fmt::format::Writer<'_>) -> std::fmt::Result {
let now = OffsetDateTime::now_utc();
write!(w, "{}", now.format(&TIME_FORMAT).unwrap())
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/rust/src/device_list.rs | frostsnapp/rust/src/device_list.rs | #![allow(unused)]
use crate::api::device_list as api;
use frostsnap_coordinator::{frostsnap_core::DeviceId, DeviceChange};
use std::collections::{HashMap, HashSet};
#[derive(Debug, Clone, Default)]
pub struct DeviceList {
devices: Vec<DeviceId>,
connected: HashMap<DeviceId, api::ConnectedDevice>,
state_counter: u32,
outbox: Vec<api::DeviceListChange>,
}
impl DeviceList {
pub fn update_ready(&self) -> bool {
!self.outbox.is_empty()
}
// Order devices by connection order, with any new devices appended
pub fn sort_as_connected(
&self,
devices: HashSet<DeviceId>,
) -> impl Iterator<Item = DeviceId> + '_ {
let ordered_devices: Vec<_> = self
.devices
.iter()
.filter(|id| devices.contains(id))
.copied()
.collect();
let remaining_devices: Vec<_> = devices
.into_iter()
.filter(|id| !self.devices.contains(id))
.collect();
ordered_devices.into_iter().chain(remaining_devices)
}
pub fn devices(&self) -> Vec<api::ConnectedDevice> {
self.devices
.iter()
.cloned()
.map(|id| self.connected.get(&id).cloned().expect("invariant"))
.collect()
}
pub fn device_at_index(&self, index: usize) -> Option<api::ConnectedDevice> {
self.devices
.get(index)
.map(|id| self.connected.get(id).cloned().expect("invariant"))
}
pub fn take_update(&mut self) -> api::DeviceListUpdate {
let changes = core::mem::take(&mut self.outbox);
let update = api::DeviceListUpdate {
changes,
state: api::DeviceListState {
devices: self.devices(),
state_id: self.state_counter,
},
};
if !update.changes.is_empty() {
self.state_counter += 1;
}
update
}
pub fn consume_manager_event(&mut self, change: DeviceChange) {
match change {
DeviceChange::Connected {
id,
firmware_digest,
latest_firmware_digest,
} => {
use frostsnap_coordinator::FirmwareVersion;
self.connected.insert(
id,
api::ConnectedDevice {
firmware: FirmwareVersion::new(firmware_digest),
latest_firmware: latest_firmware_digest.map(FirmwareVersion::new),
name: None,
id,
recovery_mode: false,
},
);
}
DeviceChange::NameChange { id, name } => {
if let Some(index) = self.index_of(id) {
let connected = self.connected.get_mut(&id).expect("invariant");
connected.name = Some(name);
self.outbox.push(api::DeviceListChange {
kind: api::DeviceListChangeKind::Named,
index: index as u32,
device: connected.clone(),
});
}
}
DeviceChange::NeedsName { id } => {
self.append(id);
}
DeviceChange::Registered { id, name } => {
let index = self.index_of(id);
let connected = self
.connected
.get_mut(&id)
.expect("registered means connected already emitted");
match index {
Some(index) => {
if connected.name.is_some() {
assert_eq!(
connected.name,
Some(name.clone()),
"we should have got a renamed event if they were different"
);
} else {
// The device had no name and now it's been named
connected.name = Some(name);
self.outbox.push(api::DeviceListChange {
kind: api::DeviceListChangeKind::Named,
index: index as u32,
device: connected.clone(),
});
}
}
None => {
connected.name = Some(name);
self.append(id);
}
}
}
DeviceChange::Disconnected { id } => {
let device = self.connected.remove(&id);
if let Some(index) = self.index_of(id) {
self.devices.remove(index);
self.outbox.push(api::DeviceListChange {
kind: api::DeviceListChangeKind::Removed,
index: index as u32,
device: device.expect("invariant"),
})
}
}
DeviceChange::AppMessage(_) => { /* not relevant */ }
DeviceChange::GenuineDevice { .. } => { /* not displayed in app yet */ }
}
}
pub fn get_device(&self, id: DeviceId) -> Option<api::ConnectedDevice> {
self.connected.get(&id).cloned()
}
fn index_of(&self, id: DeviceId) -> Option<usize> {
self.devices
.iter()
.enumerate()
.find(|(_, device_id)| **device_id == id)
.map(|(i, _)| i)
}
fn append(&mut self, id: DeviceId) {
if self.index_of(id).is_none() {
self.devices.push(id);
self.outbox.push(api::DeviceListChange {
kind: api::DeviceListChangeKind::Added,
index: (self.devices.len() - 1) as u32,
device: self.get_device(id).expect("invariant"),
});
}
}
pub fn set_recovery_mode(&mut self, id: DeviceId, recovery_mode: bool) {
if let Some(connected_device) = self.connected.get_mut(&id) {
if connected_device.recovery_mode != recovery_mode {
connected_device.recovery_mode = recovery_mode;
let connected_device = connected_device.clone();
self.outbox.push(api::DeviceListChange {
kind: api::DeviceListChangeKind::RecoveryMode,
index: self.index_of(id).expect("invariant") as u32,
device: connected_device,
})
}
}
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/rust/src/coordinator.rs | frostsnapp/rust/src/coordinator.rs | #![allow(unused)]
use crate::api;
use crate::api::backup_run::{BackupDevice, BackupRun};
use crate::api::coordinator::KeyState;
use crate::api::device_list::DeviceListUpdate;
use crate::device_list::DeviceList;
use crate::frb_generated::StreamSink;
use anyhow::{anyhow, Result};
use frostsnap_coordinator::backup_run::BackupState;
use frostsnap_coordinator::enter_physical_backup::{EnterPhysicalBackup, EnterPhysicalBackupState};
use frostsnap_coordinator::firmware_upgrade::{
FirmwareUpgradeConfirmState, FirmwareUpgradeProtocol,
};
use frostsnap_coordinator::frostsnap_comms::{
CoordinatorSendBody, CoordinatorSendMessage, Destination, Sha256Digest,
};
use frostsnap_coordinator::frostsnap_persist::DeviceNames;
use frostsnap_coordinator::nonce_replenish::NonceReplenishState;
use frostsnap_coordinator::persist::Persisted;
use frostsnap_coordinator::signing::SigningState;
use frostsnap_coordinator::verify_address::{VerifyAddressProtocol, VerifyAddressProtocolState};
use frostsnap_coordinator::wait_for_single_device::{
WaitForSingleDevice, WaitForSingleDeviceState,
};
use frostsnap_coordinator::{
AppMessageBody, DeviceChange, DeviceMode, FirmwareVersion, Sink, UiProtocol, UiStack,
UsbSender, UsbSerialManager, ValidatedFirmwareBin, WaitForToUserMessage,
};
use frostsnap_core::coordinator::restoration::{
PhysicalBackupPhase, RecoverShare, RestorationState, ToUserRestoration,
};
use frostsnap_core::coordinator::{
BeginKeygen, CoordAccessStructure, CoordFrostKey, CoordinatorSend, CoordinatorToUserMessage,
FrostCoordinator, NonceReplenishRequest,
};
use frostsnap_core::device::KeyPurpose;
use frostsnap_core::{
message, AccessStructureRef, DeviceId, KeyId, KeygenId, RestorationId, SignSessionId,
SymmetricKey, WireSignTask,
};
use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
use std::ops::DerefMut;
use std::str::FromStr;
use std::sync::{Arc, Mutex};
use std::thread::JoinHandle;
use std::time::Duration;
use tracing::{event, Level};
const N_NONCE_STREAMS: usize = 4;
pub struct FfiCoordinator {
usb_manager: Mutex<Option<UsbSerialManager>>,
key_event_stream: Arc<Mutex<Option<Box<dyn Sink<KeyState>>>>>,
signing_session_signals: Arc<Mutex<HashMap<KeyId, Signal>>>,
thread_handle: Mutex<Option<JoinHandle<()>>>,
ui_stack: Arc<Mutex<UiStack>>,
pub(crate) usb_sender: UsbSender,
firmware_bin: Option<ValidatedFirmwareBin>,
firmware_upgrade_progress: Arc<Mutex<Option<Box<dyn Sink<f32>>>>>,
device_list: Arc<Mutex<DeviceList>>,
device_list_stream: Arc<Mutex<Option<Box<dyn Sink<DeviceListUpdate>>>>>,
// // persisted things
pub(crate) db: Arc<Mutex<rusqlite::Connection>>,
device_names: Arc<Mutex<Persisted<DeviceNames>>>,
pub(crate) coordinator: Arc<Mutex<Persisted<FrostCoordinator>>>,
// backup management
pub(crate) backup_state: Arc<Mutex<Persisted<BackupState>>>,
pub(crate) backup_run_streams: Arc<Mutex<BTreeMap<KeyId, StreamSink<BackupRun>>>>,
}
type Signal = Box<dyn Sink<()>>;
impl FfiCoordinator {
pub fn new(
db: Arc<Mutex<rusqlite::Connection>>,
usb_manager: UsbSerialManager,
) -> anyhow::Result<Self> {
let mut db_ = db.lock().unwrap();
event!(Level::DEBUG, "loading core coordinator");
let coordinator = Persisted::<FrostCoordinator>::new(&mut db_, ())?;
event!(Level::DEBUG, "loading device names");
let device_names = Persisted::<DeviceNames>::new(&mut db_, ())?;
event!(Level::DEBUG, "loading backup state");
let backup_state = Persisted::<BackupState>::new(&mut db_, ())?;
let usb_sender = usb_manager.usb_sender();
let firmware_bin = usb_manager.upgrade_bin();
let usb_manager = Mutex::new(Some(usb_manager));
drop(db_);
Ok(Self {
usb_manager,
thread_handle: Default::default(),
key_event_stream: Default::default(),
signing_session_signals: Default::default(),
ui_stack: Default::default(),
firmware_upgrade_progress: Default::default(),
device_list: Default::default(),
device_list_stream: Default::default(),
usb_sender,
firmware_bin,
db,
coordinator: Arc::new(Mutex::new(coordinator)),
device_names: Arc::new(Mutex::new(device_names)),
backup_state: Arc::new(Mutex::new(backup_state)),
backup_run_streams: Default::default(),
})
}
pub fn inner(&self) -> impl DerefMut<Target = Persisted<FrostCoordinator>> + '_ {
self.coordinator.lock().unwrap()
}
pub fn start(&self) -> anyhow::Result<()> {
assert!(
self.thread_handle.lock().unwrap().is_none(),
"can't start coordinator thread again"
);
let mut usb_manager = self
.usb_manager
.lock()
.unwrap()
.take()
.expect("can only start once");
let coordinator_loop = self.coordinator.clone();
let ui_stack = self.ui_stack.clone();
let db_loop = self.db.clone();
let device_names = self.device_names.clone();
let usb_sender = self.usb_sender.clone();
let firmware_upgrade_progress = self.firmware_upgrade_progress.clone();
let device_list = self.device_list.clone();
let device_list_stream = self.device_list_stream.clone();
let handle = std::thread::spawn(move || {
loop {
// to give time for the other threads to get a lock
std::thread::sleep(Duration::from_millis(100));
// check for firmware upgrade mode before locking anything else
let mut firmware_upgrade_progress_loop = firmware_upgrade_progress.lock().unwrap();
if let Some(firmware_upgrade_pogress) = &mut *firmware_upgrade_progress_loop {
// We're in a firmware upgrade.
// Do the firmware upgrade and then carry on as usual
let mut error = Ok(());
match usb_manager.run_firmware_upgrade() {
Ok(progress_iter) => {
for progress in progress_iter {
match progress {
Ok(progress) => {
firmware_upgrade_pogress.send(progress);
}
Err(e) => {
error = Err(e);
break;
}
}
}
}
Err(e) => {
error = Err(e);
}
}
*firmware_upgrade_progress_loop = None;
match error {
Ok(_) => {
event!(Level::INFO, "firmware upgrade completed")
}
Err(e) => {
event!(
Level::ERROR,
error = e.to_string(),
"firmware upgrade error'd out"
);
}
}
}
// NOTE: Never hold locks on anything over poll_ports because poll ports makes
// blocking calls up to flutter. If flutter is blocked on something else we'll
// be deadlocked.
let device_changes = usb_manager.poll_ports();
let mut coordinator = coordinator_loop.lock().unwrap();
let mut coordinator_outbox = VecDeque::default();
let mut messages_from_devices = vec![];
let mut db = db_loop.lock().unwrap();
let mut ui_stack = ui_stack.lock().unwrap();
// process new messages from devices
{
let mut device_list = device_list.lock().unwrap();
for change in device_changes {
device_list.consume_manager_event(change.clone());
match change {
DeviceChange::Registered { id, .. } => {
if coordinator.has_backups_that_need_to_be_consolidated(id) {
device_list.set_recovery_mode(id, true);
}
ui_stack.connected(
id,
device_list
.get_device(id)
.expect("it was just registered")
.device_mode(),
);
if let Some(connected_device) = device_list.get_device(id) {
// we only send some messages out if the device has up to date firmware
if !connected_device.needs_firmware_upgrade() {
// coordinator_outbox.extend(
// coordinator.maybe_request_nonce_replenishment(
// &BTreeSet::from([id]),
// N_NONCE_STREAMS,
// &mut rand::thread_rng(),
// ),
// );
}
}
}
DeviceChange::Disconnected { id } => {
ui_stack.disconnected(id);
}
DeviceChange::NameChange { id, name } => {
let mut device_names = device_names.lock().unwrap();
// TODO: Detect name change and prompt user to accept
let result = device_names.staged_mutate(&mut *db, |names| {
names.insert(id, name.clone());
Ok(())
});
match result {
Err(e) => {
event!(
Level::ERROR,
id = id.to_string(),
name = name,
error = e.to_string(),
"failed to persist device name change"
);
}
Ok(_) => {
usb_manager.accept_device_name(id, name.clone());
}
}
}
DeviceChange::AppMessage(message) => {
messages_from_devices.push(message.clone());
}
DeviceChange::NeedsName { id } => {
ui_stack.connected(id, DeviceMode::Blank);
}
_ => { /* ignore rest */ }
}
}
if device_list.update_ready() {
if let Some(device_list_stream) = &*device_list_stream.lock().unwrap() {
device_list_stream.send(device_list.take_update());
}
}
};
for app_message in messages_from_devices {
match app_message.body {
AppMessageBody::Core(core_message) => {
let core_message = *core_message;
let result = coordinator.staged_mutate(&mut *db, |coordinator| {
match coordinator
.recv_device_message(app_message.from, core_message)
{
Ok(messages) => {
coordinator_outbox.extend(messages);
}
Err(e) => {
event!(
Level::ERROR,
from = app_message.from.to_string(),
"Failed to process message: {}",
e
);
}
}
Ok(())
});
if let Err(e) = result {
event!(
Level::ERROR,
error = e.to_string(),
"failed to persist changes from device message"
);
}
}
AppMessageBody::Misc(comms_misc) => {
ui_stack.process_comms_message(app_message.from, comms_misc);
}
}
}
drop(coordinator);
drop(db);
while let Some(message) = coordinator_outbox.pop_front() {
match message {
CoordinatorSend::ToDevice {
message,
destinations,
} => {
let send_message = CoordinatorSendMessage {
target_destinations: Destination::from(destinations),
message_body: CoordinatorSendBody::Core(message),
};
usb_sender.send(send_message);
}
CoordinatorSend::ToUser(msg) => {
ui_stack.process_to_user_message(msg);
}
}
}
// poll the ui protocol first before locking anything else because of the potential
// for dead locks with callbacks activated on stream items trying to lock things.
for message in ui_stack.poll() {
usb_sender.send(message);
}
if ui_stack.clean_finished() {
// the UI stack ahs told us we need to cancel all since one of the protocols
// completed with an abort.
usb_sender.send_cancel_all();
}
}
});
*self.thread_handle.lock().unwrap() = Some(handle);
Ok(())
}
pub fn sub_key_events(&self, stream: impl Sink<api::coordinator::KeyState>) {
let mut key_event_stream = self.key_event_stream.lock().unwrap();
let state = self.key_state();
stream.send(state);
key_event_stream.replace(Box::new(stream));
}
pub fn update_name_preview(&self, id: DeviceId, name: &str) -> anyhow::Result<()> {
let device_name: frostsnap_coordinator::frostsnap_comms::DeviceName = name.try_into()?;
self.usb_sender.update_name_preview(id, device_name);
Ok(())
}
pub fn finish_naming(&self, id: DeviceId, name: &str) -> anyhow::Result<()> {
let device_name: frostsnap_coordinator::frostsnap_comms::DeviceName = name.try_into()?;
self.usb_sender.finish_naming(id, device_name);
Ok(())
}
pub fn send_cancel(&self, id: DeviceId) {
self.usb_sender.send_cancel(id)
}
pub fn generate_new_key(
&self,
devices: Vec<DeviceId>,
threshold: u16,
key_name: String,
purpose: KeyPurpose,
sink: impl Sink<frostsnap_coordinator::keygen::KeyGenState>,
) -> anyhow::Result<()> {
let device_list = self.device_list.lock().unwrap();
let devices = devices.into_iter().collect();
// sort them as connected so we get #1 assigned to the first one etc
let devices = device_list.sort_as_connected(devices).collect();
let currently_connected = device_list.devices().into_iter().map(|device| device.id);
drop(device_list);
let begin_keygen = BeginKeygen::new(
devices,
threshold,
key_name,
purpose,
&mut rand::thread_rng(),
);
let ui_protocol = frostsnap_coordinator::keygen::KeyGen::new(
sink,
self.coordinator.lock().unwrap().MUTATE_NO_PERSIST(),
currently_connected.into_iter().collect(),
begin_keygen,
&mut rand::thread_rng(),
);
ui_protocol.emit_state();
self.start_protocol(ui_protocol);
Ok(())
}
pub fn frost_keys(&self) -> Vec<CoordFrostKey> {
self.coordinator
.lock()
.unwrap()
.iter_keys()
.cloned()
.collect()
}
pub fn nonces_available(&self, id: DeviceId) -> u32 {
self.coordinator
.lock()
.unwrap()
.nonces_available(id)
.values()
.copied()
.max()
.unwrap_or(0)
}
pub fn nonce_replenish_request(&self, devices: BTreeSet<DeviceId>) -> NonceReplenishRequest {
self.coordinator
.lock()
.unwrap()
.MUTATE_NO_PERSIST()
.maybe_request_nonce_replenishment(&devices, N_NONCE_STREAMS, &mut rand::thread_rng())
}
pub fn replenish_nonces(
&self,
nonce_request: NonceReplenishRequest,
devices: BTreeSet<DeviceId>,
sink: impl Sink<frostsnap_coordinator::nonce_replenish::NonceReplenishState>,
) -> anyhow::Result<()> {
let ui_protocol = frostsnap_coordinator::nonce_replenish::NonceReplenishProtocol::new(
devices,
nonce_request,
sink,
);
ui_protocol.emit_state();
self.start_protocol(ui_protocol);
Ok(())
}
pub fn start_signing(
&self,
access_structure_ref: AccessStructureRef,
devices: BTreeSet<DeviceId>,
task: WireSignTask,
sink: impl Sink<SigningState>,
) -> anyhow::Result<()> {
let mut coordinator = self.coordinator.lock().unwrap();
let session_id =
coordinator.staged_mutate(&mut self.db.lock().unwrap(), |coordinator| {
Ok(coordinator.start_sign(
access_structure_ref,
task,
&devices,
&mut rand::thread_rng(),
)?)
})?;
let signals = self.signing_session_signals.clone();
let sink = sink.inspect(move |_| {
if let Some(signal_sink) = signals.lock().unwrap().get(&access_structure_ref.key_id) {
signal_sink.send(());
}
});
let mut ui_protocol = frostsnap_coordinator::signing::SigningDispatcher::new(
devices,
access_structure_ref.key_id,
session_id,
sink,
);
ui_protocol.emit_state();
self.start_protocol(ui_protocol);
Ok(())
}
pub fn request_device_sign(
&self,
device_id: DeviceId,
session_id: SignSessionId,
encryption_key: SymmetricKey,
) -> anyhow::Result<()> {
let mut ui_stack = self.ui_stack.lock().unwrap();
let signing = ui_stack
.get_mut::<frostsnap_coordinator::signing::SigningDispatcher>()
.ok_or(anyhow!("somehow UI was not in KeyGen state"))?;
let mut db = self.db.lock().unwrap();
let sign_req = self
.coordinator
.lock()
.unwrap()
.staged_mutate(&mut *db, |coordinator| {
Ok(coordinator.request_device_sign(session_id, device_id, encryption_key))
})?;
signing.send_sign_request(sign_req);
Ok(())
}
pub fn try_restore_signing_session(
&self,
session_id: SignSessionId,
sink: impl Sink<SigningState>,
) -> anyhow::Result<()> {
let coordinator = self.coordinator.lock().unwrap();
let active_sign_session = coordinator
.active_signing_sessions_by_ssid()
.get(&session_id)
.ok_or(anyhow!("this signing session no longer exists"))?;
let key_id = active_sign_session.key_id;
let signals = self.signing_session_signals.clone();
let sink = sink.inspect(move |_| {
if let Some(signal_sink) = signals.lock().unwrap().get(&key_id) {
signal_sink.send(());
}
});
let mut dispatcher =
frostsnap_coordinator::signing::SigningDispatcher::restore_signing_session(
active_sign_session,
sink,
);
dispatcher.emit_state();
self.start_protocol(dispatcher);
Ok(())
}
pub fn begin_upgrade_firmware(
&self,
sink: impl Sink<FirmwareUpgradeConfirmState>,
) -> anyhow::Result<()> {
let firmware_bin = self.firmware_bin.ok_or(anyhow!(
"App wasn't compiled with BUNDLE_FIRMWARE so it can't do firmware upgrades"
))?;
let ui_protocol = {
let device_list = self.device_list.lock().unwrap();
let devices: HashMap<DeviceId, FirmwareVersion> = device_list
.devices()
.into_iter()
.map(|device| (device.id, device.firmware))
.collect();
let need_upgrade = device_list
.devices()
.into_iter()
.filter(|device| device.needs_firmware_upgrade())
.map(|device| device.id)
.collect();
let ui_protocol =
FirmwareUpgradeProtocol::new(devices, need_upgrade, firmware_bin, sink);
ui_protocol.emit_state();
ui_protocol
};
self.start_protocol(ui_protocol);
Ok(())
}
pub fn upgrade_firmware_digest(&self) -> Option<Sha256Digest> {
self.firmware_bin.map(|firmware_bin| firmware_bin.digest())
}
pub fn upgrade_firmware_version_name(&self) -> Option<String> {
self.firmware_bin
.map(|firmware_bin| firmware_bin.firmware_version().version_name())
}
pub(crate) fn start_protocol<P: UiProtocol + Send + 'static>(&self, mut protocol: P) {
for device in self.device_list.lock().unwrap().devices() {
protocol.connected(device.id, device.device_mode());
}
let mut stack = self.ui_stack.lock().unwrap();
stack.push(protocol);
}
pub fn cancel_protocol(&self) {
if self.ui_stack.lock().unwrap().cancel_all() {
self.usb_sender.send_cancel_all();
}
}
pub fn enter_firmware_upgrade_mode(&self, sink: impl Sink<f32>) -> Result<()> {
match &mut *self.firmware_upgrade_progress.lock().unwrap() {
Some(_) => {
event!(
Level::ERROR,
"tried to enter firmware upgrade mode while we were already in an upgrade"
);
return Err(anyhow!(
"trierd to enter firmware upgrade mode while already in an upgrade"
));
}
progress => *progress = Some(Box::new(sink)),
}
Ok(())
}
pub fn get_device_name(&self, id: DeviceId) -> Option<String> {
self.device_names.lock().unwrap().get(id)
}
pub fn finalize_keygen(
&self,
keygen_id: KeygenId,
symmetric_key: SymmetricKey,
) -> Result<AccessStructureRef> {
let access_structure_ref = {
let mut coordinator = self.coordinator.lock().unwrap();
let mut db = self.db.lock().unwrap();
let mut ui_stack = self.ui_stack.lock().unwrap();
let keygen = ui_stack
.get_mut::<frostsnap_coordinator::keygen::KeyGen>()
.ok_or(anyhow!("somehow UI was not in KeyGen state"))?;
let finalized_keygen = coordinator.staged_mutate(&mut db, |coordinator| {
Ok(coordinator.finalize_keygen(
keygen_id,
symmetric_key,
&mut rand::thread_rng(),
)?)
})?;
let access_structure_ref = finalized_keygen.access_structure_ref;
self.usb_sender.send_from_core(finalized_keygen);
keygen.keygen_finalized(access_structure_ref);
access_structure_ref
};
self.emit_key_state();
// Start backup run for newly created wallet
{
let coordinator = self.coordinator.lock().unwrap();
let access_structure = coordinator
.get_access_structure(access_structure_ref)
.expect("access structure must exist after keygen");
let share_indices: Vec<u32> = access_structure
.iter_shares()
.map(|(_, share_index)| {
u32::try_from(share_index).expect("share index should fit in u32")
})
.collect();
drop(coordinator);
let mut backup_state = self.backup_state.lock().unwrap();
let mut db = self.db.lock().unwrap();
backup_state.mutate2(&mut *db, |state, mutations| {
state.start_run(access_structure_ref, share_indices, mutations);
Ok(())
})?;
}
// Emit backup stream
let _ = self.backup_stream_emit(access_structure_ref.key_id);
Ok(access_structure_ref)
}
pub fn get_access_structure(&self, as_ref: AccessStructureRef) -> Option<CoordAccessStructure> {
self.coordinator
.lock()
.unwrap()
.get_access_structure(as_ref)
}
pub fn get_frost_key(&self, key_id: KeyId) -> Option<CoordFrostKey> {
self.coordinator
.lock()
.unwrap()
.get_frost_key(key_id)
.cloned()
}
pub fn verify_address(
&self,
key_id: KeyId,
address_index: u32,
stream: impl Sink<VerifyAddressProtocolState>,
) -> anyhow::Result<()> {
let coordinator = self.coordinator.lock().unwrap();
let verify_address_messages = coordinator.verify_address(key_id, address_index)?;
let ui_protocol = VerifyAddressProtocol::new(verify_address_messages.clone(), stream);
ui_protocol.emit_state();
self.start_protocol(ui_protocol);
Ok(())
}
pub fn key_state(&self) -> api::coordinator::KeyState {
key_state(&self.coordinator.lock().unwrap())
}
pub fn wait_for_single_device(&self, sink: impl Sink<WaitForSingleDeviceState>) {
let mut ui_protocol = WaitForSingleDevice::new(sink);
ui_protocol.emit_state();
self.start_protocol(ui_protocol);
}
pub fn start_restoring_wallet(
&self,
name: String,
threshold: Option<u16>,
key_purpose: KeyPurpose,
) -> Result<RestorationId> {
let restoration_id = {
let mut db = self.db.lock().unwrap();
let mut coordinator = self.coordinator.lock().unwrap();
coordinator.staged_mutate(&mut *db, |coordinator| {
let restoration_id = RestorationId::new(&mut rand::thread_rng());
coordinator.start_restoring_key(name, threshold, key_purpose, restoration_id);
Ok(restoration_id)
})?
};
self.emit_key_state();
Ok(restoration_id)
}
pub fn start_restoring_wallet_from_device_share(
&self,
recover_share: &RecoverShare,
) -> Result<RestorationId> {
let restoration_id = {
let mut coordinator = self.coordinator.lock().unwrap();
if let Some(access_structure_ref) = recover_share.held_share.access_structure_ref {
if coordinator
.get_access_structure(access_structure_ref)
.is_some()
{
return Err(anyhow!("we already know about this access structure"));
}
}
let mut db = self.db.lock().unwrap();
coordinator.staged_mutate(&mut *db, |coordinator| {
let restoration_id = RestorationId::new(&mut rand::thread_rng());
coordinator.start_restoring_key_from_recover_share(recover_share, restoration_id);
Ok(restoration_id)
})?
};
self.emit_key_state();
Ok(restoration_id)
}
pub fn continue_restoring_wallet_from_device_share(
&self,
restoration_id: RestorationId,
recover_share: &RecoverShare,
encryption_key: SymmetricKey,
) -> Result<()> {
{
let mut db = self.db.lock().unwrap();
let mut coordinator = self.coordinator.lock().unwrap();
coordinator.staged_mutate(&mut *db, |coordinator| {
coordinator.add_recovery_share_to_restoration(
restoration_id,
recover_share,
encryption_key,
)?;
Ok(())
})?;
}
self.emit_key_state();
Ok(())
}
pub fn recover_share(
&self,
access_structure_ref: AccessStructureRef,
recover_share: &RecoverShare,
encryption_key: SymmetricKey,
) -> Result<()> {
let held_by = recover_share.held_by;
{
let mut db = self.db.lock().unwrap();
let mut coordinator = self.coordinator.lock().unwrap();
coordinator.staged_mutate(&mut *db, |coordinator| {
coordinator.recover_share(access_structure_ref, recover_share, encryption_key)?;
Ok(())
})?;
}
self.exit_recovery_mode(held_by, encryption_key);
self.emit_key_state();
Ok(())
}
pub fn get_restoration_state(&self, restoration_id: RestorationId) -> Option<RestorationState> {
self.coordinator
.lock()
.unwrap()
.get_restoration_state(restoration_id)
}
pub fn finish_restoring(
&self,
restoration_id: RestorationId,
encryption_key: SymmetricKey,
) -> Result<AccessStructureRef> {
let (assid, needs_consolidation) = {
let mut db = self.db.lock().unwrap();
let mut coordinator = self.coordinator.lock().unwrap();
let restoration_state = coordinator
.get_restoration_state(restoration_id)
.ok_or(anyhow!("can't finish restoration that doesn't exist"))?;
let needs_consolidation: Vec<_> = restoration_state.needs_to_consolidate().collect();
let assid = coordinator.staged_mutate(&mut *db, |coordinator| {
Ok(coordinator.finish_restoring(
restoration_id,
encryption_key,
&mut rand::thread_rng(),
)?)
})?;
(assid, needs_consolidation)
};
for device_id in needs_consolidation {
// NOTE: This will only work for the devices that are plugged in otherwise it's a noop
self.exit_recovery_mode(device_id, encryption_key);
}
self.emit_key_state();
Ok(assid)
}
pub fn delete_key(&self, key_id: KeyId) -> Result<()> {
{
let mut db = self.db.lock().unwrap();
let mut coordinator = self.coordinator.lock().unwrap();
coordinator.staged_mutate(&mut *db, |coordinator| {
coordinator.delete_key(key_id);
Ok(())
})?;
drop(coordinator);
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | true |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/rust/src/sink_wrap.rs | frostsnapp/rust/src/sink_wrap.rs | use crate::{
api::{coordinator::KeyState, device_list::DeviceListUpdate},
frb_generated::StreamSink,
};
use frostsnap_coordinator::{
// bitcoin::chain_sync::ChainStatus,
bitcoin::chain_sync::ChainStatus,
firmware_upgrade::FirmwareUpgradeConfirmState,
keygen::KeyGenState,
nonce_replenish::NonceReplenishState,
signing::SigningState,
verify_address::VerifyAddressProtocolState,
};
// we need to wrap it so we can impl it on foreign FRB type. You can't do a single generic impl. Try
// it if you don't believe me.
pub struct SinkWrap<T>(pub StreamSink<T>);
macro_rules! bridge_sink {
($type:ty) => {
impl<A: Into<$type> + Send + 'static> frostsnap_coordinator::Sink<A> for SinkWrap<$type> {
fn send(&self, state: A) {
let _ = self.0.add(state.into());
}
}
};
}
bridge_sink!(KeyGenState);
bridge_sink!(FirmwareUpgradeConfirmState);
bridge_sink!(VerifyAddressProtocolState);
bridge_sink!(SigningState);
bridge_sink!(bool);
bridge_sink!(f32);
bridge_sink!(ChainStatus);
bridge_sink!(DeviceListUpdate);
bridge_sink!(KeyState);
bridge_sink!(NonceReplenishState);
bridge_sink!(());
bridge_sink!(crate::api::backup_run::BackupRun);
bridge_sink!(crate::api::backup_run::DisplayBackupState);
bridge_sink!(crate::api::recovery::EnterPhysicalBackupState);
bridge_sink!(crate::api::recovery::WaitForSingleDeviceState);
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/rust/src/api/bitcoin.rs | frostsnapp/rust/src/api/bitcoin.rs | pub use bitcoin::Transaction as RTransaction;
pub use bitcoin::{
psbt::Error as PsbtError, Address, Network as BitcoinNetwork, OutPoint, Psbt, ScriptBuf, TxOut,
Txid,
};
use flutter_rust_bridge::frb; // or, for example, easy_ext's;
use frostsnap_coordinator::bitcoin::chain_sync::{
default_backup_electrum_server, default_electrum_server, SUPPORTED_NETWORKS,
};
pub use frostsnap_coordinator::bitcoin::wallet::ConfirmationTime;
pub use frostsnap_coordinator::frostsnap_core::{self, MasterAppkey};
use frostsnap_core::bitcoin_transaction::TransactionTemplate;
use frostsnap_core::message::EncodedSignature;
use tracing::{event, Level};
use std::collections::HashMap;
use std::collections::HashSet;
use std::ops::Deref;
use std::{
path::{Path, PathBuf},
str::FromStr,
};
use super::super_wallet::TxState;
// Teach FRB where to get `Network`
#[frb(mirror(BitcoinNetwork))]
enum _BitcoinNetwork {
/// Mainnet Bitcoin.
Bitcoin,
/// Bitcoin's testnet network. (In future versions this will be combined
/// into a single variant containing the version)
Testnet,
/// Bitcoin's testnet4 network. (In future versions this will be combined
/// into a single variant containing the version)
Testnet4,
/// Bitcoin's signet network.
Signet,
/// Bitcoin's regtest network.
Regtest,
}
#[derive(Debug, Clone)]
#[frb(type_64bit_int)]
pub struct SendToRecipient {
pub address: Address,
pub amount: Option<u64>,
}
pub trait BitcoinNetworkExt {
#[frb(sync)]
fn name(&self) -> String;
#[frb(sync)]
fn is_mainnet(&self) -> bool;
#[frb(sync)]
fn descriptor_for_key(&self, master_appkey: MasterAppkey) -> String;
#[frb(sync)]
fn from_string(string: String) -> Option<BitcoinNetwork>;
#[frb(sync)]
fn validate_destination_address(&self, uri: &str) -> Result<SendToRecipient, String>;
#[frb(sync)]
fn default_electrum_server(&self) -> String;
#[frb(sync)]
fn default_backup_electrum_server(&self) -> String;
#[frb(ignore)]
fn bdk_file(&self, app_dir: impl AsRef<Path>) -> PathBuf;
#[frb(sync)]
fn validate_amount(&self, address: &str, value: u64) -> Option<String>;
#[frb(sync)]
fn supported_networks() -> Vec<BitcoinNetwork>;
}
impl BitcoinNetworkExt for BitcoinNetwork {
#[frb(sync)]
fn from_string(string: String) -> Option<BitcoinNetwork> {
BitcoinNetwork::from_str(&string).ok()
}
#[frb(sync)]
fn name(&self) -> String {
(*self).to_string()
}
#[frb(sync)]
fn is_mainnet(&self) -> bool {
bitcoin::NetworkKind::from(*self).is_mainnet()
}
#[frb(sync)]
fn descriptor_for_key(&self, master_appkey: MasterAppkey) -> String {
let descriptor = frostsnap_coordinator::bitcoin::multi_x_descriptor_for_account(
master_appkey,
frostsnap_core::tweak::BitcoinAccount::default(),
(*self).into(),
);
descriptor.to_string()
}
#[frb(sync)]
fn validate_destination_address(&self, uri: &str) -> Result<SendToRecipient, String> {
let uri = uri.trim();
// Try parsing as BIP21 URI first
if let Ok(parsed) = uri.parse::<bip21::Uri<bitcoin::address::NetworkUnchecked>>() {
let amount = parsed.amount.map(|amt| amt.to_sat());
let address = parsed
.address
.require_network(*self)
.map_err(|e| format!("Wrong network: {}", e))?;
Ok(SendToRecipient { address, amount })
} else {
// Not a URI -- try as plain address
let address = bitcoin::Address::from_str(uri)
// Rust-bitcoin ParseError is generally inappropriate "legacy address base58 string"
.map_err(|_| "Invalid address".to_string())?
.require_network(*self)
.map_err(|e| format!("Wrong network: {}", e))?;
Ok(SendToRecipient {
address,
amount: None,
})
}
}
#[frb(sync)]
fn default_electrum_server(&self) -> String {
default_electrum_server(*self).to_string()
}
#[frb(sync)]
fn default_backup_electrum_server(&self) -> String {
default_backup_electrum_server(*self).to_string()
}
#[frb(ignore)]
fn bdk_file(&self, app_dir: impl AsRef<Path>) -> PathBuf {
app_dir.as_ref().join(format!("wallet-{}.sql", self))
}
#[frb(sync)]
fn supported_networks() -> Vec<BitcoinNetwork> {
SUPPORTED_NETWORKS.into_iter().collect()
}
// FIXME: doesn't need to be on the network. Can get the script pubkey without the network.
#[frb(sync)]
fn validate_amount(&self, address: &str, value: u64) -> Option<String> {
match bitcoin::Address::from_str(address) {
Ok(address) => match address.require_network(*self) {
Ok(address) => {
let dust_value = address.script_pubkey().minimal_non_dust().to_sat();
if value < dust_value {
event!(
Level::DEBUG,
value = value,
dust_value = dust_value,
"address validation rejected"
);
Some(format!("Too small to send. Must be at least {dust_value}"))
} else {
None
}
}
Err(_e) => None,
},
Err(_e) => None,
}
}
}
#[derive(Debug, Clone)]
#[frb(type_64bit_int)]
pub struct Transaction {
pub inner: RTransaction,
pub txid: String,
pub confirmation_time: Option<ConfirmationTime>,
pub last_seen: Option<u64>,
pub prevouts: HashMap<bitcoin::OutPoint, bitcoin::TxOut>,
pub is_mine: HashSet<bitcoin::ScriptBuf>,
}
impl Transaction {
pub(crate) fn from_template(tx_temp: &TransactionTemplate) -> Self {
let raw_tx = tx_temp.to_rust_bitcoin_tx();
let txid = tx_temp.txid();
let is_mine = tx_temp
.iter_locally_owned_inputs()
.map(|(_, _, spk)| spk.spk())
.chain(
tx_temp
.iter_locally_owned_outputs()
.map(|(_, _, spk)| spk.spk()),
)
.collect::<HashSet<_>>();
let prevouts = tx_temp
.inputs()
.iter()
.map(|input| (input.outpoint(), input.txout()))
.collect::<HashMap<bitcoin::OutPoint, bitcoin::TxOut>>();
Self {
inner: raw_tx,
txid: txid.to_string(),
confirmation_time: None,
last_seen: None,
prevouts,
is_mine,
}
}
pub(crate) fn fill_signatures(&mut self, signatures: &[EncodedSignature]) {
for (txin, signature) in self.inner.input.iter_mut().zip(signatures) {
let schnorr_sig = bitcoin::taproot::Signature {
signature: bitcoin::secp256k1::schnorr::Signature::from_slice(&signature.0)
.unwrap(),
sighash_type: bitcoin::sighash::TapSighashType::Default,
};
let witness = bitcoin::Witness::from_slice(&[schnorr_sig.to_vec()]);
txin.witness = witness;
}
}
#[frb(sync)]
pub fn raw_txid(&self) -> Txid {
self.inner.compute_txid()
}
fn owned_input_indices(&self) -> impl Iterator<Item = usize> + '_ {
self.inner
.input
.iter()
.enumerate()
.filter(|(_, txin)| {
let prev_txout = match self.prevouts.get(&txin.previous_output) {
Some(txout) => txout,
None => return false,
};
self.is_mine.contains(&prev_txout.script_pubkey)
})
.map(|(vin, _)| vin)
}
#[frb(sync)]
pub fn attach_signatures_to_psbt(
&self,
signatures: Vec<EncodedSignature>,
psbt: &Psbt,
) -> Option<Psbt> {
let owned_indices = self.owned_input_indices().collect::<Vec<_>>();
if signatures.len() != owned_indices.len() {
return None;
}
let mut psbt = psbt.clone();
let mut signatures = signatures.into_iter();
for i in owned_indices {
let signature = signatures.next();
// we are assuming the signatures are correct here.
let input = &mut psbt.inputs[i];
let schnorr_sig = bitcoin::taproot::Signature {
signature: bitcoin::secp256k1::schnorr::Signature::from_slice(
&signature.unwrap().0,
)
.unwrap(),
sighash_type: bitcoin::sighash::TapSighashType::Default,
};
input.tap_key_sig = Some(schnorr_sig);
}
Some(psbt)
}
/// Computes the sum of all inputs, or only those whose previous output script pubkey is in
/// `filter`, if provided. The result is `None` if any input is missing a previous output.
fn _sum_inputs(&self, filter: Option<&HashSet<bitcoin::ScriptBuf>>) -> Option<u64> {
let prevouts = self
.inner
.input
.iter()
.map(|txin| self.prevouts.get(&txin.previous_output))
.collect::<Option<Vec<_>>>()?;
Some(
prevouts
.into_iter()
.filter(|prevout| {
match &filter {
Some(filter) => filter.contains(prevout.script_pubkey.as_script()),
// No filter.
None => true,
}
})
.map(|prevout| prevout.value.to_sat())
.sum(),
)
}
/// Computes the sum of all outputs, or only those whose script pubkey is in `filter`, if
/// provided.
fn _sum_outputs(&self, filter: Option<&HashSet<bitcoin::ScriptBuf>>) -> u64 {
self.inner
.output
.iter()
.filter(|txout| {
match &filter {
Some(filter) => filter.contains(txout.script_pubkey.as_script()),
// No filter.
None => true,
}
})
.map(|txout| txout.value.to_sat())
.sum()
}
/// Computes the total value of all inputs. Returns `None` if any input is missing a previous
/// output.
#[frb(sync, type_64bit_int)]
pub fn sum_inputs(&self) -> Option<u64> {
self._sum_inputs(None)
}
/// Computes the sum of all outputs.
#[frb(sync, type_64bit_int)]
pub fn sum_outputs(&self) -> u64 {
self._sum_outputs(None)
}
/// Computes the total value of inputs we own. Returns `None` if any owned input is missing a
/// previous output.
#[frb(sync, type_64bit_int)]
pub fn sum_owned_inputs(&self) -> Option<u64> {
self._sum_inputs(Some(&self.is_mine))
}
/// Computes the total value of outputs we own.
#[frb(sync, type_64bit_int)]
pub fn sum_owned_outputs(&self) -> u64 {
self._sum_outputs(Some(&self.is_mine))
}
/// Computes the total value of inputs that spend a previous output with the given `spk`.
///
/// Returns `None` if any input is missing a previous output.
#[frb(sync, type_64bit_int)]
pub fn sum_inputs_spending_spk(&self, spk: &bitcoin::ScriptBuf) -> Option<u64> {
self._sum_inputs(Some(&[spk.as_script().to_owned()].into()))
}
/// Computes the total value of outputs that send to the given script pubkey.
#[frb(sync, type_64bit_int)]
pub fn sum_outputs_to_spk(&self, spk: &bitcoin::ScriptBuf) -> u64 {
self._sum_outputs(Some(&[spk.as_script().to_owned()].into()))
}
/// Computes the net change in our owned balance: owned outputs minus owned inputs.
///
/// Returns `None` if any owned input is missing a previous output.
#[frb(sync, type_64bit_int)]
pub fn balance_delta(&self) -> Option<i64> {
let owned_inputs_sum: i64 = self
._sum_inputs(Some(&self.is_mine))?
.try_into()
.expect("net spent value must convert to i64");
let owned_outputs_sum: i64 = self
._sum_outputs(Some(&self.is_mine))
.try_into()
.expect("net created value must convert to i64");
Some(owned_outputs_sum.saturating_sub(owned_inputs_sum))
}
/// Computes the transaction fee as the difference between total input and output value.
/// Returns `None` if any input is missing a previous output.
#[frb(sync, type_64bit_int)]
pub fn fee(&self) -> Option<u64> {
let inputs_sum = self._sum_inputs(None)?;
let outputs_sum = self._sum_outputs(None);
Some(inputs_sum.saturating_sub(outputs_sum))
}
#[frb(sync, type_64bit_int)]
pub fn timestamp(&self) -> Option<u64> {
self.confirmation_time
.as_ref()
.map(|t| t.time)
.or(self.last_seen)
}
/// Feerate in sats/vbyte.
#[frb(sync)]
pub fn feerate(&self) -> Option<f64> {
Some(((self.fee()?) as f64) / (self.inner.vsize() as f64))
}
#[frb(sync)]
pub fn recipients(&self) -> Vec<TxOutInfo> {
self.inner
.output
.iter()
.zip(0_u32..)
.map(|(txout, vout)| TxOutInfo {
vout,
amount: txout.value.to_sat(),
script_pubkey: txout.script_pubkey.clone(),
is_mine: self.is_mine.contains(&txout.script_pubkey),
})
.collect()
}
/// Return a transaction with the following signatures added.
pub fn with_signatures(&self, signatures: Vec<EncodedSignature>) -> RTransaction {
let mut tx = self.inner.clone();
for (txin, signature) in tx.input.iter_mut().zip(signatures) {
let schnorr_sig = bitcoin::taproot::Signature {
signature: bitcoin::secp256k1::schnorr::Signature::from_slice(&signature.0)
.unwrap(),
sighash_type: bitcoin::sighash::TapSighashType::Default,
};
let witness = bitcoin::Witness::from_slice(&[schnorr_sig.to_vec()]);
txin.witness = witness;
}
tx
}
}
#[derive(Debug, Clone)]
#[frb(type_64bit_int)]
pub struct TxOutInfo {
pub vout: u32,
pub amount: u64,
pub script_pubkey: bitcoin::ScriptBuf,
pub is_mine: bool,
}
impl TxOutInfo {
#[frb(sync)]
pub fn address(&self, network: BitcoinNetwork) -> Option<bitcoin::Address> {
bitcoin::Address::from_script(&self.script_pubkey, network).ok()
}
}
#[frb(mirror(OutPoint), unignore)]
pub struct _OutPoint {
/// The referenced transaction's txid.
pub txid: Txid,
/// The index of the referenced output in its transaction's vout.
pub vout: u32,
}
#[frb(mirror(ConfirmationTime, unignore))]
pub struct _ConfirmationTime {
pub height: u32,
pub time: u64,
}
impl From<Vec<frostsnap_coordinator::bitcoin::wallet::Transaction>> for TxState {
fn from(txs: Vec<frostsnap_coordinator::bitcoin::wallet::Transaction>) -> Self {
let txs = txs
.into_iter()
.map(From::from)
.collect::<Vec<Transaction>>();
let mut balance = 0_i64;
let mut untrusted_pending_balance = 0_i64;
for tx in &txs {
let filter = Some(&tx.is_mine);
let net_spent: i64 = tx
._sum_inputs(filter)
.unwrap_or(0)
.try_into()
.expect("spent value must fit into i64");
let net_created: i64 = tx
._sum_outputs(filter)
.try_into()
.expect("created value must fit into i64");
if net_spent == 0 && tx.confirmation_time.is_none() {
untrusted_pending_balance += net_created;
} else {
balance += net_created;
balance -= net_spent;
}
}
// Workaround as we are too lazy to exclude spends from unconfirmed as
// `untrusted_pending_balance`.
if balance < 0 {
untrusted_pending_balance += balance;
balance = 0;
}
Self {
balance,
untrusted_pending_balance,
txs,
}
}
}
impl From<frostsnap_coordinator::bitcoin::wallet::Transaction> for Transaction {
fn from(value: frostsnap_coordinator::bitcoin::wallet::Transaction) -> Self {
Self {
inner: (value.inner).deref().clone(),
txid: value.txid.to_string(),
confirmation_time: value.confirmation_time,
last_seen: value.last_seen,
prevouts: value.prevouts,
is_mine: value.is_mine,
}
}
}
#[frb(mirror(Address), opaque)]
pub struct _Address {}
pub trait AddressExt {
#[frb(sync)]
fn spk(&self) -> ScriptBuf;
#[frb(sync, type_64bit_int)]
fn bip21_uri(&self, amount: Option<u64>, label: Option<String>) -> String;
#[frb(sync)]
fn from_string(s: &str, network: &BitcoinNetwork) -> Option<Address>;
}
#[frb(external)]
impl Address {
#[frb(sync)]
pub fn to_string(&self) -> String {}
}
impl AddressExt for bitcoin::Address {
#[frb(sync)]
fn spk(&self) -> ScriptBuf {
self.script_pubkey()
}
#[frb(sync, type_64bit_int)]
fn bip21_uri(&self, amount: Option<u64>, label: Option<String>) -> String {
let mut uri = bip21::Uri::new(self.clone());
if let Some(sats) = amount {
uri.amount = Some(bitcoin::Amount::from_sat(sats));
}
if let Some(label_str) = label {
uri.label = Some(label_str.into());
}
uri.to_string()
}
#[frb(sync)]
fn from_string(s: &str, network: &BitcoinNetwork) -> Option<Self> {
Address::from_str(s).ok()?.require_network(*network).ok()
}
}
#[frb(external)]
impl Psbt {
#[frb(sync)]
pub fn serialize(&self) -> Vec<u8> {}
#[frb(sync)]
#[allow(unused)]
pub fn deserialize(bytes: &[u8]) -> Result<Psbt, PsbtError> {}
}
#[frb(sync)]
pub fn compute_txid_of_psbt(psbt: &Psbt) -> Txid {
psbt.unsigned_tx.compute_txid()
}
#[frb(sync)]
pub fn txid_hex_string(txid: &Txid) -> String {
txid.to_string()
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/rust/src/api/settings.rs | frostsnapp/rust/src/api/settings.rs | use anyhow::{anyhow, Result};
use bitcoin::constants::genesis_block;
use bitcoin::Network as BitcoinNetwork;
use flutter_rust_bridge::frb;
use frostsnap_coordinator::bitcoin::chain_sync::{ChainClient, SUPPORTED_NETWORKS};
pub use frostsnap_coordinator::bitcoin::chain_sync::{
ChainStatus, ChainStatusState, ConnectionResult,
};
pub use frostsnap_coordinator::bitcoin::tofu::verifier::UntrustedCertificate;
use frostsnap_coordinator::persist::Persisted;
pub use frostsnap_coordinator::settings::ElectrumEnabled;
use frostsnap_coordinator::settings::Settings as RSettings;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::thread;
use crate::frb_generated::StreamSink;
use crate::sink_wrap::SinkWrap;
use super::super_wallet::SuperWallet;
#[frb(opaque)]
pub struct Settings {
settings: Persisted<RSettings>,
db: Arc<Mutex<rusqlite::Connection>>,
chain_clients: HashMap<BitcoinNetwork, ChainClient>,
#[allow(unused)]
app_directory: PathBuf,
loaded_wallets: HashMap<BitcoinNetwork, SuperWallet>,
developer_settings_stream: Option<StreamSink<DeveloperSettings>>,
display_settings_stream: Option<StreamSink<DisplaySettings>>,
electrum_settings_stream: Option<StreamSink<ElectrumSettings>>,
}
macro_rules! settings_impl {
($stream_name:ident, $stream_emit_name:ident, $stream_sub:ident, $type_name:ident) => {
pub fn $stream_sub(&mut self, stream: StreamSink<$type_name>) -> Result<()> {
self.$stream_name.replace(stream);
self.$stream_emit_name();
Ok(())
}
fn $stream_emit_name(&self) {
if let Some(stream) = &self.$stream_name {
stream
.add(<$type_name>::from_settings(&self.settings))
.unwrap();
}
}
};
}
impl Settings {
pub(crate) fn new(
db: Arc<Mutex<rusqlite::Connection>>,
app_directory: PathBuf,
) -> anyhow::Result<Self> {
let persisted: Persisted<RSettings> = {
let mut db_ = db.lock().unwrap();
Persisted::new(&mut *db_, ())?
};
let mut loaded_wallets: HashMap<BitcoinNetwork, SuperWallet> = Default::default();
let mut chain_apis = HashMap::new();
for network in SUPPORTED_NETWORKS {
let electrum_url = persisted.get_electrum_server(network);
let backup_electrum_url = persisted.get_backup_electrum_server(network);
let genesis_hash = genesis_block(bitcoin::params::Params::new(network)).block_hash();
// Load trusted certificates for this network from the database
let trusted_certificates = {
let mut db_ = db.lock().unwrap();
use frostsnap_coordinator::bitcoin::tofu::trusted_certs::TrustedCertificates;
use frostsnap_coordinator::persist::Persisted;
Persisted::<TrustedCertificates>::new(&mut *db_, network)?
};
let (chain_api, conn_handler) =
ChainClient::new(genesis_hash, trusted_certificates, db.clone());
let super_wallet =
SuperWallet::load_or_new(&app_directory, network, chain_api.clone())?;
// FIXME: the dependency relationship here is overly convoluted.
thread::spawn({
let super_wallet = super_wallet.clone();
move || {
conn_handler.run(
electrum_url,
backup_electrum_url,
super_wallet.inner.clone(),
{
let wallet_streams = super_wallet.wallet_streams.clone();
move |master_appkey, txs| {
let wallet_streams = wallet_streams.lock().unwrap();
if let Some(stream) = wallet_streams.get(&master_appkey) {
if let Err(err) = stream.add(txs.into()) {
tracing::error!(
{
master_appkey = master_appkey.to_redacted_string(),
err = err.to_string(),
},
"Failed to add txs to stream"
);
}
}
}
},
)
}
});
loaded_wallets.insert(network, super_wallet);
chain_apis.insert(network, chain_api);
}
Ok(Self {
loaded_wallets,
settings: persisted,
app_directory,
chain_clients: chain_apis,
developer_settings_stream: Default::default(),
display_settings_stream: Default::default(),
electrum_settings_stream: Default::default(),
db,
})
}
settings_impl!(
developer_settings_stream,
emit_developer_settings,
sub_developer_settings,
DeveloperSettings
);
settings_impl!(
display_settings_stream,
emit_display_settings,
sub_display_settings,
DisplaySettings
);
settings_impl!(
electrum_settings_stream,
emit_electrum_settings,
sub_electrum_settings,
ElectrumSettings
);
#[frb(sync)]
pub fn get_super_wallet(&self, network: BitcoinNetwork) -> Result<SuperWallet> {
self.loaded_wallets
.get(&network)
.cloned()
.ok_or(anyhow!("unsupported network {:?}", network))
}
pub fn set_developer_mode(&mut self, value: bool) -> Result<()> {
let mut db = self.db.lock().unwrap();
self.settings.mutate2(&mut *db, |settings, update| {
settings.set_developer_mode(value, update);
Ok(())
})?;
self.emit_developer_settings();
Ok(())
}
#[frb(sync)]
pub fn is_in_developer_mode(&self) -> bool {
self.settings.developer_mode
}
pub fn set_hide_balance(&mut self, value: bool) -> Result<()> {
let mut db = self.db.lock().unwrap();
self.settings.mutate2(&mut *db, |settings, update| {
settings.set_hide_balance(value, update);
Ok(())
})?;
self.emit_display_settings();
Ok(())
}
#[frb(sync)]
pub fn hide_balance(&self) -> bool {
self.settings.hide_balance
}
pub fn check_and_set_electrum_server(
&mut self,
network: BitcoinNetwork,
url: String,
is_backup: bool,
) -> Result<ConnectionResult> {
let chain_api = self
.chain_clients
.get(&network)
.ok_or_else(|| anyhow!("network not supported {}", network))?;
match chain_api.check_and_set_electrum_server_url(url.clone(), is_backup)? {
ConnectionResult::Success => {
// Connection succeeded, persist the setting
let mut db = self.db.lock().unwrap();
self.settings.mutate2(&mut *db, |settings, update| {
if is_backup {
settings.set_backup_electrum_server(network, url, update);
} else {
settings.set_electrum_server(network, url, update);
}
Ok(())
})?;
self.emit_electrum_settings();
Ok(ConnectionResult::Success)
}
result => {
// Return TOFU prompt or failure without persisting
Ok(result)
}
}
}
pub fn accept_certificate_and_retry(
&mut self,
network: BitcoinNetwork,
server_url: String,
certificate: Vec<u8>,
is_backup: bool,
) -> Result<ConnectionResult> {
// Use message-passing to trust the certificate
let chain_api = self
.chain_clients
.get(&network)
.ok_or_else(|| anyhow!("network not supported {}", network))?;
// Send the trust certificate message - the backend will handle persistence
chain_api.trust_certificate(server_url.clone(), certificate);
// Retry connection now that we've trusted the certificate
self.check_and_set_electrum_server(network, server_url, is_backup)
}
pub fn subscribe_chain_status(
&self,
network: BitcoinNetwork,
sink: StreamSink<ChainStatus>,
) -> Result<()> {
let chain_api = self
.chain_clients
.get(&network)
.ok_or_else(|| anyhow!("network not supported {}", network))?;
chain_api.set_status_sink(Box::new(SinkWrap(sink)));
Ok(())
}
pub fn set_electrum_servers(
&mut self,
network: BitcoinNetwork,
primary: String,
backup: String,
) -> Result<()> {
let mut db = self.db.lock().unwrap();
self.settings.mutate2(&mut *db, |settings, update| {
settings.set_electrum_server(network, primary.clone(), update);
settings.set_backup_electrum_server(network, backup.clone(), update);
Ok(())
})?;
let chain_api = self
.chain_clients
.get(&network)
.ok_or_else(|| anyhow!("network not supported {}", network))?;
chain_api.set_urls(primary, backup);
self.emit_electrum_settings();
Ok(())
}
pub fn set_electrum_enabled(
&mut self,
network: BitcoinNetwork,
enabled: ElectrumEnabled,
) -> Result<()> {
let mut db = self.db.lock().unwrap();
self.settings.mutate2(&mut *db, |settings, update| {
settings.set_electrum_enabled(network, enabled, update);
Ok(())
})?;
let chain_api = self
.chain_clients
.get(&network)
.ok_or_else(|| anyhow!("network not supported {}", network))?;
chain_api.set_enabled(enabled);
self.emit_electrum_settings();
Ok(())
}
pub fn connect_to(&self, network: BitcoinNetwork, use_backup: bool) -> Result<()> {
let chain_api = self
.chain_clients
.get(&network)
.ok_or_else(|| anyhow!("network not supported {}", network))?;
chain_api.connect_to(use_backup);
Ok(())
}
}
pub struct DeveloperSettings {
pub developer_mode: bool,
}
impl DeveloperSettings {
fn from_settings(settings: &RSettings) -> Self {
DeveloperSettings {
developer_mode: settings.developer_mode,
}
}
}
pub struct DisplaySettings {
pub hide_balance: bool,
}
impl DisplaySettings {
fn from_settings(settings: &RSettings) -> Self {
DisplaySettings {
hide_balance: settings.hide_balance,
}
}
}
pub struct ElectrumServer {
pub network: BitcoinNetwork,
pub url: String,
pub backup_url: String,
pub enabled: ElectrumEnabled,
}
pub struct ElectrumSettings {
pub electrum_servers: Vec<ElectrumServer>,
}
impl ElectrumSettings {
fn from_settings(settings: &RSettings) -> Self {
let electrum_servers = SUPPORTED_NETWORKS
.into_iter()
.map(|network| {
let url = settings.get_electrum_server(network);
let backup_url = settings.get_backup_electrum_server(network);
let enabled = settings.get_electrum_enabled(network);
ElectrumServer {
network,
url,
backup_url,
enabled,
}
})
.collect::<Vec<_>>();
ElectrumSettings { electrum_servers }
}
}
#[frb(mirror(ChainStatus))]
pub struct _ChainStatus {
pub primary_url: String,
pub backup_url: String,
pub on_backup: bool,
pub state: ChainStatusState,
}
#[frb(mirror(ChainStatusState))]
pub enum _ChainStatusState {
Idle,
Connecting,
Connected,
Disconnected,
}
#[frb(mirror(ConnectionResult))]
pub enum _ConnectionResult {
Success,
CertificatePromptNeeded(UntrustedCertificate),
Failed(String),
}
#[frb(mirror(UntrustedCertificate))]
pub struct _UntrustedCertificate {
pub fingerprint: String,
pub server_url: String,
pub is_changed: bool,
pub old_fingerprint: Option<String>,
pub certificate_der: Vec<u8>,
pub valid_for_names: Option<Vec<String>>,
}
#[frb(mirror(ElectrumEnabled))]
pub enum _ElectrumEnabled {
All,
PrimaryOnly,
None,
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/rust/src/api/keygen.rs | frostsnapp/rust/src/api/keygen.rs | use crate::{frb_generated::StreamSink, sink_wrap::SinkWrap};
use anyhow::Result;
use bitcoin::Network as BitcoinNetwork;
use flutter_rust_bridge::frb;
pub use frostsnap_coordinator::keygen::KeyGenState;
use frostsnap_core::{
device::KeyPurpose, AccessStructureRef, DeviceId, KeygenId, SessionHash, SymmetricKey,
};
#[frb(mirror(KeyGenState), unignore)]
pub struct _KeyGenState {
pub threshold: usize,
pub devices: Vec<DeviceId>, // not a set for frb compat
pub got_shares: Vec<DeviceId>,
pub all_shares: bool,
pub session_acks: Vec<DeviceId>,
pub all_acks: bool,
pub session_hash: Option<SessionHash>,
pub finished: Option<AccessStructureRef>,
pub aborted: Option<String>,
pub keygen_id: KeygenId,
}
impl super::coordinator::Coordinator {
pub fn generate_new_key(
&self,
threshold: u16,
devices: Vec<DeviceId>,
key_name: String,
network: BitcoinNetwork,
event_stream: StreamSink<KeyGenState>,
) -> Result<()> {
self.0.generate_new_key(
devices,
threshold,
key_name,
KeyPurpose::Bitcoin(network),
SinkWrap(event_stream),
)
}
pub fn finalize_keygen(
&self,
keygen_id: KeygenId,
encryption_key: SymmetricKey,
) -> Result<AccessStructureRef> {
self.0.finalize_keygen(keygen_id, encryption_key)
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/rust/src/api/broadcast.rs | frostsnapp/rust/src/api/broadcast.rs | use std::{
collections::BTreeMap,
sync::{
atomic::{AtomicBool, AtomicU32},
Arc, RwLock,
},
};
use flutter_rust_bridge::frb;
use tracing::Level;
use crate::frb_generated::{SseEncode, StreamSink};
/// A broadcast stream that can be managed from rust.
#[derive(Default, Clone)]
pub struct Broadcast<T> {
next_id: Arc<AtomicU32>,
inner: Arc<RwLock<BroadcastInner<T>>>,
}
#[derive(Default)]
struct BroadcastInner<T> {
subscriptions: BTreeMap<u32, StreamSink<T>>,
}
impl<T: SseEncode + Clone> Broadcast<T> {
#[frb(sync)]
pub fn subscribe(&self) -> BroadcastSubscription<T> {
let id = self
.next_id
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
BroadcastSubscription {
id,
is_running: Arc::new(AtomicBool::new(false)),
inner: Arc::clone(&self.inner),
}
}
#[frb(sync)]
pub fn add(&self, data: &T) {
let inner = self.inner.read().unwrap();
for (id, sink) in &inner.subscriptions {
if sink.add(data.clone()).is_err() {
tracing::event!(Level::ERROR, id, "Failed to add to sink");
}
}
}
}
#[derive(Clone)]
pub struct BroadcastSubscription<T> {
id: u32,
is_running: Arc<AtomicBool>,
inner: Arc<RwLock<BroadcastInner<T>>>,
}
#[derive(Debug, Copy, Clone)]
pub enum StartError {
/// Occurs when `BroadcastSubscription` is already started.
AlreadyRunning,
}
impl<T> BroadcastSubscription<T> {
fn _id(&self) -> u32 {
self.id
}
fn _is_running(&self) -> bool {
self.is_running.load(std::sync::atomic::Ordering::Relaxed)
}
/// Errors when the subscription is already started.
fn _start(&self, sink: StreamSink<T>) -> Result<(), StartError> {
use std::sync::atomic::Ordering;
if self
.is_running
.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
.is_err()
{
return Err(StartError::AlreadyRunning);
}
let mut inner = self.inner.write().unwrap();
inner.subscriptions.insert(self.id, sink);
Ok(())
}
fn _stop(&self) -> bool {
use std::sync::atomic::Ordering;
if self
.is_running
.compare_exchange(true, false, Ordering::Release, Ordering::Relaxed)
.is_ok()
{
let mut inner = self.inner.write().unwrap();
inner.subscriptions.remove(&self.id);
true
} else {
false
}
}
}
impl<T> Drop for BroadcastSubscription<T> {
fn drop(&mut self) {
self._stop();
}
}
pub struct UnitBroadcastSubscription(pub(crate) BroadcastSubscription<()>);
impl UnitBroadcastSubscription {
#[frb(sync)]
pub fn id(&self) -> u32 {
self.0._id()
}
#[frb(sync)]
pub fn is_running(&self) -> bool {
self.0._is_running()
}
#[frb(sync)]
pub fn start(&self, sink: StreamSink<()>) -> Result<(), StartError> {
self.0._start(sink)
}
#[frb(sync)]
pub fn stop(&self) -> bool {
self.0._stop()
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/rust/src/api/log.rs | frostsnapp/rust/src/api/log.rs | use flutter_rust_bridge::frb;
use tracing::{event, Level};
#[frb(sync)]
pub fn log(level: LogLevel, message: String) {
match level {
LogLevel::Debug => event!(Level::DEBUG, "[dart] {}", message),
LogLevel::Info => event!(Level::INFO, "[dart] {}", message),
LogLevel::Error => event!(Level::ERROR, "[dart] {}", message),
}
}
pub enum LogLevel {
Debug,
Info,
Error,
}
impl From<LogLevel> for tracing::Level {
fn from(value: LogLevel) -> Self {
match value {
LogLevel::Info => tracing::Level::INFO,
LogLevel::Debug => tracing::Level::DEBUG,
LogLevel::Error => tracing::Level::ERROR,
}
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/rust/src/api/nonce_replenish.rs | frostsnapp/rust/src/api/nonce_replenish.rs | use std::collections::HashSet;
use crate::{frb_generated::StreamSink, sink_wrap::SinkWrap};
use anyhow::Result;
use flutter_rust_bridge::frb;
pub use frostsnap_coordinator::nonce_replenish::NonceReplenishState;
use frostsnap_core::{coordinator::NonceReplenishRequest, DeviceId};
#[frb(mirror(NonceReplenishState), unignore)]
pub struct _NonceReplenishState {
pub devices: HashSet<DeviceId>,
pub completed_streams: u32,
pub total_streams: u32,
pub abort: bool,
}
#[frb(external)]
impl NonceReplenishState {
#[frb(sync)]
pub fn is_finished(&self) -> bool {}
}
impl super::coordinator::Coordinator {
#[frb(sync)]
pub fn create_nonce_request(&self, devices: Vec<DeviceId>) -> NonceRequest {
NonceRequest {
inner: self
.0
.nonce_replenish_request(devices.into_iter().collect()),
}
}
pub fn replenish_nonces(
&self,
nonce_request: NonceRequest,
devices: Vec<DeviceId>,
event_stream: StreamSink<NonceReplenishState>,
) -> Result<()> {
self.0.replenish_nonces(
nonce_request.inner,
devices.into_iter().collect(),
SinkWrap(event_stream),
)
}
}
pub struct NonceRequest {
inner: NonceReplenishRequest,
}
impl NonceRequest {
#[frb(sync)]
pub fn some_nonces_requested(&self) -> bool {
self.inner.some_nonces_requested()
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/rust/src/api/device_list.rs | frostsnapp/rust/src/api/device_list.rs | pub use crate::api::firmware::{FirmwareUpgradeEligibility, FirmwareVersion};
use anyhow::Result;
use flutter_rust_bridge::frb;
use frostsnap_coordinator::DeviceMode;
use frostsnap_core::DeviceId;
use crate::{frb_generated::StreamSink, sink_wrap::SinkWrap};
#[derive(Clone, Debug)]
pub enum DeviceListChangeKind {
Added,
Removed,
Named,
RecoveryMode,
}
#[derive(Clone, Debug)]
pub struct DeviceListChange {
pub kind: DeviceListChangeKind,
pub index: u32,
pub device: ConnectedDevice,
}
#[derive(Clone, Debug)]
pub struct DeviceListUpdate {
pub changes: Vec<DeviceListChange>,
pub state: DeviceListState,
}
#[derive(Clone, Debug)]
pub struct DeviceListState {
pub devices: Vec<ConnectedDevice>,
pub state_id: u32,
}
#[derive(Clone, Debug)]
pub struct ConnectedDevice {
pub name: Option<String>,
pub firmware: FirmwareVersion,
pub latest_firmware: Option<FirmwareVersion>,
pub id: DeviceId,
pub recovery_mode: bool,
}
impl ConnectedDevice {
#[frb(sync)]
pub fn ready(&self) -> bool {
self.name.is_some() && !self.needs_firmware_upgrade()
}
#[frb(sync)]
pub fn needs_firmware_upgrade(&self) -> bool {
!matches!(
self.firmware_upgrade_eligibility(),
FirmwareUpgradeEligibility::UpToDate
)
}
#[frb(sync)]
pub fn firmware_upgrade_eligibility(&self) -> FirmwareUpgradeEligibility {
let Some(latest_firmware) = &self.latest_firmware else {
return FirmwareUpgradeEligibility::CannotUpgrade {
reason: "No firmware available in app".to_string(),
};
};
latest_firmware.check_upgrade_eligibility(&self.firmware.digest)
}
#[frb(ignore)]
pub(crate) fn device_mode(&self) -> DeviceMode {
if self.name.is_none() {
DeviceMode::Blank
} else if self.recovery_mode {
DeviceMode::Recovery
} else {
DeviceMode::Ready
}
}
}
impl DeviceListState {
#[frb(sync)]
pub fn get_device(&self, id: DeviceId) -> Option<ConnectedDevice> {
self.devices.iter().find(|device| device.id == id).cloned()
}
}
impl super::coordinator::Coordinator {
#[frb(sync)]
pub fn device_at_index(&self, index: usize) -> Option<ConnectedDevice> {
self.0.device_at_index(index)
}
#[frb(sync)]
pub fn device_list_state(&self) -> DeviceListState {
self.0.device_list_state()
}
pub fn sub_device_events(&self, sink: StreamSink<DeviceListUpdate>) -> Result<()> {
self.0.sub_device_events(SinkWrap(sink));
Ok(())
}
#[frb(sync)]
pub fn get_connected_device(&self, id: DeviceId) -> Option<ConnectedDevice> {
self.0.get_connected_device(id)
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/rust/src/api/port.rs | frostsnapp/rust/src/api/port.rs | use crate::frb_generated::StreamSink;
use anyhow::{anyhow, Result};
use flutter_rust_bridge::frb;
pub use frostsnap_coordinator::PortDesc;
use frostsnap_coordinator::{PortOpenError, Serial, SerialPort};
pub use std::sync::mpsc::SyncSender;
pub use std::sync::{Arc, Mutex, RwLock};
use tracing::{event, Level};
#[frb(mirror(PortDesc))]
pub struct _PortDesc {
pub id: String,
pub vid: u16,
pub pid: u16,
}
#[derive(Debug)]
#[frb(opaque)]
pub struct PortOpen {
pub id: String,
ready: SyncSender<Result<i32, PortOpenError>>,
}
#[allow(dead_code)] // only used on android
#[derive(Clone, Default)]
#[frb(opaque)]
pub struct FfiSerial {
pub(crate) available_ports: Arc<Mutex<Vec<PortDesc>>>,
pub(crate) open_requests: Arc<Mutex<Option<StreamSink<PortOpen>>>>,
}
impl PortOpen {
pub fn satisfy(self, fd: i32, err: Option<String>) {
let result = match err {
Some(err) => Err(frostsnap_coordinator::PortOpenError::Other(err.into())),
None => Ok(fd),
};
let _ = self.ready.send(result);
}
}
impl FfiSerial {
pub fn set_available_ports(&self, ports: Vec<PortDesc>) {
event!(Level::INFO, "ports: {:?}", ports);
*self.available_ports.lock().unwrap() = ports
}
pub fn sub_open_requests(&mut self, sink: StreamSink<PortOpen>) {
if self.open_requests.lock().unwrap().replace(sink).is_some() {
event!(Level::WARN, "resubscribing to open requests");
}
}
}
// ========== Android implementation
impl Serial for FfiSerial {
fn available_ports(&self) -> Vec<PortDesc> {
self.available_ports.lock().unwrap().clone()
}
#[allow(unreachable_code, unused)]
fn open_device_port(&self, id: &str, baud_rate: u32) -> Result<SerialPort, PortOpenError> {
let (tx, rx) = std::sync::mpsc::sync_channel(0);
loop {
let open_requests = self.open_requests.lock().unwrap();
match &*open_requests {
Some(sink) => {
sink.add(PortOpen {
id: id.into(),
ready: tx,
})
.map_err(|e| PortOpenError::Other(anyhow!("sink error: {e}").into()))?;
break;
}
None => {
drop(open_requests);
event!(Level::WARN, "dart port open listener is not listening yet. blocking while waiting for it.");
std::thread::sleep(std::time::Duration::from_millis(100));
}
}
}
let raw_fd = rx.recv().map_err(|e| PortOpenError::Other(Box::new(e)))??;
if raw_fd < 0 {
return Err(PortOpenError::Other(
anyhow!("OS failed to open UBS device {id}: FD was < 0").into(),
));
}
#[cfg(any(target_os = "linux", target_os = "android"))]
{
use frostsnap_coordinator::cdc_acm_usb::CdcAcmSerial;
use std::os::fd::FromRawFd;
use std::os::fd::OwnedFd;
// SAFETY: on the host side (e.g. android) we've dup'd and detached this file
// descriptor. we're the only owner of it at the moment so it's fine for us to turn it
// into an `OwnedFd` which will close it when it's dropped.
let fd = unsafe { OwnedFd::from_raw_fd(raw_fd) };
let cdc_acm = CdcAcmSerial::new_auto(fd, id.to_string(), baud_rate)
.map_err(|e| PortOpenError::Other(e.into()))?;
return Ok(Box::new(cdc_acm));
}
panic!("Host handles serial not available on this operating system");
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/rust/src/api/psbt_manager.rs | frostsnapp/rust/src/api/psbt_manager.rs | use bitcoin::{Psbt, Txid};
use flutter_rust_bridge::frb;
use frostsnap_coordinator::{
bitcoin::psbt::{LoadSignSessionPsbtParams, SignSessionPsbt},
persist::Persisted,
};
use frostsnap_core::SignSessionId;
use std::sync::{Arc, Mutex};
#[frb(opaque)]
pub struct PsbtManager {
db: Arc<Mutex<rusqlite::Connection>>,
}
impl PsbtManager {
pub(crate) fn new(db: Arc<Mutex<rusqlite::Connection>>) -> Self {
Self { db }
}
#[frb(sync)]
pub fn with_ssid(&self, ssid: &SignSessionId) -> anyhow::Result<Option<Psbt>> {
let mut db = self.db.lock().unwrap();
let persisted_psbt = Persisted::<Option<SignSessionPsbt>>::new(
&mut db,
LoadSignSessionPsbtParams::Ssid(*ssid),
)?;
Ok(persisted_psbt
.as_ref()
.as_ref()
.map(|ss_psbt| ss_psbt.psbt.clone()))
}
#[frb(sync)]
pub fn with_txid(&self, txid: &Txid) -> anyhow::Result<Option<Psbt>> {
let mut db = self.db.lock().unwrap();
let persisted_psbt = Persisted::<Option<SignSessionPsbt>>::new(
&mut db,
LoadSignSessionPsbtParams::Txid(*txid),
)?;
Ok(persisted_psbt
.as_ref()
.as_ref()
.map(|ss_psbt| ss_psbt.psbt.clone()))
}
/// Assumes non-mutable txid.
#[frb(sync)]
pub fn insert(&self, ssid: &SignSessionId, psbt: &Psbt) -> anyhow::Result<()> {
let txid = psbt.unsigned_tx.compute_txid();
let mut db = self.db.lock().unwrap();
let mut persisted_psbt = Persisted::<Option<SignSessionPsbt>>::new(
&mut db,
LoadSignSessionPsbtParams::Ssid(*ssid),
)?;
persisted_psbt.mutate2(&mut db, |ss_psbt, update| {
*ss_psbt = Some(SignSessionPsbt {
ssid: *ssid,
txid,
psbt: psbt.clone(),
});
*update = ss_psbt.clone();
Ok(())
})
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/rust/src/api/mod.rs | frostsnapp/rust/src/api/mod.rs | pub mod backup_run;
pub mod bitcoin;
pub mod broadcast;
pub mod camera;
pub mod coordinator;
pub mod device_list;
pub mod firmware;
pub mod init;
pub mod keygen;
pub mod log;
pub mod name;
pub mod nonce_replenish;
pub mod port;
pub mod psbt_manager;
pub mod qr;
pub mod recovery;
pub mod settings;
pub mod signing;
pub mod super_wallet;
pub mod transaction;
use flutter_rust_bridge::frb;
use frostsnap_coordinator::frostsnap_core;
pub use frostsnap_core::{
device::KeyPurpose, message::EncodedSignature, AccessStructureId, AccessStructureRef, DeviceId,
KeyId, KeygenId, MasterAppkey, RestorationId, SessionHash, SignSessionId, SymmetricKey,
};
#[frb(mirror(KeygenId))]
pub struct _KeygenId(pub [u8; 16]);
#[frb(mirror(AccessStructureId))]
pub struct _AccessStructureId(pub [u8; 32]);
#[frb(mirror(DeviceId))]
pub struct _DeviceId(pub [u8; 33]);
#[frb(mirror(MasterAppkey))]
pub struct _MasterAppkey(pub [u8; 65]);
#[frb(mirror(KeyId))]
pub struct _KeyId(pub [u8; 32]);
#[frb(mirror(SessionHash))]
pub struct _SessionHash(pub [u8; 32]);
#[frb(mirror(EncodedSignature))]
pub struct _EncodedSignature(pub [u8; 64]);
#[frb(mirror(SignSessionId))]
pub struct _SignSessionId(pub [u8; 32]);
#[frb(mirror(AccessStructureRef))]
pub struct _AccessStructureRef {
pub key_id: KeyId,
pub access_structure_id: AccessStructureId,
}
#[frb(mirror(RestorationId))]
pub struct _RestorattionId([u8; 16]);
#[frb(mirror(SymmetricKey))]
pub struct _SymmetricKey(pub [u8; 32]);
pub struct Api {}
impl Api {}
#[frb(external)]
impl MasterAppkey {
#[frb(sync)]
pub fn key_id(&self) -> KeyId {}
}
use bitcoin::BitcoinNetwork;
#[frb(external)]
impl KeyPurpose {
#[frb(sync)]
pub fn bitcoin_network(&self) -> Option<BitcoinNetwork> {}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/rust/src/api/init.rs | frostsnapp/rust/src/api/init.rs | use super::{
coordinator::Coordinator, log::LogLevel, psbt_manager::PsbtManager, settings::Settings,
};
use crate::{
coordinator::FfiCoordinator,
frb_generated::{RustAutoOpaque, StreamSink},
};
use anyhow::{Context as _, Result};
use frostsnap_coordinator::{DesktopSerial, UsbSerialManager, ValidatedFirmwareBin};
use std::{
path::PathBuf,
str::FromStr,
sync::{Arc, Mutex},
};
use tracing::{event, Level};
use tracing_subscriber::filter::Targets;
use tracing_subscriber::{layer::SubscriberExt as _, util::SubscriberInitExt, Registry};
impl super::Api {
pub fn turn_logging_on(&self, level: LogLevel, log_stream: StreamSink<String>) -> Result<()> {
// Global default subscriber must only be set once.
if crate::logger::set_dart_logger(log_stream) {
let targets = Targets::new()
.with_target("nusb", Level::ERROR /* nusb makes spurious warnings */)
.with_target("bdk_electrum_streaming", Level::WARN)
.with_default(Level::from(level));
#[cfg(not(target_os = "android"))]
{
let fmt_layer = tracing_subscriber::fmt::layer().without_time().pretty();
Registry::default()
.with(targets.clone())
.with(fmt_layer)
.with(crate::logger::dart_logger())
.try_init()?;
}
#[cfg(target_os = "android")]
{
use tracing_logcat::{LogcatMakeWriter, LogcatTag};
use tracing_subscriber::{fmt::format::Format, layer::Layer};
let writer = LogcatMakeWriter::new(LogcatTag::Fixed("frostsnap/rust".to_owned()))
.expect("logcat writer");
let fmt_layer = tracing_subscriber::fmt::layer()
.event_format(Format::default().with_target(true).without_time().compact())
.with_writer(writer)
.with_ansi(false)
.with_filter(targets.clone());
Registry::default()
.with(targets.clone())
.with(fmt_layer)
.with(crate::logger::dart_logger())
.try_init()?;
}
event!(Level::INFO, "Rust tracing initialised");
}
Ok(())
}
// Android-specific function that returns FfiSerial
pub fn load_host_handles_serial(
&self,
app_dir: String,
) -> Result<(Coordinator, AppCtx, super::port::FfiSerial)> {
use super::port::FfiSerial;
let app_dir = PathBuf::from_str(&app_dir)?;
let ffi_serial = FfiSerial::default();
let firmware = crate::FIRMWARE.map(ValidatedFirmwareBin::new).transpose()?;
let usb_manager = UsbSerialManager::new(Box::new(ffi_serial.clone()), firmware);
let (coord, app_state) = load_internal(app_dir, usb_manager)?;
Ok((coord, app_state, ffi_serial))
}
// Desktop function using DesktopSerial
pub fn load(&self, app_dir: String) -> anyhow::Result<(Coordinator, AppCtx)> {
let app_dir = PathBuf::from_str(&app_dir)?;
let firmware = crate::FIRMWARE.map(ValidatedFirmwareBin::new).transpose()?;
let usb_manager = UsbSerialManager::new(Box::new(DesktopSerial), firmware);
load_internal(app_dir, usb_manager)
}
}
fn load_internal(
app_dir: PathBuf,
usb_serial_manager: UsbSerialManager,
) -> Result<(Coordinator, AppCtx)> {
let db_file = app_dir.join("frostsnap.sqlite");
event!(
Level::INFO,
path = db_file.display().to_string(),
"initializing database"
);
let db = rusqlite::Connection::open(&db_file).with_context(|| {
event!(
Level::ERROR,
path = db_file.display().to_string(),
"failed to load database"
);
format!("failed to load database from {}", db_file.display())
})?;
let db = Arc::new(Mutex::new(db));
let coordinator = FfiCoordinator::new(db.clone(), usb_serial_manager)?;
let coordinator = Coordinator(coordinator);
let app_state = AppCtx {
settings: RustAutoOpaque::new(Settings::new(db.clone(), app_dir)?),
psbt_manager: RustAutoOpaque::new(PsbtManager::new(db.clone())),
};
println!("loaded db");
Ok((coordinator, app_state))
}
pub struct AppCtx {
pub settings: RustAutoOpaque<Settings>,
pub psbt_manager: RustAutoOpaque<PsbtManager>,
}
#[flutter_rust_bridge::frb(init)]
pub fn init_app() {
// Default utilities - feel free to customize
flutter_rust_bridge::setup_default_user_utils();
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/rust/src/api/camera.rs | frostsnapp/rust/src/api/camera.rs | use crate::frb_generated::StreamSink;
use anyhow::{anyhow, Result};
use tracing::info;
#[cfg(any(target_os = "linux", target_os = "windows"))]
use frostsnap_desktop_camera::Camera;
#[derive(Clone, Debug)]
pub struct CameraDevice {
pub index: u32,
pub name: String,
pub width: u32,
pub height: u32,
}
#[derive(Clone, Debug)]
pub struct Frame {
pub data: Vec<u8>,
pub width: u32,
pub height: u32,
}
impl CameraDevice {
pub fn list() -> Result<Vec<CameraDevice>> {
#[cfg(any(target_os = "linux", target_os = "windows"))]
{
let devices =
Camera::list_devices().map_err(|e| anyhow!("Failed to query cameras: {}", e))?;
Ok(devices
.into_iter()
.map(|device| CameraDevice {
index: device.index as u32,
name: device.name,
width: device.resolution.width,
height: device.resolution.height,
})
.collect())
}
#[cfg(not(any(target_os = "linux", target_os = "windows")))]
{
Err(anyhow!(
"Camera support only available on Linux and Windows"
))
}
}
pub fn start(&self, sink: StreamSink<Frame>) -> Result<()> {
#[cfg(any(target_os = "linux", target_os = "windows"))]
{
let devices =
Camera::list_devices().map_err(|e| anyhow!("Failed to query cameras: {}", e))?;
let device_info = devices
.into_iter()
.find(|d| d.index == self.index as usize && d.name == self.name)
.ok_or_else(|| {
anyhow!("Camera '{}' at index {} not found", self.name, self.index)
})?;
info!(
"Opening camera '{}' (index {}) with format: {}x{} {}",
device_info.name,
device_info.index,
device_info.resolution.width,
device_info.resolution.height,
device_info.format
);
let name = device_info.name.clone();
let camera_sink = CameraSinkAdapter { sink, name };
let _camera = Camera::open(&device_info, camera_sink)
.map_err(|e| anyhow!("Failed to open camera '{}': {}", self.name, e))?;
Ok(())
}
#[cfg(not(any(target_os = "linux", target_os = "windows")))]
{
Err(anyhow!(
"Camera support only available on Linux and Windows"
))
}
}
}
#[cfg(any(target_os = "linux", target_os = "windows"))]
struct CameraSinkAdapter {
sink: StreamSink<Frame>,
name: String,
}
#[cfg(any(target_os = "linux", target_os = "windows"))]
impl frostsnap_desktop_camera::CameraSink for CameraSinkAdapter {
fn send_frame(
&self,
camera_frame: frostsnap_desktop_camera::Frame,
) -> frostsnap_desktop_camera::Result<()> {
let frame = Frame {
data: camera_frame.data,
width: camera_frame.width,
height: camera_frame.height,
};
self.sink.add(frame).map_err(|_| {
info!("Camera '{}' stream closed, stopping capture", self.name);
frostsnap_desktop_camera::CameraError::CaptureFailed("Stream closed".to_string())
})
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/rust/src/api/signing.rs | frostsnapp/rust/src/api/signing.rs | use super::super_wallet::SuperWallet;
use super::{
bitcoin::{BitcoinNetwork, RTransaction, Transaction},
coordinator::Coordinator,
};
use crate::{frb_generated::StreamSink, sink_wrap::SinkWrap};
use anyhow::{anyhow, Result};
use bitcoin::hex::DisplayHex;
use bitcoin::ScriptBuf;
use flutter_rust_bridge::frb;
pub use frostsnap_coordinator::signing::SigningState;
pub use frostsnap_core::bitcoin_transaction::TransactionTemplate;
pub use frostsnap_core::coordinator::ActiveSignSession;
pub use frostsnap_core::coordinator::{SignSessionProgress, StartSign};
use frostsnap_core::MasterAppkey;
use frostsnap_core::{
message::EncodedSignature, AccessStructureRef, DeviceId, KeyId, SignSessionId, SymmetricKey,
WireSignTask,
};
use std::collections::{HashMap, HashSet};
/// An outgoing Bitcoin transaction that has not been successfully broadcast.
///
/// May be signed or unsigned, but is guaranteed to have a signing session associated with it.
#[derive(Debug, Clone)]
#[frb]
pub struct UnbroadcastedTx {
pub tx: Transaction,
pub session_id: SignSessionId,
/// Some for active (incomplete) sign sessions.
pub active_session: Option<ActiveSignSession>,
}
impl UnbroadcastedTx {
#[frb(sync)]
pub fn is_signed(&self) -> bool {
self.active_session.is_none()
}
}
#[derive(Debug, Clone)]
#[frb(non_opaque)]
pub enum SigningDetails {
Message {
message: String,
},
Transaction {
transaction: crate::api::bitcoin::Transaction,
},
Nostr {
id: String,
content: String,
hash_bytes: String,
},
}
#[frb(mirror(SigningState), unignore)]
pub struct _SigningState {
pub session_id: SignSessionId,
pub got_shares: Vec<DeviceId>,
pub needed_from: Vec<DeviceId>,
pub finished_signatures: Option<Vec<EncodedSignature>>,
pub aborted: Option<String>,
pub connected_but_need_request: Vec<DeviceId>,
}
#[frb(mirror(ActiveSignSession), unignore)]
pub struct _ActiveSignSession {
pub progress: Vec<SignSessionProgress>,
pub init: StartSign,
pub key_id: KeyId,
pub sent_req_to_device: HashSet<DeviceId>,
}
pub trait ActiveSignSessionExt {
#[frb(sync)]
fn state(&self) -> SigningState;
#[frb(sync)]
fn details(&self) -> SigningDetails;
}
impl ActiveSignSessionExt for ActiveSignSession {
#[frb(sync)]
fn state(&self) -> SigningState {
let session_id = self.session_id();
let session_init = &self.init;
let got_shares = self.received_from();
let state = SigningState {
session_id,
got_shares: got_shares.into_iter().collect(),
needed_from: session_init.nonces.keys().copied().collect(),
finished_signatures: None,
aborted: None,
connected_but_need_request: Default::default(),
};
state
}
#[frb(sync)]
fn details(&self) -> SigningDetails {
let session_init = &self.init;
let res = match session_init.group_request.sign_task.clone() {
WireSignTask::Test { message } => SigningDetails::Message { message },
WireSignTask::Nostr { event } => SigningDetails::Nostr {
id: event.id,
content: event.content,
hash_bytes: event.hash_bytes.to_lower_hex_string(),
},
WireSignTask::BitcoinTransaction(tx_temp) => {
let raw_tx = tx_temp.to_rust_bitcoin_tx();
let txid = raw_tx.compute_txid();
let is_mine = tx_temp
.iter_locally_owned_inputs()
.map(|(_, _, spk)| spk.spk())
.chain(
tx_temp
.iter_locally_owned_outputs()
.map(|(_, _, spk)| spk.spk()),
)
.collect::<HashSet<_>>();
let prevouts = tx_temp
.inputs()
.iter()
.map(|input| (input.outpoint(), input.txout()))
.collect::<HashMap<bitcoin::OutPoint, bitcoin::TxOut>>();
SigningDetails::Transaction {
transaction: Transaction {
inner: raw_tx,
txid: txid.to_string(),
confirmation_time: None,
last_seen: None,
prevouts,
is_mine,
},
}
}
};
res
}
}
#[derive(Clone, Debug)]
pub struct UnsignedTx {
pub template_tx: TransactionTemplate,
}
impl UnsignedTx {
#[frb(sync)]
pub fn txid(&self) -> String {
self.template_tx.txid().to_string()
}
#[frb(sync, type_64bit_int)]
pub fn fee(&self) -> Option<u64> {
self.template_tx.fee()
}
#[frb(sync)]
pub fn feerate(&self) -> Option<f64> {
self.template_tx.feerate()
}
#[frb(sync)]
pub fn details(&self, super_wallet: &SuperWallet, master_appkey: MasterAppkey) -> Transaction {
let super_wallet = super_wallet.inner.lock().unwrap();
let raw_tx = self.template_tx.to_rust_bitcoin_tx();
let txid = raw_tx.compute_txid();
Transaction {
txid: txid.to_string(),
confirmation_time: None,
last_seen: None,
prevouts: super_wallet
.get_prevouts(raw_tx.input.iter().map(|txin| txin.previous_output)),
is_mine: raw_tx
.output
.iter()
.chain(
super_wallet
.get_prevouts(raw_tx.input.iter().map(|txin| txin.previous_output))
.values(),
)
.map(|txout| txout.script_pubkey.clone())
.filter(|spk| super_wallet.is_spk_mine(master_appkey, spk.clone()))
.collect::<HashSet<ScriptBuf>>(),
inner: raw_tx,
}
}
#[frb(sync)]
pub fn complete(&self, signatures: Vec<EncodedSignature>) -> SignedTx {
let mut tx = self.template_tx.to_rust_bitcoin_tx();
for (txin, signature) in tx.input.iter_mut().zip(signatures) {
let schnorr_sig = bitcoin::taproot::Signature {
signature: bitcoin::secp256k1::schnorr::Signature::from_slice(&signature.0)
.unwrap(),
sighash_type: bitcoin::sighash::TapSighashType::Default,
};
let witness = bitcoin::Witness::from_slice(&[schnorr_sig.to_vec()]);
txin.witness = witness;
}
SignedTx {
signed_tx: tx,
unsigned_tx: self.clone(),
}
}
#[frb(sync)]
pub fn effect(
&self,
master_appkey: MasterAppkey,
network: BitcoinNetwork,
) -> Result<EffectOfTx> {
use frostsnap_core::bitcoin_transaction::RootOwner;
let fee = self
.template_tx
.fee()
.ok_or(anyhow!("invalid transaction"))?;
let mut net_value = self.template_tx.net_value();
let value_for_this_key = net_value
.remove(&RootOwner::Local(master_appkey))
.ok_or(anyhow!("this transaction has no effect on this key"))?;
let foreign_receiving_addresses = net_value
.into_iter()
.filter_map(|(owner, value)| match owner {
RootOwner::Local(_) => Some(Err(anyhow!(
"we don't support spending from multiple different keys"
))),
RootOwner::Foreign(spk) => {
if value > 0 {
Some(Ok((
bitcoin::Address::from_script(spk.as_script(), network)
.expect("will have address form")
.to_string(),
value as u64,
)))
} else {
None
}
}
})
.collect::<Result<Vec<_>>>()?;
Ok(EffectOfTx {
net_value: value_for_this_key,
fee,
feerate: self.template_tx.feerate(),
foreign_receiving_addresses,
})
}
}
#[derive(Debug, Clone)]
pub struct SignedTx {
pub signed_tx: RTransaction,
pub unsigned_tx: UnsignedTx,
}
impl SignedTx {
#[frb(sync)]
pub fn txid(&self) -> String {
self.signed_tx.compute_txid().to_string()
}
#[frb(sync)]
pub fn effect(
&self,
master_appkey: MasterAppkey,
network: BitcoinNetwork,
) -> Result<EffectOfTx> {
self.unsigned_tx.effect(master_appkey, network)
}
}
impl Coordinator {
pub fn start_signing(
&self,
access_structure_ref: AccessStructureRef,
devices: Vec<DeviceId>,
message: String,
sink: StreamSink<SigningState>,
) -> Result<()> {
self.0.start_signing(
access_structure_ref,
devices.into_iter().collect(),
WireSignTask::Test { message },
SinkWrap(sink),
)?;
Ok(())
}
pub fn start_signing_tx(
&self,
access_structure_ref: AccessStructureRef,
unsigned_tx: UnsignedTx,
devices: Vec<DeviceId>,
sink: StreamSink<SigningState>,
) -> Result<()> {
self.0.start_signing(
access_structure_ref,
devices.into_iter().collect(),
WireSignTask::BitcoinTransaction(unsigned_tx.template_tx.clone()),
SinkWrap(sink),
)?;
Ok(())
}
#[frb(sync)]
pub fn nonces_available(&self, id: DeviceId) -> u32 {
self.0.nonces_available(id)
}
pub fn try_restore_signing_session(
&self,
session_id: SignSessionId,
sink: StreamSink<SigningState>,
) -> Result<()> {
self.0
.try_restore_signing_session(session_id, SinkWrap(sink))
}
#[frb(sync)]
pub fn active_signing_session(&self, session_id: SignSessionId) -> Option<ActiveSignSession> {
self.0
.inner()
.active_signing_sessions_by_ssid()
.get(&session_id)
.cloned()
}
#[frb(sync)]
pub fn active_signing_sessions(&self, key_id: KeyId) -> Vec<ActiveSignSession> {
self.0
.inner()
.active_signing_sessions()
.filter(|session| session.key_id == key_id)
.collect()
}
#[frb(sync)]
pub fn unbroadcasted_txs(
&self,
s_wallet: &SuperWallet,
master_appkey: MasterAppkey,
) -> Vec<UnbroadcastedTx> {
let key_id = master_appkey.key_id();
let coord = self.0.inner();
let s_wallet = &mut *s_wallet.inner.lock().unwrap();
let canonical_txids = s_wallet
.list_transactions(master_appkey)
.into_iter()
.map(|tx| tx.txid)
.collect::<HashSet<bitcoin::Txid>>();
let unsigned_txs = coord
.active_signing_sessions()
.filter(|session| session.key_id == key_id)
.filter_map(|session| {
let sign_task = &session.init.group_request.sign_task;
match sign_task {
WireSignTask::BitcoinTransaction(tx_temp) => {
let tx = Transaction::from_template(tx_temp);
let session_id = session.session_id();
Some(UnbroadcastedTx {
tx,
session_id,
active_session: Some(session),
})
}
_ => None,
}
});
let unbroadcasted_txs = coord
.finished_signing_sessions()
.iter()
.filter(|(_, session)| session.key_id == key_id)
.filter_map(
|(&session_id, session)| match &session.init.group_request.sign_task {
WireSignTask::BitcoinTransaction(tx_temp) => {
let mut tx = Transaction::from_template(tx_temp);
tx.fill_signatures(&session.signatures);
Some(UnbroadcastedTx {
tx,
session_id,
active_session: None,
})
}
_ => None,
},
);
unsigned_txs
.chain(unbroadcasted_txs)
.filter(move |uncanonical_tx| {
let txid = uncanonical_tx.tx.raw_txid();
!canonical_txids.contains(&txid)
})
.collect()
}
#[frb(sync)]
pub fn request_device_sign(
&self,
device_id: DeviceId,
session_id: SignSessionId,
encryption_key: SymmetricKey,
) -> Result<()> {
self.0
.request_device_sign(device_id, session_id, encryption_key)
}
pub fn cancel_sign_session(&self, ssid: SignSessionId) -> Result<()> {
self.0.cancel_sign_session(ssid)
}
pub fn forget_finished_sign_session(&self, ssid: SignSessionId) -> Result<()> {
self.0.forget_finished_sign_session(ssid)
}
pub fn sub_signing_session_signals(&self, key_id: KeyId, sink: StreamSink<()>) {
self.0.sub_signing_session_signals(key_id, SinkWrap(sink))
}
}
#[derive(Clone, Debug)]
#[frb(type_64bit_int)]
pub struct EffectOfTx {
pub net_value: i64,
pub fee: u64,
pub feerate: Option<f64>,
pub foreign_receiving_addresses: Vec<(String, u64)>,
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/rust/src/api/name.rs | frostsnapp/rust/src/api/name.rs | use flutter_rust_bridge::frb;
pub use frostsnap_coordinator::frostsnap_comms::DeviceName;
#[frb(sync, type_64bit_int)]
pub fn key_name_max_length() -> usize {
frostsnap_coordinator::frostsnap_comms::KEY_NAME_MAX_LENGTH
}
#[frb(external)]
impl DeviceName {
#[frb(sync)]
pub fn to_string(&self) -> String {}
#[frb(sync, type_64bit_int)]
pub fn max_length() -> usize {}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/rust/src/api/super_wallet.rs | frostsnapp/rust/src/api/super_wallet.rs | use super::bitcoin::BitcoinNetworkExt as _;
use super::coordinator::Coordinator;
use super::transaction::BuildTxState;
use super::{bitcoin::Transaction, signing::UnsignedTx};
use crate::api::broadcast::Broadcast;
use crate::frb_generated::{RustAutoOpaque, StreamSink};
use crate::sink_wrap::SinkWrap;
use anyhow::{Context as _, Result};
use bitcoin::Transaction as RTransaction;
use bitcoin::Txid;
pub use bitcoin::{Address, Network as BitcoinNetwork, Psbt};
use flutter_rust_bridge::frb;
pub use frostsnap_coordinator::bitcoin::wallet::AddressInfo;
pub use frostsnap_coordinator::bitcoin::wallet::PsbtValidationError;
pub use frostsnap_coordinator::bitcoin::{chain_sync::ChainClient, wallet::CoordSuperWallet};
pub use frostsnap_coordinator::verify_address::VerifyAddressProtocolState;
use frostsnap_core::{DeviceId, KeyId, MasterAppkey};
use std::collections::HashSet;
use std::str::FromStr;
use std::sync::atomic::AtomicBool;
use std::sync::RwLock;
use std::{
collections::BTreeMap,
path::Path,
sync::{Arc, Mutex},
};
use tracing::{event, Level};
pub type WalletStreams = BTreeMap<MasterAppkey, StreamSink<TxState>>;
pub struct TxState {
pub txs: Vec<Transaction>,
pub balance: i64,
pub untrusted_pending_balance: i64,
}
#[frb(external)]
impl PsbtValidationError {
#[frb(sync)]
pub fn to_string(&self) -> String {}
}
#[derive(Clone)]
#[frb(opaque)]
pub struct SuperWallet {
pub(crate) inner: Arc<Mutex<CoordSuperWallet>>,
pub(crate) wallet_streams: Arc<Mutex<WalletStreams>>,
chain_sync: ChainClient,
pub network: BitcoinNetwork,
}
impl SuperWallet {
#[allow(unused)]
pub(crate) fn load_or_new(
app_dir: impl AsRef<Path>,
network: BitcoinNetwork,
chain_sync: ChainClient,
) -> Result<SuperWallet> {
let db_file = network.bdk_file(app_dir);
let db = rusqlite::Connection::open(&db_file).context(format!(
"failed to load database from {}",
db_file.display()
))?;
let db = Arc::new(Mutex::new(db));
let super_wallet = CoordSuperWallet::load_or_init(db.clone(), network, chain_sync.clone())
.with_context(|| format!("loading wallet from data in {}", db_file.display()))?;
let wallet = SuperWallet {
inner: Arc::new(Mutex::new(super_wallet)),
chain_sync,
wallet_streams: Default::default(),
network,
};
Ok(wallet)
}
pub fn sub_tx_state(
&self,
master_appkey: MasterAppkey,
stream: StreamSink<TxState>,
) -> Result<()> {
stream.add(self.tx_state(master_appkey)).unwrap();
self.wallet_streams
.lock()
.unwrap()
.insert(master_appkey, stream);
Ok(())
}
#[frb(sync)]
pub fn height(&self) -> u32 {
self.inner.lock().unwrap().chain_tip().height()
}
#[frb(sync)]
pub fn tx_state(&self, master_appkey: MasterAppkey) -> TxState {
let txs = self.inner.lock().unwrap().list_transactions(master_appkey);
txs.into()
}
pub fn reconnect(&self) {
self.chain_sync.reconnect();
}
#[frb(sync)]
pub fn next_address(&self, master_appkey: MasterAppkey) -> AddressInfo {
self.inner
.lock()
.unwrap()
.next_address(master_appkey)
.into()
}
#[frb(sync)]
pub fn get_address_info(&self, master_appkey: MasterAppkey, index: u32) -> Option<AddressInfo> {
self.inner.lock().unwrap().address(master_appkey, index)
}
#[frb(sync)]
pub fn addresses_state(&self, master_appkey: MasterAppkey) -> Vec<AddressInfo> {
self.inner.lock().unwrap().list_addresses(master_appkey)
}
#[frb(sync)]
pub fn test_address_info() -> AddressInfo {
AddressInfo {
index: 24,
address: bitcoin::Address::from_str(
"bc1pp7w6kxnj7lzgm29pmuhezwl0vjdlcrthqukll5gn9xuqfq5n673smy4m63",
)
.unwrap()
.assume_checked(),
external: true,
used: false,
revealed: false,
derivation_path: vec![],
}
}
pub fn search_for_address(
&self,
master_appkey: MasterAppkey,
address_str: String,
start: u32,
stop: u32,
) -> Option<AddressInfo> {
self.inner
.lock()
.unwrap()
.search_for_address(master_appkey, address_str, start, stop)
}
pub fn mark_address_shared(
&self,
master_appkey: MasterAppkey,
derivation_index: u32,
) -> Result<bool> {
self.inner
.lock()
.unwrap()
.mark_address_shared(master_appkey, derivation_index)
}
pub fn rebroadcast(&self, txid: String) -> Result<()> {
let txid = Txid::from_str(&txid).expect("Txid must be valid");
let wallet = self.inner.lock().unwrap();
let tx = wallet
.get_tx(txid)
.ok_or(anyhow::anyhow!("Transaction {txid} does not exist"))?;
drop(wallet);
self.chain_sync
.broadcast(tx.as_ref().clone())
.context("Rebroadcasting failed")?;
Ok(())
}
/// Returns feerate in sat/vB.
#[frb(type_64bit_int)]
pub fn estimate_fee(&self, target_blocks: Vec<u64>) -> Result<Vec<(u64, u64)>> {
let fee_rate_map = self
.chain_sync
.estimate_fee(target_blocks.into_iter().map(|v| v as usize))?;
Ok(fee_rate_map
.into_iter()
.map(|(target, fee_rate)| (target as u64, fee_rate.to_sat_per_vb_ceil()))
.collect())
}
#[frb(type_64bit_int)]
pub fn send_to(
&self,
master_appkey: MasterAppkey,
to_address: &Address,
value: u64,
feerate: f64,
) -> Result<UnsignedTx> {
let mut super_wallet = self.inner.lock().unwrap();
let signing_task = super_wallet.send_to(
master_appkey,
[(to_address.clone(), Some(value))],
feerate as f32,
)?;
let unsigned_tx = UnsignedTx {
template_tx: signing_task,
};
Ok(unsigned_tx)
}
#[frb(sync)]
pub fn calculate_available(
&self,
master_appkey: MasterAppkey,
target_addresses: Vec<RustAutoOpaque<Address>>,
feerate: f32,
) -> u64 {
let mut wallet = self.inner.lock().unwrap();
wallet
.calculate_avaliable_value(
master_appkey,
target_addresses
.into_iter()
.map(|a| a.blocking_read().clone()),
feerate,
true,
)
.max(0) as u64
}
/// Start building transaction.
///
/// Returns `None` if wallet under `master_appkey` is incomplete.
#[frb(sync)]
pub fn build_tx(
&self,
coord: RustAutoOpaque<Coordinator>,
master_appkey: MasterAppkey,
) -> Option<BuildTxState> {
let frost_key = coord
.blocking_read()
.get_frost_key(master_appkey.key_id())?;
let state = BuildTxState {
coord,
super_wallet: self.clone(),
frost_key,
broadcast: Broadcast::default(),
is_refreshing: Arc::new(AtomicBool::new(false)),
inner: Arc::new(RwLock::new(super::transaction::BuildTxInner {
confirmation_estimates: None,
confirmation_target: super::transaction::ConfirmationTarget::default(),
recipients: Vec::new(),
access_id: None,
signers: HashSet::new(),
})),
};
Some(state)
}
pub fn broadcast_tx(&self, master_appkey: MasterAppkey, tx: RTransaction) -> Result<()> {
match self.chain_sync.broadcast(tx.clone()) {
Ok(_) => {
event!(
Level::INFO,
tx = tx.compute_txid().to_string(),
"transaction successfully broadcast"
);
let mut inner = self.inner.lock().unwrap();
inner.broadcast_success(tx);
let wallet_streams = self.wallet_streams.lock().unwrap();
if let Some(stream) = wallet_streams.get(&master_appkey) {
let txs = inner.list_transactions(master_appkey);
stream.add(txs.into()).unwrap();
}
Ok(())
}
Err(e) => {
use bitcoin::consensus::Encodable;
use frostsnap_core::schnorr_fun::fun::hex;
let mut buf = vec![];
tx.consensus_encode(&mut buf).unwrap();
let hex_tx = hex::encode(&buf);
event!(
Level::ERROR,
tx = tx.compute_txid().to_string(),
hex = hex_tx,
error = e.to_string(),
"unable to broadcast"
);
Err(e)
}
}
}
pub fn psbt_to_unsigned_tx(
&self,
psbt: &Psbt,
master_appkey: MasterAppkey,
) -> Result<UnsignedTx, PsbtValidationError> {
let template = self
.inner
.lock()
.unwrap()
.psbt_to_tx_template(psbt, master_appkey)?;
Ok(UnsignedTx {
template_tx: template,
})
}
}
#[frb(mirror(AddressInfo), unignore, opaque)]
pub struct _AddressInfo {
pub index: u32,
pub address: bitcoin::Address,
pub external: bool,
pub used: bool,
pub revealed: bool,
pub derivation_path: Vec<u32>,
}
#[frb(mirror(VerifyAddressProtocolState), unignore)]
pub struct _VerifyAddressProtocolState {
pub target_devices: Vec<DeviceId>,
pub connected_devices: std::collections::HashSet<DeviceId>,
}
impl super::coordinator::Coordinator {
pub fn verify_address(
&self,
key_id: KeyId,
address_index: u32,
sink: StreamSink<VerifyAddressProtocolState>,
) -> Result<()> {
self.0
.verify_address(key_id, address_index, SinkWrap(sink))?;
Ok(())
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/rust/src/api/qr.rs | frostsnapp/rust/src/api/qr.rs | use crate::api::camera::Frame;
use anyhow::{anyhow, Result};
use flutter_rust_bridge::frb;
use tracing::{event, Level};
pub struct PsbtQrDecoder {
decoder: ur::Decoder,
decoding_progress: DecodingProgress,
}
impl PsbtQrDecoder {
#[frb(sync)]
pub fn new() -> Self {
Self {
decoder: Default::default(),
decoding_progress: DecodingProgress {
decoded_frames: 0,
sequence_count: 0,
progress: 0.0,
},
}
}
pub fn decode_qr_image(&mut self, bytes: Vec<u8>) -> Result<QrDecoderStatus> {
let decoded_qr = read_qr_code_bytes(&bytes)?;
let decoded_ur = self.ingest_ur_strings(decoded_qr)?;
Ok(decoded_ur)
}
pub fn decode_qr_frame(&mut self, frame: Frame) -> Result<QrDecoderStatus> {
let img = image::load_from_memory(&frame.data)
.map_err(|e| anyhow!("Failed to decode JPEG frame: {}", e))?;
let luma_img = img.to_luma8();
let mut prepared_img = rqrr::PreparedImage::prepare(luma_img);
let grids = prepared_img.detect_grids();
let decoded_qr: Vec<String> = grids
.into_iter()
.filter_map(|grid| match grid.decode() {
Ok((_meta, content)) => Some(content),
Err(_) => None,
})
.collect();
let decoded_ur = self.ingest_ur_strings(decoded_qr)?;
Ok(decoded_ur)
}
pub fn ingest_ur_strings(&mut self, qr_strings: Vec<String>) -> Result<QrDecoderStatus> {
let decoder = &mut self.decoder;
let decoding_progress = &mut self.decoding_progress;
if decoder.complete() {
match decoder.message() {
Ok(message) => {
event!(Level::INFO, "Successfully decoded UR code");
let raw_psbt =
trim_until_psbt_magic(&message.expect("already checked complete"))
.expect("found magic bytes");
event!(Level::INFO, "Found PSBT magic bytes",);
return Ok(QrDecoderStatus::Decoded(raw_psbt));
}
Err(e) => return Err(anyhow!("Decoded UR code has inconsistencies: {}", e)),
}
}
for part in qr_strings {
if part.len() < 3 || part[0..3].to_lowercase() != "ur:" {
continue; // TODO: return invalid QR error
}
let decoding_part = part.to_lowercase();
// handle SinglePart URs (static QR code)
match ur::decode(&decoding_part) {
Err(e) => {
event!(Level::WARN, "Failed to decode UR: {}\n{}", e, decoding_part);
continue;
}
Ok((kind, decoded)) => {
if let ur::ur::Kind::SinglePart = kind {
event!(Level::INFO, "Successfully decoded UR code");
let raw_psbt = match trim_until_psbt_magic(&decoded) {
Some(raw_psbt) => raw_psbt,
None => {
return Err(anyhow!(
"Failed to find PSBT, is this a correct QR code?"
))
}
};
event!(Level::INFO, "Found PSBT magic bytes");
return Ok(QrDecoderStatus::Decoded(raw_psbt));
}
}
}
// receive multipart (animated QR code)
match decoder.receive(&decoding_part) {
Ok(_) => {
let sequence_count = decoder.sequence_count() as u32;
let decoded_frames = decoding_progress.decoded_frames + 1_u32;
let progress = if sequence_count > 0 {
((decoded_frames as f32) / (sequence_count as f32 * 1.75)).min(0.99)
} else {
0.0
};
*decoding_progress = DecodingProgress {
sequence_count,
decoded_frames,
progress,
};
event!(Level::INFO, "Read part of UR: {}", decoding_part)
}
Err(e) => event!(Level::WARN, "Failed to decode UR: {}\n{}", e, decoding_part),
}
if decoder.complete() {
match decoder.message() {
Ok(message) => {
event!(Level::INFO, "Successfully decoded UR code.");
let raw_psbt = match trim_until_psbt_magic(
&message.expect("already checked complete"),
) {
Some(raw_psbt) => raw_psbt,
None => {
return Err(anyhow!(
"Failed to find PSBT, is this a correct QR code?"
))
}
};
event!(Level::INFO, "Found PSBT magic bytes");
return Ok(QrDecoderStatus::Decoded(raw_psbt));
}
Err(e) => return Err(anyhow!("Decoded UR code has inconsistencies: {}", e)),
}
}
}
event!(Level::TRACE, "Scanning progress {:?}", decoding_progress);
Ok(QrDecoderStatus::Progress {
progress: decoding_progress.progress,
})
}
}
pub struct QrEncoder(ur::Encoder<'static>);
impl QrEncoder {
#[frb(sync)]
pub fn new(bytes: Vec<u8>) -> Self {
let mut length_bytes = bytes.len().to_be_bytes().to_vec();
while length_bytes.len() > 1 && length_bytes[0] == 0 {
length_bytes.remove(0);
}
// prepending OP_PUSHDATA1 and length for CBOR
let mut encode_bytes = Vec::new();
encode_bytes.extend_from_slice(&[0x59]);
encode_bytes.extend_from_slice(&length_bytes);
encode_bytes.extend_from_slice(&bytes);
QrEncoder(ur::Encoder::new(&encode_bytes, 400, "crypto-psbt").unwrap())
}
pub fn next_part(&mut self) -> String {
self.0.next_part().unwrap().to_uppercase()
}
}
pub fn read_qr_code_bytes(bytes: &[u8]) -> Result<Vec<String>> {
let img = match image::load_from_memory(bytes) {
Ok(img) => img,
Err(e) => {
return Err(anyhow!(
"Failed to read in image: {}, bytes: {:?}..",
e,
&bytes[..32.min(bytes.len())],
))
}
};
let luma_img = img.to_luma8();
let mut prepared_img = rqrr::PreparedImage::prepare(luma_img);
let grids = prepared_img.detect_grids();
let decodings = grids
.into_iter()
.filter_map(|grid| match grid.decode() {
Ok((_meta, content)) => Some(content),
Err(_) => None,
})
.collect();
Ok(decodings)
}
// TODO: Remove this, it should not be necessary after decoding a UR code.
// Figure out why there are a few extra bytes at the beginning of the data coming from the UR decoding.
// It is probably from that dodgy image_converter.dart
fn trim_until_psbt_magic(bytes: &[u8]) -> Option<Vec<u8>> {
let psbt_magic_bytes = [0x70, 0x73, 0x62, 0x74];
for i in 0..bytes.len() {
if i + psbt_magic_bytes.len() <= bytes.len()
&& bytes[i..i + psbt_magic_bytes.len()] == psbt_magic_bytes
{
return Some(bytes.split_at(i).1.to_vec());
}
}
None
}
#[derive(Clone, Debug, Default)]
pub struct DecodingProgress {
pub decoded_frames: u32,
pub sequence_count: u32,
pub progress: f32,
}
#[derive(Clone, Debug)]
pub enum QrDecoderStatus {
Progress { progress: f32 },
Decoded(Vec<u8>),
Failed(String),
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/rust/src/api/backup_run.rs | frostsnapp/rust/src/api/backup_run.rs | use anyhow::Result;
use flutter_rust_bridge::frb;
pub use frostsnap_coordinator::display_backup::DisplayBackupState;
use frostsnap_core::{AccessStructureRef, DeviceId, KeyId, SymmetricKey};
use tracing::{event, Level};
use crate::frb_generated::StreamSink;
use crate::sink_wrap::SinkWrap;
#[frb(mirror(DisplayBackupState))]
pub struct _DisplayBackupState {
pub confirmed: bool,
pub close_dialog: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub struct BackupDevice {
pub device_id: DeviceId,
pub share_index: u32,
pub complete: Option<bool>,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct BackupRun {
pub devices: Vec<BackupDevice>,
}
impl BackupRun {
pub fn is_run_complete(&self) -> bool {
self.devices
.iter()
.all(|device| device.complete == Some(true))
}
}
impl crate::api::coordinator::Coordinator {
pub fn display_backup(
&self,
id: DeviceId,
access_structure_ref: AccessStructureRef,
encryption_key: SymmetricKey,
sink: StreamSink<DisplayBackupState>,
) -> Result<()> {
use frostsnap_coordinator::display_backup::DisplayBackupProtocol;
let backup_protocol = DisplayBackupProtocol::new(
self.0.coordinator.lock().unwrap().MUTATE_NO_PERSIST(),
id,
access_structure_ref,
encryption_key,
SinkWrap(sink),
)?;
self.0.start_protocol(backup_protocol);
Ok(())
}
pub fn mark_backup_complete(
&self,
access_structure_ref: AccessStructureRef,
share_index: u32,
) -> Result<()> {
let mut backup_state = self.0.backup_state.lock().unwrap();
let mut db = self.0.db.lock().unwrap();
backup_state.mutate2(&mut *db, |state, mutations| {
state.mark_backup_complete(access_structure_ref, share_index, mutations);
Ok(())
})?;
drop(db);
drop(backup_state);
self.0.backup_stream_emit(access_structure_ref.key_id)?;
Ok(())
}
#[flutter_rust_bridge::frb(sync)]
pub fn get_backup_run(&self, key_id: KeyId) -> BackupRun {
self.0.build_backup_run(key_id)
}
pub fn backup_stream(&self, key_id: KeyId, stream: StreamSink<BackupRun>) -> Result<()> {
event!(
Level::DEBUG,
key_id = key_id.to_string(),
"backup stream subscribed"
);
if self
.0
.backup_run_streams
.lock()
.unwrap()
.insert(key_id, stream)
.is_some()
{
event!(
Level::WARN,
"backup stream was replaced this is probably a bug"
);
}
self.0.backup_stream_emit(key_id)?;
Ok(())
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/rust/src/api/recovery.rs | frostsnapp/rust/src/api/recovery.rs | pub use crate::api::KeyPurpose;
use crate::{frb_generated::StreamSink, sink_wrap::SinkWrap};
use anyhow::Result;
use bitcoin::Network as BitcoinNetwork;
use flutter_rust_bridge::frb;
pub use frostsnap_coordinator::enter_physical_backup::EnterPhysicalBackupState;
pub use frostsnap_coordinator::wait_for_single_device::WaitForSingleDeviceState;
pub use frostsnap_core::coordinator::restoration::{
PhysicalBackupPhase, RecoverShare, RecoverShareError, RecoverShareErrorKind,
RecoveringAccessStructure, RestorationShare, RestorationState, RestorationStatus,
RestorePhysicalBackupError, RestoreRecoverShareError, ShareCompatibility, ShareCount,
};
pub use frostsnap_core::coordinator::{KeyLocationState, ShareLocation};
pub use frostsnap_core::{
message::HeldShare2,
schnorr_fun::frost::{Fingerprint, ShareImage, ShareIndex, SharedKey},
};
use frostsnap_core::{AccessStructureRef, DeviceId, RestorationId, SymmetricKey};
use std::fmt;
#[frb(mirror(WaitForSingleDeviceState), non_opaque)]
pub enum _WaitForSingleDeviceState {
NoDevice,
TooManyDevices,
WaitingForDevice {
device_id: DeviceId,
},
BlankDevice {
device_id: DeviceId,
},
DeviceWithShare {
device_id: DeviceId,
share: RecoverShare,
},
}
impl super::coordinator::Coordinator {
pub fn wait_for_single_device(&self, sink: StreamSink<WaitForSingleDeviceState>) -> Result<()> {
self.0.wait_for_single_device(SinkWrap(sink));
Ok(())
}
pub fn start_restoring_wallet(
&self,
name: String,
threshold: Option<u16>,
network: BitcoinNetwork,
) -> Result<RestorationId> {
self.0
.start_restoring_wallet(name, threshold, KeyPurpose::Bitcoin(network))
}
pub fn start_restoring_wallet_from_device_share(
&self,
recover_share: &RecoverShare,
) -> Result<RestorationId> {
self.0
.start_restoring_wallet_from_device_share(recover_share)
}
pub fn check_continue_restoring_wallet_from_device_share(
&self,
restoration_id: RestorationId,
recover_share: &RecoverShare,
encryption_key: SymmetricKey,
) -> Option<RestoreRecoverShareError> {
self.0
.inner()
.check_recover_share_compatible_with_restoration(
restoration_id,
recover_share,
encryption_key,
)
.err()
}
pub fn continue_restoring_wallet_from_device_share(
&self,
restoration_id: RestorationId,
recover_share: &RecoverShare,
encryption_key: SymmetricKey,
) -> Result<()> {
self.0.continue_restoring_wallet_from_device_share(
restoration_id,
recover_share,
encryption_key,
)
}
pub fn finish_restoring(
&self,
restoration_id: RestorationId,
encryption_key: SymmetricKey,
) -> Result<AccessStructureRef> {
self.0.finish_restoring(restoration_id, encryption_key)
}
#[frb(sync)]
pub fn get_restoration_state(&self, restoration_id: RestorationId) -> Option<RestorationState> {
self.0.get_restoration_state(restoration_id)
}
pub fn cancel_restoration(&self, restoration_id: RestorationId) -> Result<()> {
self.0.cancel_restoration(restoration_id)
}
pub fn check_recover_share(
&self,
access_structure_ref: AccessStructureRef,
recover_share: &RecoverShare,
encryption_key: SymmetricKey,
) -> Option<RecoverShareError> {
self.0
.inner()
.check_recover_share_compatible_with_key(
access_structure_ref,
recover_share,
encryption_key,
)
.err()
}
pub fn check_start_restoring_key_from_device_share(
&self,
recover_share: &RecoverShare,
encryption_key: SymmetricKey,
) -> Option<StartRestorationError> {
// Use find_share to check if this share already exists
if let Some(location) = self
.0
.inner()
.find_share(recover_share.held_share.share_image, encryption_key)
{
return Some(StartRestorationError::ShareBelongsElsewhere {
location: Box::new(location),
});
}
None
}
pub fn check_physical_backup(
&self,
access_structure_ref: AccessStructureRef,
phase: &PhysicalBackupPhase,
encryption_key: SymmetricKey,
) -> bool {
self.0
.inner()
.check_physical_backup(access_structure_ref, *phase, encryption_key)
.is_ok()
}
pub fn recover_share(
&self,
access_structure_ref: AccessStructureRef,
recover_share: &RecoverShare,
encryption_key: SymmetricKey,
) -> Result<()> {
self.0
.recover_share(access_structure_ref, recover_share, encryption_key)
}
pub fn tell_device_to_enter_physical_backup(
&self,
device_id: DeviceId,
sink: StreamSink<EnterPhysicalBackupState>,
) -> Result<()> {
self.0
.tell_device_to_enter_physical_backup(device_id, SinkWrap(sink))?;
Ok(())
}
pub fn check_physical_backup_for_restoration(
&self,
restoration_id: RestorationId,
phase: &PhysicalBackupPhase,
encryption_key: SymmetricKey,
) -> Option<RestorePhysicalBackupError> {
self.0
.inner()
.check_physical_backup_compatible_with_restoration(
restoration_id,
*phase,
encryption_key,
)
.err()
}
pub fn tell_device_to_save_physical_backup(
&self,
phase: &PhysicalBackupPhase,
restoration_id: RestorationId,
) {
self.0
.tell_device_to_save_physical_backup(*phase, restoration_id)
}
pub fn tell_device_to_consolidate_physical_backup(
&self,
access_structure_ref: AccessStructureRef,
phase: &PhysicalBackupPhase,
encryption_key: SymmetricKey,
) -> anyhow::Result<()> {
self.0.tell_device_to_consolidate_physical_backup(
access_structure_ref,
*phase,
encryption_key,
)?;
Ok(())
}
pub fn exit_recovery_mode(&self, device_id: DeviceId, encryption_key: SymmetricKey) {
self.0.exit_recovery_mode(device_id, encryption_key);
}
pub fn delete_restoration_share(
&self,
restoration_id: RestorationId,
device_id: DeviceId,
) -> Result<()> {
self.0.delete_restoration_share(restoration_id, device_id)
}
}
#[frb(external)]
impl PhysicalBackupPhase {
#[frb(sync)]
pub fn device_id(&self) -> DeviceId {}
#[frb(sync)]
pub fn share_image(&self) -> ShareImage {}
}
#[derive(Debug, Clone)]
#[frb(mirror(EnterPhysicalBackupState))]
pub struct _EnterPhysicalBackupState {
pub device_id: DeviceId,
pub entered: Option<PhysicalBackupPhase>,
/// null if the user is entering the backup not to save but to check it
pub saved: bool,
pub abort: Option<String>,
}
#[frb(mirror(RecoverShare))]
pub struct _RecoverShare {
pub held_by: DeviceId,
pub held_share: HeldShare2,
}
#[frb(mirror(HeldShare2))]
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,
}
#[frb(mirror(RestorationState))]
pub struct _RestorationState {
pub restoration_id: RestorationId,
pub key_name: String,
pub access_structure: RecoveringAccessStructure,
pub key_purpose: KeyPurpose,
pub fingerprint: Fingerprint,
}
#[frb(external)]
impl RestorationState {
#[frb(sync)]
pub fn status(&self) -> RestorationStatus {}
#[frb(sync)]
pub fn is_restorable(&self) -> bool {}
}
#[frb(mirror(RecoveringAccessStructure))]
struct _RecoveringAccessStructure {
pub starting_threshold: Option<u16>,
pub held_shares: Vec<RecoverShare>,
pub shared_key: Option<SharedKey>,
}
#[frb(external)]
impl RecoveringAccessStructure {
#[frb(sync)]
pub fn effective_threshold(&self) -> Option<u16> {}
}
#[frb(mirror(RestorationStatus))]
pub struct _RestorationStatus {
pub threshold: Option<u16>,
pub shares: Vec<RestorationShare>,
pub shared_key: Option<SharedKey>,
}
#[frb(external)]
impl RestorationStatus {
#[frb(sync)]
pub fn share_count(&self) -> ShareCount {}
}
#[frb(mirror(ShareCount))]
pub struct _ShareCount {
pub got: Option<u16>,
pub needed: Option<u16>,
pub incompatible: u16,
}
#[frb(mirror(ShareCompatibility))]
pub enum _ShareCompatibility {
Compatible,
Incompatible,
Uncertain,
}
#[frb(mirror(RestorationShare))]
pub struct _RestorationShare {
pub device_id: DeviceId,
pub index: u16,
pub compatibility: ShareCompatibility,
}
#[frb(mirror(ShareLocation))]
pub struct _ShareLocation {
pub device_ids: Vec<DeviceId>,
pub share_index: ShareIndex,
pub key_name: String,
pub key_state: KeyLocationState,
}
#[frb(mirror(KeyLocationState))]
pub enum _KeyLocationState {
Complete {
access_structure_ref: AccessStructureRef,
},
Restoring {
restoration_id: RestorationId,
},
}
#[frb(mirror(RestoreRecoverShareError))]
pub enum _RestoreRecoverShareError {
UnknownRestorationId,
AcccessStructureMismatch,
AlreadyGotThisShare,
ShareBelongsElsewhere { location: Box<ShareLocation> },
}
#[frb(mirror(RestorePhysicalBackupError))]
pub enum _RestorePhysicalBackupError {
UnknownRestorationId,
AlreadyGotThisShare,
ShareBelongsElsewhere { location: Box<ShareLocation> },
}
#[frb(mirror(RecoverShareError))]
pub struct _RecoverShareError {
pub key_purpose: KeyPurpose,
pub kind: RecoverShareErrorKind,
}
#[frb(mirror(RecoverShareErrorKind))]
pub enum _RecoverShareErrorKind {
AlreadyGotThisShare,
NoSuchAccessStructure,
AccessStructureMismatch,
ShareImageIsWrong,
DecryptionError,
}
#[derive(Debug, Clone)]
pub enum StartRestorationError {
ShareBelongsElsewhere { location: Box<ShareLocation> },
}
impl fmt::Display for StartRestorationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
StartRestorationError::ShareBelongsElsewhere { location } => {
write!(f, "This key share belongs to existing {} '{}' and cannot be used to start a new restoration", location.key_purpose.key_type_noun(), location.key_name)
}
}
}
}
impl std::error::Error for StartRestorationError {}
#[frb(external)]
impl StartRestorationError {
#[frb(sync)]
pub fn to_string(&self) -> String {}
}
#[frb(external)]
impl RestoreRecoverShareError {
#[frb(sync)]
pub fn to_string(&self) -> String {}
}
#[frb(external)]
impl RestorePhysicalBackupError {
#[frb(sync)]
pub fn to_string(&self) -> String {}
}
#[frb(external)]
impl RecoverShareError {
#[frb(sync)]
pub fn to_string(&self) -> String {}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/rust/src/api/firmware.rs | frostsnapp/rust/src/api/firmware.rs | use super::coordinator::Coordinator;
use crate::{frb_generated::StreamSink, sink_wrap::SinkWrap};
use anyhow::Result;
use flutter_rust_bridge::frb;
pub use frostsnap_coordinator::firmware::*;
pub use frostsnap_coordinator::firmware_upgrade::FirmwareUpgradeConfirmState;
pub use frostsnap_coordinator::frostsnap_comms::Sha256Digest;
pub use frostsnap_coordinator::VersionNumber;
use frostsnap_core::DeviceId;
impl Coordinator {
pub fn start_firmware_upgrade(
&self,
sink: StreamSink<FirmwareUpgradeConfirmState>,
) -> Result<()> {
self.0.begin_upgrade_firmware(SinkWrap(sink))?;
Ok(())
}
#[frb(sync)]
pub fn upgrade_firmware_digest(&self) -> Option<String> {
self.0
.upgrade_firmware_digest()
.map(|digest| digest.to_string())
}
#[frb(sync)]
pub fn upgrade_firmware_version_name(&self) -> Option<String> {
self.0.upgrade_firmware_version_name()
}
pub fn enter_firmware_upgrade_mode(&self, progress: StreamSink<f32>) -> Result<()> {
self.0.enter_firmware_upgrade_mode(SinkWrap(progress))
}
}
#[frb(mirror(FirmwareUpgradeConfirmState), unignore)]
pub struct _FirmwareUpgradeConfirmState {
pub confirmations: Vec<DeviceId>,
pub devices: Vec<DeviceId>,
pub need_upgrade: Vec<DeviceId>,
pub abort: Option<String>,
pub upgrade_ready_to_start: bool,
}
#[frb(mirror(VersionNumber))]
pub struct _VersionNumber {
pub major: u8,
pub minor: u8,
pub patch: u8,
}
#[frb(mirror(FirmwareVersion))]
pub struct _FirmwareVersion {
pub digest: Sha256Digest,
pub version: Option<VersionNumber>,
}
#[frb(mirror(FirmwareUpgradeEligibility))]
pub enum _FirmwareUpgradeEligibility {
UpToDate,
CanUpgrade,
CannotUpgrade { reason: String },
}
#[frb(external)]
impl VersionNumber {
#[frb(sync)]
pub fn to_string(&self) -> String {}
}
#[frb(external)]
impl FirmwareVersion {
#[frb(sync)]
pub fn version_name(&self) -> String {}
#[frb(sync)]
pub fn check_upgrade_eligibility(
&self,
_device_digest: &Sha256Digest,
) -> FirmwareUpgradeEligibility {
}
}
#[frb(mirror(Sha256Digest))]
pub struct _Sha256Digest(pub [u8; 32]);
#[frb(external)]
impl Sha256Digest {
#[frb(sync)]
pub fn to_string(&self) -> String {}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/rust/src/api/coordinator.rs | frostsnapp/rust/src/api/coordinator.rs | pub use crate::api::KeyPurpose;
use crate::sink_wrap::SinkWrap;
use anyhow::Result;
use bitcoin::Network as BitcoinNetwork;
use flutter_rust_bridge::frb;
pub use frostsnap_core::coordinator::restoration::RestorationState;
pub use frostsnap_core::coordinator::CoordAccessStructure as AccessStructure;
use frostsnap_core::{
coordinator::CoordFrostKey,
schnorr_fun::frost::{ShareIndex, SharedKey},
tweak::Xpub,
AccessStructureId, AccessStructureRef, DeviceId, KeyId, MasterAppkey,
};
use std::collections::BTreeMap;
use tracing::{event, Level};
use crate::{coordinator::FfiCoordinator, frb_generated::StreamSink};
pub use super::backup_run::{BackupDevice, BackupRun};
#[derive(Clone, Debug)]
pub struct KeyState {
pub keys: Vec<FrostKey>,
pub restoring: Vec<RestorationState>,
}
#[derive(Clone, Debug)]
pub struct FrostKey(pub(crate) frostsnap_core::coordinator::CoordFrostKey);
impl FrostKey {
#[frb(sync)]
pub fn master_appkey(&self) -> MasterAppkey {
self.0.complete_key.master_appkey
}
#[frb(sync)]
pub fn key_id(&self) -> KeyId {
self.0.key_id
}
#[frb(sync)]
pub fn key_name(&self) -> String {
self.0.key_name.to_string()
}
#[frb(sync)]
pub fn access_structures(&self) -> Vec<AccessStructure> {
self.0
.complete_key
.access_structures
.values()
.cloned()
.collect()
}
#[frb(sync)]
pub fn get_access_structure(
&self,
access_structure_id: AccessStructureId,
) -> Option<AccessStructure> {
self.0
.complete_key
.access_structures
.get(&access_structure_id)
.cloned()
.map(From::from)
}
#[frb(sync)]
pub fn bitcoin_network(&self) -> Option<BitcoinNetwork> {
self.0.purpose.bitcoin_network()
}
}
impl From<CoordFrostKey> for FrostKey {
fn from(value: CoordFrostKey) -> Self {
FrostKey(value)
}
}
// this is here just so we can extend it
#[frb(mirror(AccessStructure))]
#[allow(unused)]
pub struct _AccessStructure {
app_shared_key: Xpub<SharedKey>,
device_to_share_index: BTreeMap<DeviceId, ShareIndex>,
}
#[frb(external)]
impl AccessStructure {
#[frb(sync)]
pub fn threshold(&self) -> u16 {}
#[frb(sync)]
pub fn access_structure_ref(&self) -> AccessStructureRef {}
#[frb(sync)]
pub fn access_structure_id(&self) -> AccessStructureId {}
#[frb(sync)]
pub fn master_appkey(&self) -> MasterAppkey {}
}
pub trait AccessStructureExt {
#[frb(sync)]
fn frb_override_devices(&self) -> Vec<DeviceId>;
#[frb(sync)]
fn short_id(&self) -> String;
#[frb(sync)]
fn get_device_short_share_index(&self, device_id: DeviceId) -> Option<u32>;
}
impl AccessStructureExt for AccessStructure {
#[frb(sync)]
fn short_id(&self) -> String {
self.access_structure_id().to_string().split_off(8)
}
#[frb(sync)]
fn frb_override_devices(&self) -> Vec<DeviceId> {
self.devices().collect()
}
#[frb(sync)]
fn get_device_short_share_index(&self, device_id: DeviceId) -> Option<u32> {
use core::convert::TryFrom;
self.device_to_share_indicies()
.get(&device_id)
.and_then(|share_index| u32::try_from(*share_index).ok())
}
}
pub struct Coordinator(pub(crate) FfiCoordinator);
impl Coordinator {
pub fn start_thread(&self) -> Result<()> {
self.0.start()
}
pub fn update_name_preview(&self, id: DeviceId, name: String) -> Result<()> {
self.0.update_name_preview(id, &name)
}
pub fn finish_naming(&self, id: DeviceId, name: String) -> Result<()> {
self.0.finish_naming(id, &name)
}
pub fn send_cancel(&self, id: DeviceId) {
event!(Level::WARN, "dart sent cancel");
self.0.send_cancel(id);
}
pub fn send_cancel_all(&self) {
event!(Level::WARN, "dart sent cancel all");
self.0.usb_sender.send_cancel_all();
}
#[frb(sync)]
pub fn key_state(&self) -> KeyState {
self.0.key_state()
}
pub fn sub_key_events(&self, stream: StreamSink<KeyState>) -> Result<()> {
self.0.sub_key_events(SinkWrap(stream));
Ok(())
}
#[frb(sync)]
pub fn access_structures_involving_device(
&self,
device_id: DeviceId,
) -> Vec<AccessStructureRef> {
self.0
.frost_keys()
.into_iter()
.flat_map(|frost_key| {
frost_key
.access_structures()
.filter(|access_structure| access_structure.contains_device(device_id))
.map(|access_structure| access_structure.access_structure_ref())
.collect::<Vec<_>>()
})
.collect()
}
#[frb(sync)]
pub fn frost_keys_involving_device(&self, device_id: DeviceId) -> Vec<FrostKey> {
self.0
.frost_keys()
.into_iter()
.filter(|coord_frost_key| {
coord_frost_key
.access_structures()
.any(|coord_access_structure| coord_access_structure.contains_device(device_id))
})
.map(FrostKey::from)
.collect()
}
#[frb(sync)]
pub fn get_frost_key(&self, key_id: KeyId) -> Option<FrostKey> {
self.0.get_frost_key(key_id).map(FrostKey::from)
}
#[frb(sync)]
pub fn get_access_structure(&self, as_ref: AccessStructureRef) -> Option<AccessStructure> {
self.0.get_access_structure(as_ref)
}
pub fn delete_key(&self, key_id: KeyId) -> Result<()> {
self.0.delete_key(key_id)
}
pub fn wipe_device_data(&self, device_id: DeviceId) {
self.0.wipe_device_data(device_id);
}
pub fn wipe_all_devices(&self) {
self.0.wipe_all_devices();
}
pub fn cancel_protocol(&self) {
self.0.cancel_protocol()
}
#[frb(sync)]
pub fn get_device_name(&self, id: DeviceId) -> Option<String> {
self.0.get_device_name(id)
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnapp/rust/src/api/transaction.rs | frostsnapp/rust/src/api/transaction.rs | use std::collections::HashSet;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, RwLock};
use bitcoin::Address;
use flutter_rust_bridge::frb;
use frostsnap_core::{AccessStructureId, DeviceId, MasterAppkey};
use crate::api::bitcoin::BitcoinNetworkExt;
use crate::api::broadcast::{Broadcast, UnitBroadcastSubscription};
use crate::api::signing::UnsignedTx;
use crate::frb_generated::RustAutoOpaque;
use super::{
coordinator::{AccessStructure, Coordinator, FrostKey},
super_wallet::SuperWallet,
};
#[derive(Default, Clone, Copy, PartialEq)]
pub enum ConfirmationTarget {
Low,
#[default]
Medium,
High,
/// Custom feerate.
Custom(f32),
}
impl ConfirmationTarget {
#[frb(sync)]
pub fn feerate(self, estimates: Option<ConfirmationEstimates>) -> Option<f32> {
Some(match self {
ConfirmationTarget::Low => estimates?.low,
ConfirmationTarget::Medium => estimates?.medium,
ConfirmationTarget::High => estimates?.high,
ConfirmationTarget::Custom(feerate) => feerate,
})
}
#[frb(sync)]
pub fn is_low(&self) -> bool {
matches!(self, Self::Low)
}
#[frb(sync)]
pub fn is_medium(&self) -> bool {
matches!(self, Self::Medium)
}
#[frb(sync)]
pub fn is_high(&self) -> bool {
matches!(self, Self::High)
}
#[frb(sync)]
pub fn is_custom(&self) -> bool {
matches!(self, Self::Custom(_))
}
}
#[derive(Clone, Copy, PartialEq)]
#[frb(type_64bit_int)]
pub struct ConfirmationEstimates {
/// Unix timestamp of last refresh.
pub last_refresh: u64,
/// 1 confirmation.
pub low: f32,
/// 2 confirmations.
pub medium: f32,
/// 3 confirmations.
pub high: f32,
}
#[derive(Clone, Copy, PartialEq, Eq)]
#[frb(type_64bit_int)]
pub enum AmountType {
/// Send all.
SendMax,
/// Value in satoshis.
Value(u64),
}
impl AmountType {
#[frb(sync, type_64bit_int)]
pub fn from_value(value: u64) -> Self {
Self::Value(value)
}
#[frb(sync, type_64bit_int)]
pub fn value(&self) -> Option<u64> {
match self {
Self::SendMax => None,
Self::Value(v) => Some(*v),
}
}
#[frb(sync)]
pub fn is_send_max(&self) -> bool {
matches!(self, Self::SendMax)
}
}
#[derive(Clone, Default)]
pub struct Recipient {
pub address: Option<Address>,
pub amount: Option<AmountType>,
}
impl Recipient {
#[frb(sync)]
pub fn new(address: Option<Address>, amount: Option<AmountType>) -> Self {
Self { address, amount }
}
}
pub(crate) struct BuildTxInner {
/// Confirmation estimates.
pub(crate) confirmation_estimates: Option<ConfirmationEstimates>,
/// Feerate in sats/vb.
pub(crate) confirmation_target: ConfirmationTarget,
/// Recipients to send to and amounts.
pub(crate) recipients: Vec<Recipient>,
/// The selected access structure.
pub(crate) access_id: Option<AccessStructureId>,
/// Selected devices to sign the transaction.
pub(crate) signers: HashSet<DeviceId>,
}
impl BuildTxInner {
fn get_or_create_recipient(&mut self, recipient: u32) -> &mut Recipient {
let i: usize = recipient.try_into().expect("recipient index too large");
while self.recipients.len() <= i {
self.recipients.push(Recipient::default());
}
self.recipients.get_mut(i).expect("must exist")
}
/// Returns `None` if confirmation target is set to low/medium/high but we don't have confirmation estimates.
fn feerate(&self) -> Option<f32> {
self.confirmation_target
.feerate(self.confirmation_estimates)
}
/// Returns `None` if no feerate is specified.
fn available_amount(
&self,
super_wallet: &SuperWallet,
master_appkey: MasterAppkey,
recipient: u32,
) -> Option<u64> {
Some(
super_wallet.calculate_available(
master_appkey,
self.recipients
.iter()
.skip(recipient.saturating_sub(1) as usize)
.filter_map(|r| r.address.clone())
.map(RustAutoOpaque::new)
.collect(),
self.feerate()?,
),
)
}
}
pub struct BuildTxState {
pub(crate) coord: RustAutoOpaque<Coordinator>,
pub(crate) super_wallet: SuperWallet,
pub(crate) frost_key: FrostKey,
pub(crate) broadcast: Broadcast<()>,
pub(crate) is_refreshing: Arc<AtomicBool>,
pub(crate) inner: Arc<RwLock<BuildTxInner>>,
}
impl BuildTxState {
#[frb(sync)]
pub fn subscribe(&self) -> UnitBroadcastSubscription {
UnitBroadcastSubscription(self.broadcast.subscribe())
}
#[frb(sync)]
pub fn master_appkey(&self) -> MasterAppkey {
self.frost_key.master_appkey()
}
#[frb(sync)]
pub fn confirmation_estimates(&self) -> Option<ConfirmationEstimates> {
self.inner.read().unwrap().confirmation_estimates
}
#[frb(sync)]
pub fn is_refreshing_confirmation_estimates(&self) -> bool {
use std::sync::atomic::Ordering;
self.is_refreshing.load(Ordering::Relaxed)
}
/// Refresh confirmation estimates.
///
/// Returns `None` if a previous referesh request has not completed yet.
pub fn refresh_confirmation_estimates(&self) -> anyhow::Result<Option<ConfirmationEstimates>> {
use std::sync::atomic::Ordering;
if self
.is_refreshing
.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
.is_err()
{
return Ok(None);
}
self._trigger_changed();
let estimates = self._refresh_confirmation_estimates()?;
self.is_refreshing.store(false, Ordering::Release);
self._trigger_changed();
Ok(Some(estimates))
}
fn _refresh_confirmation_estimates(&self) -> anyhow::Result<ConfirmationEstimates> {
let estimates = self.super_wallet.estimate_fee(vec![3, 2, 1])?;
let confirmation_estimates = ConfirmationEstimates {
last_refresh: std::time::UNIX_EPOCH.elapsed()?.as_secs(),
low: estimates[0].1 as _,
medium: estimates[1].1 as _,
high: estimates[2].1 as _,
};
let mut inner = self.inner.write().unwrap();
if inner.confirmation_estimates != Some(confirmation_estimates) {
inner.confirmation_estimates = Some(confirmation_estimates);
}
Ok(confirmation_estimates)
}
#[frb(sync)]
pub fn confirmation_blocks_of_feerate(&self) -> Option<u32> {
let inner = self.inner.read().unwrap();
match inner.confirmation_target {
ConfirmationTarget::Low => return Some(3),
ConfirmationTarget::Medium => return Some(2),
ConfirmationTarget::High => return Some(1),
ConfirmationTarget::Custom(feerate) => {
let targets = inner.confirmation_estimates?;
if feerate <= targets.high {
return Some(1);
}
if feerate <= targets.medium {
return Some(2);
}
if feerate <= targets.low {
return Some(3);
}
return None;
}
};
}
/// Remaining amount that is available for recipient.
///
/// Returns `None` if no feerate is specified.
#[frb(sync)]
pub fn available_amount(&self, recipient: u32) -> Option<u64> {
let inner = self.inner.read().unwrap();
inner.available_amount(
&self.super_wallet,
self.frost_key.master_appkey(),
recipient,
)
}
#[frb(sync)]
pub fn access_structures(&self) -> Vec<AccessStructure> {
self.frost_key.access_structures()
}
#[frb(sync)]
pub fn available_signers(&self) -> Vec<(DeviceId, Option<String>)> {
let access_id_opt = self.inner.read().unwrap().access_id;
let coord_lock = self.coord.blocking_read();
access_id_opt
.and_then(|a_id| self.frost_key.get_access_structure(a_id))
.map_or(Vec::new(), |access| {
access
.devices()
.map(move |d_id| {
let name = coord_lock.get_device_name(d_id);
(d_id, name)
})
.collect::<Vec<_>>()
})
}
#[frb(sync)]
pub fn selected_signers(&self) -> Vec<DeviceId> {
self.inner.read().unwrap().signers.iter().copied().collect()
}
#[frb(sync)]
pub fn access_struct(&self) -> Option<AccessStructure> {
let inner = self.inner.read().unwrap();
let access_id = inner.access_id?;
self.frost_key.get_access_structure(access_id)
}
#[frb(sync)]
pub fn access_id(&self) -> Option<AccessStructureId> {
self.inner.read().unwrap().access_id
}
#[frb(sync)]
pub fn set_access_id(&self, access_id: &AccessStructureId) {
let mut inner = self.inner.write().unwrap();
if inner.access_id.as_ref() != Some(access_id) {
inner.access_id = Some(*access_id);
inner.signers.clear();
self._trigger_changed();
}
}
#[frb(sync)]
pub fn select_signer(&self, d_id: DeviceId) {
let mut inner = self.inner.write().unwrap();
if inner.signers.insert(d_id) {
self._trigger_changed();
}
}
#[frb(sync)]
pub fn deselect_signer(&self, d_id: DeviceId) {
let mut inner = self.inner.write().unwrap();
if inner.signers.remove(&d_id) {
self._trigger_changed();
}
}
#[frb(sync)]
pub fn is_signer_selected(&self, d_id: DeviceId) -> bool {
let inner = self.inner.read().unwrap();
inner.signers.contains(&d_id)
}
#[frb(sync)]
pub fn recipient_count(&self) -> u64 {
let inner = self.inner.read().unwrap();
inner.recipients.len() as u64
}
#[frb(sync)]
pub fn recipient(&self, recipient: u32) -> Option<Recipient> {
let inner = self.inner.read().unwrap();
inner.recipients.get(recipient as usize).cloned()
}
/// Determines the target feerate.
///
/// If confirmation target is not `Custom`, this value uses the `ConfirmationEstimates` to
/// determine the feerate.
#[frb(sync)]
pub fn feerate(&self) -> Option<f32> {
let inner = self.inner.read().unwrap();
inner
.confirmation_target
.feerate(inner.confirmation_estimates)
}
#[frb(sync)]
pub fn confirmation_target(&self) -> ConfirmationTarget {
let inner = self.inner.read().unwrap();
inner.confirmation_target
}
#[frb(sync)]
pub fn set_confirmation_target(&self, target: ConfirmationTarget) {
let mut inner = self.inner.write().unwrap();
if inner.confirmation_target != target {
inner.confirmation_target = target;
self._trigger_changed();
}
}
#[frb(sync, type_64bit_int)]
pub fn fee(&self) -> Option<u64> {
let inner = self.inner.read().unwrap();
let mut sw = self.super_wallet.inner.lock().unwrap();
sw.send_to(
self.frost_key.master_appkey(),
inner.recipients.iter().filter_map(|r| {
let addr = r.address.clone()?;
let amount = r.amount.map_or(Some(0), |a| a.value());
Some((addr, amount))
}),
inner.feerate()?,
)
.ok()?
.fee()
}
#[frb(sync)]
pub fn set_recipient_with_uri(&self, recipient: u32, uri: &str) -> Result<(), String> {
let info = self
.super_wallet
.network
.validate_destination_address(uri)?;
let mut inner = self.inner.write().unwrap();
let r = inner.get_or_create_recipient(recipient);
let mut changed = false;
if r.address.as_ref() != Some(&info.address) {
r.address = Some(info.address);
changed = true;
}
if r.amount != info.amount.map(AmountType::Value) {
r.amount = info.amount.map(AmountType::Value);
changed = true;
}
if changed {
self._trigger_changed();
}
Ok(())
}
#[frb(sync)]
pub fn remove_recipient(&self, recipient: u32) -> bool {
let i: usize = recipient
.try_into()
.expect("recipient index must fit into usize");
let mut inner = self.inner.write().unwrap();
if inner.recipients.len() <= i {
false
} else {
inner.recipients.remove(i);
self._trigger_changed();
true
}
}
#[frb(sync)]
pub fn set_address(&self, recipient: u32, address: &Address) {
let mut inner = self.inner.write().unwrap();
let r = inner.get_or_create_recipient(recipient);
if r.address.as_ref() != Some(address) {
r.address = Some(address.clone());
self._trigger_changed();
}
}
#[frb(sync)]
pub fn clear_address(&self, recipient: u64) {
let i: usize = recipient
.try_into()
.expect("recipient index must fit in usize");
let mut inner = self.inner.write().unwrap();
let addr_opt = inner.recipients.get_mut(i).map(|r| &mut r.address);
if let Some(addr) = addr_opt {
if addr.is_some() {
*addr = None;
self._trigger_changed();
}
}
}
#[frb(sync)]
pub fn set_amount(&self, recipient: u32, amount: u64) {
let mut inner = self.inner.write().unwrap();
let r = inner.get_or_create_recipient(recipient);
if r.amount != Some(AmountType::Value(amount)) {
r.amount = Some(AmountType::Value(amount));
self._trigger_changed();
}
}
#[frb(sync)]
pub fn set_send_max(&self, recipient: u32) {
let mut inner = self.inner.write().unwrap();
let r = inner.get_or_create_recipient(recipient);
if r.amount != Some(AmountType::SendMax) {
r.amount = Some(AmountType::SendMax);
self._trigger_changed();
}
}
#[frb(sync)]
pub fn clear_amount(&self, recipient: u32) {
let mut inner = self.inner.write().unwrap();
if let Some(r) = inner.recipients.get_mut(recipient as usize) {
if r.amount.is_some() {
r.amount = None;
self._trigger_changed();
}
}
}
/// Only returns `Some` if the amount is valid and a recipient address is provided.
#[frb(sync)]
pub fn amount(&self, recipient: u32) -> Result<u64, AmountError> {
let available = self
.available_amount(recipient)
.ok_or(AmountError::UnspecifiedFeerate)?;
if available == 0 {
// TODO: Have amount below dust error.
return Err(AmountError::NoAmountAvailable);
}
let r = self.recipient(recipient);
let amount = match r
.as_ref()
.and_then(|r| r.amount)
.ok_or(AmountError::UnspecifiedAmount)?
{
AmountType::SendMax => available,
AmountType::Value(target) => {
if target > available {
return Err(AmountError::TargetExceedsAvailable { target, available });
}
target
}
};
let addr = r
.and_then(|r| r.address.clone())
.ok_or(AmountError::UnspecifiedAddress)?;
let min_non_dust = addr.script_pubkey().minimal_non_dust().to_sat();
if amount < min_non_dust {
return Err(AmountError::AmountBelowDust { min_non_dust });
}
Ok(amount)
}
#[frb(sync)]
pub fn is_send_max(&self, recipient: u32) -> bool {
let inner = self.inner.read().unwrap();
inner
.recipients
.get(recipient as usize)
.map_or(false, |r| match r.amount {
None => false,
Some(t) => t.is_send_max(),
})
}
#[frb(sync)]
pub fn toggle_send_max(&self, recipient: u32, fallback_amount: Option<u64>) -> bool {
let mut is_send_max = false;
let mut inner = self.inner.write().unwrap();
if let Some(r) = inner.recipients.get_mut(recipient as usize) {
is_send_max = r.amount == Some(AmountType::SendMax);
r.amount = if is_send_max {
fallback_amount.map(AmountType::Value)
} else {
Some(AmountType::SendMax)
};
self._trigger_changed();
}
is_send_max
}
fn _trigger_changed(&self) {
self.broadcast.add(&());
}
#[frb(sync)]
pub fn try_finish(&self) -> Result<UnsignedTx, TryFinishTxError> {
let master_appkey = self.master_appkey();
let inner = self.inner.read().unwrap();
let feerate = inner.feerate().ok_or(TryFinishTxError::MissingFeerate)?;
let recipients = inner
.recipients
.iter()
.filter_map(|r| Some((r.address.clone()?, r.amount?.value())))
.collect::<Vec<_>>();
if recipients.len() != inner.recipients.len() {
return Err(TryFinishTxError::IncompleteRecipientValues);
}
drop(inner);
let mut sw_inner = self.super_wallet.inner.lock().unwrap();
sw_inner
.send_to(master_appkey, recipients, feerate)
.map(|template_tx| UnsignedTx { template_tx })
.map_err(|_| TryFinishTxError::InsufficientBalance)
}
}
#[derive(Debug)]
pub enum AmountError {
UnspecifiedFeerate,
UnspecifiedAmount,
UnspecifiedAddress,
NoAmountAvailable,
AmountBelowDust { min_non_dust: u64 },
TargetExceedsAvailable { target: u64, available: u64 },
}
#[derive(Debug)]
pub enum TryFinishTxError {
/// Occurs when feerate target set to low/medium/high, however, we do not have feerate estimates.
MissingFeerate,
IncompleteRecipientValues,
InsufficientBalance,
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/cst816s/src/lib.rs | cst816s/src/lib.rs | #![no_std]
use core::fmt::Debug;
use embedded_hal as hal;
use hal::delay::DelayNs;
/// Errors in this crate
#[derive(Debug)]
pub enum Error<CommE, PinE> {
Comm(CommE),
Pin(PinE),
GenericError,
}
pub struct CST816S<I2C, PINT, RST> {
i2c: I2C,
pin_int: PINT,
pin_rst: RST,
blob_buf: [u8; BLOB_BUF_LEN],
}
impl<I2C, PINT, RST> CST816S<I2C, PINT, RST> {
/// Default queue capacity for touch events
pub const DEFAULT_QUEUE_CAPACITY: usize = 16;
}
// ESP32-specific constructor
impl<I2C> CST816S<I2C, esp_hal::gpio::Input<'static>, esp_hal::gpio::Output<'static>> {
/// Create a new CST816S instance with ESP32 GPIO pins
/// The interrupt pin will be automatically configured with Pull::Up
pub fn new_esp32(
i2c: I2C,
interrupt_pin: impl esp_hal::peripheral::Peripheral<P = impl esp_hal::gpio::InputPin> + 'static,
reset_pin: impl esp_hal::peripheral::Peripheral<P = impl esp_hal::gpio::OutputPin> + 'static,
) -> Self {
use esp_hal::gpio::{Input, Level, Output, Pull};
let pin_int = Input::new(interrupt_pin, Pull::Up);
Self {
i2c,
pin_int,
pin_rst: Output::new(reset_pin, Level::Low),
blob_buf: [0u8; BLOB_BUF_LEN],
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct TouchEvent {
pub x: i32,
pub y: i32,
/// the gesture that this touch is part of
pub gesture: TouchGesture,
/// 0 down, 1 lift, 2 contact
pub action: u8,
/// identifies the finger that touched (0-9)
pub finger_id: u8,
/// pressure level of touch
pub pressure: u8,
/// the surface area of the touch
pub area: u8,
}
impl<I2C, PINT, RST, CommE, PinE> CST816S<I2C, PINT, RST>
where
I2C: hal::i2c::I2c<Error = CommE>,
PINT: hal::digital::InputPin,
RST: hal::digital::StatefulOutputPin<Error = PinE>,
{
pub fn new(port: I2C, interrupt_pin: PINT, reset_pin: RST) -> Self {
Self {
i2c: port,
pin_int: interrupt_pin,
pin_rst: reset_pin,
blob_buf: [0u8; BLOB_BUF_LEN],
}
}
/// setup the driver to communicate with the device
pub fn setup(&mut self, delay_source: &mut impl DelayNs) -> Result<(), Error<CommE, PinE>> {
// reset the chip
self.pin_rst.set_low().map_err(Error::Pin)?;
delay_source.delay_us(20_000);
self.pin_rst.set_high().map_err(Error::Pin)?;
delay_source.delay_us(20_000);
Ok(())
}
/// Read enough registers to fill our read buf
pub fn read_registers(&mut self) -> Result<(), Error<CommE, PinE>> {
let read_reg = [Self::REG_FIRST; 1];
self.i2c
.write_read(Self::DEFAULT_I2C_ADDRESS, &read_reg, self.blob_buf.as_mut())
.map_err(Error::Comm)?;
Ok(())
}
pub fn read_truncated_registers(&mut self) -> Result<(), Error<CommE, PinE>> {
let read_reg = [Self::REG_FIRST; 1];
self.i2c
.write_read(
Self::DEFAULT_I2C_ADDRESS,
&read_reg,
self.blob_buf[0..ONE_EVENT_LEN].as_mut(),
)
.map_err(Error::Comm)?;
Ok(())
}
///
/// Translate raw register data into touch events
///
fn touch_event_from_data(buf: &[u8]) -> Option<TouchEvent> {
let mut touch = TouchEvent {
x: 0,
y: 0,
gesture: TouchGesture::None,
action: 0,
finger_id: 0,
pressure: 0,
area: 0,
};
// two of the registers mix 4 bits of position with other values
// four high bits of X and 2 bits of Action:
let touch_x_h_and_action = buf[Self::TOUCH_X_H_AND_ACTION_OFF];
// four high bits of Y and 4 bits of Finger:
let touch_y_h_and_finger = buf[Self::TOUCH_Y_H_AND_FINGER_OFF];
// X and Y position are both 12 bits, in pixels from top left corner?
touch.x = (buf[Self::TOUCH_X_L_OFF] as i32) | (((touch_x_h_and_action & 0x0F) as i32) << 8);
touch.y = (buf[Self::TOUCH_Y_L_OFF] as i32) | (((touch_y_h_and_finger & 0x0F) as i32) << 8);
// action of touch (0 = down, 1 = up, 2 = contact)
touch.action = touch_x_h_and_action >> 6;
touch.finger_id = touch_y_h_and_finger >> 4;
// Compute touch pressure and area
touch.pressure = buf[Self::TOUCH_PRESURE_OFF];
touch.area = buf[Self::TOUCH_AREA_OFF] >> 4;
Some(touch)
}
/// The main method for getting the current touch event.
/// Returns a touch event if available.
///
/// - `check_int_pin` -- True if we should check the interrupt pin before attempting i2c read.
/// On some devices, attempting to read registers when there is no data available results
/// in a hang in the i2c read.
///
pub fn read_one_touch_event(&mut self, check_int_pin: bool) -> Option<TouchEvent> {
let mut one_event: Option<TouchEvent> = None;
// the interrupt pin should typically be low if there is data available;
// otherwise, attempting to read i2c will cause a stall
let data_available = !check_int_pin || self.pin_int.is_low().unwrap_or(false);
if data_available && self.read_truncated_registers().is_ok() {
let gesture_id = self.blob_buf[Self::GESTURE_ID_OFF];
let num_points = (self.blob_buf[Self::NUM_POINTS_OFF] & 0x0F) as usize;
if num_points <= Self::MAX_TOUCH_CHANNELS {
//In testing with a PineTime we only ever seem to get one event
let evt_start: usize = Self::GESTURE_HEADER_LEN;
if let Some(mut evt) = Self::touch_event_from_data(
self.blob_buf[evt_start..evt_start + Self::RAW_TOUCH_EVENT_LEN].as_ref(),
) {
evt.gesture = gesture_id.into();
one_event = Some(evt);
}
}
}
one_event
}
const DEFAULT_I2C_ADDRESS: u8 = 0x15;
pub const GESTURE_HEADER_LEN: usize = 3;
/// Number of bytes for a single touch event
pub const RAW_TOUCH_EVENT_LEN: usize = 6;
/// In essence, max number of fingers
pub const MAX_TOUCH_CHANNELS: usize = 10;
/// The first register on the device
const REG_FIRST: u8 = 0x00;
/// Header bytes (first three of every register block read)
// const RESERVED_0_OFF: usize = 0;
const GESTURE_ID_OFF: usize = 1;
const NUM_POINTS_OFF: usize = 2;
/// These offsets are relative to the body start (after NUM_POINTS_OFF)
/// offset of touch X position high bits and Action bits
const TOUCH_X_H_AND_ACTION_OFF: usize = 0;
/// offset of touch X position low bits
const TOUCH_X_L_OFF: usize = 1;
/// offset of touch Y position high bits and Finger bits
const TOUCH_Y_H_AND_FINGER_OFF: usize = 2;
/// offset of touch Y position low bits
const TOUCH_Y_L_OFF: usize = 3;
const TOUCH_PRESURE_OFF: usize = 4;
const TOUCH_AREA_OFF: usize = 5;
}
const BLOB_BUF_LEN: usize = (10 * 6) + 3; // (MAX_TOUCH_CHANNELS * RAW_TOUCH_EVENT_LEN) + GESTURE_HEADER_LEN;
const ONE_EVENT_LEN: usize = 6 + 3; // RAW_TOUCH_EVENT_LEN + GESTURE_HEADER_LEN
#[derive(Debug, PartialEq, Clone, Copy)]
#[repr(u8)]
pub enum TouchGesture {
None = 0x00,
SlideDown = 0x01,
SlideUp = 0x02,
SlideLeft = 0x03,
SlideRight = 0x04,
SingleClick = 0x05,
DoubleClick = 0x0B,
LongPress = 0x0C,
}
impl core::convert::From<u8> for TouchGesture {
fn from(val: u8) -> Self {
match val {
0x01 => Self::SlideDown,
0x02 => Self::SlideUp,
0x03 => Self::SlideLeft,
0x04 => Self::SlideRight,
0x05 => Self::SingleClick,
0x0B => Self::DoubleClick,
0x0C => Self::LongPress,
_ => Self::None,
}
}
}
/// Global interrupt handling support for ESP32C3
pub mod interrupt {
use super::*;
use esp_hal::InterruptConfigurable;
use esp_hal::gpio::Input;
use esp_hal::macros::handler;
use heapless::spsc::{Consumer, Producer, Queue};
/// Default queue capacity for touch events
const QUEUE_CAPACITY: usize = 16;
/// Type alias for the touch event receiver
pub type TouchReceiver = Consumer<'static, TouchEvent, QUEUE_CAPACITY>;
/// Global CST816S instance for interrupt handling (only accessed from interrupt)
static mut GLOBAL_INSTANCE: Option<
CST816S<
esp_hal::i2c::master::I2c<'static, esp_hal::Blocking>,
Input<'static>,
esp_hal::gpio::Output<'static>,
>,
> = None;
/// Global event queue - split into producer (interrupt) and consumer (main thread)
static mut EVENT_QUEUE: Queue<TouchEvent, QUEUE_CAPACITY> = Queue::new();
static mut PRODUCER: Option<Producer<'static, TouchEvent, QUEUE_CAPACITY>> = None;
/// Register a CST816S instance as the global interrupt handler
/// Returns a Receiver for reading touch events from the main thread
pub fn register(
instance: CST816S<
esp_hal::i2c::master::I2c<'static, esp_hal::Blocking>,
Input<'static>,
esp_hal::gpio::Output<'static>,
>,
io: &mut impl InterruptConfigurable,
) -> TouchReceiver {
use esp_hal::gpio::Event;
unsafe {
// Split the queue into producer and consumer
let event_queue = &raw mut EVENT_QUEUE;
let (producer, consumer) = (*event_queue).split();
(&raw mut PRODUCER).write(Some(producer));
// Store the instance (only accessed from interrupt)
(&raw mut GLOBAL_INSTANCE).write(Some(instance));
// Set up the interrupt handler first
io.set_interrupt_handler(gpio_interrupt_handler);
// Now enable the interrupt after handler is registered
// Using LowLevel for now to ensure we don't miss touches
let cst = (&raw mut GLOBAL_INSTANCE)
.as_mut()
.unwrap()
.as_mut()
.unwrap();
cst.pin_int.listen(Event::LowLevel);
// Return the consumer for the caller to use
consumer
}
}
/// ESP32C3 GPIO interrupt handler
#[handler]
pub fn gpio_interrupt_handler() {
unsafe {
let cst = (&raw mut GLOBAL_INSTANCE)
.as_mut()
.unwrap()
.as_mut()
.unwrap();
// Read a touch event from the i2c registers.
// We don't need to read them all, if there's any left over we'll get re-interupted.
if let Some(event) = cst.read_one_touch_event(
// The pin should be low since we just got the interrupt...But
// if interrupts were frozen for a while the controller might have dropped the event.
// Reading events when the pin isn't low causes the screen to freeze 😞
true,
) {
let producer = (&raw mut PRODUCER).as_mut().unwrap().as_mut().unwrap();
// Try to enqueue the event (drops if queue is full)
let _ = producer.enqueue(event);
}
// Clear the interrupt flag to let the interrupt controller we've
// dealt with the interrupt (if there are events left over it will
// re-interrupt us).
cst.pin_int.clear_interrupt();
}
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_coordinator/src/bitcoin.rs | frostsnap_coordinator/src/bitcoin.rs | pub mod chain_sync;
mod handler_state;
pub mod outgoing;
pub mod psbt;
pub mod status_tracker;
pub mod tofu;
pub mod wallet;
mod wallet_persist;
pub use wallet::PsbtValidationError;
use bdk_chain::{
bitcoin::{
self,
bip32::{ChildNumber, DerivationPath},
ScriptBuf,
},
miniscript::{
descriptor::{DerivPaths, DescriptorMultiXKey, Wildcard},
Descriptor, DescriptorPublicKey,
},
};
use frostsnap_core::{
tweak::{AppTweakKind, BitcoinAccount, BitcoinBip32Path, DerivationPathExt, Keychain},
MasterAppkey,
};
use wallet::KeychainId;
/// Descriptor for a key.
pub fn multi_x_descriptor_for_account(
master_appkey: MasterAppkey,
account: BitcoinAccount,
network: bitcoin::NetworkKind,
) -> Descriptor<DescriptorPublicKey> {
let bitcoin_app_xpub = master_appkey.derive_appkey(AppTweakKind::Bitcoin);
let account_xpub = bitcoin_app_xpub.derive_bip32(account.path_segments_from_bitcoin_appkey());
let keychains = [Keychain::External, Keychain::Internal];
let multi_xpub = DescriptorPublicKey::MultiXPub(DescriptorMultiXKey {
origin: Some((
bitcoin_app_xpub.fingerprint(),
DerivationPath::from_normal_path_segments(account.path_segments_from_bitcoin_appkey()),
)),
xkey: account_xpub.to_bitcoin_xpub_with_lies(network),
derivation_paths: DerivPaths::new(
keychains
.into_iter()
.map(|keychain| {
DerivationPath::master()
.child(ChildNumber::from_normal_idx(keychain as u32).unwrap())
})
.collect(),
)
.unwrap(),
wildcard: Wildcard::Unhardened,
});
let desc_key = multi_xpub;
Descriptor::new_tr(desc_key, None).expect("well formed")
}
pub fn descriptor_for_account_keychain(
keychain: KeychainId,
network: bitcoin::NetworkKind,
) -> Descriptor<DescriptorPublicKey> {
let idx = keychain.1.keychain as usize;
multi_x_descriptor_for_account(keychain.0, keychain.1.account, network)
.into_single_descriptors()
.expect("infallible")
.remove(idx)
}
fn peek_spk(approot: MasterAppkey, path: BitcoinBip32Path) -> ScriptBuf {
let descriptor = descriptor_for_account_keychain(
(approot, path.account_keychain),
bitcoin::NetworkKind::Main,
);
descriptor
.at_derivation_index(path.index)
.expect("infallible")
.script_pubkey()
}
#[cfg(test)]
mod test {
use bitcoin::Network;
use core::str::FromStr;
use frostsnap_core::tweak::{AccountKind, AppTweak, BitcoinAccountKeychain, BitcoinBip32Path};
use super::*;
#[test]
fn descriptor_should_match_frostsnap_core() {
let master_appkey = MasterAppkey::from_str("0325b0d1cda060241998916f45d02e227db436bdd708a55cf1dc67f3f534e332186fd6543fbfc5dd07094e93543fa05120f12d3a80876aa011a4897b7a0770d1fb").unwrap();
let account = BitcoinAccount {
kind: AccountKind::Segwitv1,
index: 0,
};
let internal_tweak = AppTweak::Bitcoin(BitcoinBip32Path {
account_keychain: BitcoinAccountKeychain {
account,
keychain: Keychain::Internal,
},
index: 84,
});
let external_tweak = AppTweak::Bitcoin(BitcoinBip32Path {
account_keychain: BitcoinAccountKeychain {
account,
keychain: Keychain::External,
},
index: 42,
});
let multi_x_descriptor =
multi_x_descriptor_for_account(master_appkey, account, bitcoin::NetworkKind::Main);
let descriptors = multi_x_descriptor.into_single_descriptors().unwrap();
let external_address = descriptors[0]
.at_derivation_index(42)
.unwrap()
.address(Network::Bitcoin)
.unwrap();
let internal_address = descriptors[1]
.at_derivation_index(84)
.unwrap()
.address(Network::Bitcoin)
.unwrap();
assert!(external_address.is_related_to_xonly_pubkey(
&external_tweak
.derive_xonly_key(&master_appkey.to_xpub())
.into()
));
assert!(internal_address.is_related_to_xonly_pubkey(
&internal_tweak
.derive_xonly_key(&master_appkey.to_xpub())
.into(),
));
assert_ne!(external_address, internal_address);
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_coordinator/src/settings.rs | frostsnap_coordinator/src/settings.rs | use crate::{
bitcoin::chain_sync::{default_backup_electrum_server, default_electrum_server},
persist::Persist,
};
use bdk_chain::{bitcoin, rusqlite_impl::migrate_schema};
use core::str::FromStr;
use rusqlite::params;
use std::collections::BTreeMap;
use tracing::{event, Level};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ElectrumEnabled {
#[default]
All,
PrimaryOnly,
None,
}
impl std::fmt::Display for ElectrumEnabled {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ElectrumEnabled::All => write!(f, "all"),
ElectrumEnabled::PrimaryOnly => write!(f, "primary_only"),
ElectrumEnabled::None => write!(f, "none"),
}
}
}
impl FromStr for ElectrumEnabled {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"all" => Ok(ElectrumEnabled::All),
"primary_only" => Ok(ElectrumEnabled::PrimaryOnly),
"none" => Ok(ElectrumEnabled::None),
_ => Err(anyhow::anyhow!("invalid electrum enabled value: {}", s)),
}
}
}
#[derive(Default)]
pub struct Settings {
pub electrum_servers: BTreeMap<bitcoin::Network, String>,
pub backup_electrum_servers: BTreeMap<bitcoin::Network, String>,
pub electrum_enabled: BTreeMap<bitcoin::Network, ElectrumEnabled>,
pub developer_mode: bool,
pub hide_balance: bool,
}
impl Settings {
pub fn set_developer_mode(&mut self, value: bool, mutations: &mut Vec<Mutation>) {
self.mutate(Mutation::SetDeveloperMode { value }, mutations);
}
pub fn set_hide_balance(&mut self, value: bool, mutations: &mut Vec<Mutation>) {
self.mutate(Mutation::SetHideBalance { value }, mutations);
}
pub fn get_electrum_server(&self, network: bitcoin::Network) -> String {
self.electrum_servers
.get(&network)
.cloned()
.or(Some(default_electrum_server(network).to_string()))
.expect("unsupported network")
}
pub fn get_backup_electrum_server(&self, network: bitcoin::Network) -> String {
self.backup_electrum_servers
.get(&network)
.cloned()
.unwrap_or(default_backup_electrum_server(network).to_string())
}
pub fn set_electrum_server(
&mut self,
network: bitcoin::Network,
url: String,
mutations: &mut Vec<Mutation>,
) {
self.mutate(Mutation::SetElectrumServer { network, url }, mutations)
}
pub fn set_backup_electrum_server(
&mut self,
network: bitcoin::Network,
url: String,
mutations: &mut Vec<Mutation>,
) {
self.mutate(
Mutation::SetBackupElectrumServer { network, url },
mutations,
)
}
pub fn get_electrum_enabled(&self, network: bitcoin::Network) -> ElectrumEnabled {
self.electrum_enabled
.get(&network)
.copied()
.unwrap_or_default()
}
pub fn set_electrum_enabled(
&mut self,
network: bitcoin::Network,
enabled: ElectrumEnabled,
mutations: &mut Vec<Mutation>,
) {
self.mutate(Mutation::SetElectrumEnabled { network, enabled }, mutations)
}
fn mutate(&mut self, mutation: Mutation, mutations: &mut Vec<Mutation>) {
self.apply_mutation(mutation.clone());
mutations.push(mutation);
}
fn apply_mutation(&mut self, mutation: Mutation) {
match mutation {
Mutation::SetDeveloperMode { value } => {
self.developer_mode = value;
}
Mutation::SetElectrumServer { network, url } => {
self.electrum_servers.insert(network, url);
}
Mutation::SetBackupElectrumServer { network, url } => {
self.backup_electrum_servers.insert(network, url);
}
Mutation::SetHideBalance { value } => {
self.hide_balance = value;
}
Mutation::SetElectrumEnabled { network, enabled } => {
self.electrum_enabled.insert(network, enabled);
}
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Mutation {
SetDeveloperMode {
value: bool,
},
SetElectrumServer {
network: bitcoin::Network,
url: String,
},
SetBackupElectrumServer {
network: bitcoin::Network,
url: String,
},
SetHideBalance {
value: bool,
},
SetElectrumEnabled {
network: bitcoin::Network,
enabled: ElectrumEnabled,
},
}
impl Persist<rusqlite::Connection> for Settings {
type Update = Vec<Mutation>;
type LoadParams = ();
fn migrate(conn: &mut rusqlite::Connection) -> anyhow::Result<()> {
const SCHEMA_NAME: &str = "frostsnap_settings";
const MIGRATIONS: &[&str] = &[
// Version 0
"CREATE TABLE IF NOT EXISTS fs_app_global_settings ( \
key TEXT PRIMARY KEY, \
value TEXT \
)",
];
let db_tx = conn.transaction()?;
migrate_schema(&db_tx, SCHEMA_NAME, MIGRATIONS)?;
db_tx.commit()?;
Ok(())
}
fn load(conn: &mut rusqlite::Connection, _: Self::LoadParams) -> anyhow::Result<Self>
where
Self: Sized,
{
let mut settings = Settings::default();
{
let mut stmt = conn.prepare("SELECT key, value FROM fs_app_global_settings")?;
let row_iter = stmt.query_map([], |row| {
let key = row.get::<_, String>(0)?;
let value = row.get::<_, String>(1)?;
Ok((key, value))
})?;
for row in row_iter {
let (key, value) = row?;
let span =
tracing::span!(Level::DEBUG, "global settings", key = key, value = value);
let _ = span.enter();
let mutation = match key.as_str() {
"developer_mode" => Mutation::SetDeveloperMode {
value: bool::from_str(value.as_str())?,
},
"hide_balance" => Mutation::SetHideBalance {
value: bool::from_str(value.as_str())?,
},
electrum_server if electrum_server.starts_with("electrum_server_") => {
let network = electrum_server.strip_prefix("electrum_server_").unwrap();
match bitcoin::Network::from_str(network) {
Ok(network) => Mutation::SetElectrumServer {
network,
url: value.to_string(),
},
Err(_) => {
event!(
Level::WARN,
network = network,
"bitcoin network not supported",
);
continue;
}
}
}
backup if backup.starts_with("backup_electrum_server_") => {
let network = backup.strip_prefix("backup_electrum_server_").unwrap();
match bitcoin::Network::from_str(network) {
Ok(network) => Mutation::SetBackupElectrumServer {
network,
url: value.to_string(),
},
Err(_) => {
event!(
Level::WARN,
network = network,
"bitcoin network not supported",
);
continue;
}
}
}
enabled if enabled.starts_with("electrum_enabled_") => {
let network = enabled.strip_prefix("electrum_enabled_").unwrap();
match (
bitcoin::Network::from_str(network),
ElectrumEnabled::from_str(&value),
) {
(Ok(network), Ok(enabled)) => {
Mutation::SetElectrumEnabled { network, enabled }
}
_ => {
event!(
Level::WARN,
key = key,
value = value,
"invalid electrum_enabled setting",
);
continue;
}
}
}
_ => {
event!(
Level::WARN,
key = key,
value = value,
"unknown global setting",
);
continue;
}
};
settings.apply_mutation(mutation);
}
}
Ok(settings)
}
fn persist_update(
&self,
conn: &mut rusqlite::Connection,
update: Self::Update,
) -> anyhow::Result<()> {
for mutation in update {
match mutation {
Mutation::SetDeveloperMode { value } => {
event!(Level::DEBUG, value = value, "changed developer mode");
conn.execute(
"INSERT OR REPLACE INTO fs_app_global_settings (key, value) VALUES (?1, ?2)",
params!["developer_mode", value.to_string()],
)?;
}
Mutation::SetElectrumServer { network, url } => {
event!(
Level::DEBUG,
network = network.to_string(),
url,
"set electrum server for network"
);
conn.execute(
"INSERT OR REPLACE INTO fs_app_global_settings (key, value) VALUES (?1, ?2)",
params![format!("electrum_server_{}", network), url.to_string()],
)?;
}
Mutation::SetBackupElectrumServer { network, url } => {
event!(
Level::DEBUG,
network = network.to_string(),
url,
"set backup electrum server for network"
);
conn.execute(
"INSERT OR REPLACE INTO fs_app_global_settings (key, value) VALUES (?1, ?2)",
params![format!("backup_electrum_server_{}", network), url.to_string()],
)?;
}
Mutation::SetHideBalance { value } => {
event!(Level::DEBUG, value = value, "changed hide balance");
conn.execute(
"INSERT OR REPLACE INTO fs_app_global_settings (key, value) VALUES (?1, ?2)",
params!["hide_balance", value.to_string()],
)?;
}
Mutation::SetElectrumEnabled { network, enabled } => {
event!(
Level::DEBUG,
network = network.to_string(),
enabled = enabled.to_string(),
"set electrum enabled for network"
);
conn.execute(
"INSERT OR REPLACE INTO fs_app_global_settings (key, value) VALUES (?1, ?2)",
params![format!("electrum_enabled_{}", network), enabled.to_string()],
)?;
}
}
}
Ok(())
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_coordinator/src/persist.rs | frostsnap_coordinator/src/persist.rs | use std::{io::BufReader, ops::Deref, str::FromStr};
use anyhow::Result;
use bdk_chain::bitcoin::{
consensus::{Decodable, Encodable},
Txid,
};
use rusqlite::{
types::{FromSql, FromSqlError, ToSqlOutput},
ToSql,
};
pub struct Persisted<T>(T);
impl<T> Persisted<T> {
pub fn mutate<C, R, U>(
&mut self,
db: &mut C,
mutator: impl FnOnce(&mut T) -> Result<(R, U)>,
) -> Result<R>
where
T: Persist<C>,
U: Into<T::Update>,
{
let (ret, update) = (mutator)(&mut self.0)?;
self.0.persist_update(db, update.into())?;
Ok(ret)
}
pub fn mutate2<C, R>(
&mut self,
db: &mut C,
mutator: impl FnOnce(&mut T, &mut T::Update) -> Result<R>,
) -> Result<R>
where
T: Persist<C>,
T::Update: Default,
{
let mut update = T::Update::default();
let result = (mutator)(&mut self.0, &mut update);
self.0.persist_update(db, update)?;
result
}
pub fn staged_mutate<C, R>(
&mut self,
db: &mut C,
mutator: impl FnOnce(&mut T) -> Result<R>,
) -> Result<R>
where
T: Persist<C> + TakeStaged<T::Update>,
{
let ret = mutator(&mut self.0)?;
let update = self.0.take_staged_update();
if let Some(update) = update {
self.0.persist_update(db, update)?;
}
Ok(ret)
}
#[allow(non_snake_case)]
/// Scary upppercase method that allows you opt-out of persisting anything at the end of a mutation
pub fn MUTATE_NO_PERSIST(&mut self) -> &mut T {
&mut self.0
}
pub fn multi<'a, 'b, B>(
&'a mut self,
other: &'b mut Persisted<B>,
) -> Multi<(&'a mut Self, &'b mut Persisted<B>)> {
Multi((self, other))
}
pub fn new<C>(db: &mut C, params: T::LoadParams) -> Result<Self>
where
T: Persist<C>,
{
T::migrate(db)?;
Ok(Persisted(T::load(db, params)?))
}
}
pub struct Multi<L>(L);
macro_rules! impl_multi {
($($name:tt $uname:ident $index:tt),+) => {
#[allow(unused_parens)]
impl<'a, $($name),+> Multi<($(&'a mut Persisted<$name>,)+)> {
#[allow(non_snake_case)]
pub fn mutate<Conn, R, $($uname),+>(
&mut self,
db: &mut Conn,
mutator: impl FnOnce($(&mut $name),+) -> Result<(R, ($($uname),+))>,
) -> Result<R>
where
$(
$uname: Into<$name::Update>,
$name: Persist<Conn>,
)+
{
#[allow(non_snake_case)]
let (ret, ($($uname),+)) = mutator($(&mut self.0.$index.0),+)?;
$(
self.0.$index.0.persist_update(db, $uname.into())?;
)+
Ok(ret)
}
pub fn multi<'n, N>(self, next: &'n mut Persisted<N>) -> Multi<($(&'a mut Persisted<$name>,)+ &'n mut Persisted<N>)> {
Multi(($(self.0.$index,)+ next))
}
}
};
}
// Generate the implementations for tuples up to 10 items, including single element tuple
impl_multi!(A UA 0);
impl_multi!(A UA 0, B UB 1);
impl_multi!(A UA 0, B UB 1, C UC 2);
impl_multi!(A UA 0, B UB 1, C UC 2, D UD 3);
impl_multi!(A UA 0, B UB 1, C UC 2, D UD 3, E UE 4);
impl_multi!(A UA 0, B UB 1, C UC 2, D UD 3, E UE 4, F UF 5);
impl_multi!(A UA 0, B UB 1, C UC 2, D UD 3, E UE 4, F UF 5, G UG 6);
impl_multi!(A UA 0, B UB 1, C UC 2, D UD 3, E UE 4, F UF 5, G UG 6, H UH 7);
impl_multi!(A UA 0, B UB 1, C UC 2, D UD 3, E UE 4, F UF 5, G UG 6, H UH 7, I UI 8);
impl_multi!(A UA 0, B UB 1, C UC 2, D UD 3, E UE 4, F UF 5, G UG 6, H UH 7, I UI 8, J UJ 9);
impl<T> AsRef<T> for Persisted<T> {
fn as_ref(&self) -> &T {
&self.0
}
}
impl<T> Deref for Persisted<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
pub trait Persist<C> {
type Update;
type LoadParams;
fn migrate(conn: &mut C) -> Result<()>;
fn load(conn: &mut C, params: Self::LoadParams) -> Result<Self>
where
Self: Sized;
fn persist_update(&self, conn: &mut C, update: Self::Update) -> Result<()>;
}
pub trait TakeStaged<U> {
fn take_staged_update(&mut self) -> Option<U>;
}
pub struct SqlBitcoinTransaction<T = bdk_chain::bitcoin::Transaction>(pub T);
impl FromSql for SqlBitcoinTransaction {
fn column_result(value: rusqlite::types::ValueRef<'_>) -> rusqlite::types::FromSqlResult<Self> {
match value {
rusqlite::types::ValueRef::Blob(blob) => {
let tx =
bdk_chain::bitcoin::Transaction::consensus_decode(&mut BufReader::new(blob))
.map_err(|e| FromSqlError::Other(Box::new(e)))?;
Ok(SqlBitcoinTransaction(tx))
}
_ => Err(FromSqlError::InvalidType),
}
}
}
impl<T: Deref<Target = bdk_chain::bitcoin::Transaction>> ToSql for SqlBitcoinTransaction<T> {
fn to_sql(&self) -> Result<ToSqlOutput<'_>, rusqlite::Error> {
let mut buf = Vec::<u8>::new();
self.0
.consensus_encode(&mut buf)
.expect("transaction can be encoded");
Ok(ToSqlOutput::from(buf))
}
}
pub struct SqlTxid(pub bdk_chain::bitcoin::Txid);
impl FromSql for SqlTxid {
fn column_result(value: rusqlite::types::ValueRef<'_>) -> rusqlite::types::FromSqlResult<Self> {
Ok(SqlTxid(
Txid::from_str(value.as_str()?).map_err(|e| FromSqlError::Other(Box::new(e)))?,
))
}
}
impl ToSql for SqlTxid {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
Ok(ToSqlOutput::from(self.0.to_string()))
}
}
pub struct SqlBlockHash(pub bdk_chain::bitcoin::BlockHash);
impl FromSql for SqlBlockHash {
fn column_result(value: rusqlite::types::ValueRef<'_>) -> rusqlite::types::FromSqlResult<Self> {
Ok(SqlBlockHash(
bdk_chain::bitcoin::BlockHash::from_str(value.as_str()?)
.map_err(|e| FromSqlError::Other(Box::new(e)))?,
))
}
}
impl ToSql for SqlBlockHash {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
Ok(ToSqlOutput::from(self.0.to_string()))
}
}
pub struct SqlDescriptorId(pub bdk_chain::DescriptorId);
impl FromSql for SqlDescriptorId {
fn column_result(value: rusqlite::types::ValueRef<'_>) -> rusqlite::types::FromSqlResult<Self> {
Ok(SqlDescriptorId(
bdk_chain::DescriptorId::from_str(value.as_str()?)
.map_err(|e| FromSqlError::Other(Box::new(e)))?,
))
}
}
impl ToSql for SqlDescriptorId {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
Ok(ToSqlOutput::from(self.0.to_string()))
}
}
pub struct SqlSignSessionId(pub frostsnap_core::SignSessionId);
impl FromSql for SqlSignSessionId {
fn column_result(value: rusqlite::types::ValueRef<'_>) -> rusqlite::types::FromSqlResult<Self> {
use frostsnap_core::SignSessionId;
let blob_data = value.as_blob()?;
if blob_data.len() != SignSessionId::LEN {
return Err(FromSqlError::InvalidBlobSize {
expected_size: SignSessionId::LEN,
blob_size: blob_data.len(),
});
}
Ok(SqlSignSessionId(
SignSessionId::from_slice(blob_data).expect("already checked len"),
))
}
}
impl ToSql for SqlSignSessionId {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
Ok(ToSqlOutput::from(self.0.to_bytes().to_vec()))
}
}
pub struct SqlPsbt(pub bdk_chain::bitcoin::Psbt);
impl FromSql for SqlPsbt {
fn column_result(value: rusqlite::types::ValueRef<'_>) -> rusqlite::types::FromSqlResult<Self> {
use bdk_chain::bitcoin::Psbt;
let psbt =
Psbt::deserialize(value.as_bytes()?).map_err(|e| FromSqlError::Other(Box::new(e)))?;
Ok(SqlPsbt(psbt))
}
}
impl ToSql for SqlPsbt {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
Ok(ToSqlOutput::from(self.0.serialize()))
}
}
pub struct BincodeWrapper<T>(pub T);
impl<T: bincode::Encode> ToSql for BincodeWrapper<T> {
fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
let bytes = bincode::encode_to_vec(&self.0, bincode::config::standard()).unwrap();
Ok(ToSqlOutput::from(bytes))
}
}
impl<T: bincode::Decode<()>> FromSql for BincodeWrapper<T> {
fn column_result(value: rusqlite::types::ValueRef<'_>) -> rusqlite::types::FromSqlResult<Self> {
let (decoded, _len) =
bincode::decode_from_slice::<T, _>(value.as_blob()?, bincode::config::standard())
.map_err(|e| FromSqlError::Other(Box::new(e)))?;
Ok(Self(decoded))
}
}
pub struct ToStringWrapper<T>(pub T);
impl<T: ToString> ToSql for ToStringWrapper<T> {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
Ok(ToSqlOutput::from(self.0.to_string()))
}
}
impl<T: FromStr> FromSql for ToStringWrapper<T>
where
T::Err: std::error::Error + Send + 'static + Sync,
{
fn column_result(value: rusqlite::types::ValueRef<'_>) -> rusqlite::types::FromSqlResult<Self> {
let decoded = T::from_str(value.as_str()?).map_err(|e| FromSqlError::Other(Box::new(e)))?;
Ok(Self(decoded))
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_coordinator/src/lib.rs | frostsnap_coordinator/src/lib.rs | pub mod backup_run;
pub mod display_backup;
pub mod enter_physical_backup;
pub mod firmware;
pub mod firmware_upgrade;
pub mod keygen;
pub mod nonce_replenish;
mod serial_port;
pub mod signing;
mod ui_protocol;
mod usb_serial_manager;
pub mod verify_address;
pub mod wait_for_single_device;
mod wait_for_to_user_message;
pub use wait_for_to_user_message::*;
#[cfg(any(target_os = "linux", target_os = "android"))]
pub mod cdc_acm_usb;
pub use frostsnap_comms;
pub use frostsnap_core;
pub use serial_port::*;
pub mod settings;
pub use firmware::{
FirmwareBin, FirmwareUpgradeEligibility, FirmwareValidationError, FirmwareVersion,
ValidatedFirmwareBin, VersionNumber,
};
pub use ui_protocol::*;
pub use usb_serial_manager::*;
pub mod bitcoin;
pub use bdk_chain;
pub mod frostsnap_persist;
pub mod persist;
pub trait Sink<M>: Send + 'static {
fn send(&self, state: M);
fn inspect<F: Fn(&M)>(self, f: F) -> SinkInspect<Self, F>
where
Self: Sized,
{
SinkInspect { inner: self, f }
}
}
impl<M> Sink<M> for () {
fn send(&self, _: M) {}
}
pub struct SinkInspect<S, F> {
inner: S,
f: F,
}
impl<M, S: Sink<M>, F: Fn(&M) + Send + 'static> Sink<M> for SinkInspect<S, F> {
fn send(&self, state: M) {
(self.f)(&state);
self.inner.send(state);
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_coordinator/src/keygen.rs | frostsnap_coordinator/src/keygen.rs | use std::collections::BTreeSet;
use crate::{Completion, Sink, UiProtocol};
use frostsnap_comms::CoordinatorSendMessage;
use frostsnap_core::{
coordinator::{
BeginKeygen, CoordinatorToUserKeyGenMessage, CoordinatorToUserMessage, FrostCoordinator,
},
AccessStructureRef, DeviceId, KeygenId, SessionHash,
};
use tracing::{event, Level};
pub struct KeyGen {
sink: Box<dyn Sink<KeyGenState>>,
state: KeyGenState,
keygen_messages: Vec<CoordinatorSendMessage>,
send_cancel_to_all: bool,
}
impl KeyGen {
pub fn new(
keygen_sink: impl Sink<KeyGenState> + 'static,
coordinator: &mut FrostCoordinator,
currently_connected: BTreeSet<DeviceId>,
begin_keygen: BeginKeygen,
rng: &mut impl rand_core::RngCore,
) -> Self {
let mut self_ = Self {
sink: Box::new(keygen_sink),
state: KeyGenState {
devices: begin_keygen.devices_in_order.clone(),
threshold: begin_keygen.threshold.into(),
keygen_id: begin_keygen.keygen_id,
..Default::default()
},
keygen_messages: vec![],
send_cancel_to_all: false,
};
if !currently_connected.is_superset(&begin_keygen.devices()) {
self_.abort("A selected device was disconnected".into(), false);
}
match coordinator.begin_keygen(begin_keygen, rng) {
Ok(messages) => {
for message in messages {
self_.keygen_messages.push(
message
.try_into()
.expect("will only send messages to device"),
);
}
}
Err(e) => self_.abort(format!("couldn't start keygen: {e}"), false),
}
self_
}
pub fn emit_state(&self) {
self.sink.send(self.state.clone());
}
fn abort(&mut self, reason: String, send_cancel_to_all: bool) {
self.state.aborted = Some(reason);
self.send_cancel_to_all = send_cancel_to_all;
self.emit_state();
}
pub fn keygen_finalized(&mut self, as_ref: AccessStructureRef) {
self.state.finished = Some(as_ref);
self.emit_state()
}
}
impl UiProtocol for KeyGen {
fn cancel(&mut self) {
self.abort("Key generation canceled".into(), true);
}
fn is_complete(&self) -> Option<Completion> {
if self.state.finished.is_some() {
Some(Completion::Success)
} else if self.state.aborted.is_some() {
Some(Completion::Abort {
send_cancel_to_all_devices: true,
})
} else {
None
}
}
fn process_to_user_message(&mut self, message: CoordinatorToUserMessage) -> bool {
if let CoordinatorToUserMessage::KeyGen { keygen_id, inner } = message {
if keygen_id == self.state.keygen_id {
match inner {
CoordinatorToUserKeyGenMessage::ReceivedShares { from } => {
self.state.got_shares.push(from);
if self.state.got_shares.len() == self.state.devices.len() {
self.state.all_shares = true;
}
}
CoordinatorToUserKeyGenMessage::CheckKeyGen { session_hash } => {
self.state.session_hash = Some(session_hash);
}
CoordinatorToUserKeyGenMessage::KeyGenAck {
from,
all_acks_received,
} => {
self.state.session_acks.push(from);
assert_eq!(
all_acks_received,
self.state.session_acks.len() == self.state.devices.len(),
);
self.state.all_acks = all_acks_received;
}
}
}
self.emit_state();
true
} else {
false
}
}
fn poll(&mut self) -> Vec<CoordinatorSendMessage> {
core::mem::take(&mut self.keygen_messages)
}
fn disconnected(&mut self, id: frostsnap_core::DeviceId) {
if self.state.devices.contains(&id) {
event!(
Level::ERROR,
id = id.to_string(),
"Device disconnected during keygen"
);
self.abort(
"Key generation failed because a device was disconnected".into(),
true,
);
self.emit_state();
}
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn as_mut_any(&mut self) -> &mut dyn std::any::Any {
self
}
}
#[derive(Clone, Debug, Default)]
pub struct KeyGenState {
pub threshold: usize,
pub devices: Vec<DeviceId>, // not a set for frb compat
pub got_shares: Vec<DeviceId>,
pub all_shares: bool,
pub session_acks: Vec<DeviceId>,
pub all_acks: bool,
pub session_hash: Option<SessionHash>,
pub finished: Option<AccessStructureRef>,
pub aborted: Option<String>,
pub keygen_id: KeygenId,
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_coordinator/src/usb_serial_manager.rs | frostsnap_coordinator/src/usb_serial_manager.rs | // USB CDC vid and pid
const USB_VID: u16 = 12346;
const USB_PID: u16 = 4097;
use crate::firmware::ValidatedFirmwareBin;
use crate::PortOpenError;
use crate::{FramedSerialPort, Serial};
use anyhow::anyhow;
use frostsnap_comms::genuine_certificate::CertificateVerifier;
use frostsnap_comms::DeviceName;
use frostsnap_comms::{CommsMisc, ReceiveSerial};
use frostsnap_comms::{
CoordinatorSendBody, CoordinatorUpgradeMessage, Destination, DeviceSendBody, Sha256Digest,
FIRMWARE_NEXT_CHUNK_READY_SIGNAL, FIRMWARE_UPGRADE_CHUNK_LEN,
};
use frostsnap_comms::{CoordinatorSendMessage, MAGIC_BYTES_PERIOD};
use frostsnap_core::message::DeviceToCoordinatorMessage;
use frostsnap_core::schnorr_fun::fun::marker::EvenY;
use frostsnap_core::schnorr_fun::fun::Point;
use frostsnap_core::sha2::Sha256;
use frostsnap_core::{sha2, DeviceId, Gist};
use rsa::pkcs1::DecodeRsaPublicKey;
use rsa::RsaPublicKey;
use sha2::Digest;
use std::collections::BTreeSet;
use std::collections::HashMap;
use std::collections::HashSet;
use std::time::Duration;
use tracing::{event, span, Level};
/// Manages the communication between coordinator and USB serial device ports given Some `S` serial
/// system API.
pub struct UsbSerialManager {
serial_impl: Box<dyn Serial>,
/// Matches VID and PID
connected: HashSet<String>,
/// Initial state
pending: HashSet<String>,
/// After opening port and awaiting magic bytes
awaiting_magic: HashMap<String, AwaitingMagic>,
/// Read magic magic bytes
ready: HashMap<String, FramedSerialPort>,
/// ports that seems to be busy
ignored: HashSet<String>,
/// Devices who Announce'd, mappings to port serial numbers
device_ports: HashMap<DeviceId, DevicePort>,
/// Reverse lookup from ports to devices (daisy chaining)
reverse_device_ports: HashMap<String, Vec<DeviceId>>,
/// Devices we sent registration ACK to
registered_devices: BTreeSet<DeviceId>,
/// Device labels
device_names: HashMap<DeviceId, String>,
/// Messages to devices waiting to be sent
port_outbox: std::sync::mpsc::Receiver<CoordinatorSendMessage>,
/// sometimes we need to put things in the outbox internally
outbox_sender: std::sync::mpsc::Sender<CoordinatorSendMessage>,
/// The firmware binary provided to devices who are doing an upgrade
firmware_bin: Option<ValidatedFirmwareBin>,
/// Ongoing genuine check challenges to devices
challenges: HashMap<DeviceId, [u8; 32]>,
}
pub struct DevicePort {
port: String,
firmware_digest: Sha256Digest,
}
const COORDINATOR_MAGIC_BYTES_PERDIOD: std::time::Duration =
std::time::Duration::from_millis(MAGIC_BYTES_PERIOD);
struct AwaitingMagic {
port: FramedSerialPort,
last_wrote_magic_bytes: Option<std::time::Instant>,
}
impl UsbSerialManager {
/// Returns self and a `UsbSender` which can be used to queue messages
pub fn new(serial_impl: Box<dyn Serial>, firmware_bin: Option<ValidatedFirmwareBin>) -> Self {
let (sender, receiver) = std::sync::mpsc::channel();
Self {
serial_impl,
connected: Default::default(),
pending: Default::default(),
awaiting_magic: Default::default(),
ready: Default::default(),
ignored: Default::default(),
device_ports: Default::default(),
reverse_device_ports: Default::default(),
registered_devices: Default::default(),
device_names: Default::default(),
port_outbox: receiver,
outbox_sender: sender,
firmware_bin,
challenges: Default::default(),
}
}
pub fn usb_sender(&self) -> UsbSender {
UsbSender {
sender: self.outbox_sender.clone(),
}
}
fn disconnect(&mut self, port: &str, changes: &mut Vec<DeviceChange>) {
event!(Level::INFO, port = port, "disconnecting port");
self.connected.remove(port);
self.pending.remove(port);
self.awaiting_magic.remove(port);
self.ready.remove(port);
self.ignored.remove(port);
if let Some(device_ids) = self.reverse_device_ports.remove(port) {
for device_id in device_ids {
if self.device_ports.remove(&device_id).is_some() {
changes.push(DeviceChange::Disconnected { id: device_id });
}
self.registered_devices.remove(&device_id);
event!(
Level::DEBUG,
port = port,
device_id = device_id.to_string(),
"removing device because of disconnected port"
)
}
}
}
pub fn active_ports(&self) -> HashSet<String> {
self.registered_devices
.iter()
.filter_map(|device_id| {
self.device_ports
.get(device_id)
.map(|device_port| &device_port.port)
})
.cloned()
.collect::<HashSet<_>>()
}
pub fn poll_ports(&mut self) -> Vec<DeviceChange> {
let span = span!(Level::DEBUG, "poll_ports");
let _enter = span.enter();
let mut device_changes = vec![];
let connected_now: HashSet<String> = self
.serial_impl
.available_ports()
.into_iter()
.filter(|desc| desc.vid == USB_VID && desc.pid == USB_PID)
.map(|desc| desc.id)
.collect();
let newly_connected_ports = connected_now
.difference(&self.connected)
.cloned()
.collect::<Vec<_>>();
for port in newly_connected_ports {
event!(Level::INFO, port = port, "USB port connected");
self.connected.insert(port.clone());
self.pending.insert(port.clone());
}
let disconnected_ports = self
.connected
.difference(&connected_now)
.cloned()
.collect::<Vec<_>>();
for port in disconnected_ports {
event!(
Level::DEBUG,
port = port.to_string(),
"USB port disconnected"
);
self.disconnect(&port, &mut device_changes);
}
for port_name in self.pending.drain().collect::<Vec<_>>() {
let device_port = self
.serial_impl
.open_device_port(&port_name, frostsnap_comms::BAUDRATE)
.map(FramedSerialPort::new);
match device_port {
Err(e) => match e {
PortOpenError::DeviceBusy => {
if !self.ignored.contains(&port_name) {
event!(
Level::ERROR,
port = port_name,
"Could not open port because it's being used by another process"
);
self.ignored.insert(port_name.clone());
}
}
PortOpenError::PermissionDenied => {
if !self.ignored.contains(&port_name) {
event!(
Level::ERROR,
port = port_name,
"Could not open port: permission denied (udev rules may not be installed)"
);
self.ignored.insert(port_name.clone());
}
}
PortOpenError::Other(e) => {
event!(
Level::ERROR,
port = port_name,
error = e.to_string(),
"Failed to open port"
);
self.pending.insert(port_name);
}
},
Ok(device_port) => {
event!(Level::DEBUG, port = port_name, "Opened port");
self.awaiting_magic.insert(
port_name.clone(),
AwaitingMagic {
port: device_port,
last_wrote_magic_bytes: None,
},
);
}
}
}
for (port_name, mut awaiting_magic) in self.awaiting_magic.drain().collect::<Vec<_>>() {
let device_port = &mut awaiting_magic.port;
match device_port.read_for_magic_bytes() {
Ok(Some(supported_features)) => {
event!(Level::DEBUG, port = port_name, "Read magic bytes");
device_port.set_conch_enabled(supported_features.conch_enabled);
self.ready.insert(port_name, awaiting_magic.port);
}
Ok(None) => {
let time_since_last_wrote_magic = awaiting_magic
.last_wrote_magic_bytes
.as_ref()
.map(std::time::Instant::elapsed)
.unwrap_or(std::time::Duration::MAX);
if time_since_last_wrote_magic < COORDINATOR_MAGIC_BYTES_PERDIOD {
self.awaiting_magic.insert(port_name, awaiting_magic);
continue;
}
match device_port.write_magic_bytes() {
Ok(_) => {
event!(Level::DEBUG, port = port_name, "Wrote magic bytes");
awaiting_magic.last_wrote_magic_bytes = Some(std::time::Instant::now());
// we still need to read them so go again
self.awaiting_magic.insert(port_name, awaiting_magic);
}
Err(e) => {
event!(
Level::ERROR,
port = port_name,
e = e.to_string(),
"Failed to write magic bytes"
);
self.disconnect(&port_name, &mut device_changes);
}
}
}
Err(e) => {
event!(
Level::DEBUG,
port = port_name,
e = e.to_string(),
"failed to read magic bytes"
);
self.disconnect(&port_name, &mut device_changes);
}
}
}
// Read all messages from ready devices
for port_name in self.ready.keys().cloned().collect::<Vec<_>>() {
let frame = {
let device_port = self.ready.get_mut(&port_name).expect("must exist");
match device_port.try_read_message() {
Err(e) => {
event!(
Level::ERROR,
port = port_name,
error = e.to_string(),
"failed to read message from port"
);
self.disconnect(&port_name, &mut device_changes);
continue;
}
Ok(None) => continue,
Ok(Some(message)) => message,
}
};
match frame {
ReceiveSerial::MagicBytes(_) => {
event!(Level::ERROR, port = port_name, "Unexpected magic bytes");
self.disconnect(&port_name, &mut device_changes);
}
ReceiveSerial::Message(message) => {
match message.body.decode() {
Err(e) => {
event!(
Level::WARN,
from = message.from.to_string(),
error = e.to_string(),
"failed to decode encapsulated message - ignoring"
);
}
Ok(decoded) => {
event!(
Level::DEBUG,
from = message.from.to_string(),
port = port_name,
gist = decoded.gist(),
"decoded message"
);
match decoded {
DeviceSendBody::NeedName => device_changes
.push(DeviceChange::NeedsName { id: message.from }),
DeviceSendBody::DisconnectDownstream => {
if let Some(device_list) =
self.reverse_device_ports.get_mut(&port_name)
{
if let Some((i, _)) = device_list
.iter()
.enumerate()
.find(|(_, device_id)| **device_id == message.from)
{
let index_of_disconnection = i + 1;
while device_list.len() > index_of_disconnection {
let device_id = device_list.pop().unwrap();
self.device_ports.remove(&device_id);
self.registered_devices.remove(&device_id);
device_changes.push(DeviceChange::Disconnected {
id: device_id,
});
}
}
}
}
DeviceSendBody::SetName { name } => {
let name_string = name.to_string();
let existing_name = self.device_names.get(&message.from);
if existing_name != Some(&name_string) {
device_changes.push(DeviceChange::NameChange {
id: message.from,
name: name_string,
});
}
}
DeviceSendBody::Announce { firmware_digest } => {
self.handle_announce(
&port_name,
message.from,
firmware_digest,
&mut device_changes,
);
}
DeviceSendBody::Debug { message: _ } => {
// XXX: We don't need to debug log this because we already debug log the gist of every message
// event!(
// Level::DEBUG,
// port = port_name,
// from = message.from.to_string(),
// name = self
// .device_names
// .get(&message.from)
// .cloned()
// .unwrap_or("<unknown>".into()),
// dbg_message
// );
}
DeviceSendBody::Core(core_msg) => {
device_changes.push(DeviceChange::AppMessage(AppMessage {
from: message.from,
body: AppMessageBody::Core(Box::new(core_msg)),
}));
}
DeviceSendBody::_LegacyAckUpgradeMode => {
device_changes.push(DeviceChange::AppMessage(AppMessage {
from: message.from,
body: AppMessageBody::Misc(CommsMisc::AckUpgradeMode),
}))
}
DeviceSendBody::Misc(inner) => {
device_changes.push(DeviceChange::AppMessage(AppMessage {
from: message.from,
body: AppMessageBody::Misc(inner),
}))
}
DeviceSendBody::SignedChallenge {
signature,
certificate,
} => {
if let Some(challenge) = self.challenges.remove(&message.from) {
let factory_key: Point<EvenY> = Point::from_xonly_bytes(
frostsnap_comms::FACTORY_PUBLIC_KEY,
)
.unwrap();
if let Some(certificate_body) = CertificateVerifier::verify(
certificate.as_ref(),
factory_key,
) {
match RsaPublicKey::from_pkcs1_der(
certificate_body.ds_public_key(),
) {
Err(_) => {
// TODO: similarly we probably shouldnt silently ignore invalid rsa keys
}
Ok(ds_public_key) => {
let padding =
rsa::Pkcs1v15Sign::new::<Sha256>();
let message_digest: [u8; 32] =
sha2::Sha256::digest(challenge).into();
if ds_public_key
.verify(
padding,
&message_digest,
signature.as_ref(),
)
.is_ok()
{
device_changes.push(
DeviceChange::GenuineDevice {
id: message.from,
},
)
} // TODO: probably want to note if a device fails genuine
}
}
}
}
}
}
}
}
}
ReceiveSerial::Reset => {
event!(Level::DEBUG, port = port_name, "Read reset downstream!");
self.disconnect(&port_name, &mut device_changes);
}
_ => { /* unused */ }
}
}
for device_id in self.device_ports.keys() {
if self.registered_devices.contains(device_id) {
continue;
}
if let Some(device_label) = self.device_names.get(device_id) {
event!(
Level::INFO,
device_id = device_id.to_string(),
"Registered device"
);
self.registered_devices.insert(*device_id);
device_changes.push(DeviceChange::Registered {
id: *device_id,
name: device_label.to_string(),
});
}
}
while let Ok(mut send) = self.port_outbox.try_recv() {
let mut ports_to_send_on = HashSet::new();
let wire_destinations = match &mut send.target_destinations {
Destination::All => {
ports_to_send_on.extend(
self.device_ports
.values()
.map(|device_port| &device_port.port)
.cloned(),
);
Destination::All
}
Destination::Particular(devices) => {
// You might be wondering why we bother to narrow down the wire destinations to
// those devices that are actually available. There is no good reason for this
// atm but it used to be necessary and it's nice to have only the devices that
// were actually visible to the coordinator on a particular port receive
// messages for sanity.
let mut destinations_available_now = BTreeSet::default();
devices.retain(|destination| match self.device_ports.get(destination) {
Some(device_port) => {
ports_to_send_on.insert(device_port.port.clone());
destinations_available_now.insert(*destination);
false
}
None => true,
});
if !devices.is_empty() {
event!(
Level::DEBUG,
kind = send.gist(),
"message not sent to all intended recipients"
);
}
Destination::Particular(destinations_available_now)
}
};
let mut message = send.clone();
message.target_destinations = wire_destinations;
let dest_span = tracing::span!(
Level::DEBUG,
"",
destinations = message.target_destinations.gist()
);
let _dest_enter = dest_span.enter();
let gist = message.gist();
for port_name in ports_to_send_on {
let span =
tracing::span!(Level::INFO, "send on port", port = port_name, gist = gist);
let _enter = span.enter();
let port = match self.ready.get_mut(&port_name) {
Some(port) => port,
None => {
event!(
Level::DEBUG,
"not sending message because port was disconnected"
);
continue;
}
};
event!(Level::DEBUG, message = message.gist(), "queueing message");
port.queue_send(message.clone().into());
}
}
// poll the ports to send any messages we just queued (or queued from earlier!).
// This is a separate step since we only send messages if we have the conch.
for port_name in self.ready.keys().cloned().collect::<Vec<_>>() {
let port = self.ready.get_mut(&port_name).expect("must exist");
match port.poll_send() {
Err(e) => {
event!(
Level::ERROR,
port = port_name,
error = e.to_string(),
"Failed to poll sending",
);
self.disconnect(&port_name, &mut device_changes);
}
Ok(_) => { /* nothing to do */ }
}
}
device_changes
}
fn handle_announce(
&mut self,
port_name: &str,
from: DeviceId,
firmware_digest: Sha256Digest,
device_changes: &mut Vec<DeviceChange>,
) {
match self.device_ports.insert(
from,
DevicePort {
port: port_name.to_string(),
firmware_digest,
},
) {
Some(old_port_name) => {
self.reverse_device_ports
.entry(old_port_name.port)
.or_default()
.retain(|device_id| *device_id != from);
}
None => device_changes.push(DeviceChange::Connected {
id: from,
firmware_digest,
latest_firmware_digest: self.firmware_bin.map(|firmware_bin| firmware_bin.digest()),
}),
}
self.outbox_sender
.send(CoordinatorSendMessage::to(
from,
CoordinatorSendBody::AnnounceAck,
))
.unwrap();
self.reverse_device_ports
.entry(port_name.to_string())
.or_default()
.push(from);
event!(
Level::DEBUG,
port = port_name,
id = from.to_string(),
"Announced!"
);
}
pub fn registered_devices(&self) -> &BTreeSet<DeviceId> {
&self.registered_devices
}
pub fn accept_device_name(&mut self, id: DeviceId, name: String) {
self.device_names.insert(id, name);
}
pub fn serial_impl(&self) -> &dyn Serial {
&*self.serial_impl
}
pub fn serial_impl_mut(&mut self) -> &mut dyn Serial {
&mut *self.serial_impl
}
pub fn devices_by_ports(&self) -> &HashMap<String, Vec<DeviceId>> {
&self.reverse_device_ports
}
/// The firmware digest the device has declared it has
pub fn firmware_digest_for_device(&self, device_id: DeviceId) -> Option<Sha256Digest> {
self.device_ports
.get(&device_id)
.map(|device_port| device_port.firmware_digest)
}
pub fn upgrade_bin(&self) -> Option<ValidatedFirmwareBin> {
self.firmware_bin
}
pub fn run_firmware_upgrade(
&mut self,
) -> anyhow::Result<impl Iterator<Item = anyhow::Result<f32>> + '_> {
let firmware_bin = self.firmware_bin.ok_or(anyhow!(
"App wasn't compiled with BUNDLE_FIRMWARE=1 so it can't do firmware upgrades"
))?;
let n_chunks = firmware_bin.size().div_ceil(FIRMWARE_UPGRADE_CHUNK_LEN);
let total_chunks = n_chunks * self.ready.len() as u32;
let mut iters = vec![];
for (port_index, (port, io)) in self.ready.iter_mut().enumerate() {
let res = io.raw_send(ReceiveSerial::Message(CoordinatorSendMessage {
target_destinations: Destination::All,
message_body: CoordinatorSendBody::Upgrade(
CoordinatorUpgradeMessage::EnterUpgradeMode,
)
.into(),
}));
// give some time for devices to forward things and enter upgrade mode
std::thread::sleep(Duration::from_millis(100));
if let Err(e) = res {
event!(
Level::ERROR,
port = port,
error = e.to_string(),
"unable to send firmware upgrade initialiazation message"
);
continue;
}
io.wait_for_conch()?;
event!(Level::INFO, port = port, "starting writing firmware");
let mut chunks = firmware_bin
.as_bytes()
.chunks(FIRMWARE_UPGRADE_CHUNK_LEN as usize)
.enumerate();
iters.push(core::iter::from_fn(move || {
let (i, chunk) = chunks.next()?;
if let Err(e) = io.raw_write(chunk) {
event!(
Level::ERROR,
port = port,
error = e.to_string(),
"writing firmware failed"
);
return Some(Err(e.into()));
}
let mut byte = [0u8; 1];
match io.raw_read(&mut byte[..]) {
Ok(_) => {
if byte[0] != FIRMWARE_NEXT_CHUNK_READY_SIGNAL {
event!(
Level::DEBUG,
byte = byte[0].to_string(),
"downstream device wrote invalid signal byte"
);
}
}
Err(e) => {
event!(
Level::ERROR,
port = port,
error = e.to_string(),
"reading firmware progress signaling byte failed"
);
return Some(Err(e.into()));
}
}
Some(Ok(
((port_index as u32 * n_chunks) + i as u32) as f32 / (total_chunks - 1) as f32
))
}));
}
Ok(iters.into_iter().flatten())
}
}
#[derive(Clone)]
pub struct UsbSender {
sender: std::sync::mpsc::Sender<CoordinatorSendMessage>,
}
impl UsbSender {
pub fn send_cancel_all(&self) {
self.sender
.send(CoordinatorSendMessage {
target_destinations: frostsnap_comms::Destination::All,
message_body: frostsnap_comms::CoordinatorSendBody::Cancel,
})
.expect("receiver exists");
}
pub fn send_cancel(&self, device_id: DeviceId) {
self.sender
.send(CoordinatorSendMessage::to(
device_id,
frostsnap_comms::CoordinatorSendBody::Cancel,
))
.expect("receiver exists");
}
pub fn update_name_preview(&self, device_id: DeviceId, name: DeviceName) {
self.sender
.send(CoordinatorSendMessage::to(
device_id,
CoordinatorSendBody::Naming(frostsnap_comms::NameCommand::Preview(name)),
))
.expect("receiver exists");
}
pub fn finish_naming(&self, device_id: DeviceId, name: DeviceName) {
event!(
Level::INFO,
name = %name,
device_id = device_id.to_string(),
"Named device"
);
self.sender
.send(CoordinatorSendMessage::to(
device_id,
CoordinatorSendBody::Naming(frostsnap_comms::NameCommand::Prompt(name)),
))
.expect("receiver exists");
}
pub fn send(&self, message: CoordinatorSendMessage) {
self.sender.send(message).expect("receiver exists")
}
pub fn wipe_device_data(&self, device_id: DeviceId) {
event!(
Level::INFO,
device_id = device_id.to_string(),
"Wiping device"
);
self.sender
.send(CoordinatorSendMessage::to(
device_id,
CoordinatorSendBody::DataWipe,
))
.expect("receiver exists");
}
pub fn wipe_all(&self) {
self.sender
.send(CoordinatorSendMessage {
target_destinations: Destination::All,
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | true |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_coordinator/src/wait_for_to_user_message.rs | frostsnap_coordinator/src/wait_for_to_user_message.rs | use std::{collections::BTreeSet, sync};
use frostsnap_core::{coordinator::CoordinatorToUserMessage, DeviceId};
use crate::UiProtocol;
pub struct WaitForToUserMessage<F> {
callback: F,
cancel_on_disconnected: BTreeSet<DeviceId>,
finished: Option<bool>,
sender: Option<sync::mpsc::SyncSender<bool>>,
}
pub type Waiter = sync::mpsc::Receiver<bool>;
impl<F> WaitForToUserMessage<F> {
pub fn new(devices: impl IntoIterator<Item = DeviceId>, callback: F) -> (Self, Waiter) {
let (sender, recv) = sync::mpsc::sync_channel(1);
(
Self {
callback,
cancel_on_disconnected: devices.into_iter().collect(),
finished: None,
sender: Some(sender),
},
recv,
)
}
}
impl<F> UiProtocol for WaitForToUserMessage<F>
where
F: FnMut(CoordinatorToUserMessage) -> bool + Send + 'static,
{
fn is_complete(&self) -> Option<crate::Completion> {
match self.finished {
Some(false) => Some(crate::Completion::Abort {
send_cancel_to_all_devices: false,
}),
Some(true) => Some(crate::Completion::Success),
None => None,
}
}
fn disconnected(&mut self, id: frostsnap_core::DeviceId) {
if self.cancel_on_disconnected.contains(&id) {
self.finished.get_or_insert(false);
if let Some(sender) = self.sender.take() {
sender.send(false).unwrap();
}
}
}
fn process_to_user_message(&mut self, message: CoordinatorToUserMessage) -> bool {
let res = (self.callback)(message);
if res {
self.finished.get_or_insert(true);
if let Some(sender) = self.sender.take() {
sender.send(true).unwrap();
}
}
res
}
fn poll(&mut self) -> Vec<frostsnap_comms::CoordinatorSendMessage> {
vec![]
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn as_mut_any(&mut self) -> &mut dyn std::any::Any {
self
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_coordinator/src/wait_for_single_device.rs | frostsnap_coordinator/src/wait_for_single_device.rs | use frostsnap_comms::{CoordinatorSendBody, CoordinatorSendMessage};
use frostsnap_core::{
coordinator::{
restoration::{self, RecoverShare},
CoordinatorToUserMessage,
},
message::{CoordinatorRestoration, CoordinatorToDeviceMessage},
DeviceId,
};
use std::collections::HashSet;
use std::time::{Duration, Instant};
use crate::{DeviceMode, Sink, UiProtocol};
// ⏱️ Devices plugged in together connect in rapid succession - wait to detect all before emitting state
const DEVICE_SETTLE_TIME_MS: u64 = 800;
struct DeviceInfo {
id: DeviceId,
mode: DeviceMode,
shares: Vec<RecoverShare>,
}
pub struct WaitForSingleDevice {
sent_request_to: HashSet<DeviceId>,
devices: Vec<DeviceInfo>,
sink: Box<dyn Sink<WaitForSingleDeviceState>>,
abort: bool,
last_change: Option<Instant>,
last_emitted_state: Option<WaitForSingleDeviceState>,
finished: bool,
}
impl WaitForSingleDevice {
pub fn new(sink: impl Sink<WaitForSingleDeviceState>) -> Self {
Self {
sent_request_to: Default::default(),
devices: Default::default(),
sink: Box::new(sink),
abort: false,
last_change: None,
last_emitted_state: None,
finished: false,
}
}
fn compute_state(&self) -> WaitForSingleDeviceState {
match self.devices.len() {
0 => WaitForSingleDeviceState::NoDevice,
1 => {
let device = &self.devices[0];
match device.mode {
DeviceMode::Blank => WaitForSingleDeviceState::BlankDevice {
device_id: device.id,
},
_ => {
if let Some(share) = device.shares.first() {
WaitForSingleDeviceState::DeviceWithShare {
device_id: device.id,
share: share.clone(),
}
} else {
WaitForSingleDeviceState::WaitingForDevice {
device_id: device.id,
}
}
}
}
}
_ => WaitForSingleDeviceState::TooManyDevices,
}
}
pub fn emit_state(&mut self) {
let state = self.compute_state();
let found_device = matches!(
state,
WaitForSingleDeviceState::BlankDevice { .. }
| WaitForSingleDeviceState::DeviceWithShare { .. }
);
if found_device && !self.finished {
self.finished = true;
}
self.sink.send(state.clone());
self.last_emitted_state = Some(state);
}
fn mark_changed(&mut self) {
self.last_change = Some(Instant::now());
}
}
impl UiProtocol for WaitForSingleDevice {
fn cancel(&mut self) {
self.abort = true;
}
fn is_complete(&self) -> Option<crate::Completion> {
if self.abort {
Some(crate::Completion::Abort {
send_cancel_to_all_devices: false,
})
} else if self.finished {
Some(crate::Completion::Success)
} else {
None
}
}
fn disconnected(&mut self, id: DeviceId) {
self.devices.retain(|device| device.id != id);
self.sent_request_to.remove(&id);
self.mark_changed();
}
fn poll(&mut self) -> Vec<CoordinatorSendMessage> {
let mut out = vec![];
for device in &self.devices {
if device.mode != DeviceMode::Blank && !self.sent_request_to.contains(&device.id) {
out.push(CoordinatorSendMessage::to(
device.id,
CoordinatorSendBody::Core(CoordinatorToDeviceMessage::Restoration(
CoordinatorRestoration::RequestHeldShares,
)),
));
self.sent_request_to.insert(device.id);
}
}
if let Some(last_change) = self.last_change {
if last_change.elapsed() >= Duration::from_millis(DEVICE_SETTLE_TIME_MS) {
let current_state = self.compute_state();
if self.last_emitted_state.as_ref() != Some(¤t_state) {
self.emit_state();
}
self.last_change = None;
}
}
out
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn as_mut_any(&mut self) -> &mut dyn std::any::Any {
self
}
fn connected(&mut self, id: DeviceId, mode: DeviceMode) {
self.devices.push(DeviceInfo {
id,
mode,
shares: vec![],
});
self.mark_changed();
}
fn process_to_user_message(&mut self, message: CoordinatorToUserMessage) -> bool {
if let CoordinatorToUserMessage::Restoration(
restoration::ToUserRestoration::GotHeldShares { held_by, shares },
) = message
{
if let Some(device) = self.devices.iter_mut().find(|d| d.id == held_by) {
device.shares = shares
.into_iter()
.map(|held_share| RecoverShare {
held_by,
held_share,
})
.collect();
self.mark_changed();
true
} else {
false
}
} else {
false
}
}
}
#[derive(Clone, Debug, PartialEq)]
#[allow(clippy::large_enum_variant)]
pub enum WaitForSingleDeviceState {
NoDevice,
TooManyDevices,
WaitingForDevice {
device_id: DeviceId,
},
BlankDevice {
device_id: DeviceId,
},
DeviceWithShare {
device_id: DeviceId,
share: RecoverShare,
},
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_coordinator/src/ui_protocol.rs | frostsnap_coordinator/src/ui_protocol.rs | use frostsnap_comms::CoordinatorSendMessage;
use frostsnap_core::{coordinator::CoordinatorToUserMessage, DeviceId, Gist as _};
use std::any::Any;
use tracing::{event, Level};
/// A UiProtocol is a layer between the protocol the devices and the coordinator are executing e.g.
/// keygen, signing etc and the actual UI. Applications intercept frostsnap_core's
/// [`CoordinatorToUserMessage`] and send them to `UiProtocol` which usually has a channel (not
/// represented in the API) to the UI where it outputs states. Usually this channel is passed in as
/// a `Sink` into the constructor.
///
/// With the `poll` method it can communicate to the devices or the coordinator's storage.
pub trait UiProtocol: Send + Any + 'static {
fn name(&self) -> &'static str {
core::any::type_name_of_val(self)
}
fn cancel(&mut self) {}
fn is_complete(&self) -> Option<Completion>;
fn connected(&mut self, _id: DeviceId, _state: DeviceMode) {}
fn disconnected(&mut self, _id: DeviceId) {}
fn process_to_user_message(&mut self, _message: CoordinatorToUserMessage) -> bool {
false
}
fn process_comms_message(
&mut self,
_from: DeviceId,
_message: frostsnap_comms::CommsMisc,
) -> bool {
false
}
/// `poll` allows the UiProtocol to communicate to the rest of the system. The reason the ui protocol needs
/// to do this is subtle: core messages may need to be sent out only when a device is next
/// connected. The UI protocol is currently the point that manages the effect of device
/// connections and disconnections on the protocol so it is able to violate boundries here a bit
/// and send out core messages.
fn poll(&mut self) -> Vec<CoordinatorSendMessage>;
fn as_any(&self) -> &dyn Any;
fn as_mut_any(&mut self) -> &mut dyn Any;
}
#[derive(Clone, Debug)]
pub enum Completion {
Success,
Abort { send_cancel_to_all_devices: bool },
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Ord, PartialOrd)]
pub enum DeviceMode {
Blank,
Recovery,
Ready,
}
#[derive(Default)]
pub struct UiStack {
protocols: Vec<Box<dyn UiProtocol>>,
}
impl UiStack {
pub fn get_mut<T: UiProtocol>(&mut self) -> Option<&mut T> {
for protocol in self.protocols.iter_mut().rev() {
if let Some(found) = protocol.as_mut().as_mut_any().downcast_mut::<T>() {
return Some(found);
}
}
None
}
pub fn process_to_user_message(&mut self, message: CoordinatorToUserMessage) {
let mut found = false;
for protocol in self.protocols.iter_mut().rev() {
found = protocol.process_to_user_message(message.clone());
if found {
break;
}
}
if !found {
event!(
Level::WARN,
gist = message.gist(),
"got unexpected to user message"
);
}
}
pub fn process_comms_message(&mut self, from: DeviceId, message: frostsnap_comms::CommsMisc) {
let mut found = false;
for protocol in self.protocols.iter_mut().rev() {
found = protocol.process_comms_message(from, message.clone());
if found {
break;
}
}
if !found {
event!(
Level::WARN,
gist = message.gist(),
"got unexpected comms message"
);
}
}
pub fn poll(&mut self) -> Vec<CoordinatorSendMessage> {
let mut out = vec![];
for protocol in self.protocols.iter_mut().rev() {
out.extend(protocol.poll())
}
out
}
pub fn connected(&mut self, id: DeviceId, state: DeviceMode) {
for protocol in self.protocols.iter_mut().rev() {
protocol.connected(id, state);
}
}
pub fn disconnected(&mut self, id: DeviceId) {
for protocol in self.protocols.iter_mut().rev() {
protocol.disconnected(id);
}
}
#[must_use]
pub fn clean_finished(&mut self) -> bool {
let mut i = self.protocols.len();
let mut send_cancel_to_all = false;
while i > 0 {
i -= 1;
let protocol = &self.protocols[i];
match protocol.is_complete() {
Some(completion) => {
let name = protocol.name();
self.protocols.remove(i);
event!(
Level::INFO,
name = name,
outcome = format!("{:?}", completion),
stack_len = self.protocols.len(),
"UI Protocol completed",
);
match completion {
Completion::Success => { /* nothing to do */ }
Completion::Abort {
send_cancel_to_all_devices,
} => {
send_cancel_to_all |= send_cancel_to_all_devices;
}
}
}
None => { /* not complete */ }
}
}
send_cancel_to_all
}
#[must_use]
pub fn cancel_all(&mut self) -> bool {
for protocol in self.protocols.iter_mut().rev() {
protocol.cancel();
}
self.clean_finished()
}
pub fn push<T: UiProtocol>(&mut self, protocol: T) {
let name = protocol.name();
self.protocols.push(Box::new(protocol));
event!(
Level::INFO,
name = name,
stack_len = self.protocols.len(),
"Added UI protocol to stack"
);
}
}
impl core::fmt::Debug for UiStack {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("UiStack")
.field(
"protocols",
&self
.protocols
.iter()
.map(|proto| proto.name())
.collect::<Vec<_>>(),
)
.finish()
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_coordinator/src/nonce_replenish.rs | frostsnap_coordinator/src/nonce_replenish.rs | use crate::{Completion, Sink, UiProtocol};
use frostsnap_comms::{CoordinatorSendBody, CoordinatorSendMessage, Destination};
use frostsnap_core::{
coordinator::{CoordinatorToUserMessage, NonceReplenishRequest},
message::signing::OpenNonceStreams,
DeviceId,
};
use std::collections::{BTreeSet, HashMap, HashSet, VecDeque};
pub struct NonceReplenishProtocol {
state: NonceReplenishState,
pending_messages: HashMap<DeviceId, VecDeque<OpenNonceStreams>>,
awaiting_response: HashSet<DeviceId>,
completed_streams: u32,
sink: Box<dyn Sink<NonceReplenishState>>,
}
impl NonceReplenishProtocol {
pub fn new(
devices: BTreeSet<DeviceId>,
nonce_request: NonceReplenishRequest,
sink: impl Sink<NonceReplenishState> + 'static,
) -> Self {
let mut pending_messages = HashMap::new();
let mut total_streams = 0;
// Process NonceReplenishRequest into split OpenNonceStream messages
for (device_id, open_nonce_stream) in nonce_request.into_open_nonce_streams() {
// split them so we get more fine grained progress
let split_messages = open_nonce_stream.split();
total_streams += split_messages.len() as u32;
pending_messages.insert(device_id, VecDeque::from(split_messages));
}
Self {
state: NonceReplenishState {
devices: devices.into_iter().collect(),
completed_streams: 0,
total_streams,
abort: false,
},
pending_messages,
awaiting_response: HashSet::new(),
completed_streams: 0,
sink: Box::new(sink),
}
}
pub fn emit_state(&self) {
self.sink.send(self.state.clone());
}
}
impl UiProtocol for NonceReplenishProtocol {
fn cancel(&mut self) {
self.state.abort = true;
self.emit_state();
}
fn is_complete(&self) -> Option<Completion> {
if self.state.is_finished() {
Some(Completion::Success)
} else if self.state.abort {
Some(Completion::Abort {
send_cancel_to_all_devices: true,
})
} else {
None
}
}
fn disconnected(&mut self, id: DeviceId) {
if self.state.devices.contains(&id) {
self.state.abort = true;
self.emit_state();
}
}
fn process_to_user_message(&mut self, message: CoordinatorToUserMessage) -> bool {
if let CoordinatorToUserMessage::ReplenishedNonces { device_id } = message {
if self.awaiting_response.remove(&device_id) {
self.completed_streams += 1;
self.state.completed_streams = self.completed_streams;
self.emit_state();
}
true
} else {
false
}
}
fn poll(&mut self) -> Vec<CoordinatorSendMessage> {
let mut messages = vec![];
for (device_id, queue) in &mut self.pending_messages {
if !self.awaiting_response.contains(device_id) {
if let Some(open_nonce_stream) = queue.pop_front() {
let msg = CoordinatorSendMessage {
target_destinations: Destination::from([*device_id]),
message_body: CoordinatorSendBody::Core(open_nonce_stream.into()),
};
messages.push(msg);
self.awaiting_response.insert(*device_id);
}
}
}
messages
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn as_mut_any(&mut self) -> &mut dyn std::any::Any {
self
}
}
#[derive(Clone, Debug)]
pub struct NonceReplenishState {
pub devices: HashSet<DeviceId>,
pub completed_streams: u32,
pub total_streams: u32,
pub abort: bool,
}
impl NonceReplenishState {
pub fn is_finished(&self) -> bool {
self.completed_streams >= self.total_streams
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_coordinator/src/verify_address.rs | frostsnap_coordinator/src/verify_address.rs | use std::{
borrow::BorrowMut,
collections::{BTreeSet, HashSet},
};
use frostsnap_comms::{CoordinatorSendBody, CoordinatorSendMessage, Destination};
use frostsnap_core::{
coordinator::VerifyAddress, message::CoordinatorToDeviceMessage, DeviceId, MasterAppkey,
};
use crate::{Completion, DeviceMode, Sink, UiProtocol};
#[derive(Clone, Debug, Default)]
pub struct VerifyAddressProtocolState {
pub target_devices: Vec<DeviceId>, // not a set for frb compat
pub connected_devices: HashSet<DeviceId>,
}
pub struct VerifyAddressProtocol {
state: VerifyAddressProtocolState,
master_appkey: MasterAppkey,
derivation_index: u32,
is_complete: Option<Completion>,
need_to_send_to: BTreeSet<DeviceId>,
sink: Box<dyn Sink<VerifyAddressProtocolState>>,
}
impl VerifyAddressProtocol {
pub fn new(
verify_address_message: VerifyAddress,
sink: impl Sink<VerifyAddressProtocolState> + 'static,
) -> Self {
Self {
state: VerifyAddressProtocolState {
target_devices: verify_address_message.target_devices.into_iter().collect(),
connected_devices: Default::default(),
},
master_appkey: verify_address_message.master_appkey,
derivation_index: verify_address_message.derivation_index,
is_complete: None,
need_to_send_to: Default::default(),
sink: Box::new(sink),
}
}
pub fn emit_state(&self) {
self.sink.send(self.state.clone());
}
}
impl UiProtocol for VerifyAddressProtocol {
fn cancel(&mut self) {
self.is_complete = Some(Completion::Abort {
send_cancel_to_all_devices: true,
})
}
fn is_complete(&self) -> Option<Completion> {
self.is_complete.clone()
}
fn connected(&mut self, id: frostsnap_core::DeviceId, state: DeviceMode) {
if self.state.target_devices.contains(&id) {
if state == DeviceMode::Ready {
self.need_to_send_to.insert(id);
}
if self.state.connected_devices.insert(id) {
self.emit_state();
}
}
}
fn disconnected(&mut self, device_id: frostsnap_core::DeviceId) {
self.need_to_send_to.remove(&device_id);
if self.state.connected_devices.remove(&device_id) {
self.emit_state();
}
}
fn poll(&mut self) -> Vec<CoordinatorSendMessage> {
let mut messages = vec![];
if !self.need_to_send_to.is_empty() {
messages.push(CoordinatorSendMessage {
target_destinations: Destination::Particular(core::mem::take(
&mut self.need_to_send_to,
)),
message_body: CoordinatorSendBody::Core(CoordinatorToDeviceMessage::ScreenVerify(
frostsnap_core::message::screen_verify::ScreenVerify::VerifyAddress {
master_appkey: self.master_appkey,
derivation_index: self.derivation_index,
},
)),
});
}
messages
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn as_mut_any(&mut self) -> &mut dyn std::any::Any {
self.borrow_mut()
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_coordinator/src/cdc_acm_usb.rs | frostsnap_coordinator/src/cdc_acm_usb.rs | use anyhow::{anyhow, Result};
use nusb::{
descriptors::TransferType,
io::{EndpointRead, EndpointWrite},
transfer::{Bulk, ControlOut, ControlType, Direction, In, Out, Recipient},
Device, Interface, MaybeFuture,
};
use std::cell::RefCell;
use std::io;
use std::os::fd::OwnedFd;
use std::time::Duration;
use tracing::{event, Level};
#[allow(unused)]
pub struct CdcAcmSerial {
dev: Device, // keep last for correct drop order
name: String,
baud: u32,
if_comm: Interface,
if_data: Interface,
writer: EndpointWrite<Bulk>,
reader: RefCell<EndpointRead<Bulk>>,
timeout: Duration,
}
impl CdcAcmSerial {
/// Wrap an already-opened usbfs FD.
///
/// Create a blocking CDC-ACM port from an already-open usbfs FD. It automatically difures out
/// the interface numbers and bulk out/in endpoint addresses.
pub fn new_auto(fd: OwnedFd, name: String, baud: u32) -> Result<Self> {
let dev = Device::from_fd(fd).wait()?;
let cfg = dev.active_configuration()?;
// ---------------- scan for CDC interfaces & bulk endpoints -------
let mut comm_if_num = None;
let mut data_if_num = None;
let mut ep_in_addr = None;
let mut ep_out_addr = None;
for grp in cfg.interfaces() {
// alt-setting 0 (over 99 % of CDC devices have only alt 0)
let alt0 = grp.alt_settings().next().unwrap();
match (alt0.class(), alt0.subclass()) {
// -- 0x02/0x02 = CDC Communications, Abstract Control Model
(0x02, 0x02) if comm_if_num.is_none() => {
comm_if_num = Some(alt0.interface_number());
}
// -- 0x0A/** = CDC Data
(0x0A, _) if data_if_num.is_none() => {
data_if_num = Some(alt0.interface_number());
// Pick the first bulk-IN and bulk-OUT on this interface.
for ep in alt0.endpoints() {
if ep.transfer_type() == TransferType::Bulk {
match ep.direction() {
Direction::In if ep_in_addr.is_none() => {
ep_in_addr = Some(ep.address());
}
Direction::Out if ep_out_addr.is_none() => {
ep_out_addr = Some(ep.address());
}
_ => {}
}
}
}
}
_ => {}
}
}
let comm_if = comm_if_num.ok_or_else(|| anyhow!("No CDC comm IF"))?;
let data_if = data_if_num.ok_or_else(|| anyhow!("No CDC data IF"))?;
let ep_in = ep_in_addr.ok_or_else(|| anyhow!("No bulk-IN ep"))?;
let ep_out = ep_out_addr.ok_or_else(|| anyhow!("No bulk-OUT ep"))?;
// ---------------- claim interfaces (detaching any kernel driver) ---
event!(Level::DEBUG, if_num = comm_if, "claiming comm interface");
let if_comm = dev.detach_and_claim_interface(comm_if).wait()?;
event!(Level::DEBUG, if_num = data_if, "claiming data interface");
let if_data = dev.detach_and_claim_interface(data_if).wait()?;
let writer = if_data
.endpoint::<Bulk, Out>(ep_out)?
.writer(4096)
.with_num_transfers(4);
let reader = if_data
.endpoint::<Bulk, In>(ep_in)?
.reader(4096)
.with_num_transfers(4)
.with_read_timeout(Duration::from_millis(1_000));
// ---------------- mandatory CDC setup packets ---------------------
send_cdc_setup(&if_comm, baud)?;
let self_ = Self {
dev,
baud,
name,
if_comm,
if_data,
writer,
reader: RefCell::new(reader),
timeout: Duration::from_secs(1),
};
event!(Level::INFO, name = self_.name, "opened USB port");
Ok(self_)
}
}
fn send_cdc_setup(if_comm: &Interface, baud: u32) -> Result<()> {
event!(
Level::DEBUG,
if_num = if_comm.interface_number(),
"doing usb-cdc SET_LINE_CODING and SET_CONTROL_LINE_STATE"
);
// USB-CDC §6.2.3.8 – SET_LINE_CODING
let line_coding = [
(baud & 0xFF) as u8,
((baud >> 8) & 0xFF) as u8,
((baud >> 16) & 0xFF) as u8,
((baud >> 24) & 0xFF) as u8,
0x00, // 1 stop bit
0x00, // no parity
0x08, // 8 data bits
];
if_comm
.control_out(
ControlOut {
control_type: ControlType::Class,
recipient: Recipient::Interface,
request: 0x20,
value: 0,
index: if_comm.interface_number() as u16,
data: &line_coding,
},
Duration::from_millis(100),
)
.wait()?;
// USB-CDC §6.2.3.7 – SET_CONTROL_LINE_STATE (assert DTR | RTS)
if_comm
.control_out(
ControlOut {
control_type: ControlType::Class,
recipient: Recipient::Interface,
request: 0x22,
value: 0x0003,
index: if_comm.interface_number() as u16,
data: &[],
},
Duration::from_millis(100),
)
.wait()?;
Ok(())
}
//--------------------------------------------------------------------------
// std::io::Write impl –– bulk-OUT
//--------------------------------------------------------------------------
impl io::Write for CdcAcmSerial {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.writer.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.writer.submit();
Ok(())
}
}
//--------------------------------------------------------------------------
// std::io::Read impl –– bulk-IN
//--------------------------------------------------------------------------
impl io::Read for CdcAcmSerial {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.reader.borrow_mut().read(buf)
}
}
mod _impl {
use crate::serialport::*;
#[allow(unused)]
impl SerialPort for super::CdcAcmSerial {
fn name(&self) -> Option<String> {
Some(self.name.clone())
}
fn baud_rate(&self) -> Result<u32> {
Ok(self.baud)
}
fn bytes_to_read(&self) -> Result<u32> {
use futures::task::noop_waker;
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::io::AsyncBufRead;
let waker = noop_waker();
let mut cx = Context::from_waker(&waker);
// Poll without blocking to check if data is available
let mut reader = self.reader.borrow_mut();
let pin_reader = Pin::new(&mut *reader);
match pin_reader.poll_fill_buf(&mut cx) {
Poll::Ready(Ok(buf)) => Ok(buf.len() as u32),
Poll::Ready(Err(_)) => Ok(0),
Poll::Pending => Ok(0), // No data available yet, don't block
}
}
fn data_bits(&self) -> Result<DataBits> {
unimplemented!()
}
fn flow_control(&self) -> Result<FlowControl> {
unimplemented!()
}
fn parity(&self) -> Result<Parity> {
unimplemented!()
}
fn stop_bits(&self) -> Result<StopBits> {
unimplemented!()
}
fn timeout(&self) -> core::time::Duration {
unimplemented!()
}
fn set_baud_rate(&mut self, baud_rate: u32) -> Result<()> {
unimplemented!()
}
fn set_data_bits(&mut self, data_bits: DataBits) -> Result<()> {
unimplemented!()
}
fn set_flow_control(&mut self, flow_control: FlowControl) -> Result<()> {
unimplemented!()
}
fn set_parity(&mut self, parity: Parity) -> Result<()> {
unimplemented!()
}
fn set_stop_bits(&mut self, stop_bits: StopBits) -> Result<()> {
unimplemented!()
}
fn set_timeout(&mut self, timeout: core::time::Duration) -> Result<()> {
unimplemented!()
}
fn write_request_to_send(&mut self, level: bool) -> Result<()> {
unimplemented!()
}
fn write_data_terminal_ready(&mut self, level: bool) -> Result<()> {
unimplemented!()
}
fn read_clear_to_send(&mut self) -> Result<bool> {
unimplemented!()
}
fn read_data_set_ready(&mut self) -> Result<bool> {
unimplemented!()
}
fn read_ring_indicator(&mut self) -> Result<bool> {
unimplemented!()
}
fn read_carrier_detect(&mut self) -> Result<bool> {
unimplemented!()
}
fn bytes_to_write(&self) -> Result<u32> {
unimplemented!()
}
fn clear(&self, buffer_to_clear: ClearBuffer) -> Result<()> {
unimplemented!()
}
fn try_clone(&self) -> Result<Box<dyn SerialPort>> {
unimplemented!()
}
fn set_break(&self) -> Result<()> {
unimplemented!()
}
fn clear_break(&self) -> Result<()> {
unimplemented!()
}
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_coordinator/src/firmware_upgrade.rs | frostsnap_coordinator/src/firmware_upgrade.rs | use crate::{
Completion, FirmwareUpgradeEligibility, FirmwareVersion, Sink, UiProtocol, ValidatedFirmwareBin,
};
use frostsnap_comms::{
CommsMisc, CoordinatorSendBody, CoordinatorSendMessage, CoordinatorUpgradeMessage,
};
use frostsnap_core::DeviceId;
use std::collections::{BTreeSet, HashMap};
pub struct FirmwareUpgradeProtocol {
state: FirmwareUpgradeConfirmState,
sent_first_message: bool,
firmware_bin: ValidatedFirmwareBin,
devices: HashMap<DeviceId, FirmwareVersion>,
sink: Box<dyn Sink<FirmwareUpgradeConfirmState>>,
}
impl FirmwareUpgradeProtocol {
pub fn new(
devices: HashMap<DeviceId, FirmwareVersion>,
need_upgrade: BTreeSet<DeviceId>,
firmware_bin: ValidatedFirmwareBin,
sink: impl Sink<FirmwareUpgradeConfirmState> + 'static,
) -> Self {
// Check if any device has incompatible firmware
let abort_reason = devices.values().find_map(|fw| {
match firmware_bin.firmware_version().check_upgrade_eligibility(&fw.digest) {
FirmwareUpgradeEligibility::CannotUpgrade { reason } => {
Some(format!("One of the devices is incompatible with the upgrade. Unplug it to continue or try upgrading the app. Problem: {reason}"))
}
_ => None,
}
});
Self {
state: FirmwareUpgradeConfirmState {
devices: devices.keys().copied().collect(),
need_upgrade: need_upgrade.into_iter().collect(),
confirmations: Default::default(),
abort: abort_reason,
upgrade_ready_to_start: false,
},
sent_first_message: false,
firmware_bin,
devices,
sink: Box::new(sink),
}
}
pub fn emit_state(&self) {
self.sink.send(self.state.clone());
}
}
impl UiProtocol for FirmwareUpgradeProtocol {
fn cancel(&mut self) {
self.state.abort = Some("canceled".to_string());
self.emit_state();
}
fn is_complete(&self) -> Option<Completion> {
if BTreeSet::from_iter(self.state.confirmations.iter())
== BTreeSet::from_iter(self.state.devices.iter())
{
Some(Completion::Success)
} else if self.state.abort.is_some() {
Some(Completion::Abort {
send_cancel_to_all_devices: true,
})
} else {
None
}
}
fn disconnected(&mut self, id: DeviceId) {
if self.devices.contains_key(&id) {
self.state.abort = Some("Device disconnected during upgrade".to_string());
self.emit_state();
}
}
fn process_comms_message(&mut self, from: DeviceId, message: CommsMisc) -> bool {
if !self.devices.contains_key(&from) {
return false;
}
if let CommsMisc::AckUpgradeMode = message {
if !self.state.confirmations.contains(&from) {
self.state.confirmations.push(from);
self.emit_state()
}
true
} else {
false
}
}
fn poll(&mut self) -> Vec<CoordinatorSendMessage> {
let mut to_devices = vec![];
if !self.sent_first_message && self.state.abort.is_none() {
let any_device_needs_legacy = self
.devices
.values()
.any(|fw| !fw.features().upgrade_digest_no_sig);
let upgrade_message = if any_device_needs_legacy {
CoordinatorUpgradeMessage::PrepareUpgrade {
size: self.firmware_bin.size(),
firmware_digest: self.firmware_bin.digest_with_signature(),
}
} else {
CoordinatorUpgradeMessage::PrepareUpgrade2 {
size: self.firmware_bin.size(),
firmware_digest: self.firmware_bin.digest(),
}
};
to_devices.push(CoordinatorSendMessage {
target_destinations: frostsnap_comms::Destination::All,
message_body: CoordinatorSendBody::Upgrade(upgrade_message),
});
self.sent_first_message = true;
}
// we only want to emit te ready state after we've been polled so coordinator loop has a
// chance to clean up this protocol.
if matches!(self.is_complete(), Some(Completion::Success)) {
self.state.upgrade_ready_to_start = true;
self.emit_state()
}
to_devices
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn as_mut_any(&mut self) -> &mut dyn std::any::Any {
self
}
}
#[derive(Clone, Debug)]
pub struct FirmwareUpgradeConfirmState {
pub confirmations: Vec<DeviceId>,
pub devices: Vec<DeviceId>,
pub need_upgrade: Vec<DeviceId>,
pub abort: Option<String>,
pub upgrade_ready_to_start: bool,
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_coordinator/src/signing.rs | frostsnap_coordinator/src/signing.rs | use frostsnap_comms::CoordinatorSendMessage;
use frostsnap_core::{
coordinator::{
ActiveSignSession, CoordinatorSend, CoordinatorToUserMessage,
CoordinatorToUserSigningMessage, RequestDeviceSign,
},
message::EncodedSignature,
DeviceId, KeyId, SignSessionId,
};
use std::collections::BTreeSet;
use tracing::{event, Level};
use crate::{Completion, DeviceMode, UiProtocol};
/// Keeps track of when
pub struct SigningDispatcher {
pub key_id: KeyId,
pub session_id: SignSessionId,
pub finished_signatures: Option<Vec<EncodedSignature>>,
pub targets: BTreeSet<DeviceId>,
pub got_signatures: BTreeSet<DeviceId>,
pub sink: Box<dyn crate::Sink<SigningState>>,
pub aborted: Option<String>,
pub connected_but_need_request: BTreeSet<DeviceId>,
pub outbox_to_devices: Vec<CoordinatorSendMessage>,
}
impl SigningDispatcher {
pub fn new(
targets: BTreeSet<DeviceId>,
key_id: KeyId,
session_id: SignSessionId,
sink: impl crate::Sink<SigningState>,
) -> Self {
Self {
targets,
key_id,
session_id,
got_signatures: Default::default(),
finished_signatures: Default::default(),
sink: Box::new(sink),
aborted: None,
connected_but_need_request: Default::default(),
outbox_to_devices: Default::default(),
}
}
pub fn restore_signing_session(
active_sign_session: &ActiveSignSession,
sink: impl crate::Sink<SigningState>,
) -> Self {
Self {
key_id: active_sign_session.key_id,
session_id: active_sign_session.session_id(),
got_signatures: active_sign_session.received_from().collect(),
targets: active_sign_session.init.nonces.keys().cloned().collect(),
finished_signatures: None,
sink: Box::new(sink),
aborted: None,
connected_but_need_request: Default::default(),
outbox_to_devices: Default::default(),
}
}
pub fn set_signature_received(&mut self, from: DeviceId) {
self.got_signatures.insert(from);
}
pub fn emit_state(&mut self) {
let state = SigningState {
session_id: self.session_id,
got_shares: self.got_signatures.iter().cloned().collect(),
needed_from: self.targets.iter().cloned().collect(),
finished_signatures: self.finished_signatures.clone(),
aborted: self.aborted.clone(),
connected_but_need_request: self.connected_but_need_request.iter().cloned().collect(),
};
self.sink.send(state);
}
pub fn send_sign_request(&mut self, sign_req: RequestDeviceSign) {
if self.connected_but_need_request.remove(&sign_req.device_id) {
self.outbox_to_devices.push(
CoordinatorSend::from(sign_req)
.try_into()
.expect("sign_req goes to devices"),
);
self.emit_state();
}
}
}
impl UiProtocol for SigningDispatcher {
fn process_to_user_message(&mut self, message: CoordinatorToUserMessage) -> bool {
if let CoordinatorToUserMessage::Signing(message) = message {
match message {
CoordinatorToUserSigningMessage::GotShare { from, session_id } => {
if session_id != self.session_id {
return false;
}
if self.got_signatures.insert(from) {
self.emit_state()
}
}
CoordinatorToUserSigningMessage::Signed {
signatures,
session_id,
} => {
if session_id != self.session_id {
return false;
}
self.finished_signatures = Some(signatures);
event!(Level::INFO, "received signatures from all devices");
self.emit_state();
}
}
true
} else {
false
}
}
fn disconnected(&mut self, device_id: DeviceId) {
self.connected_but_need_request.remove(&device_id);
self.emit_state();
}
fn connected(&mut self, device_id: DeviceId, state: DeviceMode) {
if !self.got_signatures.contains(&device_id)
&& self.targets.contains(&device_id)
&& state == DeviceMode::Ready
{
self.connected_but_need_request.insert(device_id);
self.emit_state();
}
}
fn is_complete(&self) -> Option<Completion> {
if self.finished_signatures.is_some() {
Some(Completion::Success)
} else if self.aborted.is_some() {
Some(Completion::Abort {
send_cancel_to_all_devices: true,
})
} else {
None
}
}
fn poll(&mut self) -> Vec<CoordinatorSendMessage> {
core::mem::take(&mut self.outbox_to_devices)
}
fn cancel(&mut self) {
self.aborted = Some("Signing canceled".into());
self.emit_state()
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn as_mut_any(&mut self) -> &mut dyn std::any::Any {
self
}
}
#[derive(Clone, Debug)]
pub struct SigningState {
pub session_id: SignSessionId,
pub got_shares: Vec<DeviceId>,
pub needed_from: Vec<DeviceId>,
pub finished_signatures: Option<Vec<EncodedSignature>>,
pub aborted: Option<String>,
pub connected_but_need_request: Vec<DeviceId>,
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_coordinator/src/serial_port.rs | frostsnap_coordinator/src/serial_port.rs | use frostsnap_comms::{
DeviceSupportedFeatures, Direction, Downstream, MagicBytes, ReceiveSerial, BINCODE_CONFIG,
};
pub use serialport;
use std::collections::VecDeque;
use std::io::{BufRead, BufReader, Read};
use std::marker::PhantomData;
use tracing::{event, Level};
pub type SerialPort = Box<dyn serialport::SerialPort>;
// NOTE: This trait is not really necessary anymore because it seesm the serialport library works on
// enough platforms that we could just use it everywhere. This trait is sticking around because it's
// work to remove and maybe I'm wrong.
pub trait Serial: Send {
fn available_ports(&self) -> Vec<PortDesc>;
fn open_device_port(
&self,
unique_id: &str,
baud_rate: u32,
) -> Result<SerialPort, PortOpenError>;
}
#[derive(Debug)]
pub enum PortOpenError {
DeviceBusy,
PermissionDenied,
Other(Box<dyn std::error::Error + Send + Sync>),
}
impl core::fmt::Display for PortOpenError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
PortOpenError::DeviceBusy => write!(f, "device is busy"),
PortOpenError::PermissionDenied => write!(f, "permission denied"),
PortOpenError::Other(error) => write!(f, "{error}"),
}
}
}
#[derive(Debug, Clone)]
pub struct PortDesc {
pub id: String,
pub vid: u16,
pub pid: u16,
}
pub struct FramedSerialPort<D: Direction = Downstream> {
conch_enabled: bool,
magic_bytes_progress: usize,
has_sent_conch: bool,
inner: BufReader<SerialPort>,
send_queue: VecDeque<<D::Opposite as Direction>::RecvType>,
directions: PhantomData<D>,
}
impl<D: Direction> FramedSerialPort<D> {
pub fn new(port: SerialPort) -> Self {
Self {
inner: BufReader::new(port),
has_sent_conch: false,
conch_enabled: false,
magic_bytes_progress: 0,
send_queue: Default::default(),
directions: Default::default(),
}
}
pub fn anything_to_read(&self) -> bool {
match self.inner.get_ref().bytes_to_read() {
Ok(len) => len > 0,
// just say there's something there to get the caller to read and get the error rather than returing it here
Err(_) => true,
}
}
pub fn read_for_magic_bytes(
&mut self,
) -> Result<Option<DeviceSupportedFeatures>, std::io::Error> {
if !self.anything_to_read() {
return Ok(None);
}
self.inner.fill_buf()?;
let mut consumed = 0;
let (progress, found) = frostsnap_comms::make_progress_on_magic_bytes::<D>(
self.inner
.buffer()
.iter()
.cloned()
.inspect(|_| consumed += 1),
self.magic_bytes_progress,
);
self.inner.consume(consumed);
self.magic_bytes_progress = progress;
let supported_features = found.map(DeviceSupportedFeatures::from_version);
Ok(supported_features)
}
pub fn queue_send(&mut self, message: <D::Opposite as Direction>::RecvType) {
self.send_queue.push_back(message);
}
pub fn write_magic_bytes(&mut self) -> Result<(), bincode::error::EncodeError> {
self.raw_send(ReceiveSerial::<D::Opposite>::MagicBytes(
MagicBytes::default(),
))
}
pub fn try_read_message(
&mut self,
) -> Result<Option<ReceiveSerial<D>>, bincode::error::DecodeError> {
if !self.anything_to_read() && self.inner.buffer().is_empty() {
return Ok(None);
}
let message = bincode::decode_from_reader(&mut self.inner, BINCODE_CONFIG)?;
match &message {
ReceiveSerial::MagicBytes(_) => { /* magic bytes doesn't count as a message */ }
ReceiveSerial::Message(_) | ReceiveSerial::Conch => {
// if we receive a message we count it as the conch
use frostsnap_core::Gist;
self.has_sent_conch = false;
event!(Level::TRACE, gist = message.gist(), "GOT CONCH");
}
_ => { /* other messages (like reset are not a conch) */ }
};
Ok(Some(message))
}
pub fn raw_write(&mut self, bytes: &[u8]) -> Result<(), std::io::Error> {
let io_device = self.inner.get_mut();
io_device.write_all(bytes)?;
io_device.flush()?;
Ok(())
}
pub fn raw_read(&mut self, bytes: &mut [u8]) -> Result<(), std::io::Error> {
self.inner.read_exact(bytes)?;
Ok(())
}
pub fn discard_all_messages(&mut self) -> Result<(), bincode::error::DecodeError> {
while self.anything_to_read() || !self.inner.buffer().is_empty() {
let _message: ReceiveSerial<D> =
bincode::decode_from_reader(&mut self.inner, BINCODE_CONFIG)?;
}
Ok(())
}
pub fn has_conch(&self) -> bool {
!self.has_sent_conch
}
pub fn set_conch_enabled(&mut self, enabled: bool) {
if self.conch_enabled != enabled {
self.conch_enabled = enabled;
self.has_sent_conch = false;
}
}
pub fn wait_for_conch(&mut self) -> Result<(), bincode::error::DecodeError> {
if self.conch_enabled && !self.has_conch() {
while !self.has_conch() {
let _ = self.try_read_message()?;
}
}
Ok(())
}
pub fn raw_send(
&mut self,
frame: ReceiveSerial<D::Opposite>,
) -> Result<(), bincode::error::EncodeError> {
bincode::encode_into_std_write(frame, self.inner.get_mut(), BINCODE_CONFIG)?;
self.inner.get_mut().flush().map_err(|e| {
bincode::error::EncodeError::OtherString(format!("failed to flush: {e}"))
})?;
Ok(())
}
pub fn poll_send(&mut self) -> Result<(), bincode::error::EncodeError> {
if self.conch_enabled && self.has_sent_conch {
return Ok(());
}
if let Some(message) = self.send_queue.pop_front() {
use frostsnap_core::Gist;
event!(Level::DEBUG, gist = message.gist(), "sending message");
self.raw_send(ReceiveSerial::<D::Opposite>::Message(message))?;
}
if self.conch_enabled && !self.has_sent_conch {
event!(Level::TRACE, "SENDING CONCH");
self.raw_send(ReceiveSerial::<D::Opposite>::Conch)?;
self.has_sent_conch = true;
}
Ok(())
}
}
use std::time::Duration;
/// impl using the serialport crate
#[derive(Clone, Default, Debug)]
pub struct DesktopSerial;
impl Serial for DesktopSerial {
fn available_ports(&self) -> Vec<PortDesc> {
let mut ports: Vec<PortDesc> = serialport::available_ports()
.unwrap_or_default()
.into_iter()
.filter_map(|port| match port.port_type {
serialport::SerialPortType::UsbPort(usb_port) => Some(PortDesc {
id: port.port_name,
vid: usb_port.vid,
pid: usb_port.pid,
}),
_ => None,
})
.collect();
// On macOS, filter duplicate tty/cu devices
if cfg!(target_os = "macos") {
use std::collections::HashSet;
// Find all device numbers that have cu versions
let cu_device_numbers: HashSet<String> = ports
.iter()
.filter(|p| p.id.starts_with("/dev/cu."))
.filter_map(|p| {
// Extract device number after "cu."
p.id.strip_prefix("/dev/cu.").map(|s| s.to_string())
})
.collect();
// Keep only cu devices when both exist, otherwise keep tty
ports.retain(|p| {
if let Some(device_num) = p.id.strip_prefix("/dev/tty.") {
// This is a tty device - only keep if no corresponding cu device exists
!cu_device_numbers.contains(device_num)
} else {
// Keep all non-tty devices (including cu devices)
true
}
});
}
ports
}
fn open_device_port(&self, id: &str, baud_rate: u32) -> Result<SerialPort, PortOpenError> {
serialport::new(id, baud_rate)
// This timeout should never be hit in any normal circumstance but it's important to
// have in case a device is bisbehaving. Note: 10ms is too low and leads to errors when
// writing.
.timeout(Duration::from_millis(5_000))
.open()
.map_err(|e| {
let msg = e.to_string();
if msg == "Device or resource busy" {
PortOpenError::DeviceBusy
} else if msg == "Permission denied" {
PortOpenError::PermissionDenied
} else {
PortOpenError::Other(Box::new(e))
}
})
}
}
impl<T: Serial + Sync> Serial for std::sync::Arc<T> {
fn available_ports(&self) -> Vec<PortDesc> {
self.as_ref().available_ports()
}
fn open_device_port(
&self,
unique_id: &str,
baud_rate: u32,
) -> Result<SerialPort, PortOpenError> {
self.as_ref().open_device_port(unique_id, baud_rate)
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_coordinator/src/enter_physical_backup.rs | frostsnap_coordinator/src/enter_physical_backup.rs | use frostsnap_comms::{CoordinatorSendBody, CoordinatorSendMessage};
use frostsnap_core::{
coordinator::{restoration, CoordinatorToUserMessage},
message::{CoordinatorRestoration, CoordinatorToDeviceMessage},
DeviceId, EnterPhysicalId,
};
use crate::{DeviceMode, Sink, UiProtocol};
pub struct EnterPhysicalBackup {
sink: Box<dyn Sink<EnterPhysicalBackupState>>,
enter_physical_id: EnterPhysicalId,
chosen_device: DeviceId,
sent_req: bool,
connected: bool,
entered: Option<restoration::PhysicalBackupPhase>,
saved: bool,
abort: Option<String>,
}
impl EnterPhysicalBackup {
pub fn new(sink: impl Sink<EnterPhysicalBackupState>, chosen_device: DeviceId) -> Self {
let enter_physical_id = EnterPhysicalId::new(&mut rand::thread_rng());
Self {
sink: Box::new(sink),
enter_physical_id,
chosen_device,
sent_req: false,
connected: false,
entered: None,
saved: false,
abort: None,
}
}
pub fn emit_state(&self) {
self.sink.send(EnterPhysicalBackupState {
device_id: self.chosen_device,
entered: self.entered,
saved: self.saved,
abort: self.abort.clone(),
})
}
}
impl UiProtocol for EnterPhysicalBackup {
fn cancel(&mut self) {
self.abort = Some("entering backup canceled".into());
}
fn is_complete(&self) -> Option<crate::Completion> {
if self.saved {
Some(crate::Completion::Success)
} else if self.abort.is_some() {
Some(crate::Completion::Abort {
send_cancel_to_all_devices: true,
})
} else {
None
}
}
fn disconnected(&mut self, id: DeviceId) {
if id == self.chosen_device {
self.connected = false;
self.abort = Some("device was unplugged".into());
}
self.emit_state();
}
fn poll(&mut self) -> Vec<frostsnap_comms::CoordinatorSendMessage> {
if !self.sent_req && self.connected {
self.sent_req = true;
return vec![CoordinatorSendMessage::to(
self.chosen_device,
CoordinatorSendBody::Core(CoordinatorToDeviceMessage::Restoration(
CoordinatorRestoration::EnterPhysicalBackup {
enter_physical_id: self.enter_physical_id,
},
)),
)];
}
vec![]
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn as_mut_any(&mut self) -> &mut dyn std::any::Any {
self
}
fn connected(&mut self, id: DeviceId, _state: DeviceMode) {
if id == self.chosen_device {
self.connected = true;
}
self.emit_state();
}
fn process_to_user_message(&mut self, message: CoordinatorToUserMessage) -> bool {
match message {
CoordinatorToUserMessage::Restoration(
restoration::ToUserRestoration::PhysicalBackupEntered(physical_backup_phase),
) if physical_backup_phase.from == self.chosen_device
&& physical_backup_phase.backup.enter_physical_id == self.enter_physical_id =>
{
self.entered = Some(*physical_backup_phase);
self.emit_state();
true
}
CoordinatorToUserMessage::Restoration(
restoration::ToUserRestoration::PhysicalBackupSaved { device_id, .. },
) if device_id == self.chosen_device => {
self.saved = true;
self.emit_state();
true
}
_ => false,
}
}
}
#[derive(Debug, Clone)]
pub struct EnterPhysicalBackupState {
pub device_id: DeviceId,
pub entered: Option<restoration::PhysicalBackupPhase>,
pub saved: bool,
pub abort: Option<String>,
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_coordinator/src/backup_run.rs | frostsnap_coordinator/src/backup_run.rs | use crate::persist::{Persist, ToStringWrapper};
use bdk_chain::rusqlite_impl::migrate_schema;
use frostsnap_core::{AccessStructureId, AccessStructureRef, Gist, KeyId};
use rusqlite::params;
use std::collections::BTreeMap;
use tracing::{event, Level};
#[derive(Default, Debug)]
pub struct BackupState {
// Maps each access_structure_ref to a map of share_index -> complete boolean.
runs: BTreeMap<AccessStructureRef, BTreeMap<u32, bool>>,
}
impl BackupState {
fn apply_mutation(&mut self, mutation: &Mutation) -> bool {
match mutation {
Mutation::AddShareNeedsBackup {
access_structure_ref,
share_index,
} => {
let run = self.runs.entry(*access_structure_ref).or_default();
run.insert(*share_index, false);
true
}
Mutation::MarkShareComplete {
access_structure_ref,
share_index,
} => {
let run = self.runs.entry(*access_structure_ref).or_default();
run.insert(*share_index, true) != Some(true)
}
Mutation::ClearBackupState {
access_structure_ref,
} => self.runs.remove(access_structure_ref).is_some(),
}
}
fn mutate(&mut self, mutation: Mutation, mutations: &mut Vec<Mutation>) {
if self.apply_mutation(&mutation) {
event!(Level::DEBUG, gist = mutation.gist(), "mutating");
mutations.push(mutation);
}
}
pub fn start_run(
&mut self,
access_structure_ref: AccessStructureRef,
share_indices: Vec<u32>,
mutations: &mut Vec<Mutation>,
) {
for share_index in share_indices {
self.mutate(
Mutation::AddShareNeedsBackup {
access_structure_ref,
share_index,
},
mutations,
);
}
}
pub fn mark_backup_complete(
&mut self,
access_structure_ref: AccessStructureRef,
share_index: u32,
mutations: &mut Vec<Mutation>,
) {
self.mutate(
Mutation::MarkShareComplete {
access_structure_ref,
share_index,
},
mutations,
);
}
/// We want the API to assume there's only one access structure for key for now so we have this
/// hack. If/when we want to have backups for other access structures then we can do that and
/// change the API here.
fn guess_access_structure_ref_for_key(&self, key_id: KeyId) -> Option<AccessStructureRef> {
let (access_structure_ref, _) = self
.runs
.range(AccessStructureRef::range_for_key(key_id))
.next()?;
Some(*access_structure_ref)
}
pub fn clear_backup_run(&mut self, key_id: KeyId, mutations: &mut Vec<Mutation>) {
if let Some(access_structure_ref) = self.guess_access_structure_ref_for_key(key_id) {
self.mutate(
Mutation::ClearBackupState {
access_structure_ref,
},
mutations,
);
}
}
pub fn get_backup_run(&self, key_id: KeyId) -> BTreeMap<u32, bool> {
let access_structure_ref = match self.guess_access_structure_ref_for_key(key_id) {
Some(asref) => asref,
None => return Default::default(),
};
self.runs
.get(&access_structure_ref)
.cloned()
.unwrap_or_default()
}
}
#[derive(Debug, Clone)]
pub enum Mutation {
AddShareNeedsBackup {
access_structure_ref: AccessStructureRef,
share_index: u32,
},
MarkShareComplete {
access_structure_ref: AccessStructureRef,
share_index: u32,
},
ClearBackupState {
access_structure_ref: AccessStructureRef,
},
}
impl Gist for Mutation {
fn gist(&self) -> String {
match self {
Mutation::AddShareNeedsBackup { .. } => "AddShareNeedsBackup",
Mutation::MarkShareComplete { .. } => "MarkShareComplete",
Mutation::ClearBackupState { .. } => "ClearBackupState",
}
.to_string()
}
}
const SCHEMA_NAME: &str = "frostsnap_backup_state";
const MIGRATIONS: &[&str] = &[
// Version 0
"CREATE TABLE IF NOT EXISTS backup_runs ( \
key_id TEXT NOT NULL, \
access_structure_id TEXT NOT NULL, \
device_id TEXT NOT NULL, \
timestamp INTEGER, \
PRIMARY KEY (key_id, access_structure_id, device_id) \
)",
// Version 1: Change from timestamp + device_id to complete boolean + share_index
// Preserve the gist: create share indices 1..N where N is the number of devices
// If all devices were complete, mark all shares complete; otherwise all incomplete
"CREATE TABLE backup_runs_new ( \
key_id TEXT NOT NULL, \
access_structure_id TEXT NOT NULL, \
share_index INTEGER NOT NULL, \
complete BOOLEAN NOT NULL, \
PRIMARY KEY (key_id, access_structure_id, share_index) \
); \
WITH backup_summary AS ( \
SELECT key_id, access_structure_id, \
COUNT(*) as device_count, \
MIN(CASE WHEN timestamp IS NOT NULL THEN 1 ELSE 0 END) as all_complete \
FROM backup_runs \
GROUP BY key_id, access_structure_id \
), \
numbers(n) AS ( \
SELECT 1 \
UNION ALL \
SELECT n + 1 FROM numbers WHERE n < 50 \
) \
INSERT INTO backup_runs_new (key_id, access_structure_id, share_index, complete) \
SELECT bs.key_id, bs.access_structure_id, n.n, bs.all_complete \
FROM backup_summary bs \
JOIN numbers n ON n.n <= bs.device_count; \
DROP TABLE backup_runs; \
ALTER TABLE backup_runs_new RENAME TO backup_runs;",
];
impl Persist<rusqlite::Connection> for BackupState {
type Update = Vec<Mutation>;
type LoadParams = ();
fn migrate(conn: &mut rusqlite::Connection) -> anyhow::Result<()> {
let db_tx = conn.transaction()?;
migrate_schema(&db_tx, SCHEMA_NAME, MIGRATIONS)?;
db_tx.commit()?;
Ok(())
}
fn load(conn: &mut rusqlite::Connection, _: ()) -> anyhow::Result<Self> {
let mut stmt = conn.prepare(
r#"
SELECT key_id, access_structure_id, share_index, complete
FROM backup_runs
"#,
)?;
let rows = stmt.query_map([], |row| {
Ok((
row.get::<_, ToStringWrapper<KeyId>>(0)?.0,
row.get::<_, ToStringWrapper<AccessStructureId>>(1)?.0,
row.get::<_, u32>(2)?,
row.get::<_, bool>(3)?,
))
})?;
let mut state = BackupState::default();
for row in rows.into_iter() {
let (key_id, access_structure_id, share_index, complete) = row?;
let access_structure_ref = AccessStructureRef {
key_id,
access_structure_id,
};
state.apply_mutation(&Mutation::AddShareNeedsBackup {
access_structure_ref,
share_index,
});
if complete {
state.apply_mutation(&Mutation::MarkShareComplete {
access_structure_ref,
share_index,
});
}
}
Ok(state)
}
fn persist_update(
&self,
conn: &mut rusqlite::Connection,
update: Vec<Mutation>,
) -> anyhow::Result<()> {
let tx = conn.transaction()?;
for mutation in update {
match mutation {
Mutation::AddShareNeedsBackup {
access_structure_ref,
share_index,
} => {
tx.execute(
r#"
INSERT INTO backup_runs (key_id, access_structure_id, share_index, complete)
VALUES (?1, ?2, ?3, ?4)
"#,
params![
ToStringWrapper(access_structure_ref.key_id),
ToStringWrapper(access_structure_ref.access_structure_id),
share_index,
false
],
)?;
}
Mutation::MarkShareComplete {
access_structure_ref,
share_index,
} => {
tx.execute(
r#"
INSERT OR REPLACE INTO backup_runs (key_id, access_structure_id, share_index, complete)
VALUES (?1, ?2, ?3, ?4)
"#,
params![
ToStringWrapper(access_structure_ref.key_id),
ToStringWrapper(access_structure_ref.access_structure_id),
share_index,
true
],
)?;
}
Mutation::ClearBackupState {
access_structure_ref,
} => {
tx.execute(
r#"
DELETE FROM backup_runs
WHERE key_id=?1 AND access_structure_id=?2
"#,
params![
ToStringWrapper(access_structure_ref.key_id),
ToStringWrapper(access_structure_ref.access_structure_id),
],
)?;
}
}
}
tx.commit()?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::persist::Persist;
use rusqlite::Connection;
use std::str::FromStr;
fn setup_version_0_db(conn: &mut Connection) {
conn.execute(MIGRATIONS[0], []).unwrap();
conn.execute_batch(
"INSERT INTO backup_runs VALUES('8715c3b68a7d7f2c248b5f63e923d5aeafe7f29458bb825646e024c1816181f2','e74a55491d1dd0ba1f8ac57ef3e9ed58b1d1046aa0698009b4bec1be0e0d8bd2','027feb109a5690935a1e862f3a20be00ffe6a36dcfeed3d0eb2f7f056e5d543abb',NULL);\
INSERT INTO backup_runs VALUES('8715c3b68a7d7f2c248b5f63e923d5aeafe7f29458bb825646e024c1816181f2','e74a55491d1dd0ba1f8ac57ef3e9ed58b1d1046aa0698009b4bec1be0e0d8bd2','02f3fab71a90989c57dbc72b4bbaf5dc82b82552bcd1c416738d081daa248214c7',NULL);\
INSERT INTO backup_runs VALUES('8715c3b68a7d7f2c248b5f63e923d5aeafe7f29458bb825646e024c1816181f2','e74a55491d1dd0ba1f8ac57ef3e9ed58b1d1046aa0698009b4bec1be0e0d8bd2','0333e61a47f72480bf40ad938ddb6d6e0eb94608ddb4921305bee5d36ef0c2e5a2',NULL)"
)
.unwrap();
}
/// Tests migration from Version 0 (device_id + timestamp) to Version 1 (share_index + complete).
///
/// ## Why this change was made
///
/// The original schema tracked backup completion per DeviceId. However, this was incorrect
/// because what actually needs to be backed up is the share at a particular ShareIndex, not
/// the specific device holding it. If two devices hold the same share (same ShareIndex),
/// backing up either one satisfies the backup requirement for that share.
///
/// ## Difficulties in migration
///
/// The main difficulty is that the old schema didn't store ShareIndex at all - it only had
/// DeviceId. This means we cannot accurately map old device backups to specific share indices.
///
/// To preserve the "gist" of existing backup state, the migration:
/// 1. Counts how many devices were in each backup run
/// 2. Creates share indices 1..N (where N is the device count)
/// 3. Uses an all-or-nothing approach: if ALL old devices were complete (had timestamps),
/// mark all new shares as complete; otherwise mark all as incomplete
///
/// This is a lossy migration but preserves the essential information: whether a backup run
/// was fully completed or not.
#[test]
fn test_migration_from_v0_to_v1() {
let key_id =
KeyId::from_str("8715c3b68a7d7f2c248b5f63e923d5aeafe7f29458bb825646e024c1816181f2")
.unwrap();
// Section 1: 0 of 3 devices complete
{
let mut conn = Connection::open_in_memory().unwrap();
setup_version_0_db(&mut conn);
BackupState::migrate(&mut conn).unwrap();
let state = BackupState::load(&mut conn, ()).unwrap();
let backup_run = state.get_backup_run(key_id);
assert_eq!(backup_run.len(), 3, "Should have 3 shares");
assert_eq!(backup_run.get(&1), Some(&false));
assert_eq!(backup_run.get(&2), Some(&false));
assert_eq!(backup_run.get(&3), Some(&false));
}
// Section 2: 2 of 3 devices complete (partial completion)
{
let mut conn = Connection::open_in_memory().unwrap();
setup_version_0_db(&mut conn);
conn.execute(
"UPDATE backup_runs SET timestamp = 1761805723 WHERE device_id = '027feb109a5690935a1e862f3a20be00ffe6a36dcfeed3d0eb2f7f056e5d543abb'",
[],
)
.unwrap();
conn.execute(
"UPDATE backup_runs SET timestamp = 1761805724 WHERE device_id = '02f3fab71a90989c57dbc72b4bbaf5dc82b82552bcd1c416738d081daa248214c7'",
[],
)
.unwrap();
BackupState::migrate(&mut conn).unwrap();
let state = BackupState::load(&mut conn, ()).unwrap();
let backup_run = state.get_backup_run(key_id);
assert_eq!(backup_run.len(), 3, "Should have 3 shares");
assert_eq!(backup_run.get(&1), Some(&false));
assert_eq!(backup_run.get(&2), Some(&false));
assert_eq!(backup_run.get(&3), Some(&false));
}
// Section 3: 3 of 3 devices complete (full completion)
{
let mut conn = Connection::open_in_memory().unwrap();
setup_version_0_db(&mut conn);
conn.execute(
"UPDATE backup_runs SET timestamp = 1761805723 WHERE device_id = '027feb109a5690935a1e862f3a20be00ffe6a36dcfeed3d0eb2f7f056e5d543abb'",
[],
)
.unwrap();
conn.execute(
"UPDATE backup_runs SET timestamp = 1761805724 WHERE device_id = '02f3fab71a90989c57dbc72b4bbaf5dc82b82552bcd1c416738d081daa248214c7'",
[],
)
.unwrap();
conn.execute(
"UPDATE backup_runs SET timestamp = 1761805725 WHERE device_id = '0333e61a47f72480bf40ad938ddb6d6e0eb94608ddb4921305bee5d36ef0c2e5a2'",
[],
)
.unwrap();
BackupState::migrate(&mut conn).unwrap();
let state = BackupState::load(&mut conn, ()).unwrap();
let backup_run = state.get_backup_run(key_id);
assert_eq!(backup_run.len(), 3, "Should have 3 shares");
assert_eq!(backup_run.get(&1), Some(&true));
assert_eq!(backup_run.get(&2), Some(&true));
assert_eq!(backup_run.get(&3), Some(&true));
}
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_coordinator/src/display_backup.rs | frostsnap_coordinator/src/display_backup.rs | use crate::{Completion, DeviceMode, Sink, UiProtocol};
use frostsnap_comms::{CommsMisc, CoordinatorSendMessage};
use frostsnap_core::{coordinator::FrostCoordinator, AccessStructureRef, DeviceId, SymmetricKey};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DisplayBackupState {
pub confirmed: bool,
pub close_dialog: bool,
}
pub struct DisplayBackupProtocol {
device_id: DeviceId,
abort: bool,
messages: Vec<CoordinatorSendMessage>,
should_send: bool,
sink: Box<dyn Sink<DisplayBackupState> + Send>,
}
impl DisplayBackupProtocol {
pub fn new(
coord: &mut FrostCoordinator,
device_id: DeviceId,
access_structure_ref: AccessStructureRef,
encryption_key: SymmetricKey,
sink: impl Sink<DisplayBackupState> + 'static,
) -> anyhow::Result<Self> {
let messages = coord
.request_device_display_backup(device_id, access_structure_ref, encryption_key)?
.into_iter()
.map(|message| {
message
.try_into()
.expect("will only send messages to device")
})
.collect();
Ok(Self {
device_id,
sink: Box::new(sink),
abort: false,
messages,
should_send: true,
})
}
fn abort(&mut self) {
self.abort = true;
self.sink.send(DisplayBackupState {
confirmed: false,
close_dialog: true,
});
}
}
impl UiProtocol for DisplayBackupProtocol {
fn cancel(&mut self) {
self.abort();
}
fn is_complete(&self) -> Option<Completion> {
if self.abort {
Some(Completion::Abort {
send_cancel_to_all_devices: true,
})
} else {
None
}
}
fn connected(&mut self, id: frostsnap_core::DeviceId, _state: DeviceMode) {
if id == self.device_id {
self.should_send = true;
}
}
fn disconnected(&mut self, id: frostsnap_core::DeviceId) {
if self.device_id == id {
self.abort()
}
}
fn process_comms_message(&mut self, from: DeviceId, message: CommsMisc) -> bool {
if self.device_id != from {
return false;
}
match message {
CommsMisc::BackupRecorded => {
self.sink.send(DisplayBackupState {
confirmed: true,
close_dialog: true,
});
true
}
CommsMisc::DisplayBackupConfrimed => {
tracing::warn!("Received deprecated DisplayBackupConfrimed message. Device firmware should be updated.");
self.sink.send(DisplayBackupState {
confirmed: true,
close_dialog: false,
});
true
}
_ => false,
}
}
fn poll(&mut self) -> Vec<CoordinatorSendMessage> {
if !self.should_send {
return vec![];
}
self.should_send = false;
self.messages.clone()
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn as_mut_any(&mut self) -> &mut dyn std::any::Any {
self
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_coordinator/src/firmware.rs | frostsnap_coordinator/src/firmware.rs | use bincode::{Decode, Encode};
use frostsnap_comms::{Sha256Digest, FIRMWARE_UPGRADE_CHUNK_LEN};
#[derive(Encode, Decode, Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct FirmwareFeatures {
/// Device supports firmware digest verification without signature block
pub upgrade_digest_no_sig: bool,
}
impl FirmwareFeatures {
pub const fn all() -> Self {
Self {
upgrade_digest_no_sig: true,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FirmwareVersion {
pub digest: Sha256Digest,
pub version: Option<VersionNumber>,
}
impl FirmwareVersion {
pub fn new(digest: Sha256Digest) -> Self {
Self {
digest,
version: VersionNumber::from_digest(&digest),
}
}
pub fn features(&self) -> FirmwareFeatures {
match self.version {
Some(version) => version.features(),
None => FirmwareFeatures::all(),
}
}
pub fn version_name(&self) -> String {
match self.version {
Some(version) => format!("v{}", version),
None => {
let short_hash = frostsnap_core::hex::encode(&self.digest.0[..3]);
format!("dev-{}", short_hash)
}
}
}
pub fn check_upgrade_eligibility(
&self,
device_digest: &Sha256Digest,
) -> FirmwareUpgradeEligibility {
if *device_digest == self.digest {
return FirmwareUpgradeEligibility::UpToDate;
}
let device_version = VersionNumber::from_digest(device_digest);
let app_version = self.version;
match (device_version, app_version) {
(None, None) => FirmwareUpgradeEligibility::CanUpgrade,
(None, Some(_)) => FirmwareUpgradeEligibility::CannotUpgrade {
reason:
"Device firmware version newer app. Cannot downgrade firmware. Upgrade the app."
.to_string(),
},
(Some(_), None) => FirmwareUpgradeEligibility::CannotUpgrade {
reason: "This is a development app. Cannot upgrade proper device.".to_string(),
},
(Some(device_ver), Some(app_ver)) => {
if app_ver > device_ver {
FirmwareUpgradeEligibility::CanUpgrade
} else if app_ver == device_ver {
FirmwareUpgradeEligibility::UpToDate
} else {
FirmwareUpgradeEligibility::CannotUpgrade {
reason: "Device firmware version newer app. Cannot downgrade firmware. Upgrade the app.".to_string(),
}
}
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FirmwareUpgradeEligibility {
UpToDate,
CanUpgrade,
CannotUpgrade { reason: String },
}
#[derive(Clone, Copy)]
pub struct FirmwareBin {
bin: &'static [u8],
}
impl std::fmt::Debug for FirmwareBin {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FirmwareBin")
.field("size", &self.bin.len())
.finish()
}
}
impl frostsnap_comms::firmware_reader::FirmwareReader for FirmwareBin {
type Error = std::io::Error;
fn read_sector(
&self,
sector: u32,
) -> Result<Box<[u8; frostsnap_comms::firmware_reader::SECTOR_SIZE]>, Self::Error> {
use frostsnap_comms::firmware_reader::SECTOR_SIZE;
let sector_offset = (sector as usize) * SECTOR_SIZE;
if sector_offset >= self.bin.len() {
return Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"Sector out of bounds",
));
}
let mut sector_data = Box::new([0u8; SECTOR_SIZE]);
let end = (sector_offset + SECTOR_SIZE).min(self.bin.len());
let data_len = end - sector_offset;
sector_data[..data_len].copy_from_slice(&self.bin[sector_offset..end]);
Ok(sector_data)
}
fn n_sectors(&self) -> u32 {
use frostsnap_comms::firmware_reader::SECTOR_SIZE;
self.bin.len().div_ceil(SECTOR_SIZE) as u32
}
}
impl FirmwareBin {
pub const fn is_stub(&self) -> bool {
self.bin.is_empty()
}
pub const fn new(bin: &'static [u8]) -> Self {
Self { bin }
}
pub fn num_chunks(&self) -> u32 {
(self.bin.len() as u32).div_ceil(FIRMWARE_UPGRADE_CHUNK_LEN)
}
pub fn size(&self) -> u32 {
self.bin.len() as u32
}
pub fn as_bytes(&self) -> &'static [u8] {
self.bin
}
pub fn validate(self) -> Result<ValidatedFirmwareBin, FirmwareValidationError> {
ValidatedFirmwareBin::new(self)
}
}
#[derive(Debug, Clone)]
pub enum FirmwareValidationError {
InvalidFormat(frostsnap_comms::firmware_reader::FirmwareSizeError),
SizeMismatch { expected: u32, actual: u32 },
UnknownSignedFirmware { digest: Sha256Digest },
}
impl std::fmt::Display for FirmwareValidationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
FirmwareValidationError::InvalidFormat(err) => {
write!(f, "Invalid firmware format: {}", err)
}
FirmwareValidationError::SizeMismatch { expected, actual } => {
write!(
f,
"Firmware size mismatch: expected {} bytes, got {} bytes",
expected, actual
)
}
FirmwareValidationError::UnknownSignedFirmware { digest } => {
write!(
f,
"Unknown signed firmware with digest: {}. Signed firmware must be in KNOWN_FIRMWARE_VERSIONS",
digest
)
}
}
}
}
impl std::error::Error for FirmwareValidationError {}
#[derive(Clone, Copy, Debug)]
pub struct ValidatedFirmwareBin {
firmware: FirmwareBin,
digest_with_signature: Sha256Digest,
firmware_version: FirmwareVersion,
firmware_size: u32,
total_size: u32,
}
impl ValidatedFirmwareBin {
pub fn new(firmware: FirmwareBin) -> Result<Self, FirmwareValidationError> {
use frostsnap_core::sha2::digest::Digest;
let (firmware_size, total_size) =
frostsnap_comms::firmware_reader::firmware_size(&firmware)
.map_err(FirmwareValidationError::InvalidFormat)?;
if total_size != firmware.size() {
return Err(FirmwareValidationError::SizeMismatch {
expected: total_size,
actual: firmware.size(),
});
}
let mut digest_state = sha2::Sha256::default();
digest_state.update(firmware.as_bytes());
let digest_with_signature = Sha256Digest(digest_state.finalize().into());
let mut firmware_only_state = sha2::Sha256::default();
firmware_only_state.update(&firmware.as_bytes()[..firmware_size as usize]);
let firmware_only_digest = Sha256Digest(firmware_only_state.finalize().into());
let is_signed = firmware_size < total_size;
if is_signed {
// Signed firmware MUST be in KNOWN_FIRMWARE_VERSIONS
VersionNumber::from_digest(&firmware_only_digest).ok_or(
FirmwareValidationError::UnknownSignedFirmware {
digest: digest_with_signature,
},
)?;
}
let firmware_version = FirmwareVersion::new(firmware_only_digest);
Ok(Self {
firmware,
digest_with_signature,
firmware_version,
firmware_size,
total_size,
})
}
pub fn firmware_version(&self) -> FirmwareVersion {
self.firmware_version
}
pub fn digest(&self) -> Sha256Digest {
self.firmware_version.digest
}
pub fn digest_with_signature(&self) -> Sha256Digest {
self.digest_with_signature
}
pub fn size(&self) -> u32 {
self.total_size
}
pub fn firmware_size(&self) -> u32 {
self.firmware_size
}
pub fn total_size(&self) -> u32 {
self.total_size
}
pub fn as_bytes(&self) -> &'static [u8] {
self.firmware.as_bytes()
}
pub fn num_chunks(&self) -> u32 {
self.firmware.num_chunks()
}
pub fn is_signed(&self) -> bool {
self.firmware_size < self.total_size
}
pub fn version(&self) -> Option<VersionNumber> {
self.firmware_version.version
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct VersionNumber {
pub major: u8,
pub minor: u8,
pub patch: u8,
}
impl std::fmt::Display for VersionNumber {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
}
}
impl VersionNumber {
pub const fn new(major: u8, minor: u8, patch: u8) -> Self {
Self {
major,
minor,
patch,
}
}
pub fn from_digest(digest: &Sha256Digest) -> Option<Self> {
KNOWN_FIRMWARE_VERSIONS
.iter()
.find(|(d, _)| d == digest)
.map(|(_, v)| *v)
}
pub fn features(&self) -> FirmwareFeatures {
const V0_0_1: VersionNumber = VersionNumber::new(0, 0, 1);
FirmwareFeatures {
upgrade_digest_no_sig: *self > V0_0_1,
}
}
}
// Known firmware versions indexed by their digest
//
// NOTE: v0.0.1 has both signed and unsigned entries because we didn't have a proper
// digest-to-version system yet. Devices announced their full digest (including signature),
// so signed and unsigned builds had different digests. Starting with future versions, we
// should only track the firmware-only (deterministic) digest.
use frostsnap_macros::hex;
pub const KNOWN_FIRMWARE_VERSIONS: &[(Sha256Digest, VersionNumber)] = &[
(
Sha256Digest(hex!(
"e432d313c7698b1e8843b10ba95efa8c28e66a5723b966c56c156687d09d16e0"
)),
VersionNumber::new(0, 2, 0),
),
(
Sha256Digest(hex!(
"5ff7bd280b96d645b2c739a6b91bfc6c27197e213302770f1a7180678ca4f720"
)),
VersionNumber::new(0, 1, 0),
),
/*signed*/
(
Sha256Digest(hex!(
"57161f80b41413b1053e272f9c3da8d16ecfce44793345be69f7fe03d93f4eb0"
)),
VersionNumber::new(0, 0, 1),
),
/*unsigned*/
(
Sha256Digest(hex!(
"8f45ae6b72c241a20798acbd3c6d3e54071cae73e335df1785f2d485a915da4c"
)),
VersionNumber::new(0, 0, 1),
),
];
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_coordinator/src/frostsnap_persist.rs | frostsnap_coordinator/src/frostsnap_persist.rs | use crate::{
frostsnap_core::{
self,
coordinator::{ActiveSignSession, FrostCoordinator},
},
persist::{BincodeWrapper, Persist, TakeStaged},
};
use anyhow::Context;
use bdk_chain::rusqlite_impl::migrate_schema;
use frostsnap_core::{
coordinator::{self, restoration::RestorationMutation},
DeviceId,
};
use rusqlite::params;
use std::collections::{HashMap, VecDeque};
use tracing::{event, Level};
impl Persist<rusqlite::Connection> for FrostCoordinator {
type Update = VecDeque<coordinator::Mutation>;
type LoadParams = ();
fn migrate(conn: &mut rusqlite::Connection) -> anyhow::Result<()> {
const SCHEMA_NAME: &str = "frostsnap_coordinator";
const MIGRATIONS: &[&str] = &[
// Version 0
"CREATE TABLE IF NOT EXISTS fs_coordinator_mutations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
mutation BLOB NOT NULL,
tied_to_key TEXT,
tied_to_restoration TEXT,
version INTEGER NOT NULL
)",
];
let db_tx = conn.transaction()?;
migrate_schema(&db_tx, SCHEMA_NAME, MIGRATIONS)?;
db_tx.commit()?;
Ok(())
}
fn load(conn: &mut rusqlite::Connection, _: Self::LoadParams) -> anyhow::Result<Self>
where
Self: Sized,
{
let mut coordinator = FrostCoordinator::new();
let mut stmt =
conn.prepare("SELECT mutation, version FROM fs_coordinator_mutations ORDER BY id")?;
let row_iter = stmt.query_map([], |row| {
let version = row.get::<_, usize>(1)?;
if version != 0 {
event!(
Level::ERROR,
"Version of database is newer than the app. Upgrade the app"
)
}
let mutation = row.get::<_, BincodeWrapper<coordinator::Mutation>>(0)?.0;
Ok(mutation)
})?;
for mutation in row_iter {
let mutation = mutation.context("failed to decode an fs_coordinator_mutation")?;
let _ = coordinator.apply_mutation(mutation);
}
Ok(coordinator)
}
fn persist_update(
&self,
conn: &mut rusqlite::Connection,
update: Self::Update,
) -> anyhow::Result<()> {
for mutation in update {
match mutation {
coordinator::Mutation::Keygen(coordinator::keys::KeyMutation::DeleteKey(
key_id,
)) => {
conn.execute(
"DELETE FROM fs_coordinator_mutations WHERE tied_to_key=?1",
params![key_id],
)?;
}
coordinator::Mutation::Restoration(RestorationMutation::DeleteRestoration {
restoration_id,
}) => {
conn.execute(
"DELETE FROM fs_coordinator_mutations WHERE tied_to_restoration=?1",
params![restoration_id],
)?;
}
mutation => {
conn.execute(
"INSERT INTO fs_coordinator_mutations (tied_to_key, tied_to_restoration, mutation, version) VALUES (?1, ?2, ?3, 0)",
params![mutation.tied_to_key(self), mutation.tied_to_restoration(), BincodeWrapper(mutation)],
)?;
}
}
}
Ok(())
}
}
impl TakeStaged<VecDeque<coordinator::Mutation>> for FrostCoordinator {
fn take_staged_update(&mut self) -> Option<VecDeque<coordinator::Mutation>> {
let mutations = self.take_staged_mutations();
if mutations.is_empty() {
None
} else {
Some(mutations)
}
}
}
impl Persist<rusqlite::Connection> for Option<ActiveSignSession> {
type Update = Self;
type LoadParams = ();
fn migrate(conn: &mut rusqlite::Connection) -> anyhow::Result<()> {
const SCHEMA_NAME: &str = "frostsnap_active_sign_session";
const MIGRATIONS: &[&str] = &[
// Version 0
"CREATE TABLE IF NOT EXISTS fs_signing_session_state ( state BLOB )",
];
let db_tx = conn.transaction()?;
migrate_schema(&db_tx, SCHEMA_NAME, MIGRATIONS)?;
db_tx.commit()?;
Ok(())
}
fn load(conn: &mut rusqlite::Connection, _params: Self::LoadParams) -> anyhow::Result<Self> {
let signing_session_state =
conn.query_row("SELECT state FROM fs_signing_session_state", [], |row| {
Ok(row.get::<_, BincodeWrapper<ActiveSignSession>>(0)?.0)
});
let state = match signing_session_state {
Ok(signing_session_state) => Some(signing_session_state),
Err(rusqlite::Error::QueryReturnedNoRows) => None,
Err(e) => return Err(e.into()),
};
Ok(state)
}
fn persist_update(
&self,
conn: &mut rusqlite::Connection,
update: Self::Update,
) -> anyhow::Result<()> {
match update {
Some(signing_session_state) => {
conn.execute(
"INSERT INTO fs_signing_session_state (state) VALUES (?1)",
params![BincodeWrapper(signing_session_state)],
)?;
}
None => {
conn.execute("DELETE FROM fs_signing_session_state", [])?;
}
}
Ok(())
}
}
impl TakeStaged<Option<ActiveSignSession>> for Option<ActiveSignSession> {
fn take_staged_update(&mut self) -> Option<Option<ActiveSignSession>> {
Some(self.clone())
}
}
#[derive(Default)]
pub struct DeviceNames {
names: HashMap<DeviceId, String>,
mutations: VecDeque<(DeviceId, String)>,
}
impl DeviceNames {
pub fn insert(&mut self, device_id: DeviceId, name: String) {
if self.names.insert(device_id, name.clone()).as_ref() != Some(&name) {
self.mutations.push_back((device_id, name));
}
}
pub fn get(&self, device_id: DeviceId) -> Option<String> {
self.names.get(&device_id).cloned()
}
}
impl TakeStaged<VecDeque<(DeviceId, String)>> for DeviceNames {
fn take_staged_update(&mut self) -> Option<VecDeque<(DeviceId, String)>> {
if self.mutations.is_empty() {
None
} else {
Some(core::mem::take(&mut self.mutations))
}
}
}
impl Persist<rusqlite::Connection> for DeviceNames {
type Update = VecDeque<(DeviceId, String)>;
type LoadParams = ();
fn migrate(conn: &mut rusqlite::Connection) -> anyhow::Result<()> {
const SCHEMA_NAME: &str = "frostsnap_device_names";
const MIGRATIONS: &[&str] = &[
// Version 0
"CREATE TABLE IF NOT EXISTS fs_devices ( \
id BLOB PRIMARY KEY, \
name TEXT NOT NULL \
)",
];
let db_tx = conn.transaction()?;
migrate_schema(&db_tx, SCHEMA_NAME, MIGRATIONS)?;
db_tx.commit()?;
Ok(())
}
fn load(conn: &mut rusqlite::Connection, _params: Self::LoadParams) -> anyhow::Result<Self>
where
Self: Sized,
{
let mut stmt = conn.prepare("SELECT id, name FROM fs_devices")?;
let mut device_names = DeviceNames::default();
let row_iter = stmt.query_map([], |row| {
let device_id = row.get::<_, DeviceId>(0)?;
let name = row.get::<_, String>(1)?;
Ok((device_id, name))
})?;
for row in row_iter {
let (device_id, name) = row?;
device_names.names.insert(device_id, name);
}
Ok(device_names)
}
fn persist_update(
&self,
conn: &mut rusqlite::Connection,
update: Self::Update,
) -> anyhow::Result<()> {
for (id, name) in update {
conn.execute(
"INSERT OR REPLACE INTO fs_devices (id, name) VALUES (?1, ?2)",
params![id, name],
)?;
}
Ok(())
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_coordinator/src/bitcoin/wallet_persist.rs | frostsnap_coordinator/src/bitcoin/wallet_persist.rs | use std::collections::btree_map;
use super::wallet::{WalletIndexedTxGraph, WalletIndexedTxGraphChangeSet};
use crate::persist::Persist;
use anyhow::Result;
use bdk_chain::{
bitcoin::BlockHash,
local_chain::{self, LocalChain},
ConfirmationBlockTime,
};
impl Persist<rusqlite::Connection> for WalletIndexedTxGraph {
type Update = WalletIndexedTxGraphChangeSet;
type LoadParams = ();
fn migrate(conn: &mut rusqlite::Connection) -> Result<()> {
let db_tx = conn.transaction()?;
bdk_chain::tx_graph::ChangeSet::<ConfirmationBlockTime>::init_sqlite_tables(&db_tx)?;
bdk_chain::indexer::keychain_txout::ChangeSet::init_sqlite_tables(&db_tx)?;
db_tx.commit()?;
Ok(())
}
fn load(conn: &mut rusqlite::Connection, _: Self::LoadParams) -> anyhow::Result<Self> {
let db_tx = conn.transaction()?;
let mut indexed_tx_graph = Self::default();
indexed_tx_graph.apply_changeset(WalletIndexedTxGraphChangeSet {
tx_graph: bdk_chain::tx_graph::ChangeSet::from_sqlite(&db_tx)?,
indexer: bdk_chain::indexer::keychain_txout::ChangeSet::from_sqlite(&db_tx)?,
});
db_tx.commit()?;
Ok(indexed_tx_graph)
}
fn persist_update(&self, conn: &mut rusqlite::Connection, update: Self::Update) -> Result<()> {
let db_tx = conn.transaction()?;
update.tx_graph.persist_to_sqlite(&db_tx)?;
update.indexer.persist_to_sqlite(&db_tx)?;
db_tx.commit()?;
Ok(())
}
}
impl Persist<rusqlite::Connection> for local_chain::LocalChain {
type LoadParams = BlockHash;
type Update = local_chain::ChangeSet;
fn migrate(conn: &mut rusqlite::Connection) -> Result<()> {
let db_tx = conn.transaction()?;
bdk_chain::local_chain::ChangeSet::init_sqlite_tables(&db_tx)?;
db_tx.commit()?;
Ok(())
}
fn load(conn: &mut rusqlite::Connection, block_hash: Self::LoadParams) -> Result<Self> {
let db_tx = conn.transaction()?;
let mut changeset = bdk_chain::local_chain::ChangeSet::from_sqlite(&db_tx)?;
if let btree_map::Entry::Vacant(entry) = changeset.blocks.entry(0) {
entry.insert(Some(block_hash));
changeset.persist_to_sqlite(&db_tx)?;
}
db_tx.commit()?;
Ok(LocalChain::from_changeset(changeset).expect("must have genesis block"))
}
fn persist_update(&self, conn: &mut rusqlite::Connection, update: Self::Update) -> Result<()> {
let db_tx = conn.transaction()?;
update.persist_to_sqlite(&db_tx)?;
db_tx.commit()?;
Ok(())
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_coordinator/src/bitcoin/chain_sync.rs | frostsnap_coordinator/src/bitcoin/chain_sync.rs | //! We keep chain at arms length from the rest of the code by only communicating through mpsc channels.
use anyhow::{anyhow, Result};
pub use bdk_chain::spk_client::SyncRequest;
use bdk_chain::{
bitcoin::{self, BlockHash},
spk_client::{self},
CheckPoint, ConfirmationBlockTime,
};
use bdk_electrum_streaming::{
electrum_streaming_client::request, run_async, AsyncReceiver, AsyncState, Cache,
DerivedSpkTracker, ReqCoord, Update,
};
use frostsnap_core::MasterAppkey;
use futures::{
channel::{mpsc, oneshot},
executor::{block_on, block_on_stream},
select,
stream::FuturesUnordered,
FutureExt, StreamExt,
};
use futures::{pin_mut, select_biased};
use std::{
collections::BTreeMap,
fmt::Debug,
ops::Deref,
sync::{
self,
atomic::{AtomicBool, Ordering},
Arc,
},
time::Duration,
};
use tokio::io::AsyncWriteExt;
use tokio_util::compat::{TokioAsyncReadCompatExt, TokioAsyncWriteCompatExt};
use tracing::{event, Level};
use crate::persist::Persisted;
use crate::settings::ElectrumEnabled;
use crate::Sink;
use super::{
descriptor_for_account_keychain,
handler_state::HandlerState,
tofu::{
connection::{Conn, TargetServerReq},
trusted_certs::TrustedCertificates,
verifier::UntrustedCertificate,
},
wallet::{CoordSuperWallet, KeychainId},
};
#[derive(Debug)]
pub struct ReqAndResponse<I, O> {
request: I,
response: oneshot::Sender<O>,
}
impl<I: Send, O: Send> ReqAndResponse<I, O> {
pub fn new(request: I) -> (Self, oneshot::Receiver<O>) {
let (response, response_recv) = oneshot::channel();
(Self { request, response }, response_recv)
}
pub fn into_tuple(self) -> (I, oneshot::Sender<O>) {
(self.request, self.response)
}
}
pub const SUPPORTED_NETWORKS: [bitcoin::Network; 4] = {
use bitcoin::Network::*;
[Bitcoin, Signet, Testnet, Regtest]
};
pub type SyncResponse = spk_client::SyncResponse<ConfirmationBlockTime>;
pub type KeychainClient = bdk_electrum_streaming::AsyncClient<KeychainId>;
pub type KeychainClientReceiver = bdk_electrum_streaming::AsyncReceiver<KeychainId>;
/// The messages the client can send to the backend
pub enum Message {
ChangeUrlReq(ReqAndResponse<TargetServerReq, Result<ConnectionResult>>),
SetStatusSink(Box<dyn Sink<ChainStatus>>),
/// Start the client loop (sent once when first sync request is made)
StartClient,
Reconnect,
TrustCertificate {
server_url: String,
certificate_der: Vec<u8>,
},
SetUrls {
primary: String,
backup: String,
},
SetEnabled(ElectrumEnabled),
/// Connect to a specific server (primary or backup)
ConnectTo {
use_backup: bool,
},
}
/// Result of a connection attempt
#[derive(Debug, Clone)]
pub enum ConnectionResult {
Success,
CertificatePromptNeeded(UntrustedCertificate),
Failed(String),
}
impl std::fmt::Display for Message {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Message::ChangeUrlReq(_) => write!(f, "Message::ChangeUrlReq"),
Message::SetStatusSink(_) => write!(f, "Message::SetStatusSink"),
Message::StartClient => write!(f, "Message::StartClient"),
Message::Reconnect => write!(f, "Message::Reconnect"),
Message::TrustCertificate { server_url, .. } => {
write!(f, "Message::TrustCertificate({})", server_url)
}
Message::SetUrls { .. } => write!(f, "Message::SetUrls"),
Message::SetEnabled(enabled) => write!(f, "Message::SetEnabled({:?})", enabled),
Message::ConnectTo { use_backup } => {
write!(f, "Message::ConnectTo(use_backup={})", use_backup)
}
}
}
}
/// Opaque API to the chain
#[derive(Clone)]
pub struct ChainClient {
req_sender: mpsc::UnboundedSender<Message>,
client: KeychainClient,
connection_requested: Arc<AtomicBool>,
}
impl ChainClient {
pub fn new(
genesis_hash: BlockHash,
trusted_certificates: Persisted<TrustedCertificates>,
db: Arc<sync::Mutex<rusqlite::Connection>>,
) -> (Self, ConnectionHandler) {
let (req_sender, req_recv) = mpsc::unbounded();
let (client, client_recv) = KeychainClient::new();
let cache = Cache::default();
(
Self {
req_sender,
client: client.clone(),
connection_requested: Arc::new(AtomicBool::new(false)),
},
ConnectionHandler {
req_recv,
client_recv,
cache,
client,
genesis_hash,
trusted_certificates,
db,
},
)
}
pub fn check_and_set_electrum_server_url(
&self,
url: String,
is_backup: bool,
) -> Result<ConnectionResult> {
self.start_client();
let (req, response) = ReqAndResponse::new(TargetServerReq { url, is_backup });
self.req_sender
.unbounded_send(Message::ChangeUrlReq(req))
.unwrap();
block_on(response)?
}
pub fn monitor_keychain(&self, keychain: KeychainId, next_index: u32) {
self.start_client();
let descriptor = descriptor_for_account_keychain(
keychain,
// this does not matter
bitcoin::NetworkKind::Main,
);
self.client
.track_descriptor(keychain, descriptor, next_index)
.expect("must track keychain");
}
pub fn broadcast(&self, transaction: bitcoin::Transaction) -> Result<bitcoin::Txid> {
self.start_client();
let txid = transaction.compute_txid();
event!(Level::DEBUG, "Broadcasting: {}", transaction.compute_txid());
block_on(self.client.send_request(request::BroadcastTx(transaction)))
.inspect_err(|err| {
tracing::error!(
txid = txid.to_string(),
error = err.to_string(),
"Failed to broadcast tx"
)
})
.inspect(|txid| tracing::info!(txid = txid.to_string(), "Successfully broadcasted tx"))
}
pub fn estimate_fee(
&self,
target_blocks: impl IntoIterator<Item = usize>,
) -> Result<BTreeMap<usize, bitcoin::FeeRate>> {
self.start_client();
use futures::FutureExt;
block_on_stream(
target_blocks
.into_iter()
.map(|number| {
self.client
.send_request(request::EstimateFee { number })
.map(move |request_result| {
request_result
.map(|resp| resp.fee_rate.map(|fee_rate| (number, fee_rate)))
.transpose()
})
})
.collect::<FuturesUnordered<_>>(),
)
.flatten()
.collect()
}
pub fn set_status_sink(&self, sink: Box<dyn Sink<ChainStatus>>) {
self.req_sender
.unbounded_send(Message::SetStatusSink(sink))
.unwrap();
}
pub fn reconnect(&self) {
self.req_sender.unbounded_send(Message::Reconnect).unwrap();
}
pub fn trust_certificate(&self, server_url: String, certificate_der: Vec<u8>) {
self.req_sender
.unbounded_send(Message::TrustCertificate {
server_url,
certificate_der,
})
.unwrap();
}
fn start_client(&self) {
if !self.connection_requested.swap(true, Ordering::Relaxed) {
self.req_sender
.unbounded_send(Message::StartClient)
.unwrap();
}
}
pub fn set_urls(&self, primary: String, backup: String) {
self.req_sender
.unbounded_send(Message::SetUrls { primary, backup })
.unwrap();
}
pub fn set_enabled(&self, enabled: ElectrumEnabled) {
self.req_sender
.unbounded_send(Message::SetEnabled(enabled))
.unwrap();
}
pub fn connect_to(&self, use_backup: bool) {
self.start_client();
self.req_sender
.unbounded_send(Message::ConnectTo { use_backup })
.unwrap();
}
}
pub const fn default_electrum_server(network: bitcoin::Network) -> &'static str {
// a tooling bug means we need this
#[allow(unreachable_patterns)]
match network {
bitcoin::Network::Bitcoin => "ssl://blockstream.info:700",
// we're using the tcp:// version since ssl ain't working for some reason
bitcoin::Network::Testnet => "tcp://electrum.blockstream.info:60001",
bitcoin::Network::Testnet4 => "ssl://blackie.c3-soft.com:57010",
bitcoin::Network::Regtest => "tcp://localhost:60401",
bitcoin::Network::Signet => "ssl://mempool.space:60602",
_ => panic!("Unknown network"),
}
}
pub const fn default_backup_electrum_server(network: bitcoin::Network) -> &'static str {
// a tooling bug means we need this
#[allow(unreachable_patterns)]
match network {
bitcoin::Network::Bitcoin => "ssl://electrum.acinq.co:50002",
bitcoin::Network::Testnet => "ssl://blockstream.info:993",
bitcoin::Network::Testnet4 => "ssl://mempool.space:40002",
bitcoin::Network::Signet => "tcp://signet-electrumx.wakiyamap.dev:50001",
bitcoin::Network::Regtest => "tcp://127.0.0.1:51001",
_ => panic!("Unknown network"),
}
}
pub struct ConnectionHandler {
client: KeychainClient,
client_recv: KeychainClientReceiver,
req_recv: mpsc::UnboundedReceiver<Message>,
cache: Cache,
genesis_hash: BlockHash,
trusted_certificates: Persisted<TrustedCertificates>,
db: Arc<sync::Mutex<rusqlite::Connection>>,
}
impl ConnectionHandler {
const PING_DELAY: Duration = Duration::from_secs(21);
const PING_TIMEOUT: Duration = Duration::from_secs(3);
pub fn run<SW, F>(mut self, url: String, backup_url: String, super_wallet: SW, update_action: F)
where
SW: Deref<Target = sync::Mutex<CoordSuperWallet>> + Clone + Send + 'static,
F: FnMut(MasterAppkey, Vec<crate::bitcoin::wallet::Transaction>) + Send + 'static,
{
let lookahead: u32;
let chain_tip: CheckPoint;
let network: bitcoin::Network;
{
let super_wallet = super_wallet.lock().expect("must lock");
network = super_wallet.network;
lookahead = super_wallet.lookahead();
chain_tip = super_wallet.chain_tip();
self.cache.txs.extend(super_wallet.tx_cache());
self.cache.anchors.extend(super_wallet.anchor_cache());
}
tracing::info!("Running ConnectionHandler for {} network", network);
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("cannot build tokio runtime");
let (mut update_sender, update_recv) = mpsc::unbounded::<Update<KeychainId>>();
let _wallet_updates_jh = rt.spawn_blocking({
let super_wallet = super_wallet.clone();
move || Self::handle_wallet_updates(super_wallet, update_recv, update_action)
});
let mut handler = HandlerState::new(
self.genesis_hash,
url,
backup_url,
self.trusted_certificates,
self.db,
);
rt.block_on({
let mut electrum_state = AsyncState::<KeychainId>::new(
ReqCoord::new(rand::random::<u32>()),
self.cache,
DerivedSpkTracker::new(lookahead),
chain_tip,
);
async move {
loop {
// Wait until we should connect (started + enabled)
while !handler.should_connect() {
match self.req_recv.next().await {
Some(msg) => {
handler.handle_msg(msg).await;
}
None => return,
}
}
let mut conn = match handler.get_connection().await {
Some(conn) => conn,
None => {
tokio::time::sleep(HandlerState::RECONNECT_DELAY).await;
continue;
}
};
{
let conn_fut = Self::run_connection(
&mut conn,
&mut electrum_state,
&mut self.client_recv,
&mut update_sender,
)
.fuse();
let ping_fut = async {
loop {
tokio::time::sleep(Self::PING_DELAY).await;
let req_fut = self.client.send_request(request::Ping).fuse();
let req_timeout_fut = tokio::time::sleep(Self::PING_TIMEOUT).fuse();
pin_mut!(req_fut);
pin_mut!(req_timeout_fut);
select! {
result = req_fut => {
if let Err(err) = result {
return err;
}
tracing::trace!("Received pong from server");
},
_ = req_timeout_fut => {
return anyhow!("Timeout waiting for pong");
},
}
}
}.fuse();
pin_mut!(conn_fut);
pin_mut!(ping_fut);
// Handle messages until connection fails or we get disabled
loop {
select_biased! {
msg_opt = self.req_recv.next() => {
let msg = match msg_opt {
Some(msg) => msg,
None => return,
};
tracing::info!(msg = msg.to_string(), "Handling message");
let should_reconnect = handler.handle_msg(msg).await;
if !handler.should_connect() {
tracing::info!("Electrum disabled");
break;
}
if should_reconnect {
tracing::info!("Breaking connection loop due to reconnect request");
break;
}
}
err = ping_fut => {
tracing::error!(error = err.to_string(), "Failed to keep connection alive");
break;
},
_ = conn_fut => {
tracing::debug!("Connection service stopped");
break;
},
}
}
}
// Shutdown the connection
handler.set_disconnected();
let shutdown_result = match conn {
Conn::Tcp((rh, wh)) => rh.unsplit(wh).shutdown().await,
Conn::Ssl((rh, wh)) => rh.unsplit(wh).shutdown().await,
};
tracing::info!(result = ?shutdown_result, "Connection shutdown");
}
}
});
}
/// Run the sync loop with an established connection
async fn run_connection(
conn: &mut Conn,
state: &mut AsyncState<KeychainId>,
client_recv: &mut AsyncReceiver<KeychainId>,
update_sender: &mut mpsc::UnboundedSender<Update<KeychainId>>,
) {
let conn_result = match conn {
Conn::Tcp((read_half, write_half)) => {
run_async(
state,
update_sender,
client_recv,
read_half.compat(),
write_half.compat_write(),
)
.await
}
Conn::Ssl((read_half, write_half)) => {
run_async(
state,
update_sender,
client_recv,
read_half.compat(),
write_half.compat_write(),
)
.await
}
};
// TODO: This is not necessarily a closed connection.
match conn_result {
Ok(_) => tracing::info!("Connection service stopped gracefully"),
Err(err) => tracing::warn!(?err, "Connection service stopped"),
};
}
fn handle_wallet_updates<SW, F>(
super_wallet: SW,
update_recv: mpsc::UnboundedReceiver<Update<KeychainId>>,
mut action: F,
) where
SW: Deref<Target = sync::Mutex<CoordSuperWallet>> + Clone + Send + 'static,
F: FnMut(MasterAppkey, Vec<crate::bitcoin::wallet::Transaction>) + Send,
{
for update in block_on_stream(update_recv) {
let master_appkeys = update
.last_active_indices
.keys()
.map(|(k, _)| *k)
.collect::<Vec<_>>();
let mut wallet = super_wallet.lock().unwrap();
let changed = match wallet.apply_update(update) {
Ok(changed) => changed,
Err(err) => {
tracing::error!("Failed to apply wallet update: {}", err);
continue;
}
};
if changed {
for master_appkey in master_appkeys {
let txs = wallet.list_transactions(master_appkey);
action(master_appkey, txs);
}
}
}
}
}
#[derive(Clone)]
pub struct ChainStatus {
pub primary_url: String,
pub backup_url: String,
pub on_backup: bool,
pub state: ChainStatusState,
}
#[derive(Clone, Copy)]
pub enum ChainStatusState {
/// No connection has been attempted yet
Idle,
Connecting,
Connected,
Disconnected,
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_coordinator/src/bitcoin/handler_state.rs | frostsnap_coordinator/src/bitcoin/handler_state.rs | use bdk_chain::bitcoin::BlockHash;
use std::{
sync::{self, Arc},
time::Duration,
};
use crate::persist::Persisted;
use crate::settings::ElectrumEnabled;
use super::{
chain_sync::{ChainStatus, ChainStatusState, ConnectionResult, Message},
status_tracker::StatusTracker,
tofu::{connection::Conn, trusted_certs::TrustedCertificates, verifier::TofuError},
};
/// State needed for message handling and connection attempts.
pub(super) struct HandlerState {
pub genesis_hash: BlockHash,
pub status: StatusTracker,
pub trusted_certificates: Persisted<TrustedCertificates>,
pub db: Arc<sync::Mutex<rusqlite::Connection>>,
pub started: bool,
/// One-time preference for which server to try first
prefer_backup: bool,
}
impl HandlerState {
pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
pub const RECONNECT_DELAY: Duration = Duration::from_secs(2);
pub fn new(
genesis_hash: BlockHash,
url: String,
backup_url: String,
trusted_certificates: Persisted<TrustedCertificates>,
db: Arc<sync::Mutex<rusqlite::Connection>>,
) -> Self {
let initial_status = ChainStatus {
primary_url: url,
backup_url,
on_backup: false,
state: ChainStatusState::Idle,
};
Self {
genesis_hash,
status: StatusTracker::new(initial_status),
trusted_certificates,
db,
started: false,
prefer_backup: false,
}
}
pub fn should_connect(&self) -> bool {
self.started && self.status.enabled() != ElectrumEnabled::None
}
pub fn set_disconnected(&mut self) {
self.status.set_state(ChainStatusState::Disconnected);
}
/// Get a connection by connecting fresh.
/// Returns Some(connection) if successful, None if all servers fail.
pub async fn get_connection(&mut self) -> Option<Conn> {
self.try_connect().await.map(|(conn, _url)| conn)
}
/// Try to establish a new connection.
/// Returns Some((connection, url)) if successful, None if all servers fail.
pub async fn try_connect(&mut self) -> Option<(Conn, String)> {
let prefer_backup = std::mem::take(&mut self.prefer_backup);
let primary = self.status.primary_url().to_string();
let backup = self.status.backup_url().to_string();
let urls_to_try: Vec<(bool, String)> = match self.status.enabled() {
ElectrumEnabled::All if prefer_backup => {
vec![(true, backup), (false, primary)]
}
ElectrumEnabled::All => {
vec![(false, primary), (true, backup)]
}
ElectrumEnabled::PrimaryOnly => vec![(false, primary)],
ElectrumEnabled::None => return None,
};
for (is_backup, url) in urls_to_try {
self.status
.set_state_and_server(ChainStatusState::Connecting, is_backup);
tracing::info!("Connecting to {}.", url);
match Conn::new(
self.genesis_hash,
&url,
Self::CONNECT_TIMEOUT,
&mut self.trusted_certificates,
)
.await
{
Ok(conn) => {
self.status.set_state(ChainStatusState::Connected);
tracing::info!("Connection established with {}.", url);
return Some((conn, url));
}
Err(err) => {
self.status.set_state(ChainStatusState::Disconnected);
tracing::error!(err = err.to_string(), url, "failed to connect",);
}
}
}
tracing::error!(
reconnecting_in_secs = Self::RECONNECT_DELAY.as_secs_f32(),
"Failed to connect to all Electrum servers"
);
None
}
/// Handle a single message.
/// Returns true if the connection loop should be broken (to trigger reconnection).
pub async fn handle_msg(&mut self, msg: Message) -> bool {
match msg {
Message::ChangeUrlReq(req) => {
let (request, response) = req.into_tuple();
tracing::info!(
msg = "ChangeUrlReq",
url = request.url,
is_backup = request.is_backup,
);
let reconnect = match Conn::new(
self.genesis_hash,
&request.url,
Self::CONNECT_TIMEOUT,
&mut self.trusted_certificates,
)
.await
{
Ok(_conn) => {
let primary = if request.is_backup {
self.status.primary_url().to_string()
} else {
request.url.clone()
};
let backup = if request.is_backup {
request.url.clone()
} else {
self.status.backup_url().to_string()
};
self.status.set_urls(primary, backup);
let _ = response.send(Ok(ConnectionResult::Success));
// Reconnect if we changed the server we're currently connected to
request.is_backup == self.status.on_backup()
}
Err(err) => {
match err {
TofuError::NotTrusted(cert) => {
tracing::info!(
"Certificate not trusted for {}: {}",
request.url,
cert.fingerprint
);
let _ = response
.send(Ok(ConnectionResult::CertificatePromptNeeded(cert)));
}
TofuError::Other(e) => {
tracing::error!("Failed to connect to {}: {}", request.url, e);
let _ = response.send(Ok(ConnectionResult::Failed(e.to_string())));
}
}
false
}
};
reconnect
}
Message::SetStatusSink(new_sink) => {
tracing::info!(msg = "SetStatusSink");
self.status.set_sink(new_sink);
false
}
Message::StartClient => {
self.started = true;
false
}
Message::Reconnect => {
tracing::info!(msg = "Reconnect - forcing reconnection");
true
}
Message::TrustCertificate {
server_url,
certificate_der,
} => {
tracing::info!(msg = "TrustCertificate", server_url = server_url);
let cert = certificate_der.into();
let hostname = match server_url.split_once("://") {
Some((_, addr)) => addr
.split_once(':')
.map(|(host, _)| host)
.unwrap_or(addr)
.to_string(),
None => server_url
.split_once(':')
.map(|(host, _)| host)
.unwrap_or(&server_url)
.to_string(),
};
tracing::info!("Storing certificate for hostname: {}", hostname);
let mut db_guard = self.db.lock().unwrap();
if let Err(e) =
self.trusted_certificates
.mutate2(&mut *db_guard, |trusted_certs, update| {
trusted_certs.add_certificate(cert, hostname, update);
Ok(())
})
{
tracing::error!("Failed to trust certificate: {:?}", e);
}
false
}
Message::SetUrls { primary, backup } => {
tracing::info!(msg = "SetUrls", primary = %primary, backup = %backup);
self.status.set_urls(primary, backup);
true
}
Message::SetEnabled(new_enabled) => {
let old_enabled = self.status.enabled();
let on_backup = self.status.on_backup();
self.status.set_enabled(new_enabled);
tracing::info!(
msg = "SetEnabled",
old = ?old_enabled,
new = ?new_enabled,
);
// Break loop if we disabled the server we're currently on
let should_reconnect = match new_enabled {
ElectrumEnabled::None => true,
ElectrumEnabled::PrimaryOnly if on_backup => true,
_ => false,
};
if new_enabled == ElectrumEnabled::None {
self.status.set_state(ChainStatusState::Idle);
}
should_reconnect
}
Message::ConnectTo { use_backup } => {
tracing::info!(msg = "ConnectTo", use_backup);
if use_backup && self.status.enabled() == ElectrumEnabled::PrimaryOnly {
tracing::warn!("Cannot connect to backup server when only primary is enabled");
return false;
}
self.prefer_backup = use_backup;
true
}
}
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_coordinator/src/bitcoin/psbt.rs | frostsnap_coordinator/src/bitcoin/psbt.rs | use bdk_chain::{
bitcoin::{Psbt, Txid},
rusqlite_impl::migrate_schema,
};
use frostsnap_core::SignSessionId;
use rusqlite::{named_params, CachedStatement, ToSql};
use crate::persist::{Persist, SqlPsbt, SqlSignSessionId, SqlTxid};
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum LoadSignSessionPsbtParams {
Ssid(SignSessionId),
Txid(Txid),
}
#[derive(Debug, Clone)]
pub struct SignSessionPsbt {
pub ssid: SignSessionId,
pub txid: Txid,
pub psbt: Psbt,
}
impl Persist<rusqlite::Connection> for Option<SignSessionPsbt> {
type Update = Self;
type LoadParams = LoadSignSessionPsbtParams;
fn migrate(conn: &mut rusqlite::Connection) -> anyhow::Result<()> {
const SCHEMA_NAME: &str = "frostsnap_psbt";
const MIGRATIONS: &[&str] = &[
// Version 0
"CREATE TABLE IF NOT EXISTS fs_psbt (
id BLOB PRIMARY KEY NOT NULL,
txid TEXT NOT NULL UNIQUE,
psbt BLOB NOT NULL
) WITHOUT ROWID, STRICT",
];
let db_tx = conn.transaction()?;
migrate_schema(&db_tx, SCHEMA_NAME, MIGRATIONS)?;
db_tx.commit()?;
Ok(())
}
fn load(conn: &mut rusqlite::Connection, params: Self::LoadParams) -> anyhow::Result<Self>
where
Self: Sized,
{
let mut stmt: CachedStatement<'_>;
let stmt_param_key: &str;
let stmt_param_val: Box<dyn ToSql>;
match params {
LoadSignSessionPsbtParams::Ssid(ssid) => {
stmt = conn.prepare_cached("SELECT id, txid, psbt FROM fs_psbt WHERE id=:id")?;
stmt_param_key = ":id";
stmt_param_val = Box::new(SqlSignSessionId(ssid));
}
LoadSignSessionPsbtParams::Txid(txid) => {
stmt =
conn.prepare_cached("SELECT id, txid, psbt FROM fs_psbt WHERE txid=:txid")?;
stmt_param_key = ":txid";
stmt_param_val = Box::new(SqlTxid(txid));
}
};
let row_result = stmt.query_row(&[(stmt_param_key, &*stmt_param_val)], |row| {
Ok((
row.get::<_, SqlSignSessionId>("id")?,
row.get::<_, SqlTxid>("txid")?,
row.get::<_, SqlPsbt>("psbt")?,
))
});
Ok(match row_result {
Ok((SqlSignSessionId(ssid), SqlTxid(txid), SqlPsbt(psbt))) => {
Ok(Some(SignSessionPsbt { ssid, txid, psbt }))
}
Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
Err(err) => Err(err),
}?)
}
fn persist_update(
&self,
conn: &mut rusqlite::Connection,
update: Self::Update,
) -> anyhow::Result<()> {
let update = match update {
Some(update) => update,
None => return Ok(()),
};
let mut add_stmt = conn.prepare_cached(
"INSERT OR REPLACE INTO fs_psbt(id, txid, psbt) VALUES(:id, :txid, :psbt)",
)?;
add_stmt.execute(named_params! {
":id": SqlSignSessionId(update.ssid),
":txid": SqlTxid(update.txid),
":psbt": SqlPsbt(update.psbt),
})?;
Ok(())
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
frostsnap/frostsnap | https://github.com/frostsnap/frostsnap/blob/961deb080a81c754f402aaea24286bd141178e9d/frostsnap_coordinator/src/bitcoin/status_tracker.rs | frostsnap_coordinator/src/bitcoin/status_tracker.rs | use super::chain_sync::{ChainStatus, ChainStatusState};
use crate::settings::ElectrumEnabled;
use crate::Sink;
/// Manages chain status tracking and updates - single source of truth
pub struct StatusTracker {
current: ChainStatus,
enabled: ElectrumEnabled,
sink: Box<dyn Sink<ChainStatus>>,
}
impl StatusTracker {
pub fn new(initial_status: ChainStatus) -> Self {
Self {
current: initial_status,
enabled: ElectrumEnabled::default(),
sink: Box::new(()),
}
}
pub fn set_sink(&mut self, new_sink: Box<dyn Sink<ChainStatus>>) {
self.sink = new_sink;
self.sink.send(self.current.clone());
}
fn emit(&mut self) {
self.sink.send(self.current.clone());
}
pub fn current(&self) -> &ChainStatus {
&self.current
}
pub fn set_state(&mut self, state: ChainStatusState) {
self.current.state = state;
self.emit();
}
pub fn set_state_and_server(&mut self, state: ChainStatusState, on_backup: bool) {
self.current.state = state;
self.current.on_backup = on_backup;
self.emit();
}
pub fn set_urls(&mut self, primary: String, backup: String) {
self.current.primary_url = primary;
self.current.backup_url = backup;
self.emit();
}
pub fn set_enabled(&mut self, enabled: ElectrumEnabled) {
self.enabled = enabled;
}
pub fn primary_url(&self) -> &str {
&self.current.primary_url
}
pub fn backup_url(&self) -> &str {
&self.current.backup_url
}
pub fn enabled(&self) -> ElectrumEnabled {
self.enabled
}
pub fn on_backup(&self) -> bool {
self.current.on_backup
}
}
| rust | MIT | 961deb080a81c754f402aaea24286bd141178e9d | 2026-01-04T20:21:09.467677Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.