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
//! Block proposal logic
use crate::config::ConsensusConfig;
use crate::error::{ConsensusError, Result};
use crate::mempool::Mempool;
use std::sync::Arc;
use tenzro_types::block::{
Block, BlockHeader, BlockMetadata, ConsensusAlgorithm, ConsensusProof, FeeMarketParams,
calculate_next_base_fee,
};
use tenzro_types::primitives::{Address, BlockHeight, Hash};
use tenzro_types::transaction::SignedTransaction;
/// Block proposer responsible for creating new blocks
pub struct BlockProposer {
/// Mempool for transaction selection
mempool: Arc<Mempool>,
/// Consensus configuration
config: Arc<ConsensusConfig>,
}
impl BlockProposer {
/// Creates a new block proposer
pub fn new(mempool: Arc<Mempool>, config: Arc<ConsensusConfig>) -> Self {
Self { mempool, config }
}
/// Proposes a new block at the given HotStuff view.
///
/// The view is stamped into `BlockHeader::view` so peers receiving the
/// proposal can advance their local view to match before voting (see
/// `HotStuff2Engine::on_proposal`). Without this, votes from peers at
/// drifted views never coalesce into a quorum.
///
/// `parent_base_fee`, `parent_gas_used`, and `parent_gas_limit` come
/// from the parent block's `BlockMetadata` and feed the EIP-1559
/// base-fee derivation. The proposer stamps the resulting base fee
/// into the new block's metadata; validators independently re-derive
/// from the same parent and reject the proposal on mismatch (see
/// [`Self::validate_base_fee`]). For the genesis child (height=1),
/// pass the genesis metadata fields — `calculate_next_base_fee`
/// detects the gas-limit-zero edge and returns the initial base fee.
pub fn propose_block(
&self,
height: BlockHeight,
view: u64,
prev_hash: Hash,
proposer: Address,
state_root: Hash,
parent_base_fee: Option<u128>,
parent_gas_used: u64,
parent_gas_limit: u64,
) -> Result<Block> {
// Select transactions from mempool
let transactions = self.select_transactions()?;
if transactions.is_empty() {
tracing::debug!("No transactions available for block proposal");
}
self.assemble_block(
height,
view,
prev_hash,
proposer,
state_root,
parent_base_fee,
parent_gas_used,
parent_gas_limit,
transactions,
)
}
/// Assemble a block from a pre-selected, already-ordered transaction set.
///
/// This is the block-body-independent assembly core shared by the mempool
/// path ([`Self::propose_block`]) and the batch-certificate path
/// ([`Self::propose_block_from_transactions`]). The transactions are taken
/// verbatim in the order supplied — the caller owns ordering. Header,
/// tx-root, EIP-1559 base fee, and metadata are derived identically
/// regardless of where the transactions came from, so a block built from a
/// certified batch prefix is byte-compatible with one built from the
/// mempool and validates through the same path.
pub fn propose_block_from_transactions(
&self,
height: BlockHeight,
view: u64,
prev_hash: Hash,
proposer: Address,
state_root: Hash,
parent_base_fee: Option<u128>,
parent_gas_used: u64,
parent_gas_limit: u64,
transactions: Vec<SignedTransaction>,
) -> Result<Block> {
self.assemble_block(
height,
view,
prev_hash,
proposer,
state_root,
parent_base_fee,
parent_gas_used,
parent_gas_limit,
transactions,
)
}
#[allow(clippy::too_many_arguments)]
fn assemble_block(
&self,
height: BlockHeight,
view: u64,
prev_hash: Hash,
proposer: Address,
state_root: Hash,
parent_base_fee: Option<u128>,
parent_gas_used: u64,
parent_gas_limit: u64,
transactions: Vec<SignedTransaction>,
) -> Result<Block> {
// Calculate transaction root (Merkle root)
let tx_root = self.calculate_tx_root(&transactions);
// Derive EIP-1559 base fee for this block from the parent. Same
// pure formula validators will run during `validate_base_fee`.
let base_fee = calculate_next_base_fee(
parent_base_fee,
parent_gas_used,
parent_gas_limit,
&FeeMarketParams::default(),
);
// Create block metadata (carries the stamped base fee)
let metadata = self.create_metadata(&transactions, base_fee);
let gas_used = metadata.gas_used;
// Create consensus proof (will be filled with votes later)
let consensus_proof = ConsensusProof::new(ConsensusAlgorithm::PBFT, Vec::new());
// Create block header stamped with the proposer's current view
let header = BlockHeader::new_at_view(
height,
view,
prev_hash,
tx_root,
state_root,
proposer,
consensus_proof,
)
.with_metadata(metadata);
// Create the block
let block = Block::new(header, transactions);
tracing::info!(
height = %height,
view = view,
tx_count = block.tx_count(),
gas_used = gas_used,
base_fee_per_gas = base_fee,
proposer = %proposer,
"Block proposed"
);
Ok(block)
}
/// Selects transactions from the mempool for inclusion in a block
fn select_transactions(&self) -> Result<Vec<SignedTransaction>> {
// Clean up expired transactions first
self.mempool.cleanup_expired();
// Select transactions based on priority and limits
let transactions = self.mempool.select_transactions(
self.config.max_transactions_per_block,
self.config.max_gas_per_block,
);
Ok(transactions)
}
/// Calculates the Merkle root of transactions
fn calculate_tx_root(&self, transactions: &[SignedTransaction]) -> Hash {
if transactions.is_empty() {
return Hash::default();
}
// Simple hash-based approach (in production, use proper Merkle tree)
let mut combined = Vec::new();
for tx in transactions {
combined.extend_from_slice(tx.transaction.hash().as_bytes());
}
// Hash the combined data
let hash_bytes = tenzro_crypto::hash::sha256(&combined);
Hash::new(hash_bytes.as_bytes().try_into().unwrap_or([0u8; 32]))
}
/// Creates block metadata, stamping the EIP-1559 base fee derived
/// from the parent block.
fn create_metadata(&self, transactions: &[SignedTransaction], base_fee: u128) -> BlockMetadata {
let tx_count = transactions.len() as u64;
// Calculate total gas used
let gas_used: u64 = transactions.iter().map(|tx| tx.transaction.gas_limit).sum();
BlockMetadata {
gas_used,
gas_limit: self.config.max_gas_per_block,
tx_count,
protocol_version: 1,
base_fee_per_gas: Some(base_fee),
}
}
/// Validates a proposed block before voting
pub fn validate_proposal(&self, block: &Block, expected_height: BlockHeight) -> Result<()> {
// Check block height
if block.height() != expected_height {
return Err(ConsensusError::InvalidHeight {
expected: expected_height,
actual: block.height(),
});
}
// Validate block structure
if !block.validate_structure() {
return Err(ConsensusError::InvalidProposal(
"Invalid block structure".to_string(),
));
}
// Check transaction count limit
if block.tx_count() > self.config.max_transactions_per_block {
return Err(ConsensusError::InvalidProposal(format!(
"Too many transactions: {} > {}",
block.tx_count(),
self.config.max_transactions_per_block
)));
}
// Check gas limit
if block.header.metadata.gas_used > self.config.max_gas_per_block {
return Err(ConsensusError::InvalidProposal(format!(
"Gas limit exceeded: {} > {}",
block.header.metadata.gas_used, self.config.max_gas_per_block
)));
}
// Check block size limit
self.validate_block_size(block)?;
// Validate transaction ordering (gas price descending)
if !self.validate_transaction_ordering(&block.transactions) {
return Err(ConsensusError::InvalidProposal(
"Invalid transaction ordering".to_string(),
));
}
tracing::debug!(
height = %block.height(),
tx_count = block.tx_count(),
"Block proposal validated"
);
Ok(())
}
/// Re-derives the EIP-1559 base fee from the parent block and rejects
/// the proposal if the proposer's stamped value diverges.
///
/// This is the consensus rule that prevents a malicious proposer
/// from setting an arbitrary base fee. Every honest validator runs
/// the same pure function over the same parent and must agree.
/// Mirrors go-ethereum `consensus/misc/eip1559.VerifyEIP1559Header`.
pub fn validate_base_fee(&self, block: &Block, parent: &Block) -> Result<()> {
let expected = calculate_next_base_fee(
parent.header.metadata.base_fee_per_gas,
parent.header.metadata.gas_used,
parent.header.metadata.gas_limit,
&FeeMarketParams::default(),
);
match block.header.metadata.base_fee_per_gas {
Some(actual) if actual == expected => Ok(()),
Some(actual) => Err(ConsensusError::InvalidProposal(format!(
"EIP-1559 base fee mismatch: expected {}, got {} (parent height {}, gas_used {}, gas_limit {})",
expected,
actual,
parent.height(),
parent.header.metadata.gas_used,
parent.header.metadata.gas_limit,
))),
None => Err(ConsensusError::InvalidProposal(
"EIP-1559 base fee missing from block metadata".to_string(),
)),
}
}
/// Validates that transactions are properly ordered by gas price
fn validate_transaction_ordering(&self, transactions: &[SignedTransaction]) -> bool {
if transactions.len() <= 1 {
return true;
}
for i in 0..transactions.len() - 1 {
let current_gas_price = transactions[i].transaction.gas_price;
let next_gas_price = transactions[i + 1].transaction.gas_price;
// Transactions should be ordered by descending gas price
if current_gas_price < next_gas_price {
return false;
}
}
true
}
/// Estimates the size of a block in bytes
pub fn estimate_block_size(&self, block: &Block) -> usize {
serde_json::to_string(block).map(|s| s.len()).unwrap_or(0)
}
/// Checks if a block exceeds the maximum size
pub fn validate_block_size(&self, block: &Block) -> Result<()> {
let size = self.estimate_block_size(block);
if size > self.config.max_block_size {
return Err(ConsensusError::InvalidProposal(format!(
"Block size {} exceeds maximum {}",
size, self.config.max_block_size
)));
}
Ok(())
}
}
// Extension trait for BlockHeader
trait BlockHeaderExt {
fn with_metadata(self, metadata: BlockMetadata) -> Self;
}
impl BlockHeaderExt for BlockHeader {
fn with_metadata(mut self, metadata: BlockMetadata) -> Self {
self.metadata = metadata;
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::mempool::Mempool;
use tenzro_crypto::pq::MlDsaSigningKey;
use tenzro_types::Signature;
use tenzro_types::primitives::{ChainId, Nonce};
use tenzro_types::transaction::{Transaction, TransactionType};
fn create_test_transaction(gas_price: u64, nonce: u64) -> SignedTransaction {
let pq_key = MlDsaSigningKey::generate();
let tx = Transaction::new(
ChainId::from(1),
Address::default(),
Address::default(),
Nonce::from(nonce),
TransactionType::Transfer { amount: 1000 },
21000,
gas_price,
pq_key.verifying_key_bytes().to_vec(),
);
let pq_sig = pq_key.sign(tx.hash().as_bytes()).to_vec();
SignedTransaction::new(tx, Signature::default(), pq_sig)
}
#[test]
fn test_propose_block() {
let config = Arc::new(ConsensusConfig::default());
let mempool = Arc::new(Mempool::new(config.clone()));
let proposer = BlockProposer::new(mempool.clone(), config);
// Add transactions to mempool
mempool
.add_transaction(create_test_transaction(100, 1))
.unwrap();
mempool
.add_transaction(create_test_transaction(200, 2))
.unwrap();
// Propose a block. Genesis-edge case: parent_gas_limit=0 → child
// uses initial_base_fee.
let block = proposer
.propose_block(
BlockHeight::from(1),
0,
Hash::default(),
Address::default(),
Hash::default(),
None, // parent_base_fee
0, // parent_gas_used
0, // parent_gas_limit (genesis)
)
.unwrap();
assert_eq!(block.height(), BlockHeight::from(1));
assert_eq!(block.tx_count(), 2);
// Genesis child must stamp the initial base fee.
assert_eq!(
block.header.metadata.base_fee_per_gas,
Some(FeeMarketParams::default().initial_base_fee)
);
}
#[test]
fn test_validate_proposal() {
let config = Arc::new(ConsensusConfig::default());
let mempool = Arc::new(Mempool::new(config.clone()));
let proposer = BlockProposer::new(mempool, config);
// Create a valid block
let block = Block::new(
BlockHeader::new(
BlockHeight::from(1),
Hash::default(),
Hash::default(),
Hash::default(),
Address::default(),
ConsensusProof::new(ConsensusAlgorithm::PBFT, Vec::new()),
),
vec![],
);
// Should validate successfully
assert!(
proposer
.validate_proposal(&block, BlockHeight::from(1))
.is_ok()
);
}
#[test]
fn test_validate_wrong_height() {
let config = Arc::new(ConsensusConfig::default());
let mempool = Arc::new(Mempool::new(config.clone()));
let proposer = BlockProposer::new(mempool, config);
let block = Block::new(
BlockHeader::new(
BlockHeight::from(1),
Hash::default(),
Hash::default(),
Hash::default(),
Address::default(),
ConsensusProof::new(ConsensusAlgorithm::PBFT, Vec::new()),
),
vec![],
);
// Should fail with wrong height
let result = proposer.validate_proposal(&block, BlockHeight::from(2));
assert!(result.is_err());
}
}