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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
use std::cmp::Ordering;
use std::collections::BTreeMap;
use std::fmt::{self, Display, Formatter};
use std::hash::{Hash, Hasher};
use bitcoin::util::bip32::{ChildNumber, DerivationPath, ExtendedPubKey, Fingerprint};
use bitcoin::Network;
use chrono::{DateTime, Utc};
use hwi::error::Error as HwiError;
use hwi::HWIDevice;
use miniscript::descriptor::DescriptorType;
use wallet::hd::standards::DerivationBlockchain;
use wallet::hd::{
AccountStep, Bip43, DerivationStandard, HardenedIndex, SegmentIndexes, TerminalStep,
TrackingAccount, XpubRef,
};
use crate::model::XpubkeyCore;
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Display)]
#[derive(StrictEncode, StrictDecode)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub enum PublicNetwork {
#[display("mainnet")]
Mainnet,
#[display("testnet")]
Testnet,
#[display("signet")]
Signet,
}
impl From<PublicNetwork> for Network {
fn from(network: PublicNetwork) -> Self { Network::from(&network) }
}
impl From<&PublicNetwork> for Network {
fn from(network: &PublicNetwork) -> Self {
match network {
PublicNetwork::Mainnet => Network::Bitcoin,
PublicNetwork::Testnet => Network::Testnet,
PublicNetwork::Signet => Network::Signet,
}
}
}
impl TryFrom<Network> for PublicNetwork {
type Error = ();
fn try_from(network: Network) -> Result<Self, Self::Error> {
Ok(match network {
Network::Bitcoin => PublicNetwork::Mainnet,
Network::Testnet => PublicNetwork::Testnet,
Network::Signet => PublicNetwork::Signet,
Network::Regtest => return Err(()),
})
}
}
impl From<PublicNetwork> for DerivationBlockchain {
fn from(network: PublicNetwork) -> Self { DerivationBlockchain::from(&network) }
}
impl From<&PublicNetwork> for DerivationBlockchain {
fn from(network: &PublicNetwork) -> Self {
match network {
PublicNetwork::Mainnet => DerivationBlockchain::Bitcoin,
PublicNetwork::Testnet => DerivationBlockchain::Testnet,
PublicNetwork::Signet => DerivationBlockchain::Testnet,
}
}
}
impl Default for PublicNetwork {
fn default() -> Self { PublicNetwork::Testnet }
}
impl PublicNetwork {
pub fn is_testnet(self) -> bool {
matches!(self, PublicNetwork::Testnet | PublicNetwork::Signet)
}
pub fn electrum_port(self) -> u16 {
match self {
PublicNetwork::Mainnet => 50001,
PublicNetwork::Testnet => 60001,
PublicNetwork::Signet => 60601,
}
}
}
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[derive(StrictEncode, StrictDecode)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub enum Ownership {
Mine,
External,
}
#[derive(Clone)]
pub struct HardwareDevice {
pub device: HWIDevice,
pub device_type: String,
pub model: String,
pub default_account: HardenedIndex,
pub default_xpub: ExtendedPubKey,
}
#[derive(Debug, Display, Error)]
#[display(doc_comments)]
pub enum Error {
NoDevices(HwiError),
DerivationNotSupported(Fingerprint, String, String, Bip43, PublicNetwork, HwiError),
}
impl Error {
pub fn into_hwi_error(self) -> HwiError {
match self {
Error::NoDevices(err) => err,
Error::DerivationNotSupported(_, _, _, _, _, err) => err,
}
}
}
#[derive(Wrapper, Clone, Default, From)]
pub struct HardwareList(BTreeMap<Fingerprint, HardwareDevice>);
impl<'a> IntoIterator for &'a HardwareList {
type Item = (&'a Fingerprint, &'a HardwareDevice);
type IntoIter = std::collections::btree_map::Iter<'a, Fingerprint, HardwareDevice>;
fn into_iter(self) -> Self::IntoIter { self.0.iter() }
}
impl HardwareList {
pub fn enumerate(
scheme: &Bip43,
network: PublicNetwork,
default_account: HardenedIndex,
) -> Result<(HardwareList, Vec<Error>), Error> {
let mut devices = bmap![];
let mut log = vec![];
for device in HWIDevice::enumerate().map_err(Error::NoDevices)? {
let fingerprint = Fingerprint::from(&device.fingerprint[..]);
let derivation = scheme.to_account_derivation(default_account.into(), network.into());
let derivation_string = derivation.to_string();
match device.get_xpub(
&derivation_string.parse().expect(
"ancient bitcoin version with different derivation path implementation",
),
network.is_testnet(),
) {
Ok(hwikey) => {
let xpub = ExtendedPubKey {
network: network.into(),
depth: hwikey.xpub.depth,
parent_fingerprint: hwikey.xpub.parent_fingerprint,
child_number: hwikey.xpub.child_number,
public_key: hwikey.xpub.public_key,
chain_code: hwikey.xpub.chain_code,
};
devices.insert(fingerprint, HardwareDevice {
device_type: device.device_type.clone(),
model: device.model.clone(),
device,
default_account,
default_xpub: xpub,
});
}
Err(err) => {
log.push(Error::DerivationNotSupported(
fingerprint,
device.device_type,
device.model,
scheme.clone(),
network,
err,
));
}
};
}
Ok((devices.into(), log))
}
}
#[derive(Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]
pub enum OriginFormat {
Master,
SubMaster(ChildNumber),
Standard(Bip43, Option<HardenedIndex>, PublicNetwork),
CustomAccount(DerivationPath),
Custom(DerivationPath),
}
impl Display for OriginFormat {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
OriginFormat::Master => f.write_str("m/"),
OriginFormat::SubMaster(account) => Display::fmt(account, f),
OriginFormat::Standard(scheme, _, network) => {
Display::fmt(&scheme.to_origin_derivation((*network).into()), f)
}
OriginFormat::CustomAccount(path) => Display::fmt(path, f),
OriginFormat::Custom(path) => Display::fmt(path, f),
}
}
}
impl OriginFormat {
pub fn with_account(path: &DerivationPath, depth: u8, network: PublicNetwork) -> OriginFormat {
let bip43 = Bip43::deduce(&path);
if let Some(bip43) = bip43 {
let account = bip43
.extract_account_index(path)
.transpose()
.expect("BIP43 parser is broken");
OriginFormat::Standard(bip43, account, network)
} else if depth == 0 {
OriginFormat::Master
} else if depth == 1 {
OriginFormat::SubMaster(path[0])
} else {
let path = path.as_ref().to_vec();
let account = path.last().unwrap();
if account.is_hardened() {
OriginFormat::CustomAccount(path.into())
} else {
OriginFormat::Custom(path.into())
}
}
}
pub fn account(&self) -> Option<HardenedIndex> {
match self {
OriginFormat::Master => None,
OriginFormat::SubMaster(index) => (*index).try_into().ok(),
OriginFormat::Standard(_, index, _) => *index,
OriginFormat::Custom(_) => None,
OriginFormat::CustomAccount(_) => None,
}
}
}
#[derive(Clone, Debug)]
#[derive(StrictEncode, StrictDecode)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct Signer {
pub master_fp: Fingerprint,
pub origin: DerivationPath,
pub account: Option<HardenedIndex>,
pub xpub: ExtendedPubKey,
pub device: Option<String>,
pub name: String,
pub ownership: Ownership,
}
impl PartialEq for Signer {
fn eq(&self, other: &Self) -> bool { self.xpub_core() == other.xpub_core() }
}
impl Eq for Signer {}
impl Hash for Signer {
fn hash<H: Hasher>(&self, state: &mut H) { self.xpub.identifier().hash(state) }
}
impl PartialOrd for Signer {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) }
}
impl Ord for Signer {
fn cmp(&self, other: &Self) -> Ordering { self.xpub_core().cmp(&other.xpub_core()) }
}
impl Signer {
pub fn with_device(
fingerprint: Fingerprint,
device: HardwareDevice,
schema: &Bip43,
network: PublicNetwork,
) -> Signer {
Signer {
master_fp: fingerprint,
device: Some(device.device_type),
name: device.model.clone(),
origin: schema.to_account_derivation(device.default_account.into(), network.into()),
xpub: device.default_xpub,
account: Some(device.default_account),
ownership: Ownership::Mine,
}
}
pub fn with_xpub(xpub: ExtendedPubKey, schema: &Bip43, network: PublicNetwork) -> Self {
let (fingerprint, origin, account) = match (xpub.depth, schema.account_depth()) {
(0, _) => (xpub.fingerprint(), empty!(), None),
(1, _) => (
xpub.parent_fingerprint,
vec![xpub.child_number].into(),
HardenedIndex::try_from(xpub.child_number).ok(),
),
(depth, Some(account_depth))
if xpub.child_number.is_hardened() && depth == account_depth =>
{
let coin_depth = schema.coin_type_depth().unwrap_or(account_depth);
let max_depth = coin_depth.max(account_depth) as usize;
let min_depth = coin_depth.min(account_depth) as usize;
let path = if max_depth - min_depth != 1 {
vec![xpub.child_number]
} else {
let mut path = vec![ChildNumber::zero(); 2];
path[coin_depth as usize - min_depth] =
DerivationBlockchain::from(network).coin_type().into();
path[account_depth as usize - min_depth] = xpub.child_number;
path
};
(
zero!(),
path.into(),
HardenedIndex::try_from(xpub.child_number).ok(),
)
}
_ => (
zero!(),
vec![xpub.child_number].into(),
HardenedIndex::try_from(xpub.child_number).ok(),
),
};
Signer {
master_fp: fingerprint,
device: None,
name: "".to_string(),
origin,
xpub,
account,
ownership: Ownership::External,
}
}
pub fn is_master_known(&self) -> bool { self.master_fp != zero!() }
pub fn account_string(&self) -> String {
self.account
.as_ref()
.map(HardenedIndex::to_string)
.unwrap_or_else(|| s!("n/a"))
}
pub fn origin_format(&self, network: PublicNetwork) -> OriginFormat {
OriginFormat::with_account(&self.origin, self.xpub.depth, network)
}
pub fn xpub_core(&self) -> XpubkeyCore { XpubkeyCore::from(self.xpub) }
pub fn fingerprint(&self) -> Fingerprint { self.xpub.fingerprint() }
pub fn master_xpub(&self) -> XpubRef {
if self.is_master_known() {
XpubRef::Fingerprint(self.master_fp)
} else {
XpubRef::Unknown
}
}
pub fn to_tracking_account(&self, terminal_path: Vec<TerminalStep>) -> TrackingAccount {
let path: Vec<ChildNumber> = self.origin.clone().into();
TrackingAccount {
master: self.master_xpub(),
account_path: path
.into_iter()
.map(AccountStep::try_from)
.collect::<Result<_, _>>()
.expect("inconsistency in constructed derivation path"),
account_xpub: self.xpub,
revocation_seal: None,
terminal_path,
}
}
}
#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]
#[derive(StrictEncode, StrictDecode)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub enum DescriptorClass {
PreSegwit,
SegwitV0,
NestedV0,
TaprootC0,
}
impl From<&DescriptorType> for DescriptorClass {
fn from(ty: &DescriptorType) -> Self {
match ty {
DescriptorType::Bare
| DescriptorType::Sh
| DescriptorType::ShSortedMulti
| DescriptorType::Pkh => DescriptorClass::PreSegwit,
DescriptorType::Wpkh | DescriptorType::WshSortedMulti | DescriptorType::Wsh => {
DescriptorClass::SegwitV0
}
DescriptorType::ShWsh | DescriptorType::ShWshSortedMulti | DescriptorType::ShWpkh => {
DescriptorClass::NestedV0
}
DescriptorType::Tr => DescriptorClass::TaprootC0,
}
}
}
impl From<DescriptorType> for DescriptorClass {
fn from(ty: DescriptorType) -> Self { DescriptorClass::from(&ty) }
}
impl DescriptorClass {
pub fn bip43(self, sigs_no: usize) -> Bip43 {
match (self, sigs_no > 1) {
(DescriptorClass::PreSegwit, false) => Bip43::singlesig_pkh(),
(DescriptorClass::SegwitV0, false) => Bip43::singlesig_segwit0(),
(DescriptorClass::NestedV0, false) => Bip43::singlesig_nested0(),
(DescriptorClass::TaprootC0, false) => Bip43::singlelsig_taproot(),
(DescriptorClass::PreSegwit, true) => Bip43::multisig_ordered_sh(),
(DescriptorClass::SegwitV0, true) => Bip43::multisig_segwit0(),
(DescriptorClass::NestedV0, true) => Bip43::multisig_nested0(),
(DescriptorClass::TaprootC0, true) => Bip43::multisig_descriptor(),
}
}
pub fn is_segwit_v0(self) -> bool {
match self {
DescriptorClass::SegwitV0 | DescriptorClass::NestedV0 => true,
DescriptorClass::PreSegwit | DescriptorClass::TaprootC0 => false,
}
}
}
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Display)]
#[derive(StrictEncode, StrictDecode)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub enum SigsReq {
#[display("all signatures")]
All,
#[display("at least {0} signatures")]
AtLeast(u16),
#[display("signature by {0}")]
Specific(Fingerprint),
#[display("any signature")]
Any,
}
impl Default for SigsReq {
fn default() -> Self { SigsReq::All }
}
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Display)]
#[derive(StrictEncode, StrictDecode)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub enum TimelockDuration {
#[display("{0} days")]
Days(u8),
#[display("{0} weeks")]
Weeks(u8),
#[display("{0} months")]
Months(u8),
#[display("{0} years")]
Years(u8),
}
impl TimelockDuration {
pub fn intervals(self) -> u16 {
const DAY: u32 = 24 * 60 * 60;
const WEEK: u32 = DAY * 7;
const MONTH: u32 = DAY * 30;
const YEAR: u32 = DAY * 365;
(match self {
TimelockDuration::Days(days) => days as u32 * DAY,
TimelockDuration::Weeks(weeks) => weeks as u32 * WEEK,
TimelockDuration::Months(months) => months as u32 * MONTH,
TimelockDuration::Years(years) => years as u32 * YEAR,
} / 512) as u16
}
}
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Display)]
#[derive(StrictEncode, StrictDecode)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub enum TimelockReq {
#[display("anytime")]
Anytime,
#[display("after {0}")]
AfterPeriod(TimelockDuration),
#[display("after {0} blocks")]
AfterBlock(u16),
#[display("after {0}")]
AfterDate(DateTime<Utc>),
#[display("after block {0}")]
AfterHeight(u32),
}
impl Default for TimelockReq {
fn default() -> Self { TimelockReq::Anytime }
}
#[derive(
Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default, Display
)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
#[derive(StrictEncode, StrictDecode)]
#[display("{sigs} {timelock}")]
pub struct TimelockedSigs {
pub sigs: SigsReq,
pub timelock: TimelockReq,
}