-
Notifications
You must be signed in to change notification settings - Fork 88
feat(compile): compile taproot descriptor with randomized unspendable internal key #225
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
base: master
Are you sure you want to change the base?
Changes from all commits
a541122
6c3e071
09a381b
d763986
189c710
df6ee82
791a775
7b9a84e
fab2291
afc76aa
c3da068
787c701
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -37,12 +37,18 @@ use bdk_wallet::miniscript::miniscript; | |||||
| #[cfg(feature = "sqlite")] | ||||||
| use bdk_wallet::rusqlite::Connection; | ||||||
| use bdk_wallet::{KeychainKind, SignOptions, Wallet}; | ||||||
|
|
||||||
| #[cfg(feature = "compiler")] | ||||||
| use bdk_wallet::{ | ||||||
| bitcoin::XOnlyPublicKey, | ||||||
| bitcoin::{ | ||||||
| XOnlyPublicKey, | ||||||
| key::{Parity, rand}, | ||||||
| secp256k1::{PublicKey, Scalar, SecretKey}, | ||||||
| }, | ||||||
| descriptor::{Descriptor, Legacy, Miniscript}, | ||||||
| miniscript::{Tap, descriptor::TapTree, policy::Concrete}, | ||||||
| }; | ||||||
|
|
||||||
| use cli_table::{Cell, CellStruct, Style, Table, format::Justify}; | ||||||
| use serde_json::json; | ||||||
| #[cfg(feature = "cbf")] | ||||||
|
|
@@ -893,50 +899,70 @@ pub(crate) fn handle_compile_subcommand( | |||||
| pretty: bool, | ||||||
| ) -> Result<String, Error> { | ||||||
| let policy = Concrete::<String>::from_str(policy.as_str())?; | ||||||
| let legacy_policy: Miniscript<String, Legacy> = policy | ||||||
| .compile() | ||||||
| .map_err(|e| Error::Generic(e.to_string()))?; | ||||||
| let segwit_policy: Miniscript<String, Segwitv0> = policy | ||||||
| .compile() | ||||||
| .map_err(|e| Error::Generic(e.to_string()))?; | ||||||
| let taproot_policy: Miniscript<String, Tap> = policy | ||||||
| .compile() | ||||||
| .map_err(|e| Error::Generic(e.to_string()))?; | ||||||
|
|
||||||
| let legacy_policy: Miniscript<String, Legacy> = policy.compile()?; | ||||||
| let segwit_policy: Miniscript<String, Segwitv0> = policy.compile()?; | ||||||
| let taproot_policy: Miniscript<String, Tap> = policy.compile()?; | ||||||
|
|
||||||
| let mut r = None; | ||||||
| let mut shorten_descriptor = None; | ||||||
|
|
||||||
| let descriptor = match script_type.as_str() { | ||||||
| "sh" => Descriptor::new_sh(legacy_policy), | ||||||
| "wsh" => Descriptor::new_wsh(segwit_policy), | ||||||
| "sh-wsh" => Descriptor::new_sh_wsh(segwit_policy), | ||||||
| "tr" => { | ||||||
| // For tr descriptors, we use a well-known unspendable key (NUMS point). | ||||||
| // This ensures the key path is effectively disabled and only script path can be used. | ||||||
| // See https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#constructing-and-spending-taproot-outputs | ||||||
| // For tr descriptors, we use a randomized unspendable key (H + rG). | ||||||
| // This improves privacy by preventing observers from determining if key path spending is disabled. | ||||||
| // See BIP-341: https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#constructing-and-spending-taproot-outputs | ||||||
|
|
||||||
| let xonly_public_key = XOnlyPublicKey::from_str(NUMS_UNSPENDABLE_KEY_HEX) | ||||||
| .map_err(|e| Error::Generic(format!("Invalid NUMS key: {e}")))?; | ||||||
| let secp = Secp256k1::new(); | ||||||
| let r_secret = SecretKey::new(&mut rand::thread_rng()); | ||||||
| r = Some(r_secret.display_secret().to_string()); | ||||||
|
|
||||||
| let nums_key = XOnlyPublicKey::from_str(NUMS_UNSPENDABLE_KEY_HEX)?; | ||||||
| let nums_point = PublicKey::from_x_only_public_key(nums_key, Parity::Even); | ||||||
|
|
||||||
| let internal_key_point = nums_point.add_exp_tweak(&secp, &Scalar::from(r_secret))?; | ||||||
| let (xonly_internal_key, _) = internal_key_point.x_only_public_key(); | ||||||
|
|
||||||
| let tree = TapTree::Leaf(Arc::new(taproot_policy)); | ||||||
| Descriptor::new_tr(xonly_public_key.to_string(), Some(tree)) | ||||||
|
|
||||||
| shorten_descriptor = Some(Descriptor::new_tr( | ||||||
| shorten(xonly_internal_key, 4, 4), | ||||||
| Some(tree.clone()), | ||||||
| )?); | ||||||
|
|
||||||
| Descriptor::new_tr(xonly_internal_key.to_string(), Some(tree)) | ||||||
| } | ||||||
| _ => { | ||||||
| return Err(Error::Generic( | ||||||
| "Invalid script type. Supported types: sh, wsh, sh-wsh, tr".to_string(), | ||||||
| )); | ||||||
| } | ||||||
| }?; | ||||||
|
|
||||||
| if pretty { | ||||||
| let table = vec![vec![ | ||||||
| "Descriptor".cell().bold(true), | ||||||
| descriptor.to_string().cell(), | ||||||
| ]] | ||||||
| .table() | ||||||
| .display() | ||||||
| .map_err(|e| Error::Generic(e.to_string()))?; | ||||||
| let descriptor = shorten_descriptor.unwrap_or(descriptor); | ||||||
|
|
||||||
| let mut rows = vec![vec!["Descriptor".cell().bold(true), descriptor.cell()]]; | ||||||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. the
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Done! I also used without pretty: -> % cargo run --all-features -- compile "pk(ABC)" -t tr
{
"descriptor": "tr(1985c2a86e01bbcdb1b5806422531a73c77e568ecfdd6d2863c158a76628ea50,pk(ABC))#6qsjh5q3",
"r": "e38caa40d0db7cae7037336c982278a7fc6b770e7a80f8bbce0d79976a14d5e1"
}with pretty: -> % cargo run --all-features -- compile "pk(ABC)" -t tr --pretty
+------------+----------------------------------+
| Descriptor | tr(ccb4...b1d0,pk(ABC))#qrk923py |
+------------+----------------------------------+
| r | a129...7a14 |
+------------+----------------------------------+
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
you can remove: 908, 931-934, 946 you can also revert 951; it should size most screens comfortably. |
||||||
|
|
||||||
| if let Some(r_value) = &r { | ||||||
| rows.push(vec!["r".cell().bold(true), shorten(r_value, 4, 4).cell()]); | ||||||
| } | ||||||
|
|
||||||
| let table = rows | ||||||
| .table() | ||||||
| .display() | ||||||
| .map_err(|e| Error::Generic(e.to_string()))?; | ||||||
|
|
||||||
| Ok(format!("{table}")) | ||||||
| } else { | ||||||
| Ok(serde_json::to_string_pretty( | ||||||
| &json!({"descriptor": descriptor.to_string()}), | ||||||
| )?) | ||||||
| let mut output = json!({"descriptor": descriptor}); | ||||||
| if let Some(r_value) = r { | ||||||
| output["r"] = json!(r_value); | ||||||
| } | ||||||
| Ok(serde_json::to_string_pretty(&output)?) | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
|
|
@@ -1450,92 +1476,4 @@ mod test { | |||||
| let full_signed_psbt = Psbt::from_str("cHNidP8BAIkBAAAAASWJHzxzyVORV/C3lAynKHVVL7+Rw7/Jj8U9fuvD24olAAAAAAD+////AiBOAAAAAAAAIgAgLzY9yE4jzTFJnHtTjkc+rFAtJ9NB7ENFQ1xLYoKsI1cfqgKVAAAAACIAIFsbWgDeLGU8EA+RGwBDIbcv4gaGG0tbEIhDvwXXa/E7LwEAAAABALUCAAAAAAEBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////BALLAAD/////AgD5ApUAAAAAIgAgWxtaAN4sZTwQD5EbAEMhty/iBoYbS1sQiEO/Bddr8TsAAAAAAAAAACZqJKohqe3i9hw/cdHe/T+pmd+jaVN1XGkGiXmZYrSL69g2l06M+QEgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQErAPkClQAAAAAiACBbG1oA3ixlPBAPkRsAQyG3L+IGhhtLWxCIQ78F12vxOwEFR1IhA/JV2U/0pXW+iP49QcsYilEvkZEd4phmDM8nV8wC+MeDIQLKhV/gEZYmlsQXnsL5/Uqv5Y8O31tmWW1LQqIBkiqzCVKuIgYCyoVf4BGWJpbEF57C+f1Kr+WPDt9bZlltS0KiAZIqswkEboH3lCIGA/JV2U/0pXW+iP49QcsYilEvkZEd4phmDM8nV8wC+MeDBDS6ZSEBBwABCNsEAEgwRQIhAJzT6busDV9h12M/LNquZ17oOHFn7whg90kh9gjSpvshAiBEDu/1EYVD7BqJJzExPhq2CX/Vsap/ULLjfRRo99nEKQFHMEQCIGoFCvJ2zPB7PCpznh4+1jsY03kMie49KPoPDdr7/T9TAiB3jV7wzR9BH11FSbi+8U8gSX95PrBlnp1lOBgTUIUw3QFHUiED8lXZT/Sldb6I/j1ByxiKUS+RkR3imGYMzydXzAL4x4MhAsqFX+ARliaWxBeewvn9Sq/ljw7fW2ZZbUtCogGSKrMJUq4AACICAsqFX+ARliaWxBeewvn9Sq/ljw7fW2ZZbUtCogGSKrMJBG6B95QiAgPyVdlP9KV1voj+PUHLGIpRL5GRHeKYZgzPJ1fMAvjHgwQ0umUhAA==").unwrap(); | ||||||
| assert!(is_final(&full_signed_psbt).is_ok()); | ||||||
| } | ||||||
|
|
||||||
| #[cfg(feature = "compiler")] | ||||||
| #[test] | ||||||
| fn test_compile_taproot() { | ||||||
| use super::{NUMS_UNSPENDABLE_KEY_HEX, handle_compile_subcommand}; | ||||||
| use bdk_wallet::bitcoin::Network; | ||||||
|
|
||||||
| // Expected taproot descriptors with checksums (using NUMS key from constant) | ||||||
| let expected_pk_a = format!("tr({},pk(A))#a2mlskt0", NUMS_UNSPENDABLE_KEY_HEX); | ||||||
| let expected_and_ab = format!( | ||||||
| "tr({},and_v(v:pk(A),pk(B)))#sfplm6kv", | ||||||
| NUMS_UNSPENDABLE_KEY_HEX | ||||||
| ); | ||||||
|
|
||||||
| // Test simple pk policy compilation to taproot | ||||||
| let result = handle_compile_subcommand( | ||||||
| Network::Testnet, | ||||||
| "pk(A)".to_string(), | ||||||
| "tr".to_string(), | ||||||
| false, | ||||||
| ); | ||||||
| assert!(result.is_ok()); | ||||||
| let json_string = result.unwrap(); | ||||||
| let json_result: serde_json::Value = serde_json::from_str(&json_string).unwrap(); | ||||||
| let descriptor = json_result.get("descriptor").unwrap().as_str().unwrap(); | ||||||
| assert_eq!(descriptor, expected_pk_a); | ||||||
|
|
||||||
| // Test more complex policy | ||||||
| let result = handle_compile_subcommand( | ||||||
| Network::Testnet, | ||||||
| "and(pk(A),pk(B))".to_string(), | ||||||
| "tr".to_string(), | ||||||
| false, | ||||||
| ); | ||||||
| assert!(result.is_ok()); | ||||||
| let json_string = result.unwrap(); | ||||||
| let json_result: serde_json::Value = serde_json::from_str(&json_string).unwrap(); | ||||||
| let descriptor = json_result.get("descriptor").unwrap().as_str().unwrap(); | ||||||
| assert_eq!(descriptor, expected_and_ab); | ||||||
| } | ||||||
|
|
||||||
| #[cfg(feature = "compiler")] | ||||||
| #[test] | ||||||
| fn test_compile_invalid_cases() { | ||||||
| use super::handle_compile_subcommand; | ||||||
| use bdk_wallet::bitcoin::Network; | ||||||
|
|
||||||
| // Test invalid policy syntax | ||||||
| let result = handle_compile_subcommand( | ||||||
| Network::Testnet, | ||||||
| "invalid_policy".to_string(), | ||||||
| "tr".to_string(), | ||||||
| false, | ||||||
| ); | ||||||
| assert!(result.is_err()); | ||||||
|
|
||||||
| // Test invalid script type | ||||||
| let result = handle_compile_subcommand( | ||||||
| Network::Testnet, | ||||||
| "pk(A)".to_string(), | ||||||
| "invalid_type".to_string(), | ||||||
| false, | ||||||
| ); | ||||||
| assert!(result.is_err()); | ||||||
|
|
||||||
| // Test empty policy | ||||||
| let result = | ||||||
| handle_compile_subcommand(Network::Testnet, "".to_string(), "tr".to_string(), false); | ||||||
| assert!(result.is_err()); | ||||||
|
|
||||||
| // Test malformed policy with unmatched parentheses | ||||||
| let result = handle_compile_subcommand( | ||||||
| Network::Testnet, | ||||||
| "pk(A".to_string(), | ||||||
| "tr".to_string(), | ||||||
| false, | ||||||
| ); | ||||||
| assert!(result.is_err()); | ||||||
|
|
||||||
| // Test policy with unknown function | ||||||
| let result = handle_compile_subcommand( | ||||||
| Network::Testnet, | ||||||
| "unknown_func(A)".to_string(), | ||||||
| "tr".to_string(), | ||||||
| false, | ||||||
| ); | ||||||
| assert!(result.is_err()); | ||||||
| } | ||||||
| } | ||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| // Copyright (c) 2020-2025 Bitcoin Dev Kit Developers | ||
| // | ||
| // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE | ||
| // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | ||
| // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. | ||
| // You may not use this file except in accordance with one or both of these | ||
| // licenses. | ||
|
|
||
| //! Compile Command Tests | ||
| //! | ||
| //! Tests for compile command and subcommands | ||
| use std::process::Command; | ||
|
|
||
| fn run_cmd(cmd: &str) -> Result<String, String> { | ||
| let full_cmd = format!("run --features compiler -- {}", cmd); | ||
| let args = shlex::split(&full_cmd).unwrap(); | ||
|
|
||
| let output = Command::new("cargo") | ||
| .args(args) | ||
| .env_remove("NETWORK") | ||
| .env_remove("DATADIR") | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit: ig removing
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. You're right, |
||
| .env_remove("POLICY") | ||
| .env_remove("TYPE") | ||
| .output() | ||
| .unwrap(); | ||
|
|
||
| let stdout = String::from_utf8_lossy(&output.stdout).to_string(); | ||
| let stderr = String::from_utf8_lossy(&output.stderr).to_string(); | ||
|
|
||
| if output.status.success() { | ||
| Ok(stdout) | ||
| } else { | ||
| Err(stderr) | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_compile_taproot() { | ||
| let stdout = run_cmd(r#"compile "pk(ABC)" -t tr"#).unwrap(); | ||
| let json: serde_json::Value = serde_json::from_str(&stdout).unwrap(); | ||
|
|
||
| assert!(json.get("descriptor").is_some()); | ||
| assert!(json.get("r").is_some()); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_compile_sh() { | ||
| let stdout = run_cmd(r#"compile "pk(ABC)" -t sh"#).unwrap(); | ||
| let json: serde_json::Value = serde_json::from_str(&stdout).unwrap(); | ||
|
|
||
| assert!(json.get("descriptor").is_some()); | ||
| assert!(json.get("r").is_none()); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_invalid_cases() { | ||
| // Test invalid policy syntax | ||
| let stderr = run_cmd(r#"compile "invalid_policy""#).unwrap_err(); | ||
| assert!(stderr.contains("Miniscript error")); | ||
|
|
||
| // Test invalid script type | ||
| let stderr = run_cmd(r#"compile "pk(A)" -t invalid_type"#).unwrap_err(); | ||
| assert!(stderr.contains("error: invalid value 'invalid_type' for '--type <SCRIPT_TYPE>'")); | ||
|
|
||
| // Test empty policy | ||
| let stderr = run_cmd("compile").unwrap_err(); | ||
| assert!(stderr.contains("error: the following required arguments were not provided")); | ||
| assert!(stderr.contains("<POLICY>")); | ||
|
|
||
| // Test malformed policy with unmatched parentheses | ||
| let stderr = run_cmd(r#"compile "pk(A""#).unwrap_err(); | ||
| assert!(stderr.contains("Miniscript error: expected )")); | ||
|
|
||
| // Test policy with unknown function | ||
| let stderr = run_cmd(r#"compile "unknown_func(A)""#).unwrap_err(); | ||
| assert!(stderr.contains("Miniscript error: unexpected «unknown_func»")); | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.