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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
//! Advanced builders for Transaction(View), Header(View) and Block(View).

use crate::{
    constants, core, packed,
    prelude::*,
    utilities::{merkle_root, DIFF_TWO},
};

/*
 * Definitions
 */

/// An advanced builder for [`TransactionView`].
///
/// Base on [`packed::TransactionBuilder`] but added lots of syntactic sugar.
///
/// [`TransactionView`]: struct.TransactionView.html
/// [`packed::TransactionBuilder`]: ../packed/struct.TransactionBuilder.html
#[derive(Clone, Debug)]
pub struct TransactionBuilder {
    pub(crate) version: packed::Uint32,
    pub(crate) cell_deps: Vec<packed::CellDep>,
    pub(crate) header_deps: Vec<packed::Byte32>,
    pub(crate) inputs: Vec<packed::CellInput>,
    pub(crate) outputs: Vec<packed::CellOutput>,
    pub(crate) witnesses: Vec<packed::Bytes>,
    pub(crate) outputs_data: Vec<packed::Bytes>,
}

/// An advanced builder for [`HeaderView`].
///
/// Base on [`packed::HeaderBuilder`] but added lots of syntactic sugar.
///
/// [`HeaderView`]: struct.HeaderView.html
/// [`packed::HeaderBuilder`]: ../packed/struct.HeaderBuilder.html
#[derive(Clone, Debug)]
pub struct HeaderBuilder {
    // RawHeader
    pub(crate) version: packed::Uint32,
    pub(crate) parent_hash: packed::Byte32,
    pub(crate) timestamp: packed::Uint64,
    pub(crate) number: packed::Uint64,
    pub(crate) transactions_root: packed::Byte32,
    pub(crate) proposals_hash: packed::Byte32,
    pub(crate) compact_target: packed::Uint32,
    pub(crate) extra_hash: packed::Byte32,
    pub(crate) epoch: packed::Uint64,
    pub(crate) dao: packed::Byte32,
    // Nonce
    pub(crate) nonce: packed::Uint128,
}

/// An advanced builder for [`BlockView`].
///
/// Base on [`packed::BlockBuilder`] but added lots of syntactic sugar.
///
/// [`BlockView`]: struct.BlockView.html
/// [`packed::BlockBuilder`]: ../packed/struct.BlockBuilder.html
#[derive(Clone, Debug, Default)]
pub struct BlockBuilder {
    pub(crate) header: HeaderBuilder,
    // Others
    pub(crate) uncles: Vec<core::UncleBlockView>,
    pub(crate) transactions: Vec<core::TransactionView>,
    pub(crate) proposals: Vec<packed::ProposalShortId>,
    pub(crate) extension: Option<packed::Bytes>,
}

/*
 * Implement std traits.
 */

impl ::std::default::Default for TransactionBuilder {
    fn default() -> Self {
        Self {
            version: constants::TX_VERSION.pack(),
            cell_deps: Default::default(),
            header_deps: Default::default(),
            inputs: Default::default(),
            outputs: Default::default(),
            witnesses: Default::default(),
            outputs_data: Default::default(),
        }
    }
}

impl ::std::default::Default for HeaderBuilder {
    fn default() -> Self {
        Self {
            version: constants::BLOCK_VERSION.pack(),
            parent_hash: Default::default(),
            timestamp: Default::default(),
            number: Default::default(),
            transactions_root: Default::default(),
            proposals_hash: Default::default(),
            compact_target: DIFF_TWO.pack(),
            extra_hash: Default::default(),
            epoch: core::EpochNumberWithFraction::new(0, 0, 1).pack(),
            dao: Default::default(),
            nonce: Default::default(),
        }
    }
}

/*
 * Implementations.
 */

macro_rules! def_setter_simple {
    (__add_doc, $prefix:ident, $field:ident, $type:ident, $comment:expr) => {
        #[doc = $comment]
        pub fn $field(mut self, v: packed::$type) -> Self {
            self.$prefix.$field = v;
            self
        }
    };
    (__add_doc, $field:ident, $type:ident, $comment:expr) => {
        #[doc = $comment]
        pub fn $field(mut self, v: packed::$type) -> Self {
            self.$field = v;
            self
        }
    };
    ($prefix:ident, $field:ident, $type:ident) => {
        def_setter_simple!(
            __add_doc,
            $prefix,
            $field,
            $type,
            concat!("Sets `", stringify!($prefix), ".", stringify!($field), "`.")
        );
    };
    ($field:ident, $type:ident) => {
        def_setter_simple!(
            __add_doc,
            $field,
            $type,
            concat!("Sets `", stringify!($field), "`.")
        );
    };
}

macro_rules! def_setter_for_vector {
    (
        $prefix:ident, $field:ident, $type:ident,
        $func_push:ident, $func_extend:ident, $func_set:ident,
        $comment_push:expr, $comment_extend:expr, $comment_set:expr,
    ) => {
        #[doc = $comment_push]
        pub fn $func_push(mut self, v: $prefix::$type) -> Self {
            self.$field.push(v);
            self
        }
        #[doc = $comment_extend]
        pub fn $func_extend<T>(mut self, v: T) -> Self
        where
            T: ::std::iter::IntoIterator<Item = $prefix::$type>,
        {
            self.$field.extend(v);
            self
        }
        #[doc = $comment_set]
        pub fn $func_set(mut self, v: Vec<$prefix::$type>) -> Self {
            self.$field = v;
            self
        }
    };
    ($prefix:ident, $field:ident, $type:ident, $func_push:ident, $func_extend:ident, $func_set:ident) => {
        def_setter_for_vector!(
            $prefix,
            $field,
            $type,
            $func_push,
            $func_extend,
            $func_set,
            concat!("Pushes an item into `", stringify!($field), "`."),
            concat!(
                "Extends `",
                stringify!($field),
                "` with the contents of an iterator."
            ),
            concat!("Sets `", stringify!($field), "`."),
        );
    };
    ($field:ident, $type:ident, $func_push:ident, $func_extend:ident, $func_set:ident) => {
        def_setter_for_vector!(packed, $field, $type, $func_push, $func_extend, $func_set);
    };
}

macro_rules! def_setter_for_view_vector {
    ($field:ident, $type:ident, $func_push:ident, $func_extend:ident, $func_set:ident) => {
        def_setter_for_vector!(core, $field, $type, $func_push, $func_extend, $func_set);
    };
}

impl TransactionBuilder {
    def_setter_simple!(version, Uint32);
    def_setter_for_vector!(cell_deps, CellDep, cell_dep, cell_deps, set_cell_deps);
    def_setter_for_vector!(
        header_deps,
        Byte32,
        header_dep,
        header_deps,
        set_header_deps
    );
    def_setter_for_vector!(inputs, CellInput, input, inputs, set_inputs);
    def_setter_for_vector!(outputs, CellOutput, output, outputs, set_outputs);
    def_setter_for_vector!(witnesses, Bytes, witness, witnesses, set_witnesses);
    def_setter_for_vector!(
        outputs_data,
        Bytes,
        output_data,
        outputs_data,
        set_outputs_data
    );

    /// Converts into [`TransactionView`](struct.TransactionView.html).
    pub fn build(self) -> core::TransactionView {
        let Self {
            version,
            cell_deps,
            header_deps,
            inputs,
            outputs,
            witnesses,
            outputs_data,
        } = self;
        let raw = packed::RawTransaction::new_builder()
            .version(version)
            .cell_deps(cell_deps.pack())
            .header_deps(header_deps.pack())
            .inputs(inputs.pack())
            .outputs(outputs.pack())
            .outputs_data(outputs_data.pack())
            .build();
        let tx = packed::Transaction::new_builder()
            .raw(raw)
            .witnesses(witnesses.pack())
            .build();
        let hash = tx.calc_tx_hash();
        let witness_hash = tx.calc_witness_hash();
        core::TransactionView {
            data: tx,
            hash,
            witness_hash,
        }
    }
}

impl HeaderBuilder {
    def_setter_simple!(version, Uint32);
    def_setter_simple!(parent_hash, Byte32);
    def_setter_simple!(timestamp, Uint64);
    def_setter_simple!(number, Uint64);
    def_setter_simple!(transactions_root, Byte32);
    def_setter_simple!(proposals_hash, Byte32);
    def_setter_simple!(compact_target, Uint32);
    def_setter_simple!(extra_hash, Byte32);
    def_setter_simple!(epoch, Uint64);
    def_setter_simple!(dao, Byte32);
    def_setter_simple!(nonce, Uint128);

    /// Converts into [`HeaderView`](struct.HeaderView.html).
    pub fn build(self) -> core::HeaderView {
        let Self {
            version,
            parent_hash,
            timestamp,
            number,
            transactions_root,
            proposals_hash,
            compact_target,
            extra_hash,
            epoch,
            dao,
            nonce,
        } = self;
        debug_assert!(
            Unpack::<u32>::unpack(&compact_target) > 0,
            "[HeaderBuilder] compact_target should greater than zero"
        );
        debug_assert!(
            Unpack::<core::BlockNumber>::unpack(&number) == 0
                || Unpack::<core::EpochNumberWithFraction>::unpack(&epoch).is_well_formed(),
            "[HeaderBuilder] epoch {:x} should be well formed, \
            unless it's in the genesis block (number: {:x})",
            epoch,
            number
        );
        let raw = packed::RawHeader::new_builder()
            .version(version)
            .parent_hash(parent_hash)
            .timestamp(timestamp)
            .number(number)
            .transactions_root(transactions_root)
            .proposals_hash(proposals_hash)
            .compact_target(compact_target)
            .extra_hash(extra_hash)
            .epoch(epoch)
            .dao(dao)
            .build();
        let header = packed::Header::new_builder().raw(raw).nonce(nonce).build();
        let hash = header.calc_header_hash();
        core::HeaderView { data: header, hash }
    }
}

impl BlockBuilder {
    def_setter_simple!(header, version, Uint32);
    def_setter_simple!(header, parent_hash, Byte32);
    def_setter_simple!(header, timestamp, Uint64);
    def_setter_simple!(header, number, Uint64);
    def_setter_simple!(header, transactions_root, Byte32);
    def_setter_simple!(header, proposals_hash, Byte32);
    def_setter_simple!(header, compact_target, Uint32);
    def_setter_simple!(header, extra_hash, Byte32);
    def_setter_simple!(header, epoch, Uint64);
    def_setter_simple!(header, dao, Byte32);
    def_setter_simple!(header, nonce, Uint128);
    def_setter_for_view_vector!(uncles, UncleBlockView, uncle, uncles, set_uncles);
    def_setter_for_view_vector!(
        transactions,
        TransactionView,
        transaction,
        transactions,
        set_transactions
    );
    def_setter_for_vector!(
        proposals,
        ProposalShortId,
        proposal,
        proposals,
        set_proposals
    );

    /// Set `header`.
    pub fn header(mut self, header: core::HeaderView) -> Self {
        self.header = header.as_advanced_builder();
        self
    }

    /// Set `extension`.
    #[doc(hidden)]
    pub fn extension(mut self, extension: Option<packed::Bytes>) -> Self {
        self.extension = extension;
        self
    }

    fn build_internal(self, reset_header: bool) -> core::BlockView {
        let Self {
            header,
            uncles,
            transactions,
            proposals,
            extension,
        } = self;
        let (uncles, uncle_hashes) = {
            let len = uncles.len();
            uncles
                .into_iter()
                .map(|uncle_view| {
                    let core::UncleBlockView { data, hash } = uncle_view;
                    (data, hash)
                })
                .fold(
                    (Vec::with_capacity(len), Vec::with_capacity(len)),
                    |(mut uncles, mut hashes), (uncle, hash)| {
                        uncles.push(uncle);
                        hashes.push(hash);
                        (uncles, hashes)
                    },
                )
        };

        let (transactions, tx_hashes, tx_witness_hashes) = {
            let len = transactions.len();
            transactions
                .into_iter()
                .map(|tx_view| {
                    let core::TransactionView {
                        data,
                        hash,
                        witness_hash,
                    } = tx_view;
                    (data, hash, witness_hash)
                })
                .fold(
                    (
                        Vec::with_capacity(len),
                        Vec::with_capacity(len),
                        Vec::with_capacity(len),
                    ),
                    |(mut txs, mut hashes, mut witness_hashes), (tx, hash, witness_hash)| {
                        txs.push(tx);
                        hashes.push(hash);
                        witness_hashes.push(witness_hash);
                        (txs, hashes, witness_hashes)
                    },
                )
        };

        let proposals = proposals.pack();
        let uncles = uncles.pack();

        let core::HeaderView { data, hash } = if reset_header {
            let raw_transactions_root = merkle_root(&tx_hashes[..]);
            let witnesses_root = merkle_root(&tx_witness_hashes[..]);
            let transactions_root = merkle_root(&[raw_transactions_root, witnesses_root]);
            let proposals_hash = proposals.calc_proposals_hash();
            let extra_hash_view = core::ExtraHashView::new(
                uncles.calc_uncles_hash(),
                extension.as_ref().map(packed::Bytes::calc_raw_data_hash),
            );
            let extra_hash = extra_hash_view.extra_hash();
            header
                .transactions_root(transactions_root)
                .proposals_hash(proposals_hash)
                .extra_hash(extra_hash)
                .build()
        } else {
            header.build()
        };

        let block = if let Some(extension) = extension {
            packed::BlockV1::new_builder()
                .header(data)
                .uncles(uncles)
                .transactions(transactions.pack())
                .proposals(proposals)
                .extension(extension)
                .build()
                .as_v0()
        } else {
            packed::Block::new_builder()
                .header(data)
                .uncles(uncles)
                .transactions(transactions.pack())
                .proposals(proposals)
                .build()
        };
        core::BlockView {
            data: block,
            hash,
            uncle_hashes: uncle_hashes.pack(),
            tx_hashes,
            tx_witness_hashes,
        }
    }

    /// Converts into [`BlockView`](struct.BlockView.html) and recalculates all hashes and merkle
    /// roots in the header.
    pub fn build(self) -> core::BlockView {
        self.build_internal(true)
    }

    /// Converts into [`BlockView`](struct.BlockView.html) but does not refresh all hashes and all
    /// merkle roots in the header.
    ///
    /// # Notice
    ///
    /// [`BlockView`](struct.BlockView.html) created by this method could have invalid hashes or
    /// invalid merkle roots in the header.
    pub fn build_unchecked(self) -> core::BlockView {
        self.build_internal(false)
    }
}

/*
 * Convert a struct to an advanced builder
 */

impl packed::Transaction {
    /// Creates an advanced builder base on current data.
    pub fn as_advanced_builder(&self) -> TransactionBuilder {
        TransactionBuilder::default()
            .version(self.raw().version())
            .cell_deps(self.raw().cell_deps())
            .header_deps(self.raw().header_deps())
            .inputs(self.raw().inputs())
            .outputs(self.raw().outputs())
            .outputs_data(self.raw().outputs_data())
            .witnesses(self.witnesses())
    }
}

impl packed::Header {
    /// Creates an advanced builder base on current data.
    pub fn as_advanced_builder(&self) -> HeaderBuilder {
        HeaderBuilder::default()
            .version(self.raw().version())
            .parent_hash(self.raw().parent_hash())
            .timestamp(self.raw().timestamp())
            .number(self.raw().number())
            .transactions_root(self.raw().transactions_root())
            .proposals_hash(self.raw().proposals_hash())
            .compact_target(self.raw().compact_target())
            .extra_hash(self.raw().extra_hash())
            .epoch(self.raw().epoch())
            .dao(self.raw().dao())
            .nonce(self.nonce())
    }
}

impl packed::Block {
    /// Creates an empty advanced builder.
    pub fn new_advanced_builder() -> BlockBuilder {
        Default::default()
    }

    /// Creates an advanced builder base on current data.
    pub fn as_advanced_builder(&self) -> BlockBuilder {
        BlockBuilder::default()
            .header(self.header().into_view())
            .uncles(
                self.uncles()
                    .into_iter()
                    .map(|x| x.into_view())
                    .collect::<Vec<_>>(),
            )
            .transactions(
                self.transactions()
                    .into_iter()
                    .map(|x| x.into_view())
                    .collect::<Vec<_>>(),
            )
            .proposals(self.proposals().into_iter().collect::<Vec<_>>())
            .extension(self.extension())
    }
}

impl core::TransactionView {
    /// Creates an empty advanced builder.
    pub fn new_advanced_builder() -> TransactionBuilder {
        Default::default()
    }

    /// Creates an advanced builder base on current data.
    pub fn as_advanced_builder(&self) -> TransactionBuilder {
        self.data().as_advanced_builder()
    }
}

impl core::HeaderView {
    /// Creates an empty advanced builder.
    pub fn new_advanced_builder() -> HeaderBuilder {
        Default::default()
    }

    /// Creates an advanced builder base on current data.
    pub fn as_advanced_builder(&self) -> HeaderBuilder {
        self.data().as_advanced_builder()
    }
}

impl core::BlockView {
    /// Creates an advanced builder base on current data.
    pub fn as_advanced_builder(&self) -> BlockBuilder {
        let core::BlockView {
            data,
            uncle_hashes,
            tx_hashes,
            tx_witness_hashes,
            hash,
        } = self;
        let _ = hash;
        BlockBuilder::default()
            .header(self.header())
            .uncles(
                data.uncles()
                    .into_iter()
                    .zip(uncle_hashes.to_owned().into_iter())
                    .map(|(data, hash)| core::UncleBlockView { data, hash })
                    .collect::<Vec<_>>(),
            )
            .transactions(
                data.transactions()
                    .into_iter()
                    .zip(tx_hashes.iter())
                    .zip(tx_witness_hashes.iter())
                    .map(|((data, hash), witness_hash)| core::TransactionView {
                        data,
                        hash: hash.to_owned(),
                        witness_hash: witness_hash.to_owned(),
                    })
                    .collect::<Vec<_>>(),
            )
            .proposals(data.proposals().into_iter().collect::<Vec<_>>())
            .extension(data.extension())
    }
}