1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
// Copyright Judica, Inc 2021
//
// This Source Code Form is subject to the terms of the Mozilla Public
//  License, v. 2.0. If a copy of the MPL was not distributed with this
//  file, You can obtain one at https://mozilla.org/MPL/2.0/.

use super::Clause;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::convert::TryFrom;
use std::convert::TryInto;
use std::default::Default;
use std::fmt;
use std::marker::PhantomData;
use std::time::Duration;
#[derive(Debug)]
pub enum LockTimeError {
    DurationTooLong(Duration),
    TimeTooFarInPast(Duration),
    HeightTooHigh(u32),
    UnknownSeqType(u32),
}

/// Type Tags used for creating lock time variants. The module lets us keep them
/// public while not polluting the name space.
pub mod type_tags {
    pub trait Absolutivity {
        const IS_ABSOLUTE: bool;
    }
    pub trait TimeType {
        const IS_HEIGHT: bool;
    }
    use super::*;
    #[derive(JsonSchema, Serialize, Deserialize, Copy, Clone, PartialOrd, Ord, Eq, PartialEq)]
    pub struct Rel;
    #[derive(JsonSchema, Serialize, Deserialize, Copy, Clone, PartialOrd, Ord, Eq, PartialEq)]
    pub struct Abs;
    #[derive(JsonSchema, Serialize, Deserialize, Copy, Clone, PartialOrd, Ord, Eq, PartialEq)]
    pub struct Height;
    #[derive(JsonSchema, Serialize, Deserialize, Copy, Clone, PartialOrd, Ord, Eq, PartialEq)]
    pub struct MTP;
}
use type_tags::*;

/// LockTime represents either a nLockTime or a Sequence field.
/// They are represented generically in the same type
#[derive(JsonSchema, Serialize, Deserialize, Copy, Clone, PartialOrd, Ord, Eq, PartialEq)]
#[serde(transparent)]
pub struct LockTime<RelOrAbs: Absolutivity, HeightOrTime: TimeType>(
    u32,
    #[serde(skip)] PhantomData<(RelOrAbs, HeightOrTime)>,
);
/// Represents a type which can be either type of relative lock
#[derive(JsonSchema, Serialize, Deserialize, Copy, Clone, PartialOrd, Ord, Eq, PartialEq)]
pub enum AnyRelTimeLock {
    RH(RelHeight),
    RT(RelTime),
}

/// Represents a type which can be either type of absolute lock
#[derive(JsonSchema, Serialize, Deserialize, Copy, Clone, PartialOrd, Ord, Eq, PartialEq)]
pub enum AnyAbsTimeLock {
    AH(AbsHeight),
    AT(AbsTime),
}
/// Represents a type which can be any type of lock
#[derive(JsonSchema, Serialize, Deserialize, Copy, Clone)]
pub enum AnyTimeLock {
    R(AnyRelTimeLock),
    A(AnyAbsTimeLock),
}

/// Helpful Aliases for specific concrete lock times
mod alias {
    use super::*;
    pub type RelHeight = LockTime<Rel, Height>;
    pub type RelTime = LockTime<Rel, MTP>;
    pub type AbsHeight = LockTime<Abs, Height>;
    pub type AbsTime = LockTime<Abs, MTP>;
}
pub use alias::*;

mod trait_impls {
    use super::*;
    impl Absolutivity for Rel {
        const IS_ABSOLUTE: bool = false;
    }
    impl Absolutivity for Abs {
        const IS_ABSOLUTE: bool = true;
    }
    impl TimeType for Height {
        const IS_HEIGHT: bool = true;
    }
    impl TimeType for MTP {
        const IS_HEIGHT: bool = false;
    }

    impl<A, TT> LockTime<A, TT>
    where
        A: Absolutivity,
        TT: TimeType,
    {
        pub fn get(&self) -> u32 {
            self.0
        }
    }
    impl AnyRelTimeLock {
        pub fn get(&self) -> u32 {
            match self {
                AnyRelTimeLock::RH(u) => u.get(),
                AnyRelTimeLock::RT(u) => u.get(),
            }
        }
    }

    impl AnyAbsTimeLock {
        pub fn get(&self) -> u32 {
            match self {
                AnyAbsTimeLock::AH(u) => u.get(),
                AnyAbsTimeLock::AT(u) => u.get(),
            }
        }
    }

    impl AnyTimeLock {
        pub fn get(&self) -> u32 {
            match self {
                AnyTimeLock::A(u) => u.get(),
                AnyTimeLock::R(u) => u.get(),
            }
        }
    }

    impl<A, TT> From<LockTime<A, TT>> for Clause
    where
        A: Absolutivity,
        TT: TimeType,
    {
        fn from(lt: LockTime<A, TT>) -> Clause {
            match (A::IS_ABSOLUTE, TT::IS_HEIGHT) {
                (true, true) => Clause::After(lt.0),
                (true, false) => Clause::After(lt.0),
                (false, true) => Clause::Older(lt.0),
                (false, false) => Clause::Older(lt.0),
            }
        }
    }

    impl fmt::Display for LockTimeError {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "{:?}", self)
        }
    }
    impl std::error::Error for LockTimeError {}

    impl TryFrom<u32> for AbsTime {
        type Error = LockTimeError;
        fn try_from(u: u32) -> Result<Self, Self::Error> {
            Ok(Self(u, Default::default()))
        }
    }
    impl TryFrom<u32> for AbsHeight {
        type Error = LockTimeError;
        fn try_from(u: u32) -> Result<Self, Self::Error> {
            if u < 500_000_000 {
                Ok(Self(u, Default::default()))
            } else {
                Err(LockTimeError::HeightTooHigh(u))
            }
        }
    }
    impl From<u16> for RelTime {
        fn from(u: u16) -> Self {
            Self((u as u32) | (1 << 22), Default::default())
        }
    }
    impl From<u16> for RelHeight {
        fn from(u: u16) -> Self {
            Self((u as u32) | (1 << 22), Default::default())
        }
    }

    impl TryFrom<Duration> for RelTime {
        type Error = LockTimeError;
        fn try_from(u: Duration) -> Result<Self, Self::Error> {
            let windows = u.as_secs() / 512;
            if windows > u16::MAX as u64 {
                Err(LockTimeError::DurationTooLong(u))
            } else {
                Ok((windows as u16).into())
            }
        }
    }

    impl TryFrom<Duration> for AbsTime {
        type Error = LockTimeError;
        fn try_from(u: Duration) -> Result<Self, Self::Error> {
            let t = u.as_secs();
            if t < 500_000_000 {
                Err(LockTimeError::TimeTooFarInPast(u))
            } else if t > u32::MAX as u64 {
                Err(LockTimeError::DurationTooLong(u))
            } else {
                (t as u32).try_into()
            }
        }
    }

    impl From<AnyRelTimeLock> for Clause {
        fn from(lt: AnyRelTimeLock) -> Self {
            match lt {
                AnyRelTimeLock::RH(a) => a.into(),
                AnyRelTimeLock::RT(a) => a.into(),
            }
        }
    }
    impl From<AnyAbsTimeLock> for Clause {
        fn from(lt: AnyAbsTimeLock) -> Self {
            match lt {
                AnyAbsTimeLock::AH(a) => a.into(),
                AnyAbsTimeLock::AT(a) => a.into(),
            }
        }
    }
    impl From<AnyTimeLock> for Clause {
        fn from(lt: AnyTimeLock) -> Self {
            match lt {
                AnyTimeLock::A(a) => a.into(),
                AnyTimeLock::R(a) => a.into(),
            }
        }
    }

    impl From<RelTime> for AnyRelTimeLock {
        fn from(lt: RelTime) -> Self {
            AnyRelTimeLock::RT(lt)
        }
    }
    impl From<AbsHeight> for AnyAbsTimeLock {
        fn from(lt: AbsHeight) -> Self {
            AnyAbsTimeLock::AH(lt)
        }
    }
    impl From<AbsTime> for AnyAbsTimeLock {
        fn from(lt: AbsTime) -> Self {
            AnyAbsTimeLock::AT(lt)
        }
    }

    impl From<RelHeight> for AnyRelTimeLock {
        fn from(lt: RelHeight) -> Self {
            AnyRelTimeLock::RH(lt)
        }
    }

    impl From<AnyAbsTimeLock> for AnyTimeLock {
        fn from(lt: AnyAbsTimeLock) -> Self {
            AnyTimeLock::A(lt)
        }
    }
    impl From<AnyRelTimeLock> for AnyTimeLock {
        fn from(lt: AnyRelTimeLock) -> Self {
            AnyTimeLock::R(lt)
        }
    }
}