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 31, 2024
1 parent 3c0e9ac commit 49f512c
Show file tree
Hide file tree
Showing 15 changed files with 467 additions and 8 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
.ccls-cache
compile_commands.json
compile_flags.txt
.vscode
.DS_Store

# 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
1 change: 1 addition & 0 deletions src/rust/bitbox02-rust/src/workflow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
pub mod cancel;
pub mod confirm;
pub mod menu;
#[cfg_attr(feature = "c-unit-testing", path = "workflow/mnemonic_c_unit_tests.rs")]
pub mod mnemonic;
pub mod pairing;
pub mod password;
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
}
2 changes: 1 addition & 1 deletion src/rust/bitbox02-rust/src/workflow/mnemonic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -502,4 +502,4 @@ mod tests {
&bruteforce_lastword(&mnemonic)
);
}
}
}
48 changes: 48 additions & 0 deletions src/rust/bitbox02-rust/src/workflow/mnemonic_c_unit_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Copyright 2024 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.

pub use super::cancel::Error as CancelError;
use super::confirm;

use alloc::string::String;
use alloc::string::ToString;

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(())
}

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);

Ok(zeroize::Zeroizing::new(
words
.to_string()
))
}
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(not(feature = "testing"), cfg_attr(feature = "c-unit-testing", path = "ui/ui_stub_c_unit_tests.rs"))]
// We don't actually use ui::ui anywhere, we re-export below.
#[allow(clippy::module_inception)]
mod ui;
Expand Down
8 changes: 4 additions & 4 deletions src/rust/bitbox02/src/ui/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use util::Survive;
pub use bitbox02_sys::trinary_choice_t as TrinaryChoice;

// Taking the constant straight from C, as it's excluding the null terminator.
#[cfg_attr(feature = "testing", allow(dead_code))]
#[cfg_attr(any(feature = "testing", feature = "c-unit-testing"), allow(dead_code))]
pub(crate) const MAX_LABEL_SIZE: usize = bitbox02_sys::MAX_LABEL_SIZE as _;

#[derive(Default)]
Expand All @@ -33,7 +33,7 @@ pub enum Font {
}

impl Font {
#[cfg_attr(feature = "testing", allow(dead_code))]
#[cfg_attr(any(feature = "testing", feature = "c-unit-testing"), allow(dead_code))]
pub(crate) fn as_ptr(&self) -> *const bitbox02_sys::UG_FONT {
match self {
Font::Default => core::ptr::null() as *const _,
Expand Down Expand Up @@ -65,7 +65,7 @@ pub struct ConfirmParams<'a> {
}

impl<'a> ConfirmParams<'a> {
#[cfg_attr(feature = "testing", allow(dead_code))]
#[cfg_attr(any(feature = "testing", feature = "c-unit-testing"), allow(dead_code))]
/// `title_scratch` and `body_scratch` exist to keep the data
/// alive for as long as the C params live.
pub(crate) fn to_c_params(
Expand Down Expand Up @@ -110,7 +110,7 @@ pub struct TrinaryInputStringParams<'a> {
}

impl<'a> TrinaryInputStringParams<'a> {
#[cfg_attr(feature = "testing", allow(dead_code))]
#[cfg_attr(any(feature = "testing", feature = "c-unit-testing"), allow(dead_code))]
pub(crate) fn to_c_params(
&self,
title_scratch: &'a mut Vec<u8>,
Expand Down
Loading

0 comments on commit 49f512c

Please sign in to comment.