Skip to content

Commit 0662d2e

Browse files
committed
Merge #342: Tr compiler v2
ef4249d Add taproot compiler example usage (Aman Rojjha) cef2a5b Add Tr-compiler write-up and doc-comment (Aman Rojjha) 5233c66 Add Taproot compiler API (Aman Rojjha) Pull request description: This PR builds on top of #291. This aims to introduce an efficient version of the tapscript compiler by using a few heuristics to optimize over the expected average total cost for the TapTree. ## Strategy implemented - While merging TapTrees `A` and `B`, check whether the compilation of `Policy::Or(policy(A), policy(B))` is more efficient than a TapTree with the respective children `A` and `B`. **Note**: This doesn't include the `thresh(k, ...n..)` enumeration strategy. Planning on working on it separately. ACKs for top commit: sanket1729: ACK ef4249d Tree-SHA512: ae5949b5170ff4cc8202434655af41b4938e96801209896d117bf4e4bd85c0becc6fd0c7affb100c31655f0085c1ff5e7c19184db3433b2831f73db22d94348d
2 parents 859534b + ef4249d commit 0662d2e

File tree

5 files changed

+175
-18
lines changed

5 files changed

+175
-18
lines changed

Cargo.toml

+5
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ hashbrown = { version = "0.11", optional = true }
2828
[dev-dependencies]
2929
bitcoind = {version = "0.26.1", features=["22_0"]}
3030
actual-rand = { package = "rand", version = "0.8.4"}
31+
secp256k1 = {version = "0.22.1", features = ["rand-std"]}
3132

3233
[[example]]
3334
name = "htlc"
@@ -52,3 +53,7 @@ required-features = ["std"]
5253
[[example]]
5354
name = "xpub_descriptors"
5455
required-features = ["std"]
56+
57+
[[example]]
58+
name = "taproot"
59+
required-features = ["compiler","std"]

contrib/test.sh

+1
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ then
5353
cargo run --example verify_tx > /dev/null
5454
cargo run --example psbt
5555
cargo run --example xpub_descriptors
56+
cargo run --example taproot --features=compiler
5657
fi
5758

5859
if [ "$DO_NO_STD" = true ]

doc/Tr Compiler.pdf

96.5 KB
Binary file not shown.

examples/taproot.rs

+146
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
use std::collections::HashMap;
2+
use std::str::FromStr;
3+
4+
use bitcoin::hashes::{hash160, sha256};
5+
use bitcoin::util::address::WitnessVersion;
6+
use bitcoin::Network;
7+
use miniscript::descriptor::DescriptorType;
8+
use miniscript::policy::Concrete;
9+
use miniscript::{Descriptor, Miniscript, Tap, TranslatePk, Translator};
10+
use secp256k1::{rand, KeyPair};
11+
12+
// Refer to https://github.com/sanket1729/adv_btc_workshop/blob/master/workshop.md#creating-a-taproot-descriptor
13+
// for a detailed explanation of the policy and it's compilation
14+
15+
struct StrPkTranslator {
16+
pk_map: HashMap<String, bitcoin::XOnlyPublicKey>,
17+
}
18+
19+
impl Translator<String, bitcoin::XOnlyPublicKey, ()> for StrPkTranslator {
20+
fn pk(&mut self, pk: &String) -> Result<bitcoin::XOnlyPublicKey, ()> {
21+
self.pk_map.get(pk).copied().ok_or(())
22+
}
23+
24+
fn pkh(&mut self, _pkh: &String) -> Result<hash160::Hash, ()> {
25+
unreachable!("Policy doesn't contain any pkh fragment");
26+
}
27+
28+
fn sha256(&mut self, _sha256: &String) -> Result<sha256::Hash, ()> {
29+
unreachable!("Policy does not contain any sha256 fragment");
30+
}
31+
}
32+
33+
fn main() {
34+
let pol_str = "or(
35+
99@thresh(2,
36+
pk(hA), pk(S)
37+
),1@or(
38+
99@pk(Ca),
39+
1@and(pk(In), older(9))
40+
)
41+
)"
42+
.replace(&[' ', '\n', '\t'][..], "");
43+
44+
let pol: Concrete<String> = Concrete::from_str(&pol_str).unwrap();
45+
// In case we can't find an internal key for the given policy, we set the internal key to
46+
// a random pubkey as specified by BIP341 (which are *unspendable* by any party :p)
47+
let desc = pol.compile_tr(Some("UNSPENDABLE_KEY".to_string())).unwrap();
48+
49+
let expected_desc =
50+
Descriptor::<String>::from_str("tr(Ca,{and_v(v:pk(In),older(9)),multi_a(2,hA,S)})")
51+
.unwrap();
52+
assert_eq!(desc, expected_desc);
53+
54+
// Check whether the descriptors are safe.
55+
assert!(desc.sanity_check().is_ok());
56+
57+
// Descriptor Type and Version should match respectively for Taproot
58+
let desc_type = desc.desc_type();
59+
assert_eq!(desc_type, DescriptorType::Tr);
60+
assert_eq!(desc_type.segwit_version().unwrap(), WitnessVersion::V1);
61+
62+
if let Descriptor::Tr(ref p) = desc {
63+
// Check if internal key is correctly inferred as Ca
64+
// assert_eq!(p.internal_key(), &pubkeys[2]);
65+
assert_eq!(p.internal_key(), "Ca");
66+
67+
// Iterate through scripts
68+
let mut iter = p.iter_scripts();
69+
assert_eq!(
70+
iter.next().unwrap(),
71+
(
72+
1u8,
73+
&Miniscript::<String, Tap>::from_str("and_v(vc:pk_k(In),older(9))").unwrap()
74+
)
75+
);
76+
assert_eq!(
77+
iter.next().unwrap(),
78+
(
79+
1u8,
80+
&Miniscript::<String, Tap>::from_str("multi_a(2,hA,S)").unwrap()
81+
)
82+
);
83+
assert_eq!(iter.next(), None);
84+
}
85+
86+
let mut pk_map = HashMap::new();
87+
88+
// We require secp for generating a random XOnlyPublicKey
89+
let secp = secp256k1::Secp256k1::new();
90+
let key_pair = KeyPair::new(&secp, &mut rand::thread_rng());
91+
// Random unspendable XOnlyPublicKey provided for compilation to Taproot Descriptor
92+
let unspendable_pubkey = bitcoin::XOnlyPublicKey::from_keypair(&key_pair);
93+
94+
pk_map.insert("UNSPENDABLE_KEY".to_string(), unspendable_pubkey);
95+
let pubkeys = hardcoded_xonlypubkeys();
96+
pk_map.insert("hA".to_string(), pubkeys[0]);
97+
pk_map.insert("S".to_string(), pubkeys[1]);
98+
pk_map.insert("Ca".to_string(), pubkeys[2]);
99+
pk_map.insert("In".to_string(), pubkeys[3]);
100+
let mut t = StrPkTranslator { pk_map };
101+
102+
let real_desc = desc.translate_pk(&mut t).unwrap();
103+
104+
// Max Satisfaction Weight for compilation, corresponding to the script-path spend
105+
// `multi_a(2,PUBKEY_1,PUBKEY_2) at taptree depth 1, having
106+
// Max Witness Size = scriptSig len + control_block size + varint(script_size) + script_size +
107+
// varint(max satisfaction elements) + max satisfaction size
108+
// = 4 + 65 + 1 + 70 + 1 + 132
109+
let max_sat_wt = real_desc.max_satisfaction_weight().unwrap();
110+
assert_eq!(max_sat_wt, 273);
111+
112+
// Compute the bitcoin address and check if it matches
113+
let network = Network::Bitcoin;
114+
let addr = real_desc.address(network).unwrap();
115+
let expected_addr = bitcoin::Address::from_str(
116+
"bc1pcc8ku64slu3wu04a6g376d2s8ck9y5alw5sus4zddvn8xgpdqw2swrghwx",
117+
)
118+
.unwrap();
119+
assert_eq!(addr, expected_addr);
120+
}
121+
122+
fn hardcoded_xonlypubkeys() -> Vec<bitcoin::XOnlyPublicKey> {
123+
let serialized_keys: [[u8; 32]; 4] = [
124+
[
125+
22, 37, 41, 4, 57, 254, 191, 38, 14, 184, 200, 133, 111, 226, 145, 183, 245, 112, 100,
126+
42, 69, 210, 146, 60, 179, 170, 174, 247, 231, 224, 221, 52,
127+
],
128+
[
129+
194, 16, 47, 19, 231, 1, 0, 143, 203, 11, 35, 148, 101, 75, 200, 15, 14, 54, 222, 208,
130+
31, 205, 191, 215, 80, 69, 214, 126, 10, 124, 107, 154,
131+
],
132+
[
133+
202, 56, 167, 245, 51, 10, 193, 145, 213, 151, 66, 122, 208, 43, 10, 17, 17, 153, 170,
134+
29, 89, 133, 223, 134, 220, 212, 166, 138, 2, 152, 122, 16,
135+
],
136+
[
137+
50, 23, 194, 4, 213, 55, 42, 210, 67, 101, 23, 3, 195, 228, 31, 70, 127, 79, 21, 188,
138+
168, 39, 134, 58, 19, 181, 3, 63, 235, 103, 155, 213,
139+
],
140+
];
141+
let mut keys: Vec<bitcoin::XOnlyPublicKey> = vec![];
142+
for idx in 0..4 {
143+
keys.push(bitcoin::XOnlyPublicKey::from_slice(&serialized_keys[idx][..]).unwrap());
144+
}
145+
keys
146+
}

src/policy/concrete.rs

+23-18
Original file line numberDiff line numberDiff line change
@@ -194,19 +194,6 @@ impl<Pk: MiniscriptKey> Policy<Pk> {
194194
}
195195
}
196196

197-
/// Compile [`Policy::Or`] and [`Policy::Threshold`] according to odds
198-
#[cfg(feature = "compiler")]
199-
fn compile_tr_policy(&self) -> Result<TapTree<Pk>, Error> {
200-
let leaf_compilations: Vec<_> = self
201-
.to_tapleaf_prob_vec(1.0)
202-
.into_iter()
203-
.filter(|x| x.1 != Policy::Unsatisfiable)
204-
.map(|(prob, ref policy)| (OrdF64(prob), compiler::best_compilation(policy).unwrap()))
205-
.collect();
206-
let taptree = with_huffman_tree::<Pk>(leaf_compilations).unwrap();
207-
Ok(taptree)
208-
}
209-
210197
/// Extract the internal_key from policy tree.
211198
#[cfg(feature = "compiler")]
212199
fn extract_key(self, unspendable_key: Option<Pk>) -> Result<(Pk, Policy<Pk>), Error> {
@@ -257,10 +244,14 @@ impl<Pk: MiniscriptKey> Policy<Pk> {
257244
/// The policy tree constructed by root-level disjunctions over [`Or`][`Policy::Or`] and
258245
/// [`Thresh`][`Policy::Threshold`](1, ..) which is flattened into a vector (with respective
259246
/// probabilities derived from odds) of policies.
260-
/// For example, the policy `thresh(1,or(pk(A),pk(B)),and(or(pk(C),pk(D)),pk(E)))` gives the vector
261-
/// `[pk(A),pk(B),and(or(pk(C),pk(D)),pk(E)))]`. Each policy in the vector is compiled into
262-
/// the respective miniscripts. A Huffman Tree is created from this vector which optimizes over
263-
/// the probabilitity of satisfaction for the respective branch in the TapTree.
247+
/// For example, the policy `thresh(1,or(pk(A),pk(B)),and(or(pk(C),pk(D)),pk(E)))` gives the
248+
/// vector `[pk(A),pk(B),and(or(pk(C),pk(D)),pk(E)))]`. Each policy in the vector is compiled
249+
/// into the respective miniscripts. A Huffman Tree is created from this vector which optimizes
250+
/// over the probabilitity of satisfaction for the respective branch in the TapTree.
251+
///
252+
/// Refer to [this link](https://gist.github.com/SarcasticNastik/9e70b2b43375aab3e78c51e09c288c89)
253+
/// or [doc/Tr compiler.pdf] in the root of the repository to understand why such compilation
254+
/// is also *cost-efficient*.
264255
// TODO: We might require other compile errors for Taproot.
265256
#[cfg(feature = "compiler")]
266257
pub fn compile_tr(&self, unspendable_key: Option<Pk>) -> Result<Descriptor<Pk>, Error> {
@@ -276,7 +267,21 @@ impl<Pk: MiniscriptKey> Policy<Pk> {
276267
internal_key,
277268
match policy {
278269
Policy::Trivial => None,
279-
policy => Some(policy.compile_tr_policy()?),
270+
policy => {
271+
let vec_policies: Vec<_> = policy.to_tapleaf_prob_vec(1.0);
272+
let mut leaf_compilations: Vec<(OrdF64, Miniscript<Pk, Tap>)> = vec![];
273+
for (prob, pol) in vec_policies {
274+
// policy corresponding to the key (replaced by unsatisfiable) is skipped
275+
if pol == Policy::Unsatisfiable {
276+
continue;
277+
}
278+
let compilation = compiler::best_compilation::<Pk, Tap>(&pol)?;
279+
compilation.sanity_check()?;
280+
leaf_compilations.push((OrdF64(prob), compilation));
281+
}
282+
let taptree = with_huffman_tree::<Pk>(leaf_compilations)?;
283+
Some(taptree)
284+
}
280285
},
281286
)?;
282287
Ok(tree)

0 commit comments

Comments
 (0)