-
Notifications
You must be signed in to change notification settings - Fork 677
/
Copy pathprocess_blocks.rs
3920 lines (3695 loc) · 155 KB
/
process_blocks.rs
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::{HashSet, VecDeque};
use std::convert::TryFrom;
use std::iter::FromIterator;
use std::path::Path;
use std::str::FromStr;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, RwLock};
use actix::System;
use futures::{future, FutureExt};
use near_primitives::num_rational::Rational;
use near_actix_test_utils::run_actix;
use near_chain::chain::{ApplyStatePartsRequest, NUM_EPOCHS_TO_KEEP_STORE_DATA};
use near_chain::types::LatestKnown;
use near_chain::validate::validate_chunk_with_chunk_extra;
use near_chain::{
Block, ChainGenesis, ChainStore, ChainStoreAccess, ErrorKind, Provenance, RuntimeAdapter,
};
use near_chain_configs::{ClientConfig, Genesis};
use near_chunks::{ChunkStatus, ShardsManager};
use near_client::test_utils::{create_chunk_on_height, setup_mock_all_validators};
use near_client::test_utils::{setup_client, setup_mock, TestEnv};
use near_client::{Client, GetBlock, GetBlockWithMerkleTree};
use near_crypto::{InMemorySigner, KeyType, PublicKey, Signature, Signer};
use near_logger_utils::init_test_logger;
use near_network::routing::EdgeInfo;
use near_network::test_utils::{wait_or_panic, MockNetworkAdapter};
use near_network::types::{NetworkInfo, PeerChainInfoV2, ReasonForBan};
use near_network::{
FullPeerInfo, NetworkClientMessages, NetworkClientResponses, NetworkRequests, NetworkResponses,
PeerInfo,
};
use near_primitives::block::{Approval, ApprovalInner};
use near_primitives::block_header::BlockHeader;
#[cfg(feature = "protocol_feature_simple_nightshade")]
use near_primitives::epoch_manager::ShardConfig;
use near_primitives::errors::InvalidTxError;
use near_primitives::errors::TxExecutionError;
use near_primitives::hash::{hash, CryptoHash};
use near_primitives::merkle::verify_hash;
use near_primitives::receipt::DelayedReceiptIndices;
use near_primitives::runtime::config_store::RuntimeConfigStore;
#[cfg(feature = "protocol_feature_simple_nightshade")]
use near_primitives::shard_layout::ShardLayout;
use near_primitives::shard_layout::ShardUId;
#[cfg(not(feature = "protocol_feature_block_header_v3"))]
use near_primitives::sharding::ShardChunkHeaderV2;
use near_primitives::sharding::{EncodedShardChunk, ReedSolomonWrapper, ShardChunkHeader};
#[cfg(feature = "protocol_feature_block_header_v3")]
use near_primitives::sharding::{ShardChunkHeaderInner, ShardChunkHeaderV3};
use near_primitives::syncing::{get_num_state_parts, ShardStateSyncResponseHeader, StatePartKey};
use near_primitives::transaction::{
Action, DeployContractAction, ExecutionStatus, FunctionCallAction, SignedTransaction,
Transaction,
};
use near_primitives::trie_key::TrieKey;
use near_primitives::types::validator_stake::ValidatorStake;
use near_primitives::types::{AccountId, BlockHeight, EpochId, NumBlocks, ProtocolVersion};
use near_primitives::utils::to_timestamp;
use near_primitives::validator_signer::{InMemoryValidatorSigner, ValidatorSigner};
#[cfg(feature = "protocol_feature_simple_nightshade")]
use near_primitives::version::ProtocolFeature;
use near_primitives::version::PROTOCOL_VERSION;
use near_primitives::views::{
BlockHeaderView, FinalExecutionStatus, QueryRequest, QueryResponseKind,
};
use near_store::db::DBCol::ColStateParts;
use near_store::get;
use near_store::test_utils::create_test_store;
use nearcore::config::{GenesisExt, TESTING_INIT_BALANCE, TESTING_INIT_STAKE};
use nearcore::NEAR_BASE;
use rand::Rng;
fn set_block_protocol_version(
block: &mut Block,
block_producer: AccountId,
protocol_version: ProtocolVersion,
) {
let validator_signer = InMemoryValidatorSigner::from_seed(
block_producer.clone(),
KeyType::ED25519,
block_producer.as_ref(),
);
block.mut_header().get_mut().inner_rest.latest_protocol_version = protocol_version;
block.mut_header().resign(&validator_signer);
}
pub fn create_nightshade_runtimes(genesis: &Genesis, n: usize) -> Vec<Arc<dyn RuntimeAdapter>> {
(0..n)
.map(|_| {
Arc::new(nearcore::NightshadeRuntime::new(
Path::new("."),
create_test_store(),
genesis,
vec![],
vec![],
None,
None,
RuntimeConfigStore::test(),
)) as Arc<dyn RuntimeAdapter>
})
.collect()
}
fn produce_epochs(
env: &mut TestEnv,
epoch_number: u64,
epoch_length: u64,
height: BlockHeight,
) -> BlockHeight {
let next_height = height + epoch_number * epoch_length;
for i in height..next_height {
let block = env.clients[0].produce_block(i).unwrap().unwrap();
env.process_block(0, block.clone(), Provenance::PRODUCED);
for j in 1..env.clients.len() {
env.process_block(j, block.clone(), Provenance::NONE);
}
}
next_height
}
fn deploy_test_contract(
env: &mut TestEnv,
account_id: AccountId,
wasm_code: &[u8],
epoch_length: u64,
height: BlockHeight,
) -> BlockHeight {
let block = env.clients[0].chain.get_block_by_height(height - 1).unwrap();
let signer =
InMemorySigner::from_seed(account_id.clone(), KeyType::ED25519, account_id.as_ref());
let tx = SignedTransaction::from_actions(
height,
account_id.clone(),
account_id,
&signer,
vec![Action::DeployContract(DeployContractAction { code: wasm_code.to_vec() })],
*block.hash(),
);
env.clients[0].process_tx(tx, false, false);
produce_epochs(env, 1, epoch_length, height)
}
/// Create environment and set of transactions which cause congestion on the chain.
fn prepare_env_with_congestion(
protocol_version: ProtocolVersion,
gas_price_adjustment_rate: Option<Rational>,
number_of_transactions: u64,
) -> (TestEnv, Vec<CryptoHash>) {
init_test_logger();
let epoch_length = 100;
let mut genesis = Genesis::test(vec!["test0".parse().unwrap(), "test1".parse().unwrap()], 1);
genesis.config.protocol_version = protocol_version;
genesis.config.epoch_length = epoch_length;
genesis.config.gas_limit = 10_000_000_000_000;
if let Some(gas_price_adjustment_rate) = gas_price_adjustment_rate {
genesis.config.gas_price_adjustment_rate = gas_price_adjustment_rate;
}
let chain_genesis = ChainGenesis::from(&genesis);
let mut env =
TestEnv::new_with_runtime(chain_genesis, 1, 1, create_nightshade_runtimes(&genesis, 1));
let genesis_block = env.clients[0].chain.get_block_by_height(0).unwrap().clone();
let signer = InMemorySigner::from_seed("test0".parse().unwrap(), KeyType::ED25519, "test0");
// Deploy contract to test0.
let tx = SignedTransaction::from_actions(
1,
"test0".parse().unwrap(),
"test0".parse().unwrap(),
&signer,
vec![Action::DeployContract(DeployContractAction {
code: near_test_contracts::rs_contract().to_vec(),
})],
*genesis_block.hash(),
);
env.clients[0].process_tx(tx, false, false);
for i in 1..3 {
env.produce_block(0, i);
}
// Create function call transactions that generate promises.
let gas_1 = 9_000_000_000_000;
let gas_2 = gas_1 / 3;
let mut tx_hashes = vec![];
for i in 0..number_of_transactions {
let data = serde_json::json!([
{"create": {
"account_id": "test0",
"method_name": "call_promise",
"arguments": [],
"amount": "0",
"gas": gas_2,
}, "id": 0 }
]);
let signed_transaction = SignedTransaction::from_actions(
i + 10,
"test0".parse().unwrap(),
"test0".parse().unwrap(),
&signer,
vec![Action::FunctionCall(FunctionCallAction {
method_name: "call_promise".to_string(),
args: serde_json::to_vec(&data).unwrap(),
gas: gas_1,
deposit: 0,
})],
*genesis_block.hash(),
);
tx_hashes.push(signed_transaction.get_hash());
env.clients[0].process_tx(signed_transaction, false, false);
}
(env, tx_hashes)
}
/// Runs block producing client and stops after network mock received two blocks.
#[test]
fn produce_two_blocks() {
init_test_logger();
run_actix(async {
let count = Arc::new(AtomicUsize::new(0));
setup_mock(
vec!["test".parse().unwrap()],
"test".parse().unwrap(),
true,
false,
Box::new(move |msg, _ctx, _| {
if let NetworkRequests::Block { .. } = msg {
count.fetch_add(1, Ordering::Relaxed);
if count.load(Ordering::Relaxed) >= 2 {
System::current().stop();
}
}
NetworkResponses::NoResponse
}),
);
near_network::test_utils::wait_or_panic(5000);
});
}
/// Runs block producing client and sends it a transaction.
#[test]
// TODO: figure out how to re-enable it correctly
#[ignore]
fn produce_blocks_with_tx() {
let mut encoded_chunks: Vec<EncodedShardChunk> = vec![];
init_test_logger();
run_actix(async {
let (client, view_client) = setup_mock(
vec!["test".parse().unwrap()],
"test".parse().unwrap(),
true,
false,
Box::new(move |msg, _ctx, _| {
if let NetworkRequests::PartialEncodedChunkMessage {
account_id: _,
partial_encoded_chunk,
} = msg
{
let header = partial_encoded_chunk.header.clone();
let height = header.height_created() as usize;
assert!(encoded_chunks.len() + 2 >= height);
// the following two lines must match data_parts and total_parts in KeyValueRuntimeAdapter
let data_parts = 12 + 2 * (((height - 1) as usize) % 4);
let total_parts = 1 + data_parts * (1 + ((height - 1) as usize) % 3);
if encoded_chunks.len() + 2 == height {
encoded_chunks.push(EncodedShardChunk::from_header(
header,
total_parts,
PROTOCOL_VERSION,
));
}
for part in partial_encoded_chunk.parts.iter() {
encoded_chunks[height - 2].content_mut().parts[part.part_ord as usize] =
Some(part.part.clone());
}
let parity_parts = total_parts - data_parts;
let mut rs = ReedSolomonWrapper::new(data_parts, parity_parts);
if let ChunkStatus::Complete(_) = ShardsManager::check_chunk_complete(
&mut encoded_chunks[height - 2],
&mut rs,
) {
let chunk = encoded_chunks[height - 2].decode_chunk(data_parts).unwrap();
if chunk.transactions().len() > 0 {
System::current().stop();
}
}
}
NetworkResponses::NoResponse
}),
);
near_network::test_utils::wait_or_panic(5000);
actix::spawn(view_client.send(GetBlock::latest()).then(move |res| {
let block_hash = res.unwrap().unwrap().header.hash;
client.do_send(NetworkClientMessages::Transaction {
transaction: SignedTransaction::empty(block_hash),
is_forwarded: false,
check_only: false,
});
future::ready(())
}))
});
}
/// Runs client that receives a block from network and announces header to the network with approval.
/// Need 3 block producers, to receive approval.
#[test]
fn receive_network_block() {
init_test_logger();
run_actix(async {
// The first header announce will be when the block is received. We don't immediately endorse
// it. The second header announce will happen with the endorsement a little later.
let first_header_announce = Arc::new(RwLock::new(true));
let (client, view_client) = setup_mock(
vec!["test2".parse().unwrap(), "test1".parse().unwrap(), "test3".parse().unwrap()],
"test2".parse().unwrap(),
true,
false,
Box::new(move |msg, _ctx, _| {
if let NetworkRequests::Approval { .. } = msg {
let mut first_header_announce = first_header_announce.write().unwrap();
if *first_header_announce {
*first_header_announce = false;
} else {
System::current().stop();
}
}
NetworkResponses::NoResponse
}),
);
actix::spawn(view_client.send(GetBlockWithMerkleTree::latest()).then(move |res| {
let (last_block, mut block_merkle_tree) = res.unwrap().unwrap();
let signer = InMemoryValidatorSigner::from_seed(
"test1".parse().unwrap(),
KeyType::ED25519,
"test1",
);
block_merkle_tree.insert(last_block.header.hash);
#[cfg(feature = "protocol_feature_block_header_v3")]
let next_block_ordinal = last_block.header.block_ordinal.unwrap() + 1;
let block = Block::produce(
PROTOCOL_VERSION,
&last_block.header.clone().into(),
last_block.header.height + 1,
#[cfg(feature = "protocol_feature_block_header_v3")]
next_block_ordinal,
last_block.chunks.into_iter().map(Into::into).collect(),
EpochId::default(),
if last_block.header.prev_hash == CryptoHash::default() {
EpochId(last_block.header.hash)
} else {
EpochId(last_block.header.next_epoch_id.clone())
},
#[cfg(feature = "protocol_feature_block_header_v3")]
None,
vec![],
Rational::from_integer(0),
0,
100,
None,
vec![],
vec![],
&signer,
last_block.header.next_bp_hash,
block_merkle_tree.root(),
);
client.do_send(NetworkClientMessages::Block(block, PeerInfo::random().id, false));
future::ready(())
}));
near_network::test_utils::wait_or_panic(5000);
});
}
/// Include approvals to the next block in newly produced block.
#[test]
fn produce_block_with_approvals() {
init_test_logger();
let validators: Vec<_> =
(1..=10).map(|i| AccountId::try_from(format!("test{}", i)).unwrap()).collect();
run_actix(async {
let (client, view_client) = setup_mock(
validators.clone(),
"test1".parse().unwrap(),
true,
false,
Box::new(move |msg, _ctx, _| {
if let NetworkRequests::Block { block } = msg {
// Below we send approvals from all the block producers except for test1 and test2
// test1 will only create their approval for height 10 after their doomslug timer
// runs 10 iterations, which is way further in the future than them producing the
// block
if block.header().num_approvals() == validators.len() as u64 - 2 {
System::current().stop();
} else if block.header().height() == 10 {
println!("{}", block.header().height());
println!(
"{} != {} -2 (height: {})",
block.header().num_approvals(),
validators.len(),
block.header().height()
);
assert!(false);
}
}
NetworkResponses::NoResponse
}),
);
actix::spawn(view_client.send(GetBlockWithMerkleTree::latest()).then(move |res| {
let (last_block, mut block_merkle_tree) = res.unwrap().unwrap();
let signer1 = InMemoryValidatorSigner::from_seed(
"test2".parse().unwrap(),
KeyType::ED25519,
"test2",
);
block_merkle_tree.insert(last_block.header.hash);
#[cfg(feature = "protocol_feature_block_header_v3")]
let next_block_ordinal = last_block.header.block_ordinal.unwrap() + 1;
let block = Block::produce(
PROTOCOL_VERSION,
&last_block.header.clone().into(),
last_block.header.height + 1,
#[cfg(feature = "protocol_feature_block_header_v3")]
next_block_ordinal,
last_block.chunks.into_iter().map(Into::into).collect(),
EpochId::default(),
if last_block.header.prev_hash == CryptoHash::default() {
EpochId(last_block.header.hash)
} else {
EpochId(last_block.header.next_epoch_id.clone())
},
#[cfg(feature = "protocol_feature_block_header_v3")]
None,
vec![],
Rational::from_integer(0),
0,
100,
Some(0),
vec![],
vec![],
&signer1,
last_block.header.next_bp_hash,
block_merkle_tree.root(),
);
client.do_send(NetworkClientMessages::Block(
block.clone(),
PeerInfo::random().id,
false,
));
for i in 3..11 {
let s = AccountId::try_from(if i > 10 {
"test1".to_string()
} else {
format!("test{}", i)
})
.unwrap();
let signer =
InMemoryValidatorSigner::from_seed(s.clone(), KeyType::ED25519, s.as_ref());
let approval = Approval::new(
*block.hash(),
block.header().height(),
10, // the height at which "test1" is producing
&signer,
);
client
.do_send(NetworkClientMessages::BlockApproval(approval, PeerInfo::random().id));
}
future::ready(())
}));
near_network::test_utils::wait_or_panic(5000);
});
}
/// When approvals arrive early, they should be properly cached.
#[test]
fn produce_block_with_approvals_arrived_early() {
init_test_logger();
let validators = vec![vec![
"test1".parse().unwrap(),
"test2".parse().unwrap(),
"test3".parse().unwrap(),
"test4".parse().unwrap(),
]];
let key_pairs =
vec![PeerInfo::random(), PeerInfo::random(), PeerInfo::random(), PeerInfo::random()];
let block_holder: Arc<RwLock<Option<Block>>> = Arc::new(RwLock::new(None));
run_actix(async move {
let mut approval_counter = 0;
let network_mock: Arc<
RwLock<Box<dyn FnMut(AccountId, &NetworkRequests) -> (NetworkResponses, bool)>>,
> = Arc::new(RwLock::new(Box::new(|_: _, _: &NetworkRequests| {
(NetworkResponses::NoResponse, true)
})));
let (_, conns, _) = setup_mock_all_validators(
validators.clone(),
key_pairs,
1,
true,
2000,
false,
false,
100,
true,
vec![false; validators.iter().map(|x| x.len()).sum()],
vec![true; validators.iter().map(|x| x.len()).sum()],
false,
network_mock.clone(),
);
*network_mock.write().unwrap() =
Box::new(move |_: _, msg: &NetworkRequests| -> (NetworkResponses, bool) {
match msg {
NetworkRequests::Block { block } => {
if block.header().height() == 3 {
for (i, (client, _)) in conns.clone().into_iter().enumerate() {
if i > 0 {
client.do_send(NetworkClientMessages::Block(
block.clone(),
PeerInfo::random().id,
false,
))
}
}
*block_holder.write().unwrap() = Some(block.clone());
return (NetworkResponses::NoResponse, false);
} else if block.header().height() == 4 {
System::current().stop();
}
(NetworkResponses::NoResponse, true)
}
NetworkRequests::Approval { approval_message } => {
if approval_message.target.as_ref() == "test1"
&& approval_message.approval.target_height == 4
{
approval_counter += 1;
}
if approval_counter == 3 {
let block = block_holder.read().unwrap().clone().unwrap();
conns[0].0.do_send(NetworkClientMessages::Block(
block,
PeerInfo::random().id,
false,
));
}
(NetworkResponses::NoResponse, true)
}
_ => (NetworkResponses::NoResponse, true),
}
});
near_network::test_utils::wait_or_panic(10000);
});
}
/// Sends one invalid block followed by one valid block, and checks that client announces only valid block.
/// and that the node bans the peer for invalid block header.
fn invalid_blocks_common(is_requested: bool) {
init_test_logger();
run_actix(async move {
let mut ban_counter = 0;
let (client, view_client) = setup_mock(
vec!["test".parse().unwrap()],
"other".parse().unwrap(),
true,
false,
Box::new(move |msg, _ctx, _client_actor| {
match msg {
NetworkRequests::Block { block } => {
if is_requested {
panic!("rebroadcasting requested block");
} else {
assert_eq!(block.header().height(), 1);
assert_eq!(block.header().chunk_mask().len(), 1);
assert_eq!(ban_counter, 2);
System::current().stop();
}
}
NetworkRequests::BanPeer { ban_reason, .. } => {
assert_eq!(ban_reason, &ReasonForBan::BadBlockHeader);
ban_counter += 1;
if ban_counter == 3 && is_requested {
System::current().stop();
}
}
_ => {}
};
NetworkResponses::NoResponse
}),
);
actix::spawn(view_client.send(GetBlockWithMerkleTree::latest()).then(move |res| {
let (last_block, mut block_merkle_tree) = res.unwrap().unwrap();
let signer = InMemoryValidatorSigner::from_seed(
"test".parse().unwrap(),
KeyType::ED25519,
"test",
);
block_merkle_tree.insert(last_block.header.hash);
#[cfg(feature = "protocol_feature_block_header_v3")]
let next_block_ordinal = last_block.header.block_ordinal.unwrap() + 1;
let valid_block = Block::produce(
PROTOCOL_VERSION,
&last_block.header.clone().into(),
last_block.header.height + 1,
#[cfg(feature = "protocol_feature_block_header_v3")]
next_block_ordinal,
last_block.chunks.iter().cloned().map(Into::into).collect(),
EpochId::default(),
if last_block.header.prev_hash == CryptoHash::default() {
EpochId(last_block.header.hash)
} else {
EpochId(last_block.header.next_epoch_id.clone())
},
#[cfg(feature = "protocol_feature_block_header_v3")]
None,
vec![],
Rational::from_integer(0),
0,
100,
Some(0),
vec![],
vec![],
&signer,
last_block.header.next_bp_hash,
block_merkle_tree.root(),
);
// Send block with invalid chunk mask
let mut block = valid_block.clone();
block.mut_header().get_mut().inner_rest.chunk_mask = vec![];
block.mut_header().get_mut().init();
client.do_send(NetworkClientMessages::Block(
block.clone(),
PeerInfo::random().id,
is_requested,
));
// Send block with invalid chunk signature
let mut block = valid_block.clone();
let mut chunks: Vec<_> = block.chunks().iter().cloned().collect();
let some_signature = Signature::from_parts(KeyType::ED25519, &[1; 64]).unwrap();
match &mut chunks[0] {
ShardChunkHeader::V1(chunk) => {
chunk.signature = some_signature;
}
ShardChunkHeader::V2(chunk) => {
chunk.signature = some_signature;
}
#[cfg(feature = "protocol_feature_block_header_v3")]
ShardChunkHeader::V3(chunk) => {
chunk.signature = some_signature;
}
};
block.set_chunks(chunks);
client.do_send(NetworkClientMessages::Block(
block.clone(),
PeerInfo::random().id,
is_requested,
));
// Send proper block.
let block2 = valid_block.clone();
client.do_send(NetworkClientMessages::Block(
block2.clone(),
PeerInfo::random().id,
is_requested,
));
if is_requested {
let mut block3 = block2.clone();
block3.mut_header().get_mut().inner_rest.chunk_headers_root = hash(&[1]);
block3.mut_header().get_mut().init();
client.do_send(NetworkClientMessages::Block(
block3.clone(),
PeerInfo::random().id,
is_requested,
));
}
future::ready(())
}));
near_network::test_utils::wait_or_panic(5000);
});
}
#[test]
fn test_invalid_blocks_not_requested() {
invalid_blocks_common(false);
}
#[test]
fn test_invalid_blocks_requested() {
invalid_blocks_common(true);
}
enum InvalidBlockMode {
/// Header is invalid
InvalidHeader,
/// Block is ill-formed (roots check fail)
IllFormed,
/// Block is invalid for other reasons
InvalidBlock,
}
fn ban_peer_for_invalid_block_common(mode: InvalidBlockMode) {
init_test_logger();
let validators = vec![vec![
"test1".parse().unwrap(),
"test2".parse().unwrap(),
"test3".parse().unwrap(),
"test4".parse().unwrap(),
]];
let key_pairs =
vec![PeerInfo::random(), PeerInfo::random(), PeerInfo::random(), PeerInfo::random()];
run_actix(async move {
let mut ban_counter = 0;
let network_mock: Arc<
RwLock<Box<dyn FnMut(AccountId, &NetworkRequests) -> (NetworkResponses, bool)>>,
> = Arc::new(RwLock::new(Box::new(|_: _, _: &NetworkRequests| {
(NetworkResponses::NoResponse, true)
})));
let (_, conns, _) = setup_mock_all_validators(
validators.clone(),
key_pairs,
1,
true,
100,
false,
false,
100,
true,
vec![false; validators.iter().map(|x| x.len()).sum()],
vec![true; validators.iter().map(|x| x.len()).sum()],
false,
network_mock.clone(),
);
let mut sent_bad_blocks = false;
*network_mock.write().unwrap() =
Box::new(move |_: _, msg: &NetworkRequests| -> (NetworkResponses, bool) {
match msg {
NetworkRequests::Block { block } => {
if block.header().height() >= 4 && !sent_bad_blocks {
let block_producer_idx =
block.header().height() as usize % validators[0].len();
let block_producer = &validators[0][block_producer_idx];
let validator_signer1 = InMemoryValidatorSigner::from_seed(
block_producer.clone(),
KeyType::ED25519,
block_producer.as_ref(),
);
sent_bad_blocks = true;
let mut block_mut = block.clone();
match mode {
InvalidBlockMode::InvalidHeader => {
// produce an invalid block with invalid header.
block_mut.mut_header().get_mut().inner_rest.chunk_mask = vec![];
block_mut.mut_header().resign(&validator_signer1);
}
InvalidBlockMode::IllFormed => {
// produce an ill-formed block
block_mut
.mut_header()
.get_mut()
.inner_rest
.chunk_headers_root = hash(&[1]);
block_mut.mut_header().resign(&validator_signer1);
}
InvalidBlockMode::InvalidBlock => {
// produce an invalid block whose invalidity cannot be verified by just
// having its header.
#[cfg(feature = "protocol_feature_block_header_v3")]
let proposals = vec![ValidatorStake::new(
"test1".parse().unwrap(),
PublicKey::empty(KeyType::ED25519),
0,
false,
)];
#[cfg(not(feature = "protocol_feature_block_header_v3"))]
let proposals = vec![ValidatorStake::new(
"test1".parse().unwrap(),
PublicKey::empty(KeyType::ED25519),
0,
)];
block_mut
.mut_header()
.get_mut()
.inner_rest
.validator_proposals = proposals;
block_mut.mut_header().resign(&validator_signer1);
}
}
for (i, (client, _)) in conns.clone().into_iter().enumerate() {
if i != block_producer_idx {
client.do_send(NetworkClientMessages::Block(
block_mut.clone(),
PeerInfo::random().id,
false,
))
}
}
return (NetworkResponses::NoResponse, false);
}
if block.header().height() > 20 {
match mode {
InvalidBlockMode::InvalidHeader | InvalidBlockMode::IllFormed => {
assert_eq!(ban_counter, 3);
}
_ => {}
}
System::current().stop();
}
(NetworkResponses::NoResponse, true)
}
NetworkRequests::BanPeer { peer_id, ban_reason } => match mode {
InvalidBlockMode::InvalidHeader | InvalidBlockMode::IllFormed => {
assert_eq!(ban_reason, &ReasonForBan::BadBlockHeader);
ban_counter += 1;
if ban_counter > 3 {
panic!("more bans than expected");
}
(NetworkResponses::NoResponse, true)
}
InvalidBlockMode::InvalidBlock => {
panic!("banning peer {:?} unexpectedly for {:?}", peer_id, ban_reason);
}
},
_ => (NetworkResponses::NoResponse, true),
}
});
near_network::test_utils::wait_or_panic(20000);
});
}
/// If a peer sends a block whose header is valid and passes basic validation, the peer is not banned.
#[test]
fn test_not_ban_peer_for_invalid_block() {
ban_peer_for_invalid_block_common(InvalidBlockMode::InvalidBlock);
}
/// If a peer sends a block whose header is invalid, we should ban them and do not forward the block
#[test]
fn test_ban_peer_for_invalid_block_header() {
ban_peer_for_invalid_block_common(InvalidBlockMode::InvalidHeader);
}
/// If a peer sends a block that is ill-formed, we should ban them and do not forward the block
#[test]
fn test_ban_peer_for_ill_formed_block() {
ban_peer_for_invalid_block_common(InvalidBlockMode::IllFormed);
}
/// Runs two validators runtime with only one validator online.
/// Present validator produces blocks on it's height after deadline.
#[test]
fn skip_block_production() {
init_test_logger();
run_actix(async {
setup_mock(
vec!["test1".parse().unwrap(), "test2".parse().unwrap()],
"test2".parse().unwrap(),
true,
false,
Box::new(move |msg, _ctx, _client_actor| {
match msg {
NetworkRequests::Block { block } => {
if block.header().height() > 3 {
System::current().stop();
}
}
_ => {}
};
NetworkResponses::NoResponse
}),
);
wait_or_panic(10000);
});
}
/// Runs client that requests syncing headers from peers.
#[test]
fn client_sync_headers() {
init_test_logger();
run_actix(async {
let peer_info1 = PeerInfo::random();
let peer_info2 = peer_info1.clone();
let (client, _) = setup_mock(
vec!["test".parse().unwrap()],
"other".parse().unwrap(),
false,
false,
Box::new(move |msg, _ctx, _client_actor| match msg {
NetworkRequests::BlockHeadersRequest { hashes, peer_id } => {
assert_eq!(*peer_id, peer_info1.id);
assert_eq!(hashes.len(), 1);
// TODO: check it requests correct hashes.
System::current().stop();
NetworkResponses::NoResponse
}
_ => NetworkResponses::NoResponse,
}),
);
client.do_send(NetworkClientMessages::NetworkInfo(NetworkInfo {
active_peers: vec![FullPeerInfo {
peer_info: peer_info2.clone(),
chain_info: PeerChainInfoV2 {
genesis_id: Default::default(),
height: 5,
tracked_shards: vec![],
archival: false,
},
edge_info: EdgeInfo::default(),
}],
num_active_peers: 1,
peer_max_count: 1,
highest_height_peers: vec![FullPeerInfo {
peer_info: peer_info2.clone(),
chain_info: PeerChainInfoV2 {
genesis_id: Default::default(),
height: 5,
tracked_shards: vec![],
archival: false,
},
edge_info: EdgeInfo::default(),
}],
sent_bytes_per_sec: 0,
received_bytes_per_sec: 0,
known_producers: vec![],
peer_counter: 0,
}));
wait_or_panic(2000);
});
}
fn produce_blocks(client: &mut Client, num: u64) {
for i in 1..num {
let b = client.produce_block(i).unwrap().unwrap();
let (mut accepted_blocks, _) = client.process_block(b, Provenance::PRODUCED);
let f = |_| {};
let more_accepted_blocks = client.run_catchup(&vec![], &f).unwrap();
accepted_blocks.extend(more_accepted_blocks);
for accepted_block in accepted_blocks {
client.on_block_accepted(
accepted_block.hash,
accepted_block.status,
accepted_block.provenance,
);
}
}
}
#[test]
fn test_process_invalid_tx() {
init_test_logger();
let store = create_test_store();
let network_adapter = Arc::new(MockNetworkAdapter::default());
let mut chain_genesis = ChainGenesis::test();
chain_genesis.transaction_validity_period = 10;
let mut client = setup_client(
store,
vec![vec!["test1".parse().unwrap()]],
1,
1,
Some("test1".parse().unwrap()),
false,
network_adapter,
chain_genesis,
);
let signer = InMemorySigner::from_seed("test1".parse().unwrap(), KeyType::ED25519, "test1");
let tx = SignedTransaction::new(
Signature::empty(KeyType::ED25519),
Transaction {
signer_id: AccountId::test_account(),
public_key: signer.public_key(),
nonce: 0,
receiver_id: AccountId::test_account(),
block_hash: *client.chain.genesis().hash(),
actions: vec![],
},
);
produce_blocks(&mut client, 12);
assert_eq!(
client.process_tx(tx, false, false),
NetworkClientResponses::InvalidTx(InvalidTxError::Expired)
);
let tx2 = SignedTransaction::new(
Signature::empty(KeyType::ED25519),
Transaction {
signer_id: AccountId::test_account(),
public_key: signer.public_key(),
nonce: 0,
receiver_id: AccountId::test_account(),
block_hash: hash(&[1]),