Skip to content

Commit

Permalink
btc: support Taproot policies
Browse files Browse the repository at this point in the history
This mostly involves fixing PSBT signing to be able to handle Taproot
leaf script spends.

Integration tests with the simulator are added. The signed PSBTs are
checked to be correctly signed by rust-miniscript and
rust-bitcoinconsensus.
  • Loading branch information
benma committed Jul 18, 2024
1 parent 383bca0 commit f8349f4
Show file tree
Hide file tree
Showing 6 changed files with 391 additions and 49 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ required-features = ["usb", "tokio/rt", "tokio/macros"]

[[example]]
name = "btc_miniscript"
required-features = ["usb", "tokio/rt", "tokio/macros"]
required-features = ["simulator", "tokio/rt", "tokio/macros"]

[[example]]
name = "eth"
Expand Down
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ example-btc-psbt:
example-btc-sign-msg:
cargo run --example btc_sign_msg --features=usb,tokio/rt,tokio/macros
example-btc-miniscript:
cargo run --example btc_miniscript --features=usb,tokio/rt,tokio/macros
cargo run --example btc_miniscript --features=tokio/rt,tokio/macros,simulator
example-eth:
cargo run --example eth --features=usb,tokio/rt,tokio/macros,rlp
example-cardano:
Expand Down
49 changes: 27 additions & 22 deletions examples/btc_miniscript.rs

Large diffs are not rendered by default.

5 changes: 2 additions & 3 deletions examples/btc_sign_psbt.rs

Large diffs are not rendered by default.

81 changes: 59 additions & 22 deletions src/btc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -215,13 +215,19 @@ pub enum PsbtError {
enum OurKey {
Segwit(bitcoin::secp256k1::PublicKey, Keypath),
TaprootInternal(Keypath),
TaprootScript(
bitcoin::secp256k1::XOnlyPublicKey,
bitcoin::taproot::TapLeafHash,
Keypath,
),
}

impl OurKey {
fn keypath(&self) -> Keypath {
match self {
OurKey::Segwit(_, kp) => kp.clone(),
OurKey::TaprootInternal(kp) => kp.clone(),
OurKey::TaprootScript(_, _, kp) => kp.clone(),
}
}
}
Expand Down Expand Up @@ -295,19 +301,34 @@ fn find_our_key<T: PsbtOutputInfo>(
our_root_fingerprint: &[u8],
output_info: T,
) -> Result<OurKey, PsbtError> {
if let Some(tap_internal_key) = output_info.get_tap_internal_key() {
let (leaf_hashes, (fingerprint, derivation_path)) = output_info
.get_tap_key_origins()
.get(tap_internal_key)
.ok_or(PsbtError::KeyNotFound)?;
if !leaf_hashes.is_empty() {
return Err(PsbtError::UnsupportedTapScript);
}
for (xonly, (leaf_hashes, (fingerprint, derivation_path))) in
output_info.get_tap_key_origins().iter()
{
if &fingerprint[..] == our_root_fingerprint {
// TODO: check for fingerprint collision
return Ok(OurKey::TaprootInternal(derivation_path.into()));

if let Some(tap_internal_key) = output_info.get_tap_internal_key() {
if tap_internal_key == xonly {
if !leaf_hashes.is_empty() {
// TODO change err msg, we don't support the
// same key as internal key and also in a leaf
// script.
return Err(PsbtError::UnsupportedTapScript);
}
return Ok(OurKey::TaprootInternal(derivation_path.into()));
}
}
if leaf_hashes.len() != 1 {
// TODO change err msg, per BIP-388 all pubkeys are
// unique, so it can't be in multiple leafs.
return Err(PsbtError::UnsupportedTapScript);
}
return Ok(OurKey::TaprootScript(
*xonly,
leaf_hashes[0],
derivation_path.into(),
));
}
return Err(PsbtError::KeyNotFound);
}
for (pubkey, (fingerprint, derivation_path)) in output_info.get_bip32_derivation().iter() {
if &fingerprint[..] == our_root_fingerprint {
Expand Down Expand Up @@ -516,15 +537,26 @@ pub fn make_script_config_policy(policy: &str, keys: &[KeyOriginInfo]) -> pb::Bt
}
}

fn is_taproot(script_config: &pb::BtcScriptConfigWithKeypath) -> bool {
matches!(script_config,
pb::BtcScriptConfigWithKeypath {
script_config:
Some(pb::BtcScriptConfig {
config: Some(pb::btc_script_config::Config::SimpleType(simple_type)),
}),
..
} if *simple_type == pb::btc_script_config::SimpleType::P2tr as i32)
fn is_taproot_simple(script_config: &pb::BtcScriptConfigWithKeypath) -> bool {
matches!(
script_config.script_config.as_ref(),
Some(pb::BtcScriptConfig {
config: Some(pb::btc_script_config::Config::SimpleType(simple_type)),
}) if *simple_type == pb::btc_script_config::SimpleType::P2tr as i32
)
}

fn is_taproot_policy(script_config: &pb::BtcScriptConfigWithKeypath) -> bool {
matches!(
script_config.script_config.as_ref(),
Some(pb::BtcScriptConfig {
config: Some(pb::btc_script_config::Config::Policy(policy)),
}) if policy.policy.as_str().starts_with("tr("),
)
}

fn is_schnorr(script_config: &pb::BtcScriptConfigWithKeypath) -> bool {
is_taproot_simple(script_config) | is_taproot_policy(script_config)
}

impl<R: Runtime> PairedBitBox<R> {
Expand Down Expand Up @@ -621,7 +653,7 @@ impl<R: Runtime> PairedBitBox<R> {
format_unit: pb::btc_sign_init_request::FormatUnit,
) -> Result<Vec<Vec<u8>>, Error> {
self.validate_version(">=9.4.0")?; // anti-klepto since 9.4.0
if transaction.script_configs.iter().any(is_taproot) {
if transaction.script_configs.iter().any(is_taproot_simple) {
self.validate_version(">=9.10.0")?; // taproot since 9.10.0
}

Expand All @@ -648,7 +680,7 @@ impl<R: Runtime> PairedBitBox<R> {
let input_index: usize = next_response.index as _;
let tx_input: &TxInput = &transaction.inputs[input_index];

let input_is_schnorr = is_taproot(
let input_is_schnorr = is_schnorr(
&transaction.script_configs[tx_input.script_config_index as usize],
);
let perform_antiklepto = is_inputs_pass2 && !input_is_schnorr;
Expand Down Expand Up @@ -844,7 +876,12 @@ impl<R: Runtime> PairedBitBox<R> {
psbt_input.tap_key_sig = Some(
bitcoin::taproot::Signature::from_slice(signature)
.map_err(|_| Error::InvalidSignature)?,
)
);
}
OurKey::TaprootScript(xonly, leaf_hash, _) => {
let sig = bitcoin::taproot::Signature::from_slice(signature)
.map_err(|_| Error::InvalidSignature)?;
psbt_input.tap_script_sigs.insert((xonly, leaf_hash), sig);
}
}
}
Expand Down
Loading

0 comments on commit f8349f4

Please sign in to comment.