Skip to main content

trezor_connect_rs/protocol/
mod.rs

1//! Protocol layer for Trezor communication.
2//!
3//! This module handles encoding and decoding of messages for communication
4//! with Trezor devices. Two protocols are supported:
5//!
6//! - **Protocol v1** - Legacy unencrypted protocol (USB)
7//! - **Protocol v2 (THP)** - Encrypted Trezor Host Protocol (Bluetooth/Safe 7)
8
9pub mod chunk;
10pub mod thp;
11pub mod v1;
12
13use crate::error::Result;
14
15/// Decoded message from the device
16#[derive(Debug, Clone)]
17pub struct DecodedMessage {
18    /// Message type (protobuf message ID)
19    pub message_type: u16,
20    /// Total length of the payload
21    pub length: u32,
22    /// Message payload (protobuf-encoded data)
23    pub payload: Vec<u8>,
24}
25
26/// Protocol trait for encoding/decoding messages
27pub trait Protocol: Send + Sync {
28    /// Get the chunk size for this protocol
29    fn chunk_size(&self) -> usize;
30
31    /// Encode a message with the given type and data
32    fn encode(&self, message_type: u16, data: &[u8]) -> Result<Vec<u8>>;
33
34    /// Decode a received buffer into a message header
35    fn decode(&self, buffer: &[u8]) -> Result<DecodedMessage>;
36
37    /// Get the message header and continuation chunk header
38    fn get_headers(&self, data: &[u8]) -> (Vec<u8>, Vec<u8>);
39
40    /// Check if a buffer is a continuation chunk
41    fn is_continuation(&self, buffer: &[u8]) -> bool;
42}
43
44/// Protocol version enum
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub enum ProtocolVersion {
47    /// Protocol v1 (legacy, unencrypted)
48    V1,
49    /// Protocol v2 (THP, encrypted)
50    V2,
51}
52
53impl ProtocolVersion {
54    /// Get the appropriate chunk size for this protocol version
55    pub fn chunk_size(&self, is_bluetooth: bool) -> usize {
56        match self {
57            ProtocolVersion::V1 => {
58                if is_bluetooth {
59                    crate::constants::BLE_CHUNK_SIZE
60                } else {
61                    crate::constants::USB_CHUNK_SIZE
62                }
63            }
64            ProtocolVersion::V2 => crate::constants::BLE_CHUNK_SIZE,
65        }
66    }
67}