Skip to content

Instantly share code, notes, and snippets.

@alexbosworth
Created February 21, 2017 17:53
Show Gist options
  • Save alexbosworth/686dd5a5a15c4231c1527f45bf7c7176 to your computer and use it in GitHub Desktop.
Save alexbosworth/686dd5a5a15c4231c1527f45bf7c7176 to your computer and use it in GitHub Desktop.
import Foundation
/** Can be included after this time marker
*/
enum Locktime {
case date(Date)
case height(Int)
/** Number of bytes
*/
static let byteCount = 4
/** Get the earliest possible lock time
*/
static let genesis = Locktime.height(Int())
/** Determine if a value refers to a block height
*/
private static func isBlockHeight(value: Int) -> Bool {
return value < maximalHeight
}
/** Height before which locktime values are treated as block heights
*/
private static let maximalHeight = 500_000_000
// MARK: - Init
/** Create from little endian encoded data
*/
init(from data: Data) {
self.init(from: Int(UInt32(fromLittleEndian: data)))
}
/** Create from raw value
*/
init(from value: Int) {
switch type(of: self).isBlockHeight(value: value) {
case false:
self = .date(Date(timeIntervalSince1970: TimeInterval(value)))
case true:
self = .height(value)
}
}
}
// MARK: - UInt32
extension Locktime {
/** Determine the serialized uint32 value
*/
var asSerializedUint32: UInt32 {
switch self {
case .date(let date):
return UInt32(date.timeIntervalSince1970)
case .height(let height):
return UInt32(height)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment