This repository has been archived by the owner on Jul 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathmod.rs
424 lines (371 loc) · 15.4 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
422
423
424
#[macro_use]
mod macros;
mod app_init;
mod commit;
mod end_block;
mod query;
mod rewards;
mod staking_event;
pub mod validate_tx;
use abci::Pair as KVPair;
use abci::*;
use log::info;
use std::convert::{TryFrom, TryInto};
use std::env;
#[cfg(fuzzing)]
pub use self::app_init::check_validators;
pub use self::app_init::{
get_validator_key, init_app_hash, BufferType, ChainNodeApp, ChainNodeState,
};
use crate::app::staking_event::StakingEvent;
use crate::app::validate_tx::ResponseWithCodeAndLog;
use crate::enclave_bridge::EnclaveProxy;
use crate::staking::RewardsDistribution;
use crate::storage::{TxAction, TxEnclaveAction, TxPublicAction};
use chain_core::common::{TendermintEventKey, TendermintEventType, Timespec};
use chain_core::init::coin::Coin;
use chain_core::init::config::NetworkParameters;
use chain_core::state::account::PunishmentKind;
use chain_core::state::tendermint::{BlockHeight, TendermintValidatorAddress, TendermintVotePower};
use chain_core::tx::TxAux;
use parity_scale_codec::Decode;
fn get_version() -> String {
format!(
"{} {}:{}",
env!("CARGO_PKG_VERSION"),
env!("VERGEN_BUILD_DATE"),
env!("VERGEN_SHA_SHORT")
)
}
/// Encapsulate some information for begin block event
pub struct BeginBlockInfo<'a> {
pub params: &'a NetworkParameters,
pub block_time: Timespec,
pub block_height: BlockHeight,
pub max_evidence_age: Timespec,
pub voters: &'a [(TendermintValidatorAddress, bool)],
pub evidences: &'a [(TendermintValidatorAddress, BlockHeight, Timespec)],
}
impl<'a> BeginBlockInfo<'a> {
/// Get unbonding period which is the same as `max_evidence_age`
pub fn get_unbonding_period(&self) -> Timespec {
self.max_evidence_age
}
}
/// TODO: sanity checks in abci https://github.com/tendermint/rust-abci/issues/49
impl<T: EnclaveProxy + 'static> abci::Application for ChainNodeApp<T> {
/// Query Connection: Called on startup from Tendermint. The application should normally
/// return the last know state so Tendermint can determine if it needs to replay blocks
/// to the application.
fn info(&mut self, _req: &RequestInfo) -> ResponseInfo {
info!("received info request");
let mut resp = ResponseInfo::new();
resp.app_version = chain_core::APP_VERSION;
resp.version = get_version();
if let Some(raw) = chain_storage::get_last_app_state(&self.storage) {
let app_state =
ChainNodeState::decode(&mut raw.as_slice()).expect("decode chain node state");
resp.last_block_app_hash = app_state.last_apphash.to_vec();
resp.last_block_height = app_state.last_block_height.value().try_into().unwrap();
resp.data = serde_json::to_string(&app_state).expect("serialize app state to json");
} else {
resp.last_block_app_hash = self.genesis_app_hash.to_vec();
}
resp
}
/// Query Connection: Query your application. This usually resolves through a merkle tree holding
/// the state of the app.
fn query(&mut self, _req: &RequestQuery) -> ResponseQuery {
info!("received query request");
ChainNodeApp::query_handler(self, _req)
}
/// Mempool Connection: Used to validate incoming transactions. If the application responds
/// with a non-zero value, the transaction is added to Tendermint's mempool for processing
/// on the deliver_tx call below.
fn check_tx(&mut self, req: &RequestCheckTx) -> ResponseCheckTx {
info!("received checktx request");
let mut resp = ResponseCheckTx::new();
match self.process_tx(req, BufferType::Mempool) {
Ok(_) => {
resp.set_code(0);
}
Err(msg) => {
resp.set_code(1);
resp.add_log(&msg.to_string());
log::warn!("check tx failed: {}", msg);
}
}
resp
}
/// Consensus Connection: Called once on startup. Usually used to establish initial (genesis)
/// state.
fn init_chain(&mut self, _req: &RequestInitChain) -> ResponseInitChain {
info!("received initchain request");
ChainNodeApp::init_chain_handler(self, _req)
}
/// Consensus Connection: Called at the start of processing a block of transactions
/// The flow is:
/// begin_block()
/// deliver_tx() for each transaction in the block
/// end_block()
/// commit()
fn begin_block(&mut self, req: &RequestBeginBlock) -> ResponseBeginBlock {
info!("received beginblock request");
// TODO: Check security implications once https://github.com/tendermint/tendermint/issues/2653 is closed
let header = req
.header
.as_ref()
.expect("No block header in begin block request from tendermint");
let block_height = abci_block_height(header.height).expect("invalid block height");
let block_time = abci_timespec(&header.time).expect("invalid block time");
let voters = if let Some(last_commit_info) = req.last_commit_info.as_ref() {
// ignore the invalid items (logged)
iter_votes(last_commit_info)
.filter_map(|vote| {
abci_validator(&vote.validator).map(|(addr, _)| (addr, vote.signed_last_block))
})
.collect::<Vec<_>>()
} else {
if block_height > 2.into() {
log::error!(
"No last commit info in begin block request for height: {}",
block_height
);
}
vec![]
};
let last_state = self
.last_state
.as_mut()
.expect("executing begin block, but no app state stored (i.e. no initchain or recovery was executed)");
last_state.block_time = block_time;
last_state.block_height = block_height;
// ignore the invalid items (logged)
let evidences = req
.byzantine_validators
.iter()
.filter_map(|ev| {
abci_validator(&ev.validator).and_then(|(addr, _)| {
abci_block_height(ev.height).and_then(|height| {
abci_timespec(&ev.time).and_then(|time| {
if time.saturating_add(last_state.max_evidence_age) > block_time {
Some((addr, height, time))
} else {
None
}
})
})
})
})
.collect::<Vec<_>>();
let punishment_outcomes = last_state.staking_table.begin_block(
&mut staking_store!(self, last_state.staking_version),
&BeginBlockInfo {
params: &last_state.top_level.network_params,
block_time: last_state.block_time,
block_height: last_state.block_height,
max_evidence_age: last_state.max_evidence_age,
voters: &voters,
evidences: &evidences,
},
);
let mut response = ResponseBeginBlock::new();
let rewards_pool = &mut last_state.top_level.rewards_pool;
for punishment_outcome in punishment_outcomes.iter() {
// slashed_amount <= bonded + unbonded <= max supply
let slashed_amount = punishment_outcome
.slashed_coin
.sum()
.expect("sum of bonded and unbonded slash amount exceed maximum coin");
rewards_pool.period_bonus = (rewards_pool.period_bonus + slashed_amount)
.expect("rewards pool + fee greater than max coin?");
self.rewards_pool_updated = true;
let event = StakingEvent::Slash(
&punishment_outcome.staking_address,
punishment_outcome.slashed_coin.bonded,
punishment_outcome.slashed_coin.unbonded,
punishment_outcome.punishment_kind,
);
response.events.push(event.into());
if punishment_outcome.punishment_kind == PunishmentKind::ByzantineFault {
let jailed_until = punishment_outcome
.jailed_until
.expect("jailed until should exist when being jailed");
let event = StakingEvent::Jail(
&punishment_outcome.staking_address,
jailed_until,
punishment_outcome.punishment_kind,
);
response.events.push(event.into());
}
}
if let Some(last_commit_info) = req.last_commit_info.as_ref() {
for vote_info in iter_votes(last_commit_info) {
if vote_info.signed_last_block {
let validator = abci_validator(&vote_info.validator);
if let Some((validator_address, validator_voting_power)) = validator {
last_state.staking_table.reward_record(
&staking_getter!(self, last_state.staking_version),
&validator_address,
validator_voting_power,
);
}
}
}
}
if let Some((distributed, minted)) = self.rewards_try_distribute() {
let events = generate_reward_events(distributed, minted);
for event in events.iter() {
response.events.push(event.to_owned());
}
}
response
}
/// Consensus Connection: Actually processing the transaction, performing some form of a
/// state transistion.
fn deliver_tx(&mut self, req: &RequestDeliverTx) -> ResponseDeliverTx {
info!("received delivertx request");
let mut resp = ResponseDeliverTx::new();
let result = self.process_tx(req, BufferType::Consensus);
match result {
Ok((txaux, tx_action)) => {
let fee_amount = tx_action.fee().to_coin();
let tx_events = generate_tx_events(&txaux, tx_action);
resp.set_code(0);
for event in tx_events.iter() {
resp.events.push(event.to_owned());
}
self.delivered_txs.push(txaux);
if fee_amount > Coin::zero() {
let rewards_pool =
&mut self.last_state.as_mut().unwrap().top_level.rewards_pool;
rewards_pool.period_bonus = (rewards_pool.period_bonus + fee_amount)
.expect("rewards pool + fee greater than max coin?");
self.rewards_pool_updated = true;
}
}
Err(msg) => {
resp.set_code(1);
resp.add_log(&msg.to_string());
log::error!("deliver tx failed: {}", msg);
}
}
resp
}
/// Consensus Connection: Called at the end of the block. used to update the validator set.
fn end_block(&mut self, req: &RequestEndBlock) -> ResponseEndBlock {
info!("received endblock request");
ChainNodeApp::end_block_handler(self, req)
}
/// Consensus Connection: Commit the block with the latest state from the application.
fn commit(&mut self, _req: &RequestCommit) -> ResponseCommit {
info!("received commit request");
let resp = ChainNodeApp::commit_handler(self, _req);
if sanity_check_enabled() {
self.check_circulating_coins();
}
resp
}
}
fn iter_votes(last_commit_info: &LastCommitInfo) -> impl Iterator<Item = &VoteInfo> {
last_commit_info.votes.iter()
}
fn abci_validator(
v: &::protobuf::SingularPtrField<Validator>,
) -> Option<(TendermintValidatorAddress, TendermintVotePower)> {
let result = v.as_ref().and_then(|v| {
let addr = TendermintValidatorAddress::try_from(v.address.as_slice()).ok();
let power = TendermintVotePower::new(v.power).ok();
addr.and_then(|addr| power.map(|power| (addr, power)))
});
if result.is_none() {
log::error!("invalid validator from abci");
}
result
}
fn abci_timespec(
v: &::protobuf::SingularPtrField<::protobuf::well_known_types::Timestamp>,
) -> Option<Timespec> {
let result = v.as_ref().and_then(|t| t.seconds.try_into().ok());
if result.is_none() {
log::error!("invalid abci timestamp");
}
result
}
fn abci_block_height(i: i64) -> Option<BlockHeight> {
let result = i.try_into().ok();
if result.is_none() {
log::error!("invalid abci block height");
}
result
}
fn generate_reward_events(distribution: RewardsDistribution, minted: Coin) -> Vec<Event> {
let mut events: Vec<Event> = Vec::new();
for reward in distribution.iter() {
let event = StakingEvent::Reward(&reward.0, reward.1).into();
events.push(event);
}
let mut reward_event = Event::new();
reward_event.field_type = TendermintEventType::Reward.to_string();
let mut minted_kvpair = KVPair::new();
minted_kvpair.key = TendermintEventKey::CoinMinted.into();
minted_kvpair.value = serde_json::to_string(&minted)
.expect("encode coin minted failed")
.as_bytes()
.to_owned();
reward_event.attributes.push(minted_kvpair);
events.push(reward_event);
events
}
fn generate_tx_events(txaux: &TxAux, tx_action: TxAction) -> Vec<abci::Event> {
let mut events = Vec::new();
let mut valid_txs_event = Event::new();
valid_txs_event.field_type = TendermintEventType::ValidTransactions.to_string();
let mut fee_kvpair = KVPair::new();
let fee = tx_action.fee();
fee_kvpair.key = TendermintEventKey::Fee.into();
fee_kvpair.value = Vec::from(format!("{}", fee.to_coin()));
valid_txs_event.attributes.push(fee_kvpair);
let mut txid_kvpair = KVPair::new();
txid_kvpair.key = TendermintEventKey::TxId.into();
txid_kvpair.value = Vec::from(hex::encode(txaux.tx_id()).as_bytes());
valid_txs_event.attributes.push(txid_kvpair);
events.push(valid_txs_event);
let maybe_tx_staking_event = generate_tx_staking_change_event(tx_action);
if let Some(tx_staking_event) = maybe_tx_staking_event {
events.push(tx_staking_event);
}
events
}
fn generate_tx_staking_change_event(tx_action: TxAction) -> Option<abci::Event> {
match tx_action {
TxAction::Enclave(tx_enclave_action) => match tx_enclave_action {
TxEnclaveAction::Transfer { .. } => None,
TxEnclaveAction::Deposit { deposit, .. } => {
Some(StakingEvent::Deposit(&deposit.0, deposit.1).into())
}
TxEnclaveAction::Withdraw { withdraw, .. } => {
Some(StakingEvent::Withdraw(&withdraw.0, withdraw.1).into())
}
},
TxAction::Public(tx_public_action) => match tx_public_action {
TxPublicAction::Unbond {
unbond,
unbonded_from,
fee,
..
} => Some(StakingEvent::Unbond(&unbond.0, unbond.1, unbonded_from, fee).into()),
TxPublicAction::NodeJoin {
address,
council_node,
..
} => Some(StakingEvent::NodeJoin(&address, council_node).into()),
TxPublicAction::Unjail(staking_address) => {
Some(StakingEvent::Unjail(&staking_address).into())
}
},
}
}
pub fn sanity_check_enabled() -> bool {
env::var("CRYPTO_CHAIN_ENABLE_SANITY_CHECKS") == Ok("1".to_owned())
}