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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
//! The traits defined here is intent to describe the requirements of current
//!  library code and only implemented the trait in upper level code.

pub mod default_impls;
pub mod dummy_impls;
pub mod offchain_impls;

pub use default_impls::{
    DefaultCellCollector, DefaultCellDepResolver, DefaultHeaderDepResolver,
    DefaultTransactionDependencyProvider, SecpCkbRawKeySigner,
};
pub use offchain_impls::{
    OffchainCellCollector, OffchainCellDepResolver, OffchainHeaderDepResolver,
    OffchainTransactionDependencyProvider,
};

use thiserror::Error;

use ckb_hash::blake2b_256;
use ckb_traits::{BlockEpoch, CellDataProvider, EpochProvider, HeaderProvider};
use ckb_types::{
    bytes::Bytes,
    core::{
        cell::{CellMetaBuilder, CellProvider, CellStatus, HeaderChecker},
        error::OutPointError,
        EpochExt, HeaderView, TransactionView,
    },
    packed::{Byte32, CellDep, CellOutput, OutPoint, Script, Transaction},
    prelude::*,
};

use crate::util::is_mature;

/// Signer errors
#[derive(Error, Debug)]
pub enum SignerError {
    #[error("the id is not found in the signer")]
    IdNotFound,

    #[error("invalid message, reason: `{0}`")]
    InvalidMessage(String),

    #[error("invalid transaction, reason: `{0}`")]
    InvalidTransaction(String),

    // maybe hardware wallet error or io error
    #[error("other error: `{0}`")]
    Other(#[from] Box<dyn std::error::Error>),
}

/// A signer abstraction, support signer type:
///    * secp256k1 ckb signer
///    * secp256k1 eth signer
///    * RSA signer
///    * Hardware wallet signer
pub trait Signer {
    /// typecial id are blake160(pubkey) and keccak256(pubkey)[12..20]
    fn match_id(&self, id: &[u8]) -> bool;

    /// `message` type is variable length, because different algorithm have
    /// different length of message:
    ///   * secp256k1 => 256bits
    ///   * RSA       => 512bits (when key size is 1024bits)
    fn sign(
        &self,
        id: &[u8],
        message: &[u8],
        recoverable: bool,
        tx: &TransactionView,
    ) -> Result<Bytes, SignerError>;
}

/// Transaction dependency provider errors
#[derive(Error, Debug)]
pub enum TransactionDependencyError {
    #[error("the resource is not found in the provider: `{0}`")]
    NotFound(String),

    #[error("other error: `{0}`")]
    Other(#[from] Box<dyn std::error::Error>),
}

/// Provider dependency information of a transaction:
///   * inputs
///   * cell_deps
///   * header_deps
pub trait TransactionDependencyProvider {
    // For verify certain cell belong to certain transaction
    fn get_transaction(
        &self,
        tx_hash: &Byte32,
    ) -> Result<TransactionView, TransactionDependencyError>;
    // For get the output information of inputs or cell_deps, those cell should be live cell
    fn get_cell(&self, out_point: &OutPoint) -> Result<CellOutput, TransactionDependencyError>;
    // For get the output data information of inputs or cell_deps
    fn get_cell_data(&self, out_point: &OutPoint) -> Result<Bytes, TransactionDependencyError>;
    // For get the header information of header_deps
    fn get_header(&self, block_hash: &Byte32) -> Result<HeaderView, TransactionDependencyError>;
}

// Implement CellDataProvider trait is currently for `DaoCalculator`
impl CellDataProvider for &dyn TransactionDependencyProvider {
    fn get_cell_data(&self, out_point: &OutPoint) -> Option<Bytes> {
        TransactionDependencyProvider::get_cell_data(*self, out_point).ok()
    }
    fn get_cell_data_hash(&self, out_point: &OutPoint) -> Option<Byte32> {
        TransactionDependencyProvider::get_cell_data(*self, out_point)
            .ok()
            .map(|data| blake2b_256(data.as_ref()).pack())
    }
}
// Implement CellDataProvider trait is currently for `DaoCalculator`
impl EpochProvider for &dyn TransactionDependencyProvider {
    fn get_epoch_ext(&self, _block_header: &HeaderView) -> Option<EpochExt> {
        None
    }
    fn get_block_epoch(&self, _block_header: &HeaderView) -> Option<BlockEpoch> {
        None
    }
}
// Implement CellDataProvider trait is currently for `DaoCalculator`
impl HeaderProvider for &dyn TransactionDependencyProvider {
    fn get_header(&self, hash: &Byte32) -> Option<HeaderView> {
        TransactionDependencyProvider::get_header(*self, hash).ok()
    }
}
impl HeaderChecker for &dyn TransactionDependencyProvider {
    fn check_valid(&self, block_hash: &Byte32) -> Result<(), OutPointError> {
        TransactionDependencyProvider::get_header(*self, block_hash)
            .map(|_| ())
            .map_err(|_| OutPointError::InvalidHeader(block_hash.clone()))
    }
}
impl CellProvider for &dyn TransactionDependencyProvider {
    fn cell(&self, out_point: &OutPoint, _eager_load: bool) -> CellStatus {
        match self.get_transaction(&out_point.tx_hash()) {
            Ok(tx) => tx
                .outputs()
                .get(out_point.index().unpack())
                .map(|cell| {
                    let data = tx
                        .outputs_data()
                        .get(out_point.index().unpack())
                        .expect("output data");

                    let cell_meta = CellMetaBuilder::from_cell_output(cell, data.unpack())
                        .out_point(out_point.to_owned())
                        .build();

                    CellStatus::live_cell(cell_meta)
                })
                .unwrap_or(CellStatus::Unknown),
            Err(_err) => CellStatus::Unknown,
        }
    }
}

/// Cell collector errors
#[derive(Error, Debug)]
pub enum CellCollectorError {
    #[error("internal error: `{0}`")]
    Internal(Box<dyn std::error::Error>),

    #[error("other error: `{0}`")]
    Other(Box<dyn std::error::Error>),
}

#[derive(Debug, Clone)]
pub struct LiveCell {
    pub output: CellOutput,
    pub output_data: Bytes,
    pub out_point: OutPoint,
    pub block_number: u64,
    pub tx_index: u32,
}

/// The value range option: `start <= value < end`
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct ValueRangeOption {
    pub start: u64,
    pub end: u64,
}
impl ValueRangeOption {
    pub fn new(start: u64, end: u64) -> ValueRangeOption {
        ValueRangeOption { start, end }
    }
    pub fn new_exact(value: u64) -> ValueRangeOption {
        ValueRangeOption {
            start: value,
            end: value + 1,
        }
    }
    pub fn new_min(start: u64) -> ValueRangeOption {
        ValueRangeOption {
            start,
            end: u64::max_value(),
        }
    }
    pub fn match_value(&self, value: u64) -> bool {
        self.start <= value && value < self.end
    }
}

/// The primary serach script type
///   * if primary script type is `lock` then secondary script type is `type`
///   * if primary script type is `type` then secondary script type is `lock`
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum PrimaryScriptType {
    Lock,
    Type,
}

#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum MaturityOption {
    Mature,
    Immature,
    Both,
}
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum QueryOrder {
    Desc,
    Asc,
}

#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct CellQueryOptions {
    pub primary_script: Script,
    pub primary_type: PrimaryScriptType,
    pub secondary_script: Option<Script>,
    pub data_len_range: Option<ValueRangeOption>,
    pub capacity_range: Option<ValueRangeOption>,
    pub block_range: Option<ValueRangeOption>,

    pub order: QueryOrder,
    pub limit: Option<u32>,
    /// Filter cell by its maturity
    pub maturity: MaturityOption,
    /// Try to collect at least `min_total_capacity` shannons of cells, if
    /// satisfied will stop collecting. The default value is 1 shannon means
    /// collect only one cell at most.
    pub min_total_capacity: u64,
}
impl CellQueryOptions {
    pub fn new(primary_script: Script, primary_type: PrimaryScriptType) -> CellQueryOptions {
        CellQueryOptions {
            primary_script,
            primary_type,
            secondary_script: None,
            data_len_range: None,
            capacity_range: None,
            block_range: None,
            limit: None,
            order: QueryOrder::Asc,
            maturity: MaturityOption::Mature,
            min_total_capacity: 1,
        }
    }
    pub fn new_lock(primary_script: Script) -> CellQueryOptions {
        CellQueryOptions::new(primary_script, PrimaryScriptType::Lock)
    }
    pub fn new_type(primary_script: Script) -> CellQueryOptions {
        CellQueryOptions::new(primary_script, PrimaryScriptType::Type)
    }
    pub fn match_cell(&self, cell: &LiveCell, max_mature_number: u64) -> bool {
        fn extract_raw_data(script: &Script) -> Vec<u8> {
            [
                script.code_hash().as_slice(),
                script.hash_type().as_slice(),
                &script.args().raw_data(),
            ]
            .concat()
        }
        let filter_prefix = self.secondary_script.as_ref().map(|script| {
            if script != &Script::default() {
                extract_raw_data(script)
            } else {
                Vec::new()
            }
        });
        match self.primary_type {
            PrimaryScriptType::Lock => {
                // check primary script
                if cell.output.lock() != self.primary_script {
                    return false;
                }

                // if primary is `lock`, secondary is `type`
                if let Some(prefix) = filter_prefix {
                    if prefix.is_empty() {
                        if cell.output.type_().is_some() {
                            return false;
                        }
                    } else if cell
                        .output
                        .type_()
                        .to_opt()
                        .as_ref()
                        .map(extract_raw_data)
                        .filter(|data| data.starts_with(&prefix))
                        .is_none()
                    {
                        return false;
                    }
                }
            }
            PrimaryScriptType::Type => {
                // check primary script
                if cell.output.type_().to_opt().as_ref() != Some(&self.primary_script) {
                    return false;
                }

                // if primary is `type`, secondary is `lock`
                if let Some(prefix) = filter_prefix {
                    if !extract_raw_data(&cell.output.lock()).starts_with(&prefix) {
                        return false;
                    }
                }
            }
        }

        if let Some(range) = self.data_len_range {
            if !range.match_value(cell.output_data.len() as u64) {
                return false;
            }
        }
        if let Some(range) = self.capacity_range {
            let capacity: u64 = cell.output.capacity().unpack();
            if !range.match_value(capacity) {
                return false;
            }
        }
        if let Some(range) = self.block_range {
            if !range.match_value(cell.block_number) {
                return false;
            }
        }
        let cell_is_mature = is_mature(cell, max_mature_number);
        match self.maturity {
            MaturityOption::Mature => cell_is_mature,
            MaturityOption::Immature => !cell_is_mature,
            MaturityOption::Both => true,
        }
    }
}
pub trait CellCollector {
    /// Collect live cells by query options, if `apply_changes` is true will
    /// mark all collected cells as dead cells.
    fn collect_live_cells(
        &mut self,
        query: &CellQueryOptions,
        apply_changes: bool,
    ) -> Result<(Vec<LiveCell>, u64), CellCollectorError>;

    /// Mark this cell as dead cell
    fn lock_cell(&mut self, out_point: OutPoint) -> Result<(), CellCollectorError>;
    /// Mark all inputs as dead cells and outputs as live cells in the transaction.
    fn apply_tx(&mut self, tx: Transaction) -> Result<(), CellCollectorError>;

    /// Clear cache and locked cells
    fn reset(&mut self);
}

pub trait CellDepResolver {
    /// Resolve cell dep by script
    fn resolve(&self, script: &Script) -> Option<CellDep>;
}
pub trait HeaderDepResolver {
    /// Resolve header dep by trancation hash
    fn resolve_by_tx(
        &self,
        tx_hash: &Byte32,
    ) -> Result<Option<HeaderView>, Box<dyn std::error::Error>>;

    /// Resolve header dep by block number
    fn resolve_by_number(
        &self,
        number: u64,
    ) -> Result<Option<HeaderView>, Box<dyn std::error::Error>>;
}