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
use exonum::blockchain::{ExecutionResult, Schema as CoreSchema, StoredConfiguration, Transaction};
use exonum::crypto::{CryptoHash, Hash, PublicKey};
use exonum::encoding::Error as EncodingError;
use exonum::messages::{Message, RawTransaction};
use exonum::node::State;
use exonum::storage::{Fork, Snapshot};
use errors::Error as ServiceError;
use schema::{MaybeVote, ProposeData, Schema};
transactions! {
Any {
const SERVICE_ID = super::SERVICE_ID;
struct Propose {
from: &PublicKey,
cfg: &str,
}
struct Vote {
from: &PublicKey,
cfg_hash: &Hash,
}
}
}
fn validator_index(snapshot: &Snapshot, key: &PublicKey) -> Option<usize> {
let actual_config = CoreSchema::new(snapshot).actual_configuration();
let keys = actual_config.validator_keys;
keys.iter().position(|k| k.service_key == *key)
}
fn enough_votes_to_commit(snapshot: &Snapshot, cfg_hash: &Hash) -> bool {
let actual_config = CoreSchema::new(snapshot).actual_configuration();
let schema = Schema::new(snapshot);
let votes = schema.votes_by_config_hash(cfg_hash);
let votes_count = votes.iter().filter(|vote| vote.is_some()).count();
votes_count >= State::byzantine_majority_count(actual_config.validator_keys.len())
}
impl Propose {
fn precheck(&self, snapshot: &Snapshot) -> Result<(StoredConfiguration, Hash), ServiceError> {
use exonum::storage::StorageValue;
use self::ServiceError::*;
let following_config = CoreSchema::new(snapshot).following_configuration();
if let Some(following) = following_config {
Err(AlreadyScheduled(following))?;
}
if validator_index(snapshot, self.from()).is_none() {
Err(UnknownSender)?;
}
let config_candidate = StoredConfiguration::try_deserialize(self.cfg().as_bytes())
.map_err(InvalidConfig)?;
self.check_config_candidate(&config_candidate, snapshot)?;
let cfg = StoredConfiguration::from_bytes(self.cfg().as_bytes().into());
let cfg_hash = CryptoHash::hash(&cfg);
if let Some(old_propose) = Schema::new(snapshot).propose(&cfg_hash) {
Err(AlreadyProposed(old_propose))?;
}
Ok((cfg, cfg_hash))
}
fn check_config_candidate(
&self,
candidate: &StoredConfiguration,
snapshot: &Snapshot,
) -> Result<(), ServiceError> {
use self::ServiceError::*;
let actual_config = CoreSchema::new(snapshot).actual_configuration();
if candidate.previous_cfg_hash != actual_config.hash() {
return Err(InvalidConfigRef(actual_config));
}
let current_height = CoreSchema::new(snapshot).height().next();
if candidate.actual_from <= current_height {
return Err(ActivationInPast(current_height));
}
Ok(())
}
fn save(&self, fork: &mut Fork, cfg: &StoredConfiguration, cfg_hash: Hash) {
let prev_cfg = CoreSchema::new(fork.as_ref())
.configs()
.get(&cfg.previous_cfg_hash)
.unwrap();
let mut schema = Schema::new(fork);
let propose_data = {
let mut votes_table = schema.votes_by_config_hash_mut(&cfg_hash);
debug_assert!(votes_table.is_empty());
let num_validators = prev_cfg.validator_keys.len();
for _ in 0..num_validators {
votes_table.push(MaybeVote::none());
}
ProposeData::new(
self.clone(),
&votes_table.root_hash(),
num_validators as u64,
)
};
{
let mut propose_data_table = schema.propose_data_by_config_hash_mut();
debug_assert!(propose_data_table.get(&cfg_hash).is_none());
propose_data_table.put(&cfg_hash, propose_data);
}
schema.config_hash_by_ordinal_mut().push(cfg_hash);
}
}
impl Transaction for Propose {
fn verify(&self) -> bool {
self.verify_signature(self.from())
}
fn execute(&self, fork: &mut Fork) -> ExecutionResult {
let (cfg, cfg_hash) = self.precheck(fork.as_ref()).map_err(|err| {
error!("Discarding propose {:?}: {}", self, err);
err
})?;
self.save(fork, &cfg, cfg_hash);
trace!("Put propose {:?} to config_proposes table", self);
Ok(())
}
}
impl Vote {
fn precheck(&self, snapshot: &Snapshot) -> Result<StoredConfiguration, ServiceError> {
use self::ServiceError::*;
let following_config = CoreSchema::new(snapshot).following_configuration();
if let Some(following) = following_config {
Err(AlreadyScheduled(following))?;
}
if let Some(validator_id) = validator_index(snapshot, self.from()) {
let vote = Schema::new(snapshot)
.votes_by_config_hash(self.cfg_hash())
.get(validator_id as u64)
.unwrap();
if vote.is_some() {
Err(AlreadyVoted)?;
}
} else {
Err(UnknownSender)?;
}
let propose = Schema::new(snapshot).propose(self.cfg_hash()).ok_or_else(
|| {
UnknownConfigRef(*self.cfg_hash())
},
)?;
let parsed = StoredConfiguration::try_deserialize(propose.cfg().as_bytes()).unwrap();
propose.check_config_candidate(&parsed, snapshot)?;
Ok(parsed)
}
fn save(&self, fork: &mut Fork) {
use exonum::storage::StorageValue;
let cfg_hash = self.cfg_hash();
let propose_data: ProposeData = Schema::new(fork.as_ref())
.propose_data_by_config_hash()
.get(cfg_hash)
.unwrap();
let propose = propose_data.tx_propose();
let prev_cfg_hash = StoredConfiguration::from_bytes(propose.cfg().as_bytes().into())
.previous_cfg_hash;
let prev_cfg = CoreSchema::new(fork.as_ref())
.configs()
.get(&prev_cfg_hash)
.unwrap();
let validator_id = prev_cfg
.validator_keys
.iter()
.position(|pk| pk.service_key == *self.from())
.unwrap();
let mut schema = Schema::new(fork);
let propose_data = {
let mut votes = schema.votes_by_config_hash_mut(cfg_hash);
votes.set(validator_id as u64, MaybeVote::some(self.clone()));
propose_data.set_history_hash(&votes.root_hash())
};
schema.propose_data_by_config_hash_mut().put(
cfg_hash,
propose_data,
);
}
}
impl Transaction for Vote {
fn verify(&self) -> bool {
self.verify_signature(self.from())
}
fn execute(&self, fork: &mut Fork) -> ExecutionResult {
let parsed_config = self.precheck(fork.as_ref()).map_err(|err| {
error!("Discarding vote {:?}: {}", self, err);
err
})?;
self.save(fork);
trace!(
"Put Vote:{:?} to corresponding cfg votes_by_config_hash table",
self
);
if enough_votes_to_commit(fork.as_ref(), self.cfg_hash()) {
CoreSchema::new(fork).commit_configuration(parsed_config);
}
Ok(())
}
}
pub(crate) fn tx_from_raw(raw: RawTransaction) -> Result<Box<Transaction>, EncodingError> {
use exonum::blockchain::TransactionSet;
Any::tx_from_raw(raw).map(Any::into)
}