-
Notifications
You must be signed in to change notification settings - Fork 289
/
mod.rs
421 lines (378 loc) · 13.6 KB
/
mod.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
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::create_block_template::metrics::BlockBuilderMetrics;
use anyhow::{anyhow, format_err, Result};
use futures::executor::block_on;
use starcoin_account_api::{AccountAsyncService, AccountInfo, DefaultAccountChangeEvent};
use starcoin_account_service::AccountService;
use starcoin_chain::BlockChain;
use starcoin_chain::{ChainReader, ChainWriter};
use starcoin_config::ChainNetwork;
use starcoin_config::NodeConfig;
use starcoin_consensus::Consensus;
use starcoin_crypto::hash::HashValue;
use starcoin_dag::blockdag::BlockDAG;
use starcoin_executor::VMMetrics;
use starcoin_logger::prelude::*;
use starcoin_open_block::OpenedBlock;
use starcoin_service_registry::{
ActorService, EventHandler, ServiceContext, ServiceFactory, ServiceHandler, ServiceRequest,
};
use starcoin_storage::{BlockStore, Storage, Store};
use starcoin_txpool::TxPoolService;
use starcoin_txpool_api::TxPoolSyncService;
use starcoin_types::{
block::{BlockHeader, BlockTemplate, ExecutedBlock},
system_events::{NewBranch, NewHeadBlock},
};
use starcoin_vm_types::transaction::SignedUserTransaction;
use std::cmp::min;
use std::{collections::HashMap, sync::Arc};
mod metrics;
#[cfg(test)]
mod test_create_block_template;
#[derive(Debug)]
pub struct GetHeadRequest;
impl ServiceRequest for GetHeadRequest {
type Response = HashValue;
}
#[derive(Debug)]
pub struct BlockTemplateRequest;
impl ServiceRequest for BlockTemplateRequest {
type Response = Result<BlockTemplateResponse>;
}
#[derive(Debug)]
pub struct BlockTemplateResponse {
pub parent: BlockHeader,
pub template: BlockTemplate,
}
pub struct BlockBuilderService {
inner: Inner<TxPoolService>,
}
impl BlockBuilderService {}
impl ServiceFactory<Self> for BlockBuilderService {
fn create(ctx: &mut ServiceContext<BlockBuilderService>) -> Result<BlockBuilderService> {
let config = ctx.get_shared::<Arc<NodeConfig>>()?;
let storage = ctx.get_shared::<Arc<Storage>>()?;
let startup_info = storage
.get_startup_info()?
.expect("Startup info should exist when service start.");
//TODO support get service ref by AsyncAPI;
let account_service = ctx.service_ref::<AccountService>()?;
let miner_account = block_on(async { account_service.get_default_account().await })?
.ok_or_else(|| {
format_err!("Default account should exist when BlockBuilderService start.")
})?;
let txpool = ctx.get_shared::<TxPoolService>()?;
let metrics = config
.metrics
.registry()
.and_then(|registry| BlockBuilderMetrics::register(registry).ok());
let vm_metrics = ctx.get_shared_opt::<VMMetrics>()?;
let dag = ctx.get_shared::<BlockDAG>()?;
let inner = Inner::new(
config.net(),
storage,
startup_info.main,
txpool,
config.miner.block_gas_limit,
miner_account,
metrics,
vm_metrics,
dag,
)?;
Ok(Self { inner })
}
}
impl ActorService for BlockBuilderService {
fn started(&mut self, ctx: &mut ServiceContext<Self>) -> Result<()> {
ctx.subscribe::<NewHeadBlock>();
ctx.subscribe::<NewBranch>();
ctx.subscribe::<DefaultAccountChangeEvent>();
Ok(())
}
fn stopped(&mut self, ctx: &mut ServiceContext<Self>) -> Result<()> {
ctx.unsubscribe::<NewHeadBlock>();
ctx.unsubscribe::<NewBranch>();
ctx.unsubscribe::<DefaultAccountChangeEvent>();
Ok(())
}
}
impl EventHandler<Self, NewHeadBlock> for BlockBuilderService {
fn handle_event(&mut self, msg: NewHeadBlock, _ctx: &mut ServiceContext<BlockBuilderService>) {
if let Err(e) = self.inner.update_chain(msg.executed_block.as_ref().clone()) {
error!("err : {:?}", e)
}
}
}
impl EventHandler<Self, NewBranch> for BlockBuilderService {
fn handle_event(&mut self, msg: NewBranch, _ctx: &mut ServiceContext<BlockBuilderService>) {
self.inner.insert_uncle(msg.0.block.header().clone());
}
}
impl EventHandler<Self, DefaultAccountChangeEvent> for BlockBuilderService {
fn handle_event(
&mut self,
msg: DefaultAccountChangeEvent,
_ctx: &mut ServiceContext<BlockBuilderService>,
) {
info!("Miner account change to {}", msg.new_account.address);
self.inner.miner_account = msg.new_account;
}
}
impl ServiceHandler<Self, BlockTemplateRequest> for BlockBuilderService {
fn handle(
&mut self,
_msg: BlockTemplateRequest,
_ctx: &mut ServiceContext<BlockBuilderService>,
) -> Result<BlockTemplateResponse> {
let template = self.inner.create_block_template();
self.inner.uncles_prune();
template
}
}
impl ServiceHandler<Self, GetHeadRequest> for BlockBuilderService {
fn handle(
&mut self,
_msg: GetHeadRequest,
_ctx: &mut ServiceContext<BlockBuilderService>,
) -> HashValue {
self.inner.chain.current_header().id()
}
}
pub trait TemplateTxProvider {
fn get_txns(&self, max: u64) -> Vec<SignedUserTransaction>;
fn remove_invalid_txn(&self, txn_hash: HashValue);
}
pub struct EmptyProvider;
impl TemplateTxProvider for EmptyProvider {
fn get_txns(&self, _max: u64) -> Vec<SignedUserTransaction> {
vec![]
}
fn remove_invalid_txn(&self, _txn_hash: HashValue) {}
}
impl TemplateTxProvider for TxPoolService {
fn get_txns(&self, max: u64) -> Vec<SignedUserTransaction> {
self.get_pending_txns(Some(max), None)
}
fn remove_invalid_txn(&self, txn_hash: HashValue) {
self.remove_txn(txn_hash, true);
}
}
pub struct Inner<P> {
storage: Arc<dyn Store>,
chain: BlockChain,
tx_provider: P,
parent_uncle: HashMap<HashValue, Vec<HashValue>>,
uncles: HashMap<HashValue, BlockHeader>,
local_block_gas_limit: Option<u64>,
miner_account: AccountInfo,
metrics: Option<BlockBuilderMetrics>,
vm_metrics: Option<VMMetrics>,
dag: BlockDAG,
}
impl<P> Inner<P>
where
P: TemplateTxProvider,
{
pub fn new(
net: &ChainNetwork,
storage: Arc<dyn Store>,
block_id: HashValue,
tx_provider: P,
local_block_gas_limit: Option<u64>,
miner_account: AccountInfo,
metrics: Option<BlockBuilderMetrics>,
vm_metrics: Option<VMMetrics>,
dag: BlockDAG,
) -> Result<Self> {
let chain = BlockChain::new(
net.time_service(),
block_id,
storage.clone(),
vm_metrics.clone(),
dag.clone(),
)?;
Ok(Inner {
storage,
chain,
tx_provider,
parent_uncle: HashMap::new(),
uncles: HashMap::new(),
local_block_gas_limit,
miner_account,
metrics,
vm_metrics,
dag,
})
}
pub fn insert_uncle(&mut self, uncle: BlockHeader) {
self.parent_uncle
.entry(uncle.parent_hash())
.or_default()
.push(uncle.id());
self.uncles.insert(uncle.id(), uncle);
if let Some(metrics) = self.metrics.as_ref() {
metrics
.current_epoch_maybe_uncles
.set(self.uncles.len() as u64);
}
}
pub fn update_chain(&mut self, block: ExecutedBlock) -> Result<()> {
let current_header = self.chain.current_header();
let current_id = current_header.id();
if self.chain.can_connect(&block) {
self.chain.connect(block)?;
} else {
self.chain = BlockChain::new(
self.chain.time_service(),
block.header().id(),
self.storage.clone(),
self.vm_metrics.clone(),
self.dag.clone(),
)?;
//current block possible be uncle.
self.uncles.insert(current_id, current_header);
if let Some(metrics) = self.metrics.as_ref() {
metrics
.current_epoch_maybe_uncles
.set(self.uncles.len() as u64);
}
}
Ok(())
}
pub fn find_uncles(&self) -> Vec<BlockHeader> {
let mut new_uncle = Vec::new();
let epoch = self.chain.epoch();
if epoch.end_block_number() != (self.chain.current_header().number() + 1) {
for maybe_uncle in self.uncles.values() {
if new_uncle.len() as u64 >= epoch.max_uncles_per_block() {
break;
}
if self.chain.can_be_uncle(maybe_uncle).unwrap_or_default() {
new_uncle.push(maybe_uncle.clone())
}
}
}
new_uncle
}
fn uncles_prune(&mut self) {
if !self.uncles.is_empty() {
let epoch = self.chain.epoch();
// epoch的end_number是开区间,当前块已经生成但还没有apply,所以应该在epoch(最终状态)
// 的倒数第二块处理时清理uncles
if epoch.end_block_number() == (self.chain.current_header().number() + 2) {
self.uncles.clear();
}
}
if let Some(metrics) = self.metrics.as_ref() {
metrics
.current_epoch_maybe_uncles
.set(self.uncles.len() as u64);
}
}
pub fn create_block_template(&self) -> Result<BlockTemplateResponse> {
let on_chain_block_gas_limit = self.chain.epoch().block_gas_limit();
let block_gas_limit = self
.local_block_gas_limit
.map(|block_gas_limit| min(block_gas_limit, on_chain_block_gas_limit))
.unwrap_or(on_chain_block_gas_limit);
//TODO use a GasConstant value to replace 200.
// block_gas_limit / min_gas_per_txn
let max_txns = (block_gas_limit / 200) * 2;
let txns = self.tx_provider.get_txns(max_txns);
let author = *self.miner_account.address();
let previous_header = self.chain.current_header();
let current_number = previous_header.number().saturating_add(1);
let epoch = self.chain.epoch();
let strategy = epoch.strategy();
let mut now_millis = self.chain.time_service().now_millis();
if now_millis <= previous_header.timestamp() {
info!(
"Adjust new block timestamp by parent timestamp, parent.timestamp: {}, now: {}, gap: {}",
previous_header.timestamp(), now_millis, previous_header.timestamp() - now_millis,
);
now_millis = previous_header.timestamp() + 1;
}
let difficulty = strategy.calculate_next_difficulty(&self.chain)?;
let tips_hash = if current_number > self.chain.dag_fork_height()?.unwrap_or(u64::MAX) {
let (_dag_genesis, tips_hash) = self
.chain
.current_tips_hash(&previous_header)?
.ok_or_else(|| {
anyhow!(
"the number of the block is larger than the dag fork number but no dag state!"
)
})?;
Some(tips_hash)
} else {
None
};
info!(
"block:{} tips(dag state):{:?}",
self.chain.current_header().number(),
&tips_hash,
);
let (uncles, blue_blocks) = {
match &tips_hash {
None => (self.find_uncles(), None),
Some(tips) => {
let mut blues = self.dag.ghostdata(tips)?.mergeset_blues.to_vec();
info!(
"create block template with tips:{:?},ghostdata blues:{:?}",
&tips_hash, blues
);
let mut blue_blocks = vec![];
let __selected_parent = blues.remove(0);
for blue in &blues {
// todo: make sure blue block has been executed successfully
let block = self
.storage
.get_block_by_hash(blue.to_owned())?
.expect("Block should exist");
blue_blocks.push(block);
}
(
blue_blocks
.as_slice()
.iter()
.map(|b| b.header.clone())
.collect(),
Some(blue_blocks),
)
}
}
};
info!(
"[CreateBlockTemplate] previous_header: {:?}, block_gas_limit: {}, max_txns: {}, txn len: {}, uncles len: {}, timestamp: {}",
previous_header,
block_gas_limit,
max_txns,
txns.len(),
uncles.len(),
now_millis,
);
let mut opened_block = OpenedBlock::new(
self.storage.clone(),
previous_header.clone(),
block_gas_limit,
author,
now_millis,
uncles,
difficulty,
strategy,
self.vm_metrics.clone(),
Some(tips_hash.unwrap_or_default()),
blue_blocks,
)?;
let excluded_txns = opened_block.push_txns(txns)?;
let template = opened_block.finalize()?;
for invalid_txn in excluded_txns.discarded_txns {
self.tx_provider.remove_invalid_txn(invalid_txn.id());
}
Ok(BlockTemplateResponse {
parent: previous_header,
template,
})
}
}