Skip to content

Commit

Permalink
simulator: implement a simulator for bitbox02 device
Browse files Browse the repository at this point in the history
HWI is thinking of updating its support policy such that supported wallets
must implement a simulator/emulator. See bitcoin-core/HWI#685.
That's why a simulator is implemented for bitbox02, supporting functionalities of
its API.

This first version of the simulator is capable of nearly every functionality of a
normal Bitbox02 device, without promising any security or production use. Its main
aim is to be able to run unit tests for features and test the API.

In addition, it will be configured to run automated tests in CI, which helps both
us and HWI integration.

Right now, the simulator has 3 different ways to communicate with a client: giving
inputs/getting output from CLI, using pipes or opening sockets. Socket is the most
convenient and reliable choice in this version. It expects the clients to open a
socket on port 15432, which is selected intentionally to avoid possible conflicts.

The simulator resides with C unit-tests since it uses same mocks, therefore it can
be built by `make unit-test`.

Lastly, Python client implemented in `py/send_message.py` is updated to support
communicating with simulator with the socket configuration mentioned above. Client
can be started up with `./py/send_message.py --simulator` command. To run the
simulator, `build-build/bin/test_simulator` command is sufficient.

Signed-off-by: asi345 <[email protected]>
  • Loading branch information
asi345 committed Jan 25, 2024
1 parent 3c0e9ac commit f02e81f
Show file tree
Hide file tree
Showing 13 changed files with 657 additions and 2 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
.ccls-cache
compile_commands.json
compile_flags.txt
.vscode

# gnu global
/src/GPATH
Expand Down
69 changes: 69 additions & 0 deletions py/send_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
# pylint: disable=too-many-lines

import argparse
import socket
import pprint
import sys
from typing import List, Any, Optional, Callable, Union, Tuple, Sequence
Expand All @@ -41,6 +42,7 @@
FirmwareVersionOutdatedException,
u2fhid,
bitbox_api_protocol,
PhysicalLayer,
)

import u2f
Expand Down Expand Up @@ -1556,6 +1558,65 @@ def run(self) -> int:
return 0


def connect_to_simulator_bitbox(debug: bool) -> int:
"""
Connects and runs the main menu on host computer,
simulating a BitBox02 connected over USB.
"""

class Simulator(PhysicalLayer):
"""
Simulator class handles the communication
with the firmware simulator
"""

def __init__(self) -> None:
self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 15423
self.client_socket.bind(("", port))
self.client_socket.listen(50)
print(f"Waiting for connection on port {port}")
self.connection, addr = self.client_socket.accept()
print(f"Connected to {addr}")

def write(self, data: bytes) -> None:
self.connection.send(data[1:])
if debug:
print(f"Written to the simulator:\n{data.hex()[2:]}")

def read(self, size: int, timeout_ms: int) -> bytes:
res = self.connection.recv(64)
if debug:
print(f"Read from the simulator:\n{res.hex()}")
return res

def __del__(self) -> None:
print("Simulator quit")
if self.connection:
self.connection.shutdown(socket.SHUT_RDWR)
self.connection.close()

simulator = Simulator()

device_info: devices.DeviceInfo = {
"serial_number": "v9.16.0",
"path": b"",
"product_string": "BitBox02BTC",
}
noise_config = bitbox_api_protocol.BitBoxNoiseConfig()
bitbox_connection = bitbox02.BitBox02(
transport=u2fhid.U2FHid(simulator),
device_info=device_info,
noise_config=noise_config,
)
try:
bitbox_connection.check_min_version()
except FirmwareVersionOutdatedException as exc:
print("WARNING: ", exc)

return SendMessage(bitbox_connection, debug).run()


def connect_to_usb_bitbox(debug: bool, use_cache: bool) -> int:
"""
Connects and runs the main menu on a BitBox02 connected
Expand Down Expand Up @@ -1643,6 +1704,11 @@ def main() -> int:
parser = argparse.ArgumentParser(description="Tool for communicating with bitbox device")
parser.add_argument("--debug", action="store_true", help="Print messages sent and received")
parser.add_argument("--u2f", action="store_true", help="Use u2f menu instead")
parser.add_argument(
"--simulator",
action="store_true",
help="Connect to the BitBox02 simulator instead of a real BitBox02",
)
parser.add_argument(
"--no-cache", action="store_true", help="Don't use cached or store noise keys"
)
Expand All @@ -1663,6 +1729,9 @@ def main() -> int:
return u2fapp.run()
return 1

if args.simulator:
return connect_to_simulator_bitbox(args.debug)

return connect_to_usb_bitbox(args.debug, not args.no_cache)


Expand Down
2 changes: 2 additions & 0 deletions src/rust/bitbox02-rust/src/workflow/confirm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,7 @@ pub async fn confirm(params: &Params<'_>) -> Result<(), UserAbort> {
};
});
component.screen_stack_push();
#[cfg(feature = "c-unit-testing")]
bitbox02::print_stdout(&format!("CONFIRM SCREEN START\nTITLE: {}\nBODY: {}\nCONFIRM SCREEN END\n", params.title, params.body));
option_no_screensaver(&result).await
}
33 changes: 33 additions & 0 deletions src/rust/bitbox02-rust/src/workflow/mnemonic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ use super::trinary_input_string;

use alloc::boxed::Box;
use alloc::string::String;
use alloc::string::ToString;
use alloc::vec::Vec;
use core::cell::RefCell;

Expand Down Expand Up @@ -107,6 +108,7 @@ async fn confirm_word(choices: &[&str], title: &str) -> Result<u8, CancelError>
with_cancel("Recovery\nwords", &mut component, &result).await
}

#[cfg(not(feature = "c-unit-testing"))]
pub async fn show_and_confirm_mnemonic(words: &[&str]) -> Result<(), CancelError> {
// Part 1) Scroll through words
show_mnemonic(words).await?;
Expand Down Expand Up @@ -140,6 +142,25 @@ pub async fn show_and_confirm_mnemonic(words: &[&str]) -> Result<(), CancelError
Ok(())
}

#[cfg(feature = "c-unit-testing")]
pub async fn show_and_confirm_mnemonic(words: &[&str]) -> Result<(), CancelError> {
let _ = confirm::confirm(&confirm::Params {
title: "",
body: "Please confirm\neach word",
accept_only: true,
accept_is_nextarrow: true,
..Default::default()
})
.await;

for word in words.iter() {
bitbox02::println_stdout(word);
}
bitbox02::println_stdout("Words confirmed");

Ok(())
}

/// Given 11/17/23 initial words, this function returns a list of candidate words for the last word,
/// such that the resulting bip39 phrase has a valid checksum. There are always exactly 8 such words
/// for 24 word mnemonics, 32 words for 18 word mnemonics and 128 words for 12 word mnemonics.
Expand Down Expand Up @@ -289,6 +310,7 @@ async fn get_12th_18th_word(
}
}

#[cfg(not(feature = "c-unit-testing"))]
/// Retrieve a BIP39 mnemonic sentence of 12, 18 or 24 words from the user.
pub async fn get() -> Result<zeroize::Zeroizing<String>, CancelError> {
let num_words: usize = match choose("How many words?", "12", "18", "24").await {
Expand Down Expand Up @@ -403,6 +425,17 @@ pub async fn get() -> Result<zeroize::Zeroizing<String>, CancelError> {
))
}

#[cfg(feature = "c-unit-testing")]
pub async fn get() -> Result<zeroize::Zeroizing<String>, CancelError> {
let words = "boring mistake dish oyster truth pigeon viable emerge sort crash wire portion cannon couple enact box walk height pull today solid off enable tide";
bitbox02::println_stdout("Restored from recovery words below:");
bitbox02::println_stdout(words);
return Ok(zeroize::Zeroizing::new(
words
.to_string()
));
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
2 changes: 2 additions & 0 deletions src/rust/bitbox02-rust/src/workflow/status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,7 @@ pub async fn status(title: &str, status_success: bool) {
*result.borrow_mut() = Some(());
});
component.screen_stack_push();
#[cfg(feature = "c-unit-testing")]
bitbox02::print_stdout(&format!("STATUS SCREEN START\nTITLE: {}\nSTATUS SCREEN END\n", title));
option_no_screensaver(&result).await
}
2 changes: 2 additions & 0 deletions src/rust/bitbox02-rust/src/workflow/trinary_input_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ pub async fn enter(
bitbox02::ui::trinary_input_string_set_input(&mut component, preset);
}
component.screen_stack_push();
#[cfg(feature = "c-unit-testing")]
bitbox02::print_stdout(&format!("ENTER SCREEN START\nTITLE: {}\nENTER SCREEN END\n", params.title));
option(&result)
.await
.or(Err(super::cancel::Error::Cancelled))
Expand Down
8 changes: 8 additions & 0 deletions src/rust/bitbox02/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,14 @@ pub fn print_stdout(msg: &str) {
}
}

#[cfg(any(feature = "testing", feature = "c-unit-testing"))]
pub fn println_stdout(msg: &str) {
unsafe {
bitbox02_sys::printf(crate::util::str_to_cstr_vec(msg).unwrap().as_ptr());
bitbox02_sys::printf(crate::util::str_to_cstr_vec("\n").unwrap().as_ptr());
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
1 change: 1 addition & 0 deletions src/rust/bitbox02/src/ui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
mod types;

#[cfg_attr(feature = "testing", path = "ui/ui_stub.rs")]
#[cfg_attr(feature = "c-unit-testing", path = "ui/ui_stub_c.rs")]
// We don't actually use ui::ui anywhere, we re-export below.
#[allow(clippy::module_inception)]
mod ui;
Expand Down
163 changes: 163 additions & 0 deletions src/rust/bitbox02/src/ui/ui_stub_c.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
// Copyright 2020 Shift Crypto AG
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Stubs for testing.

pub use super::types::{
AcceptRejectCb, ConfirmParams, ContinueCancelCb, Font, MenuParams, SelectWordCb, TrinaryChoice,
TrinaryChoiceCb, TrinaryInputStringParams,
};

use crate::input::SafeInputString;

use core::marker::PhantomData;

extern crate alloc;

pub struct Component<'a> {
is_pushed: bool,
_p: PhantomData<&'a ()>,
}

impl<'a> Component<'a> {
pub fn screen_stack_push(&mut self) {
if self.is_pushed {
panic!("component pushed twice");
}
self.is_pushed = true;
}
}

impl<'a> Drop for Component<'a> {
fn drop(&mut self) {
if !self.is_pushed {
panic!("component not pushed");
}
}
}

pub fn trinary_input_string_create<'a, F>(
_params: &TrinaryInputStringParams,
mut confirm_callback: F,
_cancel_callback: Option<ContinueCancelCb<'a>>,
) -> Component<'a>
where
F: FnMut(SafeInputString) + 'a,
{
confirm_callback(SafeInputString::new());
Component {
is_pushed: false,
_p: PhantomData,
}
}

pub fn confirm_create<'a, F>(_params: &ConfirmParams, mut result_callback: F) -> Component<'a>
where
F: FnMut(bool) + 'a,
{
result_callback(true);
Component {
is_pushed: false,
_p: PhantomData,
}
}

pub fn screen_process() {}

pub fn status_create<'a, F>(_text: &str, _status_success: bool, mut callback: F) -> Component<'a>
where
F: FnMut() + 'a,
{
callback();
Component {
is_pushed: false,
_p: PhantomData,
}
}

pub fn sdcard_create<'a, F>(_insert: bool, mut continue_callback: F) -> Component<'a>
where
F: FnMut() + 'a,
{
continue_callback();
Component {
is_pushed: false,
_p: PhantomData,
}
}

pub fn menu_create(_params: MenuParams<'_>) -> Component<'_> {
panic!("not implemented");
}

pub fn trinary_choice_create<'a>(
_message: &'a str,
_label_left: &'a str,
_label_middle: &'a str,
_label_right: &'a str,
_chosen_callback: TrinaryChoiceCb,
) -> Component<'a> {
panic!("not implemented")
}

pub fn confirm_transaction_address_create<'a, 'b>(
_amount: &'a str,
_address: &'a str,
mut callback: AcceptRejectCb<'b>,
) -> Component<'b> {
callback(true);
Component {
is_pushed: false,
_p: PhantomData,
}
}

pub fn confirm_transaction_fee_create<'a, 'b>(
_amount: &'a str,
_fee: &'a str,
_longtouch: bool,
mut callback: AcceptRejectCb<'b>,
) -> Component<'b> {
callback(true);
Component {
is_pushed: false,
_p: PhantomData,
}
}

pub fn trinary_input_string_set_input(_component: &mut Component, _word: &str) {
panic!("not implemented")
}

pub fn with_lock_animation<F: Fn()>(f: F) {
f()
}

pub fn screen_stack_pop_all() {}

pub fn progress_create<'a>(_title: &str) -> Component<'a> {
Component {
is_pushed: false,
_p: PhantomData,
}
}

pub fn progress_set(_component: &mut Component, _progress: f32) {}

pub fn empty_create<'a>() -> Component<'a> {
Component {
is_pushed: false,
_p: PhantomData,
}
}
Binary file added test/.DS_Store
Binary file not shown.
Loading

0 comments on commit f02e81f

Please sign in to comment.