1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
use std::convert::TryFrom;
use std::ops::Deref;
use std::str::FromStr;

use bitcoin::address::{Address, NetworkUnchecked};
use bitcoin::bip32::{Fingerprint, Xpub};
use bitcoin::Network;
use bitcoin::Psbt;

use pyo3::types::PyModule;
use pyo3::{IntoPy, PyObject};
use serde::{Deserialize, Deserializer};

#[cfg(feature = "miniscript")]
use miniscript::{Descriptor, DescriptorPublicKey};

use crate::error::{Error, ErrorCode};

#[derive(Clone, Eq, PartialEq, Debug, Deserialize)]
pub struct HWIExtendedPubKey {
    pub xpub: Xpub,
}

impl Deref for HWIExtendedPubKey {
    type Target = Xpub;

    fn deref(&self) -> &Self::Target {
        &self.xpub
    }
}

#[derive(Clone, Eq, PartialEq, Debug, Deserialize)]
pub struct HWISignature {
    #[serde(deserialize_with = "from_b64")]
    pub signature: Vec<u8>,
}

fn from_b64<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
    use bitcoin::base64::{engine::general_purpose, Engine as _};

    let b64_string = String::deserialize(d)?;
    general_purpose::STANDARD
        .decode(b64_string)
        .map_err(|_| serde::de::Error::custom("error while deserializing signature"))
}

impl Deref for HWISignature {
    type Target = Vec<u8>;

    fn deref(&self) -> &Self::Target {
        &self.signature
    }
}

#[derive(Clone, Eq, PartialEq, Debug, Deserialize)]
pub struct HWIAddress {
    pub address: Address<NetworkUnchecked>,
}

#[derive(Clone, Eq, PartialEq, Debug, Deserialize)]
pub struct HWIPartiallySignedTransaction {
    #[serde(deserialize_with = "deserialize_psbt")]
    pub psbt: Psbt,
}

fn deserialize_psbt<'de, D: Deserializer<'de>>(d: D) -> Result<Psbt, D::Error> {
    let s = String::deserialize(d)?;
    Psbt::from_str(&s).map_err(serde::de::Error::custom)
}

impl Deref for HWIPartiallySignedTransaction {
    type Target = Psbt;

    fn deref(&self) -> &Self::Target {
        &self.psbt
    }
}

pub trait ToDescriptor {}
impl ToDescriptor for String {}
#[cfg(feature = "miniscript")]
impl ToDescriptor for Descriptor<DescriptorPublicKey> {}

#[derive(Clone, Eq, PartialEq, Debug, Deserialize)]
pub struct HWIDescriptor<T>
where
    T: ToDescriptor,
{
    pub internal: Vec<T>,
    pub receive: Vec<T>,
}

#[derive(Clone, Eq, PartialEq, Debug, Deserialize)]
pub struct HWIKeyPoolElement {
    pub desc: String,
    pub range: Vec<u32>,
    pub timestamp: String,
    pub internal: bool,
    pub keypool: bool,
    pub watchonly: bool,
}

#[derive(Clone, Eq, PartialEq, Debug, Deserialize)]
#[allow(non_camel_case_types)]
pub enum HWIAddressType {
    Legacy,
    Sh_Wit,
    Wit,
    Tap,
}

impl IntoPy<PyObject> for HWIAddressType {
    fn into_py(self, py: pyo3::Python) -> PyObject {
        let addrtype = PyModule::import(py, "hwilib.common")
            .unwrap()
            .getattr("AddressType")
            .unwrap();
        match self {
            HWIAddressType::Legacy => addrtype.get_item("LEGACY").unwrap().into(),
            HWIAddressType::Sh_Wit => addrtype.get_item("SH_WIT").unwrap().into(),
            HWIAddressType::Wit => addrtype.get_item("WIT").unwrap().into(),
            HWIAddressType::Tap => addrtype.get_item("TAP").unwrap().into(),
        }
    }
}

#[derive(Clone, Eq, PartialEq, Debug, Deserialize)]
pub struct HWIChain(bitcoin::Network);

impl IntoPy<PyObject> for HWIChain {
    fn into_py(self, py: pyo3::Python) -> PyObject {
        use bitcoin::Network::*;

        let chain = PyModule::import(py, "hwilib.common")
            .unwrap()
            .getattr("Chain")
            .unwrap();
        match self.0 {
            Bitcoin => chain.get_item("MAIN").unwrap().into(),
            Testnet => chain.get_item("TEST").unwrap().into(),
            Regtest => chain.get_item("REGTEST").unwrap().into(),
            Signet => chain.get_item("SIGNET").unwrap().into(),
            // This handles non_exhaustive on Network which is only there to future proof
            // rust-bitcoin, will need to check this when upgrading rust-bitcoin.
            // Sane as of rust-bitcoin v0.30.0
            _ => panic!("unknown network"),
        }
    }
}

impl From<Network> for HWIChain {
    fn from(network: Network) -> Self {
        Self(network)
    }
}

#[cfg(test)]
pub const TESTNET: HWIChain = HWIChain(Network::Testnet);

// Used internally to deserialize the result of `hwi enumerate`. This might
// contain an `error`, when it does, it might not contain all the fields `HWIDevice`
// is supposed to have - for this reason, they're all Option.
#[derive(Clone, Eq, PartialEq, Debug, Deserialize)]
pub(crate) struct HWIDeviceInternal {
    #[serde(rename(deserialize = "type"))]
    pub device_type: Option<String>,
    pub model: Option<String>,
    pub path: Option<String>,
    pub needs_pin_sent: Option<bool>,
    pub needs_passphrase_sent: Option<bool>,
    pub fingerprint: Option<Fingerprint>,
    pub error: Option<String>,
    pub code: Option<i8>,
}

#[derive(Clone, Eq, PartialEq, Debug, Deserialize)]
pub struct HWIDevice {
    #[serde(rename(deserialize = "type"))]
    pub device_type: HWIDeviceType,
    pub model: String,
    pub path: String,
    pub needs_pin_sent: bool,
    pub needs_passphrase_sent: bool,
    pub fingerprint: Fingerprint,
}

impl TryFrom<HWIDeviceInternal> for HWIDevice {
    type Error = Error;
    fn try_from(h: HWIDeviceInternal) -> Result<HWIDevice, Error> {
        match h.error {
            Some(e) => {
                let code = h.code.and_then(|c| ErrorCode::try_from(c).ok());
                Err(Error::Hwi(e, code))
            }
            // When HWIDeviceInternal contains errors, some fields might be missing
            // (depending on the error, hwi might not be able to know all of them).
            // When there's no error though, all the fields must be present, and
            // for this reason we expect here.
            None => Ok(HWIDevice {
                device_type: HWIDeviceType::from(
                    h.device_type.expect("Device type should be here"),
                ),
                model: h.model.expect("Model should be here"),
                path: h.path.expect("Path should be here"),
                needs_pin_sent: h.needs_pin_sent.expect("needs_pin_sent should be here"),
                needs_passphrase_sent: h
                    .needs_passphrase_sent
                    .expect("needs_passphrase_sent should be here"),
                fingerprint: h.fingerprint.expect("Fingerprint should be here"),
            }),
        }
    }
}

#[derive(Clone, Eq, PartialEq, Debug, Deserialize)]
pub struct HWIStatus {
    pub success: bool,
}

impl From<HWIStatus> for Result<(), Error> {
    fn from(s: HWIStatus) -> Self {
        if s.success {
            Ok(())
        } else {
            Err(Error::Hwi(
                "request returned with failure".to_string(),
                None,
            ))
        }
    }
}

#[derive(Clone, Eq, PartialEq, Debug, Deserialize)]
pub enum HWIDeviceType {
    Ledger,
    Trezor,
    BitBox01,
    BitBox02,
    KeepKey,
    Coldcard,
    Jade,
    Other(String),
}

impl<T> From<T> for HWIDeviceType
where
    T: AsRef<str>,
{
    fn from(s: T) -> Self {
        match s.as_ref() {
            "ledger" => Self::Ledger,
            "trezor" => Self::Trezor,
            "digitalbitbox" => Self::BitBox01,
            "bitbox02" => Self::BitBox02,
            "keepkey" => Self::KeepKey,
            "coldcard" => Self::Coldcard,
            "jade" => Self::Jade,
            name => Self::Other(name.to_string()),
        }
    }
}

impl ToString for HWIDeviceType {
    fn to_string(&self) -> String {
        match self {
            Self::Ledger => String::from("ledger"),
            Self::Trezor => String::from("trezor"),
            Self::BitBox01 => String::from("digitalbitbox"),
            Self::BitBox02 => String::from("bitbox02"),
            Self::KeepKey => String::from("keepkey"),
            Self::Coldcard => String::from("coldcard"),
            Self::Jade => String::from("jade"),
            Self::Other(name) => name.to_string(),
        }
    }
}

pub enum LogLevel {
    DEBUG,
    INFO,
    WARNING,
    ERROR,
    CRITICAL,
}

#[derive(Clone, Eq, PartialEq, Debug, Copy)]
#[repr(u8)]
/// The number of words in the recovery phrase
pub enum HWIWordCount {
    W12 = 12,
    W18 = 18,
    W24 = 24,
}