Skip to content

Commit 67b8db0

Browse files
committed
Converting LeafVersion into an enum
1 parent 2405417 commit 67b8db0

File tree

3 files changed

+44
-31
lines changed

3 files changed

+44
-31
lines changed

src/util/psbt/serialize.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,7 @@ impl Serialize for (Script, LeafVersion) {
235235
fn serialize(&self) -> Vec<u8> {
236236
let mut buf = Vec::with_capacity(self.0.len() + 1);
237237
buf.extend(self.0.as_bytes());
238-
buf.push(self.1.as_u8());
238+
buf.push(self.1.into_consensus());
239239
buf
240240
}
241241
}
@@ -247,7 +247,7 @@ impl Deserialize for (Script, LeafVersion) {
247247
}
248248
// The last byte is LeafVersion.
249249
let script = Script::deserialize(&bytes[..bytes.len() - 1])?;
250-
let leaf_ver = LeafVersion::from_u8(bytes[bytes.len() - 1])
250+
let leaf_ver = LeafVersion::from_consensus(bytes[bytes.len() - 1])
251251
.map_err(|_| encode::Error::ParseFailed("invalid leaf version"))?;
252252
Ok((script, leaf_ver))
253253
}
@@ -283,7 +283,7 @@ impl Serialize for TapTree {
283283
// TaprootMerkleBranch can only have len atmost 128(TAPROOT_CONTROL_MAX_NODE_COUNT).
284284
// safe to cast from usize to u8
285285
buf.push(leaf_info.merkle_branch.as_inner().len() as u8);
286-
buf.push(leaf_info.ver.as_u8());
286+
buf.push(leaf_info.ver.into_consensus());
287287
leaf_info.script.consensus_encode(&mut buf).expect("Vecs dont err");
288288
}
289289
buf
@@ -305,7 +305,7 @@ impl Deserialize for TapTree {
305305
bytes_iter.nth(consumed - 1);
306306
}
307307

308-
let leaf_version = LeafVersion::from_u8(*version)
308+
let leaf_version = LeafVersion::from_consensus(*version)
309309
.map_err(|_| encode::Error::ParseFailed("Leaf Version Error"))?;
310310
builder = builder.add_leaf_with_ver(usize::from(*depth), script, leaf_version)
311311
.map_err(|_| encode::Error::ParseFailed("Tree not in DFS order"))?;

src/util/sighash.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -229,13 +229,13 @@ impl<'s> ScriptPath<'s> {
229229
}
230230
/// Create a new ScriptPath structure using default leaf version value
231231
pub fn with_defaults(script: &'s Script) -> Self {
232-
Self::new(script, LeafVersion::default())
232+
Self::new(script, LeafVersion::TapScript)
233233
}
234234
/// Compute the leaf hash
235235
pub fn leaf_hash(&self) -> TapLeafHash {
236236
let mut enc = TapLeafHash::engine();
237237

238-
self.leaf_version.as_u8().consensus_encode(&mut enc).expect("Writing to hash enging should never fail");
238+
self.leaf_version.into_consensus().consensus_encode(&mut enc).expect("Writing to hash enging should never fail");
239239
self.script.consensus_encode(&mut enc).expect("Writing to hash enging should never fail");
240240

241241
TapLeafHash::from_engine(enc)

src/util/taproot.rs

Lines changed: 38 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
//!
1616
//! This module provides support for taproot tagged hashes.
1717
//!
18+
1819
use prelude::*;
1920
use io;
2021
use secp256k1::{self, Secp256k1};
@@ -120,7 +121,7 @@ impl TapLeafHash {
120121
/// function to compute leaf hash from components
121122
pub fn from_script(script: &Script, ver: LeafVersion) -> TapLeafHash {
122123
let mut eng = TapLeafHash::engine();
123-
ver.as_u8()
124+
ver.into_consensus()
124125
.consensus_encode(&mut eng)
125126
.expect("engines don't error");
126127
script
@@ -142,6 +143,8 @@ pub const TAPROOT_LEAF_MASK: u8 = 0xfe;
142143
/// Tapscript leaf version
143144
// https://github.com/bitcoin/bitcoin/blob/e826b22da252e0599c61d21c98ff89f366b3120f/src/script/interpreter.h#L226
144145
pub const TAPROOT_LEAF_TAPSCRIPT: u8 = 0xc0;
146+
/// Taproot annex prefix
147+
pub const TAPROOT_ANNEX_PREFIX: u8 = 0x50;
145148
/// Tapscript control base size
146149
// https://github.com/bitcoin/bitcoin/blob/e826b22da252e0599c61d21c98ff89f366b3120f/src/script/interpreter.h#L227
147150
pub const TAPROOT_CONTROL_BASE_SIZE: usize = 33;
@@ -152,6 +155,7 @@ pub const TAPROOT_CONTROL_MAX_SIZE: usize =
152155

153156
// type alias for versioned tap script corresponding merkle proof
154157
type ScriptMerkleProofMap = BTreeMap<(Script, LeafVersion), BTreeSet<TaprootMerkleBranch>>;
158+
155159
/// Data structure for representing Taproot spending information.
156160
/// Taproot output corresponds to a combination of a
157161
/// single public key condition (known the internal key), and zero or more
@@ -216,7 +220,7 @@ impl TaprootSpendInfo {
216220
{
217221
let mut node_weights = BinaryHeap::<(Reverse<u64>, NodeInfo)>::new();
218222
for (p, leaf) in script_weights {
219-
node_weights.push((Reverse(p as u64), NodeInfo::new_leaf_with_ver(leaf, LeafVersion::default())));
223+
node_weights.push((Reverse(p as u64), NodeInfo::new_leaf_with_ver(leaf, LeafVersion::TapScript)));
220224
}
221225
if node_weights.is_empty() {
222226
return Err(TaprootBuilderError::IncompleteTree);
@@ -409,7 +413,7 @@ impl TaprootBuilder {
409413
/// See [`TaprootBuilder::add_leaf_with_ver`] for adding a leaf with specific version
410414
/// See [Uncyclopedia](https://en.wikipedia.org/wiki/Depth-first_search) for more details
411415
pub fn add_leaf(self, depth: usize, script: Script) -> Result<Self, TaprootBuilderError> {
412-
self.add_leaf_with_ver(depth, script, LeafVersion::default())
416+
self.add_leaf_with_ver(depth, script, LeafVersion::TapScript)
413417
}
414418

415419
/// Add a hidden/omitted node at a depth `depth` to the builder.
@@ -680,7 +684,7 @@ impl ControlBlock {
680684
return Err(TaprootError::InvalidControlBlockSize(sl.len()));
681685
}
682686
let output_key_parity = secp256k1::Parity::from((sl[0] & 1) as i32);
683-
let leaf_version = LeafVersion::from_u8(sl[0] & TAPROOT_LEAF_MASK)?;
687+
let leaf_version = LeafVersion::from_consensus(sl[0] & TAPROOT_LEAF_MASK)?;
684688
let internal_key = UntweakedPublicKey::from_slice(&sl[1..TAPROOT_CONTROL_BASE_SIZE])
685689
.map_err(TaprootError::InvalidInternalKey)?;
686690
let merkle_branch = TaprootMerkleBranch::from_slice(&sl[TAPROOT_CONTROL_BASE_SIZE..])?;
@@ -700,7 +704,7 @@ impl ControlBlock {
700704

701705
/// Serialize to a writer. Returns the number of bytes written
702706
pub fn encode<Write: io::Write>(&self, mut writer: Write) -> io::Result<usize> {
703-
let first_byte: u8 = i32::from(self.output_key_parity) as u8 | self.leaf_version.as_u8();
707+
let first_byte: u8 = i32::from(self.output_key_parity) as u8 | self.leaf_version.into_consensus();
704708
let mut bytes_written = 0;
705709
bytes_written += writer.write(&[first_byte])?;
706710
bytes_written += writer.write(&self.internal_key.serialize())?;
@@ -759,16 +763,16 @@ impl ControlBlock {
759763
/// The leaf version for tapleafs
760764
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
761765
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
762-
pub struct LeafVersion(u8);
766+
pub enum LeafVersion {
767+
/// BIP-342 tapscript
768+
TapScript,
763769

764-
impl Default for LeafVersion {
765-
fn default() -> Self {
766-
LeafVersion(TAPROOT_LEAF_TAPSCRIPT)
767-
}
770+
/// Future leaf version
771+
Future(u8)
768772
}
769773

770774
impl LeafVersion {
771-
/// Obtain LeafVersion from u8, will error when last bit of ver is even or
775+
/// Obtain LeafVersion from u8, will error when last bit of ver is odd or
772776
/// when ver is 0x50 (ANNEX_TAG)
773777
// Text from BIP341:
774778
// In order to support some forms of static analysis that rely on
@@ -779,23 +783,32 @@ impl LeafVersion {
779783
// or an opcode that is not valid as the first opcode).
780784
// The values that comply to this rule are the 32 even values between
781785
// 0xc0 and 0xfe and also 0x66, 0x7e, 0x80, 0x84, 0x96, 0x98, 0xba, 0xbc, 0xbe
782-
pub fn from_u8(ver: u8) -> Result<Self, TaprootError> {
783-
if ver & TAPROOT_LEAF_MASK == ver && ver != 0x50 {
784-
Ok(LeafVersion(ver))
785-
} else {
786-
Err(TaprootError::InvalidTaprootLeafVersion(ver))
786+
pub fn from_consensus(version: u8) -> Result<Self, TaprootError> {
787+
match version {
788+
TAPROOT_LEAF_TAPSCRIPT => Ok(LeafVersion::TapScript),
789+
TAPROOT_ANNEX_PREFIX => Err(TaprootError::InvalidTaprootLeafVersion(TAPROOT_ANNEX_PREFIX)),
790+
odd if odd & TAPROOT_LEAF_MASK != odd => Err(TaprootError::InvalidTaprootLeafVersion(odd)),
791+
future => Ok(LeafVersion::Future(future)),
787792
}
788793
}
789794

790795
/// Get the inner version from LeafVersion
791-
pub fn as_u8(&self) -> u8 {
792-
self.0
796+
pub fn into_consensus(self) -> u8 {
797+
match self {
798+
LeafVersion::TapScript => TAPROOT_LEAF_TAPSCRIPT,
799+
LeafVersion::Future(version) => version,
800+
}
793801
}
794802
}
795803

796-
impl Into<u8> for LeafVersion {
797-
fn into(self) -> u8 {
798-
self.0
804+
impl fmt::Display for LeafVersion {
805+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
806+
match (self, f.alternate()) {
807+
(LeafVersion::TapScript, false) => f.write_str("tapscript"),
808+
(LeafVersion::TapScript, true) => fmt::Display::fmt(&TAPROOT_LEAF_TAPSCRIPT, f),
809+
(LeafVersion::Future(version), false) => write!(f, "future_script_{:#02x}", version),
810+
(LeafVersion::Future(version), true) => fmt::Display::fmt(version, f),
811+
}
799812
}
800813
}
801814

@@ -1063,7 +1076,7 @@ mod test {
10631076
length,
10641077
tree_info
10651078
.script_map
1066-
.get(&(Script::from_hex(script).unwrap(), LeafVersion::default()))
1079+
.get(&(Script::from_hex(script).unwrap(), LeafVersion::TapScript))
10671080
.expect("Present Key")
10681081
.iter()
10691082
.next()
@@ -1078,7 +1091,7 @@ mod test {
10781091

10791092
// Try to create and verify a control block from each path
10801093
for (_weights, script) in script_weights {
1081-
let ver_script = (script, LeafVersion::default());
1094+
let ver_script = (script, LeafVersion::TapScript);
10821095
let ctrl_block = tree_info.control_block(&ver_script).unwrap();
10831096
assert!(ctrl_block.verify_taproot_commitment(&secp, &output_key, &ver_script.0))
10841097
}
@@ -1114,7 +1127,7 @@ mod test {
11141127
let output_key = tree_info.output_key();
11151128

11161129
for script in vec![a, b, c, d, e] {
1117-
let ver_script = (script, LeafVersion::default());
1130+
let ver_script = (script, LeafVersion::TapScript);
11181131
let ctrl_block = tree_info.control_block(&ver_script).unwrap();
11191132
assert!(ctrl_block.verify_taproot_commitment(&secp, &output_key, &ver_script.0))
11201133
}
@@ -1137,7 +1150,7 @@ mod test {
11371150
}
11381151
} else {
11391152
let script = Script::from_str(v["script"].as_str().unwrap()).unwrap();
1140-
let ver = LeafVersion::from_u8(v["leafVersion"].as_u64().unwrap() as u8).unwrap();
1153+
let ver = LeafVersion::from_consensus(v["leafVersion"].as_u64().unwrap() as u8).unwrap();
11411154
leaves.push((script.clone(), ver));
11421155
builder = builder.add_leaf_with_ver(depth, script, ver).unwrap();
11431156
}

0 commit comments

Comments
 (0)