Skip to content

Commit dcce9a9

Browse files
committed
descriptor: allow "raw" pubkeys to have origin
Signed-off-by: Antoine Poinsot <[email protected]>
1 parent 7150566 commit dcce9a9

File tree

1 file changed

+108
-46
lines changed

1 file changed

+108
-46
lines changed

src/descriptor/mod.rs

Lines changed: 108 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -77,10 +77,16 @@ pub enum Descriptor<Pk: MiniscriptKey> {
7777

7878
#[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)]
7979
pub enum DescriptorPublicKey {
80-
PubKey(bitcoin::PublicKey),
80+
SinglePub(DescriptorSinglePub),
8181
XPub(DescriptorXPub),
8282
}
8383

84+
#[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)]
85+
pub struct DescriptorSinglePub {
86+
origin: Option<(bip32::Fingerprint, bip32::DerivationPath)>,
87+
key: bitcoin::PublicKey,
88+
}
89+
8490
#[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)]
8591
pub struct DescriptorXPub {
8692
origin: Option<(bip32::Fingerprint, bip32::DerivationPath)>,
@@ -101,16 +107,13 @@ impl fmt::Display for DescriptorKeyParseError {
101107
impl fmt::Display for DescriptorPublicKey {
102108
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
103109
match *self {
104-
DescriptorPublicKey::PubKey(ref pk) => pk.fmt(f),
110+
DescriptorPublicKey::SinglePub(ref pk) => {
111+
maybe_fmt_master_id(f, &pk.origin)?;
112+
pk.key.fmt(f)?;
113+
Ok(())
114+
}
105115
DescriptorPublicKey::XPub(ref xpub) => {
106-
if let Some((ref master_id, ref master_deriv)) = xpub.origin {
107-
fmt::Formatter::write_str(f, "[")?;
108-
for byte in master_id.into_bytes().iter() {
109-
write!(f, "{:02x}", byte)?;
110-
}
111-
fmt_derivation_path(f, master_deriv)?;
112-
fmt::Formatter::write_str(f, "]")?;
113-
}
116+
maybe_fmt_master_id(f, &xpub.origin)?;
114117
xpub.xpub.fmt(f)?;
115118
fmt_derivation_path(f, &xpub.derivation_path)?;
116119
if xpub.is_wildcard {
@@ -122,6 +125,23 @@ impl fmt::Display for DescriptorPublicKey {
122125
}
123126
}
124127

128+
/// Writes the fingerprint of the origin, if there is one.
129+
fn maybe_fmt_master_id(
130+
f: &mut fmt::Formatter,
131+
origin: &Option<(bip32::Fingerprint, bip32::DerivationPath)>,
132+
) -> fmt::Result {
133+
if let Some((ref master_id, ref master_deriv)) = *origin {
134+
fmt::Formatter::write_str(f, "[")?;
135+
for byte in master_id.into_bytes().iter() {
136+
write!(f, "{:02x}", byte)?;
137+
}
138+
fmt_derivation_path(f, master_deriv)?;
139+
fmt::Formatter::write_str(f, "]")?;
140+
}
141+
142+
Ok(())
143+
}
144+
125145
/// Writes a derivation path to the formatter, no leading 'm'
126146
fn fmt_derivation_path(f: &mut fmt::Formatter, path: &bip32::DerivationPath) -> fmt::Result {
127147
for child in path {
@@ -134,12 +154,18 @@ impl FromStr for DescriptorPublicKey {
134154
type Err = DescriptorKeyParseError;
135155

136156
fn from_str(s: &str) -> Result<Self, Self::Err> {
157+
// A "raw" public key without any origin is the least we accept.
137158
if s.len() < 66 {
138-
Err(DescriptorKeyParseError(
159+
return Err(DescriptorKeyParseError(
139160
"Key too short (<66 char), doesn't match any format",
140-
))
141-
} else if s.chars().next().unwrap() == '[' {
142-
let mut parts = s[1..].split(']');
161+
));
162+
}
163+
164+
let mut parts = s[1..].split(']');
165+
166+
// They may specify an origin
167+
let mut origin = None;
168+
if s.chars().next().unwrap() == '[' {
143169
let mut raw_origin = parts
144170
.next()
145171
.ok_or(DescriptorKeyParseError("Unclosed '['"))?
@@ -164,30 +190,33 @@ impl FromStr for DescriptorPublicKey {
164190
.map_err(|_| {
165191
DescriptorKeyParseError("Error while parsing master derivation path")
166192
})?;
193+
origin = Some((parent_fingerprint, origin_path));
194+
}
167195

168-
let key_deriv = parts
196+
let key_part = if origin == None {
197+
Ok(s)
198+
} else {
199+
parts
169200
.next()
170-
.ok_or(DescriptorKeyParseError("No key after origin."))?;
201+
.ok_or(DescriptorKeyParseError("No key after origin."))
202+
}?;
171203

172-
let (xpub, derivation_path, is_wildcard) = Self::parse_xpub_deriv(key_deriv)?;
204+
// To support testnet as well
205+
if key_part.contains("pub") {
206+
let (xpub, derivation_path, is_wildcard) = Self::parse_xpub_deriv(key_part)?;
173207

174208
Ok(DescriptorPublicKey::XPub(DescriptorXPub {
175-
origin: Some((parent_fingerprint, origin_path)),
209+
origin,
176210
xpub,
177211
derivation_path,
178212
is_wildcard,
179213
}))
180-
} else if s.starts_with("02") || s.starts_with("03") || s.starts_with("04") {
181-
let pk = bitcoin::PublicKey::from_str(s)
182-
.map_err(|_| DescriptorKeyParseError("Error while parsing simple public key"))?;
183-
Ok(DescriptorPublicKey::PubKey(pk))
184214
} else {
185-
let (xpub, derivation_path, is_wildcard) = Self::parse_xpub_deriv(s)?;
186-
Ok(DescriptorPublicKey::XPub(DescriptorXPub {
187-
origin: None,
188-
xpub,
189-
derivation_path,
190-
is_wildcard,
215+
let key = bitcoin::PublicKey::from_str(key_part)
216+
.map_err(|_| DescriptorKeyParseError("Error while parsing simple public key"))?;
217+
Ok(DescriptorPublicKey::SinglePub(DescriptorSinglePub {
218+
key,
219+
origin,
191220
}))
192221
}
193222
}
@@ -240,7 +269,7 @@ impl DescriptorPublicKey {
240269
assert!(path.into_iter().all(|c| c.is_normal()));
241270

242271
match self {
243-
DescriptorPublicKey::PubKey(_) => self,
272+
DescriptorPublicKey::SinglePub(_) => self,
244273
DescriptorPublicKey::XPub(xpub) => {
245274
if xpub.is_wildcard {
246275
DescriptorPublicKey::XPub(DescriptorXPub {
@@ -273,7 +302,7 @@ impl MiniscriptKey for DescriptorPublicKey {
273302
impl ToPublicKey for DescriptorPublicKey {
274303
fn to_public_key(&self) -> bitcoin::PublicKey {
275304
match *self {
276-
DescriptorPublicKey::PubKey(ref pk) => *pk,
305+
DescriptorPublicKey::SinglePub(ref spub) => spub.key.to_public_key(),
277306
DescriptorPublicKey::XPub(ref xpub) => {
278307
let ctx = secp256k1::Secp256k1::verification_only();
279308
xpub.xpub
@@ -794,7 +823,7 @@ mod tests {
794823
use bitcoin::hashes::{hash160, sha256};
795824
use bitcoin::util::bip32;
796825
use bitcoin::{self, secp256k1, PublicKey};
797-
use descriptor::{DescriptorPublicKey, DescriptorXPub};
826+
use descriptor::{DescriptorPublicKey, DescriptorSinglePub, DescriptorXPub};
798827
use miniscript::satisfy::BitcoinSig;
799828
use std::collections::HashMap;
800829
use std::str::FromStr;
@@ -1360,37 +1389,52 @@ mod tests {
13601389

13611390
// Raw (compressed) pubkey
13621391
let key = "03f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8";
1363-
let expected = DescriptorPublicKey::PubKey(
1364-
bitcoin::PublicKey::from_str(
1392+
let expected = DescriptorPublicKey::SinglePub(DescriptorSinglePub {
1393+
key: bitcoin::PublicKey::from_str(
13651394
"03f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8",
13661395
)
13671396
.unwrap(),
1368-
);
1397+
origin: None,
1398+
});
13691399
assert_eq!(expected, key.parse().unwrap());
13701400
assert_eq!(format!("{}", expected), key);
13711401

13721402
// Raw (uncompressed) pubkey
13731403
let key = "04f5eeb2b10c944c6b9fbcfff94c35bdeecd93df977882babc7f3a2cf7f5c81d3b09a68db7f0e04f21de5d4230e75e6dbe7ad16eefe0d4325a62067dc6f369446a";
1374-
let expected = DescriptorPublicKey::PubKey(
1375-
bitcoin::PublicKey::from_str(
1404+
let expected = DescriptorPublicKey::SinglePub(DescriptorSinglePub {
1405+
key: bitcoin::PublicKey::from_str(
13761406
"04f5eeb2b10c944c6b9fbcfff94c35bdeecd93df977882babc7f3a2cf7f5c81d3b09a68db7f0e04f21de5d4230e75e6dbe7ad16eefe0d4325a62067dc6f369446a",
13771407
)
13781408
.unwrap(),
1379-
);
1409+
origin: None,
1410+
});
13801411
assert_eq!(expected, key.parse().unwrap());
13811412
assert_eq!(format!("{}", expected), key);
1413+
1414+
// Raw pubkey with origin
1415+
let desc =
1416+
"[78412e3a/0'/42/0']0231c7d3fc85c148717848033ce276ae2b464a4e2c367ed33886cc428b8af48ff8";
1417+
let expected = DescriptorPublicKey::SinglePub(DescriptorSinglePub {
1418+
key: bitcoin::PublicKey::from_str(
1419+
"0231c7d3fc85c148717848033ce276ae2b464a4e2c367ed33886cc428b8af48ff8",
1420+
)
1421+
.unwrap(),
1422+
origin: Some((
1423+
bip32::Fingerprint::from(&[0x78, 0x41, 0x2e, 0x3a][..]),
1424+
(&[
1425+
bip32::ChildNumber::from_hardened_idx(0).unwrap(),
1426+
bip32::ChildNumber::from_normal_idx(42).unwrap(),
1427+
bip32::ChildNumber::from_hardened_idx(0).unwrap(),
1428+
][..])
1429+
.into(),
1430+
)),
1431+
});
1432+
assert_eq!(expected, desc.parse().expect("Parsing desc"));
1433+
assert_eq!(format!("{}", expected), desc);
13821434
}
13831435

13841436
#[test]
13851437
fn parse_descriptor_key_errors() {
1386-
// origin is only supported for xpubs
1387-
let desc =
1388-
"[78412e3a/0'/0'/0']0231c7d3fc85c148717848033ce276ae2b464a4e2c367ed33886cc428b8af48ff8";
1389-
assert_eq!(
1390-
DescriptorPublicKey::from_str(desc),
1391-
Err(DescriptorKeyParseError("Error while parsing xpub."))
1392-
);
1393-
13941438
// We refuse creating descriptors which claim to be able to derive hardened childs
13951439
let desc = "[78412e3a/44'/0'/0']xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/1/42'/*";
13961440
assert_eq!(
@@ -1418,12 +1462,30 @@ mod tests {
14181462
))
14191463
);
14201464

1421-
// And ones with invalid xpubs
1465+
// And ones with invalid xpubs..
14221466
let desc = "[78412e3a]xpub1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaLcgJvLJuZZvRcEL/1/*";
14231467
assert_eq!(
14241468
DescriptorPublicKey::from_str(desc),
14251469
Err(DescriptorKeyParseError("Error while parsing xpub."))
14261470
);
1471+
1472+
// ..or invalid raw keys
1473+
let desc = "[78412e3a]0208a117f3897c3a13c9384b8695eed98dc31bc2500feb19a1af424cd47a5d83/1/*";
1474+
assert_eq!(
1475+
DescriptorPublicKey::from_str(desc),
1476+
Err(DescriptorKeyParseError(
1477+
"Error while parsing simple public key"
1478+
))
1479+
);
1480+
1481+
// ..or invalid separators
1482+
let desc = "[78412e3a]]03f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8";
1483+
assert_eq!(
1484+
DescriptorPublicKey::from_str(desc),
1485+
Err(DescriptorKeyParseError(
1486+
"Error while parsing simple public key"
1487+
))
1488+
);
14271489
}
14281490

14291491
#[test]

0 commit comments

Comments
 (0)