Skip to content

Commit ad3e035

Browse files
committed
Implement TryFrom for WitnessVersion
We have a bunch of 'from' methods that are fallible; `TryFrom` became available in Rust 1.34 so we can use it now we have bumped our MSRV. Implement the various `WitnessVersion` from methods using `TryFrom` and deprecate the originals.
1 parent 48cc8c1 commit ad3e035

File tree

2 files changed

+113
-39
lines changed

2 files changed

+113
-39
lines changed

src/blockdata/script.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ use crate::consensus::encode::MAX_VEC_SIZE;
2727
use crate::prelude::*;
2828

2929
use crate::io;
30+
use core::convert::TryFrom;
3031
use core::{fmt, default::Default};
3132
use core::ops::Index;
3233

@@ -498,7 +499,7 @@ impl Script {
498499
/// Returns witness version of the script, if any, assuming the script is a `scriptPubkey`.
499500
#[inline]
500501
pub fn witness_version(&self) -> Option<WitnessVersion> {
501-
self.0.get(0).and_then(|opcode| WitnessVersion::from_opcode(opcodes::All::from(*opcode)).ok())
502+
self.0.get(0).and_then(|opcode| WitnessVersion::try_from(opcodes::All::from(*opcode)).ok())
502503
}
503504

504505
/// Checks whether a script pubkey is a P2SH output.
@@ -550,7 +551,7 @@ impl Script {
550551
}
551552
let ver_opcode = opcodes::All::from(self.0[0]); // Version 0 or PUSHNUM_1-PUSHNUM_16
552553
let push_opbyte = self.0[1]; // Second byte push opcode 2-40 bytes
553-
WitnessVersion::from_opcode(ver_opcode).is_ok()
554+
WitnessVersion::try_from(ver_opcode).is_ok()
554555
&& push_opbyte >= opcodes::all::OP_PUSHBYTES_2.to_u8()
555556
&& push_opbyte <= opcodes::all::OP_PUSHBYTES_40.to_u8()
556557
// Check that the rest of the script has the correct size

src/util/address.rs

Lines changed: 110 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
3535
use crate::prelude::*;
3636

37+
use core::convert::TryFrom;
3738
use core::fmt;
3839
use core::num::ParseIntError;
3940
use core::str::FromStr;
@@ -243,8 +244,8 @@ impl FromStr for WitnessVersion {
243244
type Err = Error;
244245

245246
fn from_str(s: &str) -> Result<Self, Self::Err> {
246-
let version = s.parse().map_err(Error::UnparsableWitnessVersion)?;
247-
WitnessVersion::from_num(version)
247+
let version: u8 = s.parse().map_err(Error::UnparsableWitnessVersion)?;
248+
WitnessVersion::try_from(version)
248249
}
249250
}
250251

@@ -258,8 +259,9 @@ impl WitnessVersion {
258259
/// # Errors
259260
/// If the integer does not correspond to any witness version, errors with
260261
/// [`Error::InvalidWitnessVersion`].
262+
#[deprecated(since = "0.29.0", note = "use try_from instead")]
261263
pub fn from_u5(value: ::bech32::u5) -> Result<Self, Error> {
262-
WitnessVersion::from_num(value.to_u8())
264+
Self::try_from(value)
263265
}
264266

265267
/// Converts an 8-bit unsigned integer value into [`WitnessVersion`] variant.
@@ -270,27 +272,9 @@ impl WitnessVersion {
270272
/// # Errors
271273
/// If the integer does not correspond to any witness version, errors with
272274
/// [`Error::InvalidWitnessVersion`].
275+
#[deprecated(since = "0.29.0", note = "use try_from instead")]
273276
pub fn from_num(no: u8) -> Result<Self, Error> {
274-
Ok(match no {
275-
0 => WitnessVersion::V0,
276-
1 => WitnessVersion::V1,
277-
2 => WitnessVersion::V2,
278-
3 => WitnessVersion::V3,
279-
4 => WitnessVersion::V4,
280-
5 => WitnessVersion::V5,
281-
6 => WitnessVersion::V6,
282-
7 => WitnessVersion::V7,
283-
8 => WitnessVersion::V8,
284-
9 => WitnessVersion::V9,
285-
10 => WitnessVersion::V10,
286-
11 => WitnessVersion::V11,
287-
12 => WitnessVersion::V12,
288-
13 => WitnessVersion::V13,
289-
14 => WitnessVersion::V14,
290-
15 => WitnessVersion::V15,
291-
16 => WitnessVersion::V16,
292-
wrong => return Err(Error::InvalidWitnessVersion(wrong)),
293-
})
277+
Self::try_from(no)
294278
}
295279

296280
/// Converts bitcoin script opcode into [`WitnessVersion`] variant.
@@ -301,13 +285,9 @@ impl WitnessVersion {
301285
/// # Errors
302286
/// If the opcode does not correspond to any witness version, errors with
303287
/// [`Error::MalformedWitnessVersion`].
288+
#[deprecated(since = "0.29.0", note = "use try_from instead")]
304289
pub fn from_opcode(opcode: opcodes::All) -> Result<Self, Error> {
305-
match opcode.to_u8() {
306-
0 => Ok(WitnessVersion::V0),
307-
version if version >= opcodes::all::OP_PUSHNUM_1.to_u8() && version <= opcodes::all::OP_PUSHNUM_16.to_u8() =>
308-
WitnessVersion::from_num(version - opcodes::all::OP_PUSHNUM_1.to_u8() + 1),
309-
_ => Err(Error::MalformedWitnessVersion)
310-
}
290+
Self::try_from(opcode)
311291
}
312292

313293
/// Converts bitcoin script [`Instruction`] (parsed opcode) into [`WitnessVersion`] variant.
@@ -319,12 +299,9 @@ impl WitnessVersion {
319299
/// # Errors
320300
/// If the opcode does not correspond to any witness version, errors with
321301
/// [`Error::MalformedWitnessVersion`] for the rest of opcodes.
302+
#[deprecated(since = "0.29.0", note = "use try_from instead")]
322303
pub fn from_instruction(instruction: Instruction) -> Result<Self, Error> {
323-
match instruction {
324-
Instruction::Op(op) => WitnessVersion::from_opcode(op),
325-
Instruction::PushBytes(bytes) if bytes.is_empty() => Ok(WitnessVersion::V0),
326-
Instruction::PushBytes(_) => Err(Error::MalformedWitnessVersion),
327-
}
304+
Self::try_from(instruction)
328305
}
329306

330307
/// Returns integer version number representation for a given [`WitnessVersion`] value.
@@ -355,6 +332,102 @@ impl WitnessVersion {
355332
}
356333
}
357334

335+
impl TryFrom<bech32::u5> for WitnessVersion {
336+
type Error = Error;
337+
338+
/// Converts 5-bit unsigned integer value matching single symbol from Bech32(m) address encoding
339+
/// ([`bech32::u5`]) into [`WitnessVersion`] variant.
340+
///
341+
/// # Returns
342+
/// Version of the Witness program.
343+
///
344+
/// # Errors
345+
/// If the integer does not correspond to any witness version, errors with
346+
/// [`Error::InvalidWitnessVersion`].
347+
fn try_from(value: bech32::u5) -> Result<Self, Self::Error> {
348+
Self::try_from(value.to_u8())
349+
}
350+
}
351+
352+
impl TryFrom<u8> for WitnessVersion {
353+
type Error = Error;
354+
355+
/// Converts an 8-bit unsigned integer value into [`WitnessVersion`] variant.
356+
///
357+
/// # Returns
358+
/// Version of the Witness program.
359+
///
360+
/// # Errors
361+
/// If the integer does not correspond to any witness version, errors with
362+
/// [`Error::InvalidWitnessVersion`].
363+
fn try_from(no: u8) -> Result<Self, Self::Error> {
364+
use WitnessVersion::*;
365+
366+
Ok(match no {
367+
0 => V0,
368+
1 => V1,
369+
2 => V2,
370+
3 => V3,
371+
4 => V4,
372+
5 => V5,
373+
6 => V6,
374+
7 => V7,
375+
8 => V8,
376+
9 => V9,
377+
10 => V10,
378+
11 => V11,
379+
12 => V12,
380+
13 => V13,
381+
14 => V14,
382+
15 => V15,
383+
16 => V16,
384+
wrong => return Err(Error::InvalidWitnessVersion(wrong)),
385+
})
386+
}
387+
}
388+
389+
impl TryFrom<opcodes::All> for WitnessVersion {
390+
type Error = Error;
391+
392+
/// Converts bitcoin script opcode into [`WitnessVersion`] variant.
393+
///
394+
/// # Returns
395+
/// Version of the Witness program (for opcodes in range of `OP_0`..`OP_16`).
396+
///
397+
/// # Errors
398+
/// If the opcode does not correspond to any witness version, errors with
399+
/// [`Error::MalformedWitnessVersion`].
400+
fn try_from(opcode: opcodes::All) -> Result<Self, Self::Error> {
401+
match opcode.to_u8() {
402+
0 => Ok(WitnessVersion::V0),
403+
version if version >= opcodes::all::OP_PUSHNUM_1.to_u8() && version <= opcodes::all::OP_PUSHNUM_16.to_u8() =>
404+
WitnessVersion::try_from(version - opcodes::all::OP_PUSHNUM_1.to_u8() + 1),
405+
_ => Err(Error::MalformedWitnessVersion)
406+
}
407+
}
408+
}
409+
410+
impl<'a> TryFrom<Instruction<'a>> for WitnessVersion {
411+
type Error = Error;
412+
413+
/// Converts bitcoin script [`Instruction`] (parsed opcode) into [`WitnessVersion`] variant.
414+
///
415+
/// # Returns
416+
/// Version of the Witness program for [`Instruction::Op`] and [`Instruction::PushBytes`] with
417+
/// byte value within `1..=16` range.
418+
///
419+
/// # Errors
420+
/// If the opcode does not correspond to any witness version, errors with
421+
/// [`Error::MalformedWitnessVersion`] for the rest of opcodes.
422+
fn try_from(instruction: Instruction) -> Result<Self, Self::Error> {
423+
match instruction {
424+
Instruction::Op(op) => WitnessVersion::try_from(op),
425+
Instruction::PushBytes(bytes) if bytes.is_empty() => Ok(WitnessVersion::V0),
426+
Instruction::PushBytes(_) => Err(Error::MalformedWitnessVersion),
427+
}
428+
}
429+
}
430+
358431
impl From<WitnessVersion> for ::bech32::u5 {
359432
/// Converts [`WitnessVersion`] instance into corresponding Bech32(m) u5-value ([`bech32::u5`]).
360433
fn from(version: WitnessVersion) -> Self {
@@ -405,7 +478,7 @@ impl Payload {
405478
}
406479

407480
Payload::WitnessProgram {
408-
version: WitnessVersion::from_opcode(opcodes::All::from(script[0]))?,
481+
version: WitnessVersion::try_from(opcodes::All::from(script[0]))?,
409482
program: script[2..].to_vec(),
410483
}
411484
} else {
@@ -856,7 +929,7 @@ impl FromStr for Address {
856929
// Get the script version and program (converted from 5-bit to 8-bit)
857930
let (version, program): (WitnessVersion, Vec<u8>) = {
858931
let (v, p5) = payload.split_at(1);
859-
(WitnessVersion::from_u5(v[0])?, bech32::FromBase32::from_base32(p5)?)
932+
(WitnessVersion::try_from(v[0])?, bech32::FromBase32::from_base32(p5)?)
860933
};
861934

862935
if program.len() < 2 || program.len() > 40 {
@@ -1277,7 +1350,7 @@ mod tests {
12771350
];
12781351
let segwit_payload = (0..=16).map(|version| {
12791352
Payload::WitnessProgram {
1280-
version: WitnessVersion::from_num(version).unwrap(),
1353+
version: WitnessVersion::try_from(version).unwrap(),
12811354
program: vec![]
12821355
}
12831356
}).collect::<Vec<_>>();

0 commit comments

Comments
 (0)