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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
//! Versionbits 9 defines a finite-state-machine to deploy a softfork in multiple stages.
//!

mod convert;

use crate::consensus::Consensus;
use ckb_types::{
    core::{EpochExt, EpochNumber, HeaderView, Ratio, TransactionView, Version},
    packed::{Byte32, CellbaseWitnessReader},
    prelude::*,
};
use ckb_util::Mutex;
use std::collections::{hash_map, HashMap};
use std::sync::Arc;

/// What bits to set in version for versionbits blocks
pub const VERSIONBITS_TOP_BITS: Version = 0x00000000;
/// What bitmask determines whether versionbits is in use
pub const VERSIONBITS_TOP_MASK: Version = 0xE0000000;
/// Total bits available for versionbits
pub const VERSIONBITS_NUM_BITS: u32 = 29;

/// RFC0043 defines a finite-state-machine to deploy a soft fork in multiple stages.
/// State transitions happen during epoch if conditions are met
/// In case of reorg, transitions can go backward. Without transition, state is
/// inherited between epochs. All blocks of a epoch share the same state.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum ThresholdState {
    /// First state that each softfork starts.
    /// The 0 epoch is by definition in this state for each deployment.
    Defined,
    /// For epochs past the `start` epoch.
    Started,
    /// For one epoch after the first epoch period with STARTED epochs of
    /// which at least `threshold` has the associated bit set in `version`.
    LockedIn,
    /// For all epochs after the LOCKED_IN epoch.
    Active,
    /// For one epoch period past the `timeout_epoch`, if LOCKED_IN was not reached.
    Failed,
}

/// This is useful for testing, as it means tests don't need to deal with the activation
/// process. Only tests that specifically test the behaviour during activation cannot use this.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum ActiveMode {
    /// Indicating that the deployment is normal active.
    Normal,
    /// Indicating that the deployment is always active.
    /// This is useful for testing, as it means tests don't need to deal with the activation
    Always,
    /// Indicating that the deployment is never active.
    /// This is useful for testing.
    Never,
}

/// Soft fork deployment
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
pub enum DeploymentPos {
    /// Dummy
    Testdummy,
    /// light client protocol
    LightClient,
}

/// VersionbitsIndexer
pub trait VersionbitsIndexer {
    /// Gets epoch index by block hash
    fn block_epoch_index(&self, block_hash: &Byte32) -> Option<Byte32>;
    /// Gets epoch ext by index
    fn epoch_ext(&self, index: &Byte32) -> Option<EpochExt>;
    /// Gets block header by block hash
    fn block_header(&self, block_hash: &Byte32) -> Option<HeaderView>;
    /// Gets cellbase by block hash
    fn cellbase(&self, block_hash: &Byte32) -> Option<TransactionView>;
    /// Gets ancestor of specified epoch.
    fn ancestor_epoch(&self, index: &Byte32, target: EpochNumber) -> Option<EpochExt> {
        let mut epoch_ext = self.epoch_ext(index)?;

        if epoch_ext.number() < target {
            return None;
        }
        while epoch_ext.number() > target {
            let last_block_header_in_previous_epoch =
                self.block_header(&epoch_ext.last_block_hash_in_previous_epoch())?;
            let previous_epoch_index =
                self.block_epoch_index(&last_block_header_in_previous_epoch.hash())?;
            epoch_ext = self.epoch_ext(&previous_epoch_index)?;
        }
        Some(epoch_ext)
    }
}

///Struct for each individual consensus rule change using soft fork.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Deployment {
    /// Determines which bit in the `version` field of the block is to be used to signal the softfork lock-in and activation.
    /// It is chosen from the set {0,1,2,...,28}.
    pub bit: u8,
    /// Specifies the first epoch in which the bit gains meaning.
    pub start: EpochNumber,
    /// Specifies an epoch at which the miner signaling ends.
    /// Once this epoch has been reached, if the softfork has not yet locked_in (excluding this epoch block's bit state),
    /// the deployment is considered failed on all descendants of the block.
    pub timeout: EpochNumber,
    /// Specifies the epoch at which the softfork is allowed to become active.
    pub min_activation_epoch: EpochNumber,
    /// Specifies length of epochs of the signalling period.
    pub period: EpochNumber,
    /// This is useful for testing, as it means tests don't need to deal with the activation process
    pub active_mode: ActiveMode,
    /// Specifies the minimum ratio of block per `period`,
    /// which indicate the locked_in of the softfork during the `period`.
    pub threshold: Ratio,
}

type Cache = Mutex<HashMap<Byte32, ThresholdState>>;

/// RFC0000 allows multiple soft forks to be deployed in parallel. We cache
/// per-epoch state for every one of them. */
#[derive(Clone, Debug, Default)]
pub struct VersionbitsCache {
    caches: Arc<HashMap<DeploymentPos, Cache>>,
}

impl VersionbitsCache {
    /// Construct new VersionbitsCache instance from deployments
    pub fn new<'a>(deployments: impl Iterator<Item = &'a DeploymentPos>) -> Self {
        let caches: HashMap<_, _> = deployments
            .map(|pos| (*pos, Mutex::new(HashMap::new())))
            .collect();
        VersionbitsCache {
            caches: Arc::new(caches),
        }
    }

    /// Returns a reference to the cache corresponding to the deployment.
    pub fn cache(&self, pos: &DeploymentPos) -> Option<&Cache> {
        self.caches.get(pos)
    }
}

/// Struct Implements versionbits threshold logic, and caches results.
pub struct Versionbits<'a> {
    id: DeploymentPos,
    consensus: &'a Consensus,
}

/// Trait that implements versionbits threshold logic, and caches results.
pub trait VersionbitsConditionChecker {
    /// Specifies the first epoch in which the bit gains meaning.
    fn start(&self) -> EpochNumber;
    /// Specifies an epoch at which the miner signaling ends.
    /// Once this epoch has been reached,
    /// if the softfork has not yet locked_in (excluding this epoch block's bit state),
    /// the deployment is considered failed on all descendants of the block.
    fn timeout(&self) -> EpochNumber;
    /// Active mode for testing.
    fn active_mode(&self) -> ActiveMode;
    // fn condition(&self, header: &HeaderView) -> bool;
    /// Determines whether bit in the `version` field of the block is to be used to signal
    fn condition<I: VersionbitsIndexer>(&self, header: &HeaderView, indexer: &I) -> bool;
    /// Specifies the epoch at which the softfork is allowed to become active.
    fn min_activation_epoch(&self) -> EpochNumber;
    /// The period for signal statistics are counted
    fn period(&self) -> EpochNumber;
    /// Specifies the minimum ratio of block per epoch,
    /// which indicate the locked_in of the softfork during the epoch.
    fn threshold(&self) -> Ratio;
    /// Returns the state for a header. Applies any state transition if conditions are present.
    /// Caches state from first block of period.
    fn get_state<I: VersionbitsIndexer>(
        &self,
        header: &HeaderView,
        cache: &Cache,
        indexer: &I,
    ) -> Option<ThresholdState> {
        let active_mode = self.active_mode();
        let start = self.start();
        let timeout = self.timeout();
        let period = self.period();
        let min_activation_epoch = self.min_activation_epoch();

        if active_mode == ActiveMode::Always {
            return Some(ThresholdState::Active);
        }

        if active_mode == ActiveMode::Never {
            return Some(ThresholdState::Failed);
        }

        let start_index = indexer.block_epoch_index(&header.hash())?;
        let epoch_number = header.epoch().number();
        let target = epoch_number.saturating_sub((epoch_number + 1) % period);

        let mut epoch_ext = indexer.ancestor_epoch(&start_index, target)?;
        let mut g_cache = cache.lock();
        let mut to_compute = Vec::new();
        let mut state = loop {
            let epoch_index = epoch_ext.last_block_hash_in_previous_epoch();
            match g_cache.entry(epoch_index.clone()) {
                hash_map::Entry::Occupied(entry) => {
                    break *entry.get();
                }
                hash_map::Entry::Vacant(entry) => {
                    // The genesis is by definition defined.
                    if epoch_ext.is_genesis() || epoch_ext.number() < start {
                        entry.insert(ThresholdState::Defined);
                        break ThresholdState::Defined;
                    }
                    let next_epoch_ext = indexer
                        .ancestor_epoch(&epoch_index, epoch_ext.number().saturating_sub(period))?;
                    to_compute.push(epoch_ext);
                    epoch_ext = next_epoch_ext;
                }
            }
        };

        while let Some(epoch_ext) = to_compute.pop() {
            let mut next_state = state;

            match state {
                ThresholdState::Defined => {
                    if epoch_ext.number() >= start {
                        next_state = ThresholdState::Started;
                    }
                }
                ThresholdState::Started => {
                    // We need to count
                    debug_assert!(epoch_ext.number() + 1 >= period);

                    let mut count = 0;
                    let mut total = 0;
                    let mut header =
                        indexer.block_header(&epoch_ext.last_block_hash_in_previous_epoch())?;

                    let mut current_epoch_ext = epoch_ext.clone();
                    for _ in 0..period {
                        let current_epoch_length = current_epoch_ext.length();
                        total += current_epoch_length;
                        for _ in 0..current_epoch_length {
                            if self.condition(&header, indexer) {
                                count += 1;
                            }
                            header = indexer.block_header(&header.parent_hash())?;
                        }
                        let last_block_header_in_previous_epoch = indexer
                            .block_header(&current_epoch_ext.last_block_hash_in_previous_epoch())?;
                        let previous_epoch_index = indexer
                            .block_epoch_index(&last_block_header_in_previous_epoch.hash())?;
                        current_epoch_ext = indexer.epoch_ext(&previous_epoch_index)?;
                    }

                    let threshold_number = threshold_number(total, self.threshold())?;
                    if count >= threshold_number {
                        next_state = ThresholdState::LockedIn;
                    } else if epoch_ext.number() >= timeout {
                        next_state = ThresholdState::Failed;
                    }
                }
                ThresholdState::LockedIn => {
                    if epoch_ext.number() >= min_activation_epoch {
                        next_state = ThresholdState::Active;
                    }
                }
                ThresholdState::Failed | ThresholdState::Active => {
                    // Nothing happens, these are terminal states.
                }
            }
            state = next_state;
            g_cache.insert(epoch_ext.last_block_hash_in_previous_epoch(), state);
        }

        Some(state)
    }
}

impl<'a> Versionbits<'a> {
    /// construct new Versionbits wrapper
    pub fn new(id: DeploymentPos, consensus: &'a Consensus) -> Self {
        Versionbits { id, consensus }
    }

    fn deployment(&self) -> &Deployment {
        &self.consensus.deployments[&self.id]
    }

    /// return bit mask corresponding deployment
    pub fn mask(&self) -> u32 {
        1u32 << self.deployment().bit as u32
    }
}

impl<'a> VersionbitsConditionChecker for Versionbits<'a> {
    fn start(&self) -> EpochNumber {
        self.deployment().start
    }

    fn timeout(&self) -> EpochNumber {
        self.deployment().timeout
    }

    fn period(&self) -> EpochNumber {
        self.deployment().period
    }

    fn condition<I: VersionbitsIndexer>(&self, header: &HeaderView, indexer: &I) -> bool {
        if let Some(cellbase) = indexer.cellbase(&header.hash()) {
            if let Some(witness) = cellbase.witnesses().get(0) {
                if let Ok(reader) = CellbaseWitnessReader::from_slice(&witness.raw_data()) {
                    let message = reader.message().to_entity();
                    if message.len() >= 4 {
                        if let Ok(raw) = message.raw_data()[..4].try_into() {
                            let version = u32::from_le_bytes(raw);
                            return ((version & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS)
                                && (version & self.mask()) != 0;
                        }
                    }
                }
            }
        }
        false
    }

    // fn condition(&self, header: &HeaderView) -> bool {
    //     let version = header.version();
    //     (((version & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) && (version & self.mask()) != 0)
    // }

    fn min_activation_epoch(&self) -> EpochNumber {
        self.deployment().min_activation_epoch
    }

    fn active_mode(&self) -> ActiveMode {
        self.deployment().active_mode
    }

    fn threshold(&self) -> Ratio {
        self.deployment().threshold
    }
}

fn threshold_number(length: u64, threshold: Ratio) -> Option<u64> {
    length
        .checked_mul(threshold.numer())
        .and_then(|ret| ret.checked_div(threshold.denom()))
}