Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

btc: support Taproot policies #80

Merged
merged 1 commit into from
Oct 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG-npm.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
## 0.7.0
- btc: handle error when an input's previous transaction is required but missing
- btc: add support for regtest
- btc: add support for Taproot wallet policies

## 0.6.0

Expand Down
1 change: 1 addition & 0 deletions CHANGELOG-rust.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
## 0.6.0
- btc: handle error when an input's previous transaction is required but missing
- btc: add support for regtest
- btc: add support for Taproot wallet policies
- cardano: added support for vote delegation

## 0.5.0
Expand Down
87 changes: 62 additions & 25 deletions src/btc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -242,9 +242,9 @@ pub enum PsbtError {
#[error("{0}")]
#[cfg_attr(feature = "wasm", assoc(js_code = "sign-error"))]
SignError(#[from] bitcoin::psbt::SignError),
#[error("The BitBox does not support Taproot script path spending.")]
#[cfg_attr(feature = "wasm", assoc(js_code = "unsupported-tap-script"))]
UnsupportedTapScript,
#[error("Taproot pubkeys must be unique across the internal key and all leaf scripts.")]
#[cfg_attr(feature = "wasm", assoc(js_code = "key-not-unique"))]
KeyNotUnique,
#[error("Could not find our key in an input.")]
#[cfg_attr(feature = "wasm", assoc(js_code = "key-not-found"))]
KeyNotFound,
Expand All @@ -256,13 +256,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 @@ -336,19 +342,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::KeyNotUnique);
}
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::KeyNotUnique);
}
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 @@ -576,15 +597,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 @@ -681,7 +713,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 Down Expand Up @@ -709,7 +741,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 @@ -897,7 +929,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
8 changes: 8 additions & 0 deletions tests/simulators.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,13 @@
{
"url": "https://github.com/BitBoxSwiss/bitbox02-firmware/releases/download/firmware%2Fv9.19.0/bitbox02-multi-v9.19.0-simulator1.0.0-linux-amd64",
"sha256": "e28be3fd6c7777624ad2574546ba125b7f134f095fa951acc8fb7295f3d33931"
},
{
"url": "https://github.com/BitBoxSwiss/bitbox02-firmware/releases/download/firmware%2Fv9.20.0/bitbox02-multi-v9.20.0-simulator1.0.0-linux-amd64",
"sha256": "ac32c1a71bd0a3a934bc7b94268f651c655f2e3afbb954811a256e551a420b3d"
},
{
"url": "https://github.com/BitBoxSwiss/bitbox02-firmware/releases/download/firmware%2Fv9.21.0/bitbox02-multi-v9.21.0-simulator1.0.0-linux-amd64",
"sha256": "72031b226ea344970a6a1506893838a63b075e0bad726557ab9d941b42c534f5"
}
]
Loading
Loading