use crate::consensus::{self, CanonicalBytes};
use std::fmt::Debug;
use std::str::FromStr;
#[derive(PartialEq, Eq, PartialOrd, Clone, Debug, Hash, Copy, Display, Serialize, Deserialize)]
#[display("{0} blocks")]
pub struct CSVTimelock(u32);
impl FromStr for CSVTimelock {
type Err = consensus::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let x = s
.parse::<u32>()
.map_err(|_| consensus::Error::ParseFailed("Failed parsing CSV timelock"))?;
Ok(CSVTimelock(x))
}
}
impl CSVTimelock {
pub fn new(timelock: u32) -> Self {
Self(timelock)
}
pub fn as_u32(&self) -> u32 {
self.0
}
pub fn disable() -> u32 {
(1 << 31) as u32
}
}
impl From<u32> for CSVTimelock {
fn from(u: u32) -> Self {
Self::new(u)
}
}
impl From<CSVTimelock> for u32 {
fn from(ti: CSVTimelock) -> Self {
ti.as_u32()
}
}
impl From<u16> for CSVTimelock {
fn from(u: u16) -> Self {
Self::new(u as u32)
}
}
impl From<u8> for CSVTimelock {
fn from(u: u8) -> Self {
Self::new(u as u32)
}
}
impl CanonicalBytes for CSVTimelock {
fn as_canonical_bytes(&self) -> Vec<u8> {
bitcoin::consensus::encode::serialize(&self.0)
}
fn from_canonical_bytes(bytes: &[u8]) -> Result<Self, consensus::Error>
where
Self: Sized,
{
Ok(CSVTimelock(
bitcoin::consensus::encode::deserialize(bytes).map_err(consensus::Error::new)?,
))
}
}