1 | <?php |
||
5 | class Locktime |
||
6 | { |
||
7 | const INT_MAX = 0xffffffff; |
||
8 | |||
9 | /** |
||
10 | * Maximum block height that can be used in locktime, as beyond |
||
11 | * this is reserved for timestamp locktimes |
||
12 | */ |
||
13 | const BLOCK_MAX = 500000000; |
||
14 | |||
15 | /** |
||
16 | * Maximum timestamp that can be encoded in locktime |
||
17 | * (TIME_MAX + BLOCK_MAX = INT_MAX) |
||
18 | */ |
||
19 | const TIME_MAX = self::INT_MAX - self::BLOCK_MAX; |
||
20 | |||
21 | /** |
||
22 | * Convert a $timestamp to a locktime. |
||
23 | * Max timestamp is 3794967296 - 04/04/2090 @ 5:34am (UTC) |
||
24 | * |
||
25 | * @param int $timestamp |
||
26 | * @return int |
||
27 | * @throws \Exception |
||
28 | */ |
||
29 | 9 | public function fromTimestamp($timestamp) |
|
30 | { |
||
31 | 9 | if ($timestamp > self::TIME_MAX) { |
|
32 | 3 | throw new \Exception('Timestamp out of range'); |
|
33 | } |
||
34 | |||
35 | 9 | $locktime = self::BLOCK_MAX + $timestamp; |
|
36 | 9 | return $locktime; |
|
37 | } |
||
38 | |||
39 | /** |
||
40 | * Convert a lock time to the timestamp it's locked to. |
||
41 | * Throws an exception when: |
||
42 | * - Lock time appears to be in the block locktime range ( < Locktime::BLOCK_MAX ) |
||
43 | * - When the lock time exceeds the max possible lock time ( > Locktime::INT_MAX ) |
||
44 | * |
||
45 | * @param int $lockTime |
||
46 | * @return int |
||
47 | * @throws \Exception |
||
48 | */ |
||
49 | 9 | public function toTimestamp($lockTime) |
|
50 | { |
||
51 | 9 | if ($lockTime <= self::BLOCK_MAX) { |
|
52 | 3 | throw new \Exception('Lock time out of range for timestamp'); |
|
53 | } |
||
54 | |||
55 | 6 | if ($lockTime > self::INT_MAX) { |
|
56 | 3 | throw new \Exception('Lock time too large'); |
|
57 | } |
||
58 | |||
59 | 6 | $timestamp = $lockTime - self::BLOCK_MAX; |
|
60 | 6 | return $timestamp; |
|
61 | } |
||
62 | |||
63 | /** |
||
64 | * Convert $blockHeight to lock time. Doesn't convert anything really, |
||
65 | * but does check the bounds of the given block height. |
||
66 | * |
||
67 | * @param int $blockHeight |
||
68 | * @return int |
||
69 | * @throws \Exception |
||
70 | */ |
||
71 | 9 | public function fromBlockHeight($blockHeight) |
|
79 | |||
80 | /** |
||
81 | * Convert locktime to block height tx is locked to. Doesn't convert anything |
||
82 | * really, but does check the bounds of the supplied locktime. |
||
83 | * |
||
84 | * @param int $lockTime |
||
85 | * @return int |
||
86 | * @throws \Exception |
||
87 | */ |
||
88 | 6 | public function toBlockHeight($lockTime) |
|
96 | } |
||
97 |