ckb-sync 0.116.1

The ckb sync/relayer protocols implementation
Documentation
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
use crate::relayer::block_transactions_process::BlockTransactionsProcess;
use crate::relayer::tests::helper::{build_chain, MockProtocolContext};
use crate::{Status, StatusCode};
use ckb_network::{PeerIndex, SupportProtocols};
use ckb_store::ChainStore;
use ckb_tx_pool::{PlugTarget, TxEntry};
use ckb_types::prelude::*;
use ckb_types::{
    bytes::Bytes,
    core::{BlockBuilder, Capacity, TransactionBuilder},
    packed::{
        self, BlockTransactions, CellInput, CellOutputBuilder, CompactBlock, Header,
        IndexTransaction, OutPoint,
    },
};
use std::collections::HashMap;
use std::sync::Arc;

#[test]
fn test_accept_block() {
    let (relayer, _) = build_chain(5);
    let peer_index: PeerIndex = 100.into();
    let other_peer_index: PeerIndex = 101.into();

    let tx1 = TransactionBuilder::default().build();
    let tx2 = TransactionBuilder::default()
        .output(
            CellOutputBuilder::default()
                .capacity(Capacity::bytes(1).unwrap().pack())
                .build(),
        )
        .output_data(Bytes::new().pack())
        .build();

    let tx3 = TransactionBuilder::default()
        .output(
            CellOutputBuilder::default()
                .capacity(Capacity::bytes(2).unwrap().pack())
                .build(),
        )
        .output_data(Bytes::new().pack())
        .build();
    let uncle = BlockBuilder::default()
        .proposals(vec![tx3.proposal_short_id()].pack())
        .build();

    let block = BlockBuilder::default()
        .transactions(vec![tx1, tx2.clone()])
        .uncle(uncle.as_uncle())
        .build();
    let prefilled = vec![0usize].into_iter().collect();

    let compact_block = CompactBlock::build_from_block(&block, &prefilled);
    let hash = compact_block.header().calc_header_hash();

    {
        let mut pending_compact_blocks = relayer.shared.state().pending_compact_blocks();
        pending_compact_blocks.insert(
            hash.clone(),
            (
                compact_block,
                HashMap::from_iter(vec![
                    (peer_index, (vec![1], vec![0])),
                    (other_peer_index, (vec![1], vec![])),
                ]),
                ckb_systemtime::unix_time_as_millis(),
            ),
        );
    }

    let block_transactions: BlockTransactions = packed::BlockTransactions::new_builder()
        .block_hash(block.header().hash())
        .transactions(vec![tx2.data()].pack())
        .uncles(vec![uncle.as_uncle().data()].pack())
        .build();

    let mock_protocol_context = MockProtocolContext::new(SupportProtocols::RelayV2);
    let nc = Arc::new(mock_protocol_context);

    let process = BlockTransactionsProcess::new(
        block_transactions.as_reader(),
        &relayer,
        Arc::<MockProtocolContext>::clone(&nc),
        peer_index,
    );

    assert_eq!(process.execute(), Status::ok());

    let pending_compact_blocks = relayer.shared.state().pending_compact_blocks();
    assert!(pending_compact_blocks.get(&hash).is_none());

    assert!(relayer
        .shared
        .state()
        .contains_inflight_proposal(&tx3.proposal_short_id()));
}

#[test]
fn test_unknown_request() {
    let (relayer, _) = build_chain(5);
    let peer_index: PeerIndex = 100.into();

    let tx1 = TransactionBuilder::default().build();
    let tx2 = TransactionBuilder::default()
        .output(
            CellOutputBuilder::default()
                .capacity(Capacity::bytes(1).unwrap().pack())
                .build(),
        )
        .output_data(Bytes::new().pack())
        .build();

    let block = BlockBuilder::default()
        .transactions(vec![tx1, tx2.clone()])
        .build();

    let prefilled = vec![0usize].into_iter().collect();

    let compact_block = CompactBlock::build_from_block(&block, &prefilled);

    let foo_peer_index: PeerIndex = 998.into();
    {
        let mut pending_compact_blocks = relayer.shared.state().pending_compact_blocks();
        pending_compact_blocks.insert(
            compact_block.header().calc_header_hash(),
            (
                compact_block,
                HashMap::from_iter(vec![(foo_peer_index, (vec![1], vec![]))]),
                ckb_systemtime::unix_time_as_millis(),
            ),
        );
    }

    let block_transactions: BlockTransactions = packed::BlockTransactions::new_builder()
        .block_hash(block.header().hash())
        .transactions(vec![tx2.data()].pack())
        .build();

    let mock_protocol_context = MockProtocolContext::new(SupportProtocols::RelayV2);
    let nc = Arc::new(mock_protocol_context);

    let process = BlockTransactionsProcess::new(
        block_transactions.as_reader(),
        &relayer,
        Arc::<MockProtocolContext>::clone(&nc),
        peer_index,
    );
    assert_eq!(process.execute(), Status::ignored());
}

#[test]
fn test_invalid_transaction_root() {
    let (relayer, _) = build_chain(5);
    let peer_index: PeerIndex = 100.into();

    let tx1 = TransactionBuilder::default().build();
    let tx2 = TransactionBuilder::default()
        .output(
            CellOutputBuilder::default()
                .capacity(Capacity::bytes(1).unwrap().pack())
                .build(),
        )
        .output_data(Bytes::new().pack())
        .build();

    let prefilled = IndexTransaction::new_builder()
        .index(0u32.pack())
        .transaction(tx1.data())
        .build();

    let header_with_invalid_tx_root = Header::new_builder()
        .raw(
            packed::RawHeader::new_builder()
                .transactions_root(packed::Byte32::zero())
                .build(),
        )
        .build();

    let compact_block = packed::CompactBlock::new_builder()
        .header(header_with_invalid_tx_root)
        .short_ids(vec![tx2.proposal_short_id()].pack())
        .prefilled_transactions(vec![prefilled].pack())
        .build();

    let block_hash = compact_block.header().calc_header_hash();

    {
        let mut pending_compact_blocks = relayer.shared.state().pending_compact_blocks();
        pending_compact_blocks.insert(
            block_hash.clone(),
            (
                compact_block,
                HashMap::from_iter(vec![(peer_index, (vec![1], vec![]))]),
                ckb_systemtime::unix_time_as_millis(),
            ),
        );
    }

    let block_transactions: BlockTransactions = packed::BlockTransactions::new_builder()
        .block_hash(block_hash)
        .transactions(vec![tx2.data()].pack())
        .build();

    let mock_protocol_context = MockProtocolContext::new(SupportProtocols::RelayV2);
    let nc = Arc::new(mock_protocol_context);

    let process = BlockTransactionsProcess::new(
        block_transactions.as_reader(),
        &relayer,
        Arc::<MockProtocolContext>::clone(&nc),
        peer_index,
    );
    assert_eq!(
        process.execute(),
        StatusCode::CompactBlockHasUnmatchedTransactionRootWithReconstructedBlock.into(),
    );
}

#[test]
fn test_collision_and_send_missing_indexes() {
    let (relayer, _) = build_chain(5);

    let active_chain = relayer.shared.active_chain();
    let last_block = relayer
        .shared
        .store()
        .get_block(&active_chain.tip_hash())
        .unwrap();
    let last_cellbase = last_block.transactions().first().cloned().unwrap();

    let peer_index: PeerIndex = 100.into();

    let tx1 = TransactionBuilder::default().build();
    let tx2 = TransactionBuilder::default()
        .output(
            CellOutputBuilder::default()
                .capacity(Capacity::bytes(1000).unwrap().pack())
                .build(),
        )
        .output_data(Bytes::new().pack())
        .build();
    let tx3 = TransactionBuilder::default()
        .input(CellInput::new(OutPoint::new(last_cellbase.hash(), 0), 0))
        .output(
            CellOutputBuilder::default()
                .capacity(Capacity::bytes(2).unwrap().pack())
                .build(),
        )
        .output_data(Bytes::new().pack())
        .build();

    let fake_hash = tx3
        .hash()
        .as_builder()
        .nth31(0u8.into())
        .nth30(0u8.into())
        .nth29(0u8.into())
        .nth28(0u8.into())
        .build();
    // Fake tx with the same ProposalShortId but different hash with tx3
    let fake_tx = tx3.clone().fake_hash(fake_hash);

    assert_eq!(tx3.proposal_short_id(), fake_tx.proposal_short_id());
    assert_ne!(tx3.hash(), fake_tx.hash());

    let block = BlockBuilder::default()
        .transactions(vec![tx1, tx2.clone(), fake_tx])
        .build_unchecked();

    let prefilled = vec![0usize].into_iter().collect();

    let compact_block = CompactBlock::build_from_block(&block, &prefilled);

    {
        let tx_pool = relayer.shared.shared().tx_pool_controller();
        let entry = TxEntry::dummy_resolve(tx3.clone(), 0, Capacity::shannons(0), 0);
        tx_pool
            .plug_entry(vec![entry], PlugTarget::Pending)
            .unwrap();
    }

    let hash = compact_block.header().calc_header_hash();
    {
        let mut pending_compact_blocks = relayer.shared.state().pending_compact_blocks();
        pending_compact_blocks.insert(
            hash.clone(),
            (
                compact_block,
                vec![(peer_index, (vec![1], vec![]))].into_iter().collect(),
                ckb_systemtime::unix_time_as_millis(),
            ),
        );
    }

    let block_transactions = packed::BlockTransactions::new_builder()
        .block_hash(block.header().hash())
        .transactions(vec![tx2.data()].pack())
        .build();

    let mock_protocol_context = MockProtocolContext::new(SupportProtocols::RelayV2);
    let nc = Arc::new(mock_protocol_context);

    let process = BlockTransactionsProcess::new(
        block_transactions.as_reader(),
        &relayer,
        Arc::<MockProtocolContext>::clone(&nc),
        peer_index,
    );
    assert_eq!(
        process.execute(),
        StatusCode::CompactBlockMeetsShortIdsCollision.into()
    );

    let content = packed::GetBlockTransactions::new_builder()
        .block_hash(block.header().hash())
        .indexes([1u32, 2u32].pack())
        .build();
    let message = packed::RelayMessage::new_builder().set(content).build();
    let data = message.as_bytes();

    // send missing indexes messages
    assert!(nc.has_sent(SupportProtocols::RelayV2.protocol_id(), peer_index, data));

    // update cached missing_index
    {
        let pending_compact_blocks = relayer.shared.state().pending_compact_blocks();
        assert_eq!(
            pending_compact_blocks
                .get(&hash)
                .unwrap()
                .1
                .get(&peer_index),
            Some(&(vec![1, 2], vec![]))
        );
    }

    // resend BlockTransactions with all the transactions without prefilled
    let new_block_transactions = packed::BlockTransactions::new_builder()
        .block_hash(block.header().hash())
        .transactions(vec![tx2.data(), tx3.data()].pack())
        .build();

    let mock_protocol_context = MockProtocolContext::new(SupportProtocols::RelayV2);
    let nc = Arc::new(mock_protocol_context);

    let process = BlockTransactionsProcess::new(
        new_block_transactions.as_reader(),
        &relayer,
        Arc::<MockProtocolContext>::clone(&nc),
        peer_index,
    );
    assert_eq!(
        process.execute(),
        StatusCode::CompactBlockHasUnmatchedTransactionRootWithReconstructedBlock.into(),
    );
}

#[test]
fn test_missing() {
    // test case:
    //  1. Relayer received a compact block with 3 tx
    //  2. Assuming that tx1 is prefilled, tx2 makes a request, and tx3 is in the transaction pool
    //  3. When the relayer receives the return from tx2, tx3 is not in the transaction pool
    //  4. Relayer must make another request for tx2 and tx3

    let (relayer, _) = build_chain(5);
    let peer_index: PeerIndex = 100.into();

    let tx1 = TransactionBuilder::default().build();
    let tx2 = TransactionBuilder::default()
        .output(
            CellOutputBuilder::default()
                .capacity(Capacity::bytes(1).unwrap().pack())
                .build(),
        )
        .output_data(Bytes::new().pack())
        .build();
    let tx3 = TransactionBuilder::default()
        .output(
            CellOutputBuilder::default()
                .capacity(Capacity::bytes(2).unwrap().pack())
                .build(),
        )
        .output_data(Bytes::new().pack())
        .build();

    let block = BlockBuilder::default()
        .transactions(vec![tx1, tx2.clone(), tx3])
        .build();

    let prefilled = vec![0usize].into_iter().collect();

    let compact_block = CompactBlock::build_from_block(&block, &prefilled);

    // tx3 should be in tx_pool already, but it's not.
    // so the reconstruct block will fail
    {
        let mut pending_compact_blocks = relayer.shared.state().pending_compact_blocks();
        pending_compact_blocks.insert(
            compact_block.header().calc_header_hash(),
            (
                compact_block,
                HashMap::from_iter(vec![(peer_index, (vec![1], vec![]))]),
                ckb_systemtime::unix_time_as_millis(),
            ),
        );
    }

    let block_transactions = packed::BlockTransactions::new_builder()
        .block_hash(block.header().hash())
        .transactions(vec![tx2.data()].pack())
        .build();

    let mock_protocol_context = MockProtocolContext::new(SupportProtocols::RelayV2);
    let nc = Arc::new(mock_protocol_context);

    let process = BlockTransactionsProcess::new(
        block_transactions.as_reader(),
        &relayer,
        Arc::<MockProtocolContext>::clone(&nc),
        peer_index,
    );
    assert_eq!(
        process.execute(),
        StatusCode::CompactBlockRequiresFreshTransactions.into()
    );

    let content = packed::GetBlockTransactions::new_builder()
        .block_hash(block.header().hash())
        .indexes([1, 2u32].pack())
        .build();
    let message = packed::RelayMessage::new_builder().set(content).build();

    // send missing indexes messages
    assert!(nc.has_sent(
        SupportProtocols::RelayV2.protocol_id(),
        peer_index,
        message.as_bytes()
    ));
}