-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathon_propose.rs
1138 lines (1028 loc) · 45.2 KB
/
on_propose.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
// Copyright 2023 The Tari Project
// SPDX-License-Identifier: BSD-3-Clause
use std::{
collections::{BTreeSet, HashMap, HashSet},
fmt::Display,
num::NonZeroU64,
};
use log::*;
use tari_common_types::types::{FixedHash, PublicKey};
use tari_crypto::tari_utilities::epoch_time::EpochTime;
use tari_dan_common_types::{
committee::{Committee, CommitteeInfo},
option::Displayable,
optional::Optional,
shard::Shard,
Epoch,
ExtraData,
NodeHeight,
ToSubstateAddress,
VersionedSubstateId,
};
use tari_dan_storage::{
consensus_models::{
AbortReason,
Block,
BlockHeader,
BlockId,
BlockTransactionExecution,
BurntUtxo,
Command,
Decision,
EvictNodeAtom,
ForeignProposal,
ForeignSendCounters,
HighQc,
LastProposed,
LeafBlock,
LockedBlock,
PendingShardStateTreeDiff,
QcId,
QuorumCertificate,
SubstateChange,
TransactionAtom,
TransactionExecution,
TransactionPool,
TransactionPoolRecord,
TransactionPoolStage,
TransactionRecord,
ValidatorConsensusStats,
},
StateStore,
};
use tari_engine_types::{commit_result::RejectReason, substate::Substate};
use tari_epoch_manager::EpochManagerReader;
use tari_transaction::TransactionId;
use tokio::task;
use crate::{
hotstuff::{
apply_leader_fee_to_substate_store,
block_change_set::ProposedBlockChangeSet,
calculate_state_merkle_root,
error::HotStuffError,
filter_diff_for_committee,
substate_store::PendingSubstateStore,
to_public_key_bytes,
transaction_manager::{
ConsensusTransactionManager,
LocalPreparedTransaction,
PledgedTransaction,
PreparedTransaction,
TransactionLockConflicts,
},
HotstuffConfig,
},
messages::{HotstuffMessage, ProposalMessage},
tracing::TraceTimer,
traits::{ConsensusSpec, OutboundMessaging, ValidatorSignatureService, WriteableSubstateStore},
};
const LOG_TARGET: &str = "tari::dan::consensus::hotstuff::on_local_propose";
struct NextBlock {
block: Block,
foreign_proposals: Vec<ForeignProposal>,
executed_transactions: HashMap<TransactionId, TransactionExecution>,
lock_conflicts: TransactionLockConflicts,
}
#[derive(Debug, Clone)]
pub struct OnPropose<TConsensusSpec: ConsensusSpec> {
config: HotstuffConfig,
store: TConsensusSpec::StateStore,
epoch_manager: TConsensusSpec::EpochManager,
transaction_pool: TransactionPool<TConsensusSpec::StateStore>,
transaction_manager: ConsensusTransactionManager<TConsensusSpec::TransactionExecutor, TConsensusSpec::StateStore>,
signing_service: TConsensusSpec::SignatureService,
outbound_messaging: TConsensusSpec::OutboundMessaging,
}
impl<TConsensusSpec> OnPropose<TConsensusSpec>
where TConsensusSpec: ConsensusSpec
{
pub fn new(
config: HotstuffConfig,
store: TConsensusSpec::StateStore,
epoch_manager: TConsensusSpec::EpochManager,
transaction_pool: TransactionPool<TConsensusSpec::StateStore>,
transaction_manager: ConsensusTransactionManager<
TConsensusSpec::TransactionExecutor,
TConsensusSpec::StateStore,
>,
signing_service: TConsensusSpec::SignatureService,
outbound_messaging: TConsensusSpec::OutboundMessaging,
) -> Self {
Self {
config,
store,
epoch_manager,
transaction_pool,
transaction_manager,
signing_service,
outbound_messaging,
}
}
#[allow(clippy::too_many_lines)]
pub async fn handle(
&mut self,
epoch: Epoch,
next_height: NodeHeight,
local_committee: &Committee<TConsensusSpec::Addr>,
local_committee_info: CommitteeInfo,
local_claim_public_key: &PublicKey,
leaf_block: LeafBlock,
propose_epoch_end: bool,
) -> Result<(), HotStuffError> {
let _timer = TraceTimer::info(LOG_TARGET, "OnPropose");
if let Some(last_proposed) = self.store.with_read_tx(|tx| LastProposed::get(tx)).optional()? {
if last_proposed.epoch == epoch && last_proposed.height >= next_height {
info!(
target: LOG_TARGET,
"⤵️ SKIPPING propose for {} ({}) because we already proposed block {}",
next_height,
leaf_block,
last_proposed,
);
return Ok(());
}
}
let (current_base_layer_block_height, current_base_layer_block_hash) =
self.epoch_manager.current_base_layer_block_info().await?;
let base_layer_block_hash = current_base_layer_block_hash;
let base_layer_block_height = current_base_layer_block_height;
let on_propose = self.clone();
let local_claim_public_key = to_public_key_bytes(local_claim_public_key);
let (next_block, foreign_proposals) = task::spawn_blocking(move || {
on_propose.store.with_write_tx(|tx| {
let high_qc = HighQc::get(&**tx, epoch)?;
let high_qc_cert = high_qc.get_quorum_certificate(&**tx)?;
info!(
target: LOG_TARGET,
"🌿 PROPOSE local block with parent {}. HighQC: {}",
leaf_block,
high_qc_cert,
);
let next_block = on_propose.build_next_block(
tx,
epoch,
next_height,
leaf_block,
high_qc_cert,
&local_committee_info,
local_claim_public_key,
false,
base_layer_block_height,
base_layer_block_hash,
propose_epoch_end,
)?;
let NextBlock {
block: next_block,
foreign_proposals,
executed_transactions,
lock_conflicts,
} = next_block;
lock_conflicts.save_for_block(tx, next_block.id())?;
// Add executions for this block
if !executed_transactions.is_empty() {
debug!(
target: LOG_TARGET,
"Saving {} executed transaction(s) for block {}",
executed_transactions.len(),
next_block.id()
);
}
for executed in executed_transactions.into_values() {
executed.for_block(*next_block.id()).insert_if_required(tx)?;
}
next_block.as_last_proposed().set(tx)?;
Ok::<_, HotStuffError>((next_block, foreign_proposals))
})
})
.await??;
info!(
target: LOG_TARGET,
"🌿 [{}] PROPOSING new local block {} to {} validators. justify: {} ({}), parent: {}",
self.signing_service.public_key(),
next_block,
local_committee.len(),
next_block.justify().block_id(),
next_block.justify().block_height(),
next_block.parent()
);
self.broadcast_local_proposal(next_block, foreign_proposals, &local_committee_info)
.await?;
Ok(())
}
pub async fn broadcast_local_proposal(
&mut self,
next_block: Block,
foreign_proposals: Vec<ForeignProposal>,
local_committee_info: &CommitteeInfo,
) -> Result<(), HotStuffError> {
let epoch = next_block.epoch();
let leaf_block = next_block.as_leaf_block();
let msg = HotstuffMessage::Proposal(ProposalMessage {
block: next_block,
foreign_proposals,
});
// Broadcast to local and foreign committees
self.outbound_messaging.send_self(msg.clone()).await?;
// If we are the only VN in this committee, no need to multicast
if local_committee_info.num_shard_group_members() <= 1 {
info!(
target: LOG_TARGET,
"🌿 This node is the only member of the local committee. No need to multicast proposal {leaf_block}",
);
} else {
let committee = self
.epoch_manager
.get_committee_by_shard_group(epoch, local_committee_info.shard_group(), None)
.await?;
info!(
target: LOG_TARGET,
"🌿 Broadcasting local proposal to {}/{} local committee members {}",
committee.len(), local_committee_info.num_shard_group_members(), leaf_block,
);
if let Err(err) = self.outbound_messaging.multicast(committee.into_addresses(), msg).await {
warn!(
target: LOG_TARGET,
"Failed to multicast proposal to local committee: {}",
err
);
}
}
Ok(())
}
/// Returns Ok(None) if the command cannot be sequenced yet due to lock conflicts.
fn transaction_pool_record_to_command(
&self,
tx: &<TConsensusSpec::StateStore as StateStore>::ReadTransaction<'_>,
start_of_chain_id: &LeafBlock,
mut tx_rec: TransactionPoolRecord,
local_committee_info: &CommitteeInfo,
substate_store: &mut PendingSubstateStore<TConsensusSpec::StateStore>,
executed_transactions: &mut HashMap<TransactionId, TransactionExecution>,
lock_conflicts: &mut TransactionLockConflicts,
) -> Result<Option<Command>, HotStuffError> {
match tx_rec.current_stage() {
TransactionPoolStage::New => self.prepare_transaction(
start_of_chain_id,
&mut tx_rec,
local_committee_info,
substate_store,
executed_transactions,
lock_conflicts,
),
// Leader thinks all local nodes have prepared
TransactionPoolStage::Prepared => {
if tx_rec.current_decision().is_abort() {
let atom = tx_rec.get_current_transaction_atom();
return Ok(Some(Command::LocalAccept(atom)));
}
if tx_rec
.evidence()
.is_committee_output_only(local_committee_info.shard_group())
{
if !tx_rec.has_all_required_foreign_input_pledges(tx, local_committee_info)? {
error!(
target: LOG_TARGET,
"BUG: attempted to propose transaction {} as Prepared but not all foreign input pledges were found. \
This transaction should not have been marked as ready. {}",
tx_rec.transaction_id(),
tx_rec.evidence()
);
return Ok(None);
}
let atom = tx_rec.get_local_transaction_atom();
debug!(
target: LOG_TARGET,
"ℹ️ Transaction {} is output-only for {}, proposing LocalAccept",
tx_rec.transaction_id(),
local_committee_info.shard_group()
);
Ok(Some(Command::LocalAccept(atom)))
} else {
let atom = tx_rec.get_local_transaction_atom();
Ok(Some(Command::LocalPrepare(atom)))
}
},
// Leader thinks all foreign PREPARE pledges have been received (condition for LocalPrepared stage to be
// ready)
TransactionPoolStage::LocalPrepared => self.all_or_some_prepare_transaction(
tx,
start_of_chain_id,
local_committee_info,
&mut tx_rec,
substate_store,
executed_transactions,
),
// Leader thinks that all local nodes agree that all shard groups have prepared, we are ready to accept
// locally
TransactionPoolStage::AllPrepared => Ok(Some(Command::LocalAccept(
self.get_transaction_atom_with_leader_fee(&mut tx_rec)?,
))),
// Leader thinks local nodes are ready to accept an ABORT
TransactionPoolStage::SomePrepared => Ok(Some(Command::LocalAccept(tx_rec.get_current_transaction_atom()))),
// Leader thinks that all foreign ACCEPT pledges have been received and, we are ready to accept the result
// (COMMIT/ABORT)
TransactionPoolStage::LocalAccepted => {
self.accept_transaction(tx, start_of_chain_id, &mut tx_rec, local_committee_info, substate_store)
},
// Not reachable as there is nothing to propose for these stages. To confirm that all local nodes
// agreed with the Accept, more (possibly empty) blocks with QCs will be
// proposed and accepted, otherwise the Accept block will not be committed.
TransactionPoolStage::AllAccepted |
TransactionPoolStage::SomeAccepted |
TransactionPoolStage::LocalOnly => {
unreachable!(
"It is invalid for TransactionPoolStage::{} to be ready to propose",
tx_rec.current_stage()
)
},
}
}
fn process_newly_justified_block(
&self,
tx: &<TConsensusSpec::StateStore as StateStore>::ReadTransaction<'_>,
new_leaf_block: &Block,
high_qc_id: QcId,
local_committee_info: &CommitteeInfo,
change_set: &mut ProposedBlockChangeSet,
) -> Result<(), HotStuffError> {
let locked_block = LockedBlock::get(tx, new_leaf_block.epoch())?;
info!(
target: LOG_TARGET,
"✅ New leaf block {} is justified. Updating evidence for transactions",
new_leaf_block,
);
let leaf = new_leaf_block.as_leaf_block();
for cmd in new_leaf_block.commands() {
if !cmd.is_local_prepare() && !cmd.is_local_accept() {
continue;
}
let atom = cmd.transaction().expect("Command must be a transaction");
let Some(mut pool_tx) = change_set
.get_transaction(tx, &locked_block, &leaf, atom.id())
.optional()?
else {
return Err(HotStuffError::InvariantError(format!(
"Transaction {} in newly justified block {} not found in the pool",
atom.id(),
leaf,
)));
};
if cmd.is_local_prepare() {
pool_tx
.evidence_mut()
.add_shard_group(local_committee_info.shard_group())
.set_prepare_qc(high_qc_id);
} else if cmd.is_local_accept() {
pool_tx
.evidence_mut()
.add_shard_group(local_committee_info.shard_group())
.set_accept_qc(high_qc_id);
} else {
// Nothing
}
// Set readiness
if !pool_tx.is_ready() && pool_tx.is_ready_for_pending_stage() {
pool_tx.set_ready(true);
}
debug!(
target: LOG_TARGET,
"ON PROPOSE: process_newly_justified_block {} {} {}, QC[{}]",
pool_tx.transaction_id(),
pool_tx.current_stage(),
local_committee_info.shard_group(),
high_qc_id
);
change_set.set_next_transaction_update(pool_tx)?;
}
Ok(())
}
#[allow(clippy::too_many_lines)]
fn build_next_block(
&self,
tx: &<TConsensusSpec::StateStore as StateStore>::ReadTransaction<'_>,
epoch: Epoch,
next_height: NodeHeight,
parent_block: LeafBlock,
high_qc_certificate: QuorumCertificate,
local_committee_info: &CommitteeInfo,
local_claim_public_key_bytes: [u8; 32],
dont_propose_transactions: bool,
base_layer_block_height: u64,
base_layer_block_hash: FixedHash,
propose_epoch_end: bool,
) -> Result<NextBlock, HotStuffError> {
// The parent block will only ever not exist if it is a dummy block
let parent_exists = Block::record_exists(tx, parent_block.block_id())?;
let start_of_chain_block = if parent_exists {
// Parent exists - we can include its state in the MR calc, foreign propose etc
parent_block
} else {
// Parent does not exist which means we have dummy blocks between the parent and the justified block so we
// can exclude them from the query. There are a few queries that will fail if we used a non-existent block.
high_qc_certificate.as_leaf_block()
};
let mut total_leader_fee = 0;
let batch = if propose_epoch_end {
ProposalBatch::default()
} else {
self.fetch_next_proposal_batch(
tx,
local_committee_info,
dont_propose_transactions,
start_of_chain_block,
)?
};
debug!(target: LOG_TARGET, "🌿 PROPOSE: {batch}");
let mut commands = if propose_epoch_end {
BTreeSet::from_iter([Command::EndEpoch])
} else {
BTreeSet::from_iter(
batch
.foreign_proposals
.iter()
.map(|fp| Command::ForeignProposal(fp.to_atom()))
.chain(
batch
.burnt_utxos
.iter()
.map(|bu| Command::MintConfidentialOutput(bu.to_atom())),
)
.chain(
batch
.evict_nodes
.into_iter()
.map(|public_key| Command::EvictNode(EvictNodeAtom { public_key })),
),
)
};
let mut change_set = ProposedBlockChangeSet::new(high_qc_certificate.as_leaf_block());
// No need to include evidence from justified block if no transactions are included in the next block
if !batch.transactions.is_empty() {
// TODO(protocol-efficiency): We should process any foreign proposals included in this block to include
// evidence. And that should determine if they are ready. However this is difficult because we
// get the batch from the database which isnt aware of which foreign proposals we're going to
// propose. This is why the system currently never proposes foreign proposals affecting a
// transaction in the same block for LocalPrepare/LocalAccept and can result in evidence in the
// atom having missing Prepare/Accept QCs (which are added on subsequent proposals).
// let locked_block = LockedBlock::get(tx, epoch)?;
// let num_proposals = batch.foreign_proposals.len();
// let foreign_proposals = mem::replace(&mut batch.foreign_proposals, Vec::with_capacity(num_proposals));
// for fp in foreign_proposals {
// if let Err(err) = process_foreign_block(
// tx,
// &high_qc_certificate.as_leaf_block(),
// &locked_block,
// &fp,
// local_committee_info,
// &mut change_set,
// ) {
// warn!(
// target: LOG_TARGET,
// "Failed to process foreign proposal: {}. Skipping this proposal...",
// err
// );
// // TODO: mark as invalid
// continue;
// }
// batch.foreign_proposals.push(fp);
// }
let justified_block = high_qc_certificate.get_block(tx)?;
if !justified_block.is_justified() {
// TODO: we dont need to process transactions here that are not in the batch
self.process_newly_justified_block(
tx,
&justified_block,
*high_qc_certificate.id(),
local_committee_info,
&mut change_set,
)?;
}
}
// batch is empty for is_empty, is_epoch_end and is_epoch_start blocks
let mut substate_store = PendingSubstateStore::new(
tx,
*start_of_chain_block.block_id(),
self.config.consensus_constants.num_preshards,
);
let mut executed_transactions = HashMap::new();
let timer = TraceTimer::info(LOG_TARGET, "Generating commands").with_iterations(batch.transactions.len());
let mut lock_conflicts = TransactionLockConflicts::new();
for mut transaction in batch.transactions {
// Apply the transaction updates (if any) that occurred as a result of the justified block.
// This allows us to propose evidence in the next block that relates to transactions in the justified block.
change_set.apply_transaction_update(&mut transaction);
if let Some(command) = self.transaction_pool_record_to_command(
tx,
&start_of_chain_block,
transaction,
local_committee_info,
&mut substate_store,
&mut executed_transactions,
&mut lock_conflicts,
)? {
total_leader_fee += command
.committing()
.and_then(|tx| tx.leader_fee.as_ref())
.map(|f| f.fee)
.unwrap_or(0);
// TODO: a BTreeSet changes the order from the original batch. Uncertain if this is a problem since the
// proposer also processes transactions in the completed block order, however on_propose does perform
// some operations (e.g. prepare, execute) in batch order. To ensure correctness, we should process
// on_propose in canonical order.
commands.insert(command);
}
}
timer.done();
// This relies on the UTXO commands being ordered after transaction commands
for utxo in batch.burnt_utxos {
let id = VersionedSubstateId::new(utxo.commitment, 0);
let shard = id.to_substate_address().to_shard(local_committee_info.num_preshards());
let change = SubstateChange::Up {
id,
shard,
// N/A
transaction_id: Default::default(),
substate: Substate::new(0, utxo.output),
};
substate_store.put(change)?;
}
debug!(
target: LOG_TARGET,
"command(s) for next block: [{}]",
commands.display()
);
let timer = TraceTimer::info(LOG_TARGET, "Propose calculate state root");
let pending_tree_diffs =
PendingShardStateTreeDiff::get_all_up_to_commit_block(tx, start_of_chain_block.block_id())?;
// Add proposer fee substate
if total_leader_fee > 0 {
let total_leader_fee_amt = total_leader_fee.try_into().map_err(|e| {
HotStuffError::InvariantError(format!(
"Total leader fee ({total_leader_fee}) under/overflowed the Amount type: {e}"
))
})?;
// Apply leader fee to substate store before we calculate the state root
apply_leader_fee_to_substate_store(
&mut substate_store,
local_claim_public_key_bytes,
local_committee_info.shard_group().start(),
local_committee_info.num_preshards(),
total_leader_fee_amt,
)?;
}
let (state_root, _) = calculate_state_merkle_root(
tx,
local_committee_info.shard_group(),
pending_tree_diffs,
substate_store.diff(),
)?;
timer.done();
let non_local_shards = get_non_local_shards(substate_store.diff(), local_committee_info);
let foreign_counters = ForeignSendCounters::get_or_default(tx, parent_block.block_id())?;
let foreign_indexes = non_local_shards
.iter()
.map(|shard| (*shard, foreign_counters.get_count(*shard) + 1))
.collect();
let mut header = BlockHeader::create(
self.config.network,
*parent_block.block_id(),
*high_qc_certificate.id(),
next_height,
epoch,
local_committee_info.shard_group(),
self.signing_service.public_key().clone(),
state_root,
&commands,
total_leader_fee,
foreign_indexes,
None,
EpochTime::now().as_u64(),
base_layer_block_height,
base_layer_block_hash,
ExtraData::new(),
)?;
let signature = self.signing_service.sign(header.id());
header.set_signature(signature);
let next_block = Block::new(header, high_qc_certificate, commands);
Ok(NextBlock {
block: next_block,
foreign_proposals: batch.foreign_proposals,
executed_transactions,
lock_conflicts,
})
}
#[allow(clippy::too_many_lines)]
fn fetch_next_proposal_batch(
&self,
tx: &<<TConsensusSpec as ConsensusSpec>::StateStore as StateStore>::ReadTransaction<'_>,
local_committee_info: &CommitteeInfo,
dont_propose_transactions: bool,
start_of_chain_block: LeafBlock,
) -> Result<ProposalBatch, HotStuffError> {
let _timer = TraceTimer::debug(LOG_TARGET, "fetch_next_proposal_batch");
let foreign_proposals = ForeignProposal::get_all_new(
tx,
start_of_chain_block.block_id(),
self.config.consensus_constants.max_block_size / 4,
)?;
if !foreign_proposals.is_empty() {
debug!(
target: LOG_TARGET,
"🌿 Found {} foreign proposals for next block",
foreign_proposals.len()
);
}
let mut remaining_block_size = subtract_block_size_checked(
Some(self.config.consensus_constants.max_block_size),
foreign_proposals.len() * 4,
);
let burnt_utxos = remaining_block_size
.map(|size| BurntUtxo::get_all_unproposed(tx, start_of_chain_block.block_id(), size))
.transpose()?
.unwrap_or_default();
if !burnt_utxos.is_empty() {
debug!(
target: LOG_TARGET,
"🌿 Found {} burnt utxos for next block",
burnt_utxos.len()
);
}
remaining_block_size = subtract_block_size_checked(remaining_block_size, burnt_utxos.len());
let evict_nodes = remaining_block_size
.map(|max| {
let num_evicted =
ValidatorConsensusStats::count_number_evicted_nodes(tx, start_of_chain_block.epoch())?;
let max_allowed_to_evict = u64::from(local_committee_info.max_failures())
.saturating_sub(num_evicted)
.min(max as u64);
ValidatorConsensusStats::get_nodes_to_evict(
tx,
start_of_chain_block.block_id(),
self.config.consensus_constants.missed_proposal_evict_threshold,
max_allowed_to_evict,
)
})
.transpose()?
.unwrap_or_default();
if !evict_nodes.is_empty() {
debug!(
target: LOG_TARGET,
"🌿 Found {} EVICT nodes for next block",
evict_nodes.len()
)
}
remaining_block_size = subtract_block_size_checked(remaining_block_size, evict_nodes.len());
let transactions = if dont_propose_transactions {
vec![]
} else {
remaining_block_size
.map(|size| {
self.transaction_pool
.get_batch_for_next_block(tx, size, start_of_chain_block.block_id())
})
.transpose()?
.unwrap_or_default()
};
Ok(ProposalBatch {
foreign_proposals,
burnt_utxos,
transactions,
evict_nodes,
})
}
#[allow(clippy::too_many_lines)]
fn prepare_transaction(
&self,
parent_block: &LeafBlock,
tx_rec: &mut TransactionPoolRecord,
local_committee_info: &CommitteeInfo,
substate_store: &mut PendingSubstateStore<TConsensusSpec::StateStore>,
executed_transactions: &mut HashMap<TransactionId, TransactionExecution>,
lock_conflicts: &mut TransactionLockConflicts,
) -> Result<Option<Command>, HotStuffError> {
info!(
target: LOG_TARGET,
"👨🔧 PROPOSE: PREPARE transaction {}",
tx_rec.transaction_id(),
);
let prepared = self
.transaction_manager
.prepare(
substate_store,
local_committee_info,
parent_block.epoch(),
tx_rec,
parent_block.block_id(),
)
.map_err(|e| HotStuffError::TransactionExecutorError(e.to_string()))?;
if prepared.lock_status().is_any_failed() && !prepared.lock_status().is_hard_conflict() {
warn!(
target: LOG_TARGET,
"⚠️ Transaction {} has lock conflicts, but no hard conflicts. Skipping proposing this transaction...",
tx_rec.transaction_id(),
);
lock_conflicts.add(
*tx_rec.transaction_id(),
prepared.into_lock_status().into_lock_conflicts(),
);
return Ok(None);
}
let command = match prepared {
PreparedTransaction::LocalOnly(LocalPreparedTransaction::Accept { execution, .. }) => {
// Update the decision so that we can propose it
tx_rec.update_from_execution(
local_committee_info.num_preshards(),
local_committee_info.num_committees(),
&execution,
);
info!(
target: LOG_TARGET,
"🏠️ Transaction {} is local only, proposing LocalOnly",
tx_rec.transaction_id(),
);
if tx_rec.current_decision().is_commit() {
let involved = NonZeroU64::new(1).expect("1 > 0");
let leader_fee =
tx_rec.calculate_leader_fee(involved, self.config.consensus_constants.fee_exhaust_divisor);
tx_rec.set_leader_fee(leader_fee);
let diff = execution.result().finalize.result.accept().ok_or_else(|| {
HotStuffError::InvariantError(format!(
"prepare_transaction: Transaction {} has COMMIT decision but execution failed when \
proposing",
tx_rec.transaction_id(),
))
})?;
if let Err(err) = substate_store.put_diff(*tx_rec.transaction_id(), diff) {
error!(
target: LOG_TARGET,
"🔒 Failed to write to temporary state store for transaction {} for LocalOnly: {}. Skipping proposing this transaction...",
tx_rec.transaction_id(),
err,
);
// Only error if it is not related to lock errors
let _err = err.ok_lock_failed()?;
return Ok(None);
}
}
executed_transactions.insert(*tx_rec.transaction_id(), execution);
let atom = tx_rec.get_current_transaction_atom();
Command::LocalOnly(atom)
},
PreparedTransaction::LocalOnly(LocalPreparedTransaction::EarlyAbort { execution }) => {
info!(
target: LOG_TARGET,
"⚠️ Transaction is LOCAL-ONLY EARLY ABORT, proposing LocalOnly({}, ABORT)",
tx_rec.transaction_id(),
);
tx_rec.set_local_decision(Decision::Abort(AbortReason::EarlyAbort));
info!(
target: LOG_TARGET,
"⚠️ Transaction is LOCAL-ONLY EARLY ABORT, proposing LocalOnly({}, ABORT)",
tx_rec.transaction_id(),
);
tx_rec.update_from_execution(
local_committee_info.num_preshards(),
local_committee_info.num_committees(),
&execution,
);
executed_transactions.insert(*tx_rec.transaction_id(), execution);
let atom = tx_rec.get_current_transaction_atom();
Command::LocalOnly(atom)
},
PreparedTransaction::MultiShard(multishard) => {
match multishard.current_decision() {
Decision::Commit => {
if multishard.is_executed() {
let involves_inputs = multishard.involve_any_inputs();
// CASE: All inputs are local and outputs are foreign (i.e. the transaction is executed), or
// all inputs are foreign and this shard group is output only.
let execution = multishard.into_execution().expect("Abort should have execution");
tx_rec.update_from_execution(
local_committee_info.num_preshards(),
local_committee_info.num_committees(),
&execution,
);
if !involves_inputs {
let num_involved_shard_groups = tx_rec.evidence().num_shard_groups();
let involved = NonZeroU64::new(num_involved_shard_groups as u64).ok_or_else(|| {
HotStuffError::InvariantError("Number of involved shard groups is 0".to_string())
})?;
let leader_fee = tx_rec.calculate_leader_fee(
involved,
self.config.consensus_constants.fee_exhaust_divisor,
);
tx_rec.set_leader_fee(leader_fee);
}
executed_transactions.insert(*tx_rec.transaction_id(), execution);
} else {
// CASE: All local inputs were resolved. We need to continue with consensus to get the
// foreign inputs/outputs.
tx_rec.set_local_decision(Decision::Commit);
// Set partial evidence using local inputs and known outputs.
tx_rec
.evidence_mut()
.update(&multishard.to_initial_evidence(local_committee_info));
}
},
Decision::Abort(reason) => {
warn!(target: LOG_TARGET, "Prepare transaction abort: {reason:?}");
let initial_evidence = multishard.to_initial_evidence(local_committee_info);
// CASE: The transaction was ABORTed due to a lock conflict
let execution = multishard.into_execution().expect("Abort must have execution");
tx_rec.update_from_execution(
local_committee_info.num_preshards(),
local_committee_info.num_committees(),
&execution,
);
tx_rec.evidence_mut().update(&initial_evidence);
executed_transactions.insert(*tx_rec.transaction_id(), execution);
},
}
info!(
target: LOG_TARGET,
"🌍 Transaction involves foreign shard groups, proposing Prepare({}, {})",
tx_rec.transaction_id(),
tx_rec.current_decision(),
);
let atom = tx_rec.get_local_transaction_atom();
Command::Prepare(atom)
},
};
Ok(Some(command))
}
fn all_or_some_prepare_transaction(
&self,
tx: &<TConsensusSpec::StateStore as StateStore>::ReadTransaction<'_>,
parent_block: &LeafBlock,
local_committee_info: &CommitteeInfo,
tx_rec: &mut TransactionPoolRecord,
substate_store: &mut PendingSubstateStore<TConsensusSpec::StateStore>,
executed_transactions: &mut HashMap<TransactionId, TransactionExecution>,
) -> Result<Option<Command>, HotStuffError> {
// Only set to abort if either the local or one or more foreign shards decided to ABORT
if tx_rec.current_decision().is_abort() {
return Ok(Some(Command::SomePrepare(tx_rec.get_current_transaction_atom())));
}
let transaction = TransactionRecord::get(tx, tx_rec.transaction_id())?;
if !transaction.has_all_required_input_pledges(tx, local_committee_info)? {
// TODO: investigate - this case does occur when all_input_shard_groups_prepared is used vs
// all_shard_groups_prepared in can_continue_to, not sure why.
// Once case where this can happen if we received a LocalAccept pledge, which will skip sending the substate
// values, but not LocalPrepare (which contains substate values). This could be solved by
// (re-)requesting the LocalPrepare pledge.
error!(
target: LOG_TARGET,
"BUG: attempted to propose transaction {} as AllPrepared but not all input pledges were found. This transaction should not have been marked as ready.",
tx_rec.transaction_id(),
);
return Ok(None);
}
let mut execution = self.execute_transaction(tx, &parent_block.block_id, parent_block.epoch, transaction)?;
// Try to lock all local outputs
let local_outputs = execution.resulting_outputs().iter().filter(|o| {
o.substate_id().is_transaction_receipt() || local_committee_info.includes_substate_id(o.substate_id())
});
let lock_status = substate_store.try_lock_all(*tx_rec.transaction_id(), local_outputs, false)?;
if let Some(err) = lock_status.failures().first() {
warn!(
target: LOG_TARGET,
"⚠️ Failed to lock outputs for transaction {}: {}",
tx_rec.transaction_id(),
err,
);
// If the transaction does not lock, we propose to abort it
execution.set_abort_reason(RejectReason::FailedToLockOutputs(err.to_string()));
tx_rec.update_from_execution(
local_committee_info.num_preshards(),
local_committee_info.num_committees(),
&execution,
);
executed_transactions.insert(*tx_rec.transaction_id(), execution);
return Ok(Some(Command::AllPrepare(tx_rec.get_current_transaction_atom())));
}
tx_rec.update_from_execution(