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
#![deny(
missing_debug_implementations,
missing_docs,
unsafe_code,
bare_trait_objects
)]
pub use self::{
configure::{Configure, ConfigureCall, CONFIGURE_INTERFACE_NAME},
errors::Error,
proto_structures::{
ConfigChange, ConfigProposalWithHash, ConfigPropose, ConfigVote, DeployConfirmation,
DeployRequest, ServiceConfig, StartService,
},
schema::Schema,
transactions::SupervisorInterface,
};
use exonum::{
crypto::Hash,
runtime::{
rust::{
api::ServiceApiBuilder, AfterCommitContext, Broadcaster, CallContext, DefaultInstance,
Service,
},
BlockchainData, InstanceId, SUPERVISOR_INSTANCE_ID,
},
};
use exonum_derive::*;
use exonum_merkledb::Snapshot;
pub mod mode;
mod api;
mod configure;
mod errors;
mod multisig;
mod proto;
mod proto_structures;
mod schema;
mod transactions;
pub type DecentralizedSupervisor = Supervisor<mode::Decentralized>;
pub type SimpleSupervisor = Supervisor<mode::Simple>;
pub const fn supervisor_name() -> &'static str {
Supervisor::<mode::Decentralized>::NAME
}
const NOT_SUPERVISOR_MSG: &str = "`Supervisor` is installed as a non-privileged service. \
For correct operation, `Supervisor` needs to have numeric ID 0.";
fn update_configs(context: &mut CallContext<'_>, changes: Vec<ConfigChange>) -> Result<(), ()> {
for change in changes.into_iter() {
match change {
ConfigChange::Consensus(config) => {
log::trace!("Updating consensus configuration {:?}", config);
context
.writeable_core_schema()
.consensus_config_entry()
.set(config);
}
ConfigChange::Service(config) => {
log::trace!(
"Updating service instance configuration, instance ID is {}",
config.instance_id
);
context
.interface::<ConfigureCall<'_>>(config.instance_id)
.expect("Obtaining Configure interface failed")
.apply_config(config.params.clone())
.map_err(|e| {
log::error!(
"An error occurred while applying service configuration. {}",
e
);
})?;
}
ConfigChange::StartService(start_service) => {
log::trace!(
"Request add service with name {:?} from artifact {:?}",
start_service.name,
start_service.artifact
);
let id = assign_instance_id(context);
let (instance_spec, config) = start_service.into_parts(id);
context
.start_adding_service(instance_spec, config)
.map_err(|e| {
log::error!("Service start request failed. {}", e);
})?;
}
}
}
Ok(())
}
fn assign_instance_id(context: &CallContext<'_>) -> InstanceId {
let mut schema = Schema::new(context.service_data());
match schema.assign_instance_id() {
Some(id) => id,
None => {
let dispatcher_schema = context.data().for_dispatcher();
let builtin_instances = dispatcher_schema.service_instances();
let new_instance_id = builtin_instances
.values()
.map(|state| state.spec.id)
.max()
.unwrap_or(SUPERVISOR_INSTANCE_ID)
+ 1;
let vacant_instance_id = new_instance_id + 1;
schema.vacant_instance_id.set(vacant_instance_id);
new_instance_id
}
}
}
#[derive(Debug, Default, Clone, ServiceFactory, ServiceDispatcher)]
#[service_dispatcher(implements("transactions::SupervisorInterface"))]
#[service_factory(
proto_sources = "proto",
artifact_name = "exonum-supervisor",
service_constructor = "Self::construct"
)]
pub struct Supervisor<Mode>
where
Mode: mode::SupervisorMode,
{
phantom: std::marker::PhantomData<Mode>,
}
impl<Mode> Supervisor<Mode>
where
Mode: mode::SupervisorMode,
{
pub const NAME: &'static str = "supervisor";
pub fn new() -> Supervisor<Mode> {
Supervisor {
phantom: std::marker::PhantomData::<Mode>::default(),
}
}
pub fn construct(&self) -> Box<Self> {
Box::new(Self::new())
}
}
impl<Mode> Service for Supervisor<Mode>
where
Mode: mode::SupervisorMode,
{
fn state_hash(&self, data: BlockchainData<&dyn Snapshot>) -> Vec<Hash> {
Schema::new(data.for_executing_service()).state_hash()
}
fn before_commit(&self, mut context: CallContext<'_>) {
let mut schema = Schema::new(context.service_data());
let core_schema = context.data().for_core();
let validator_count = core_schema.consensus_config().validator_keys.len();
let height = core_schema.height();
let requests_to_remove = schema
.pending_deployments
.values()
.filter(|request| request.deadline_height < height)
.collect::<Vec<_>>();
for request in requests_to_remove {
schema.pending_deployments.remove(&request.artifact);
log::trace!("Removed outdated deployment request {:?}", request);
}
let entry = schema.pending_proposal.get();
if let Some(entry) = entry {
if entry.config_propose.actual_from <= height {
log::trace!("Removed outdated config proposal");
schema.pending_proposal.remove();
} else if entry.config_propose.actual_from == height.next() {
if Mode::config_approved(
&entry.propose_hash,
&schema.config_confirms,
validator_count,
) {
log::info!(
"New configuration has been accepted: {:?}",
entry.config_propose
);
schema.pending_proposal.remove();
drop(schema);
let update_result = update_configs(&mut context, entry.config_propose.changes);
if update_result.is_err() {
panic!("Config update failed")
}
}
}
}
}
fn after_commit(&self, mut context: AfterCommitContext<'_>) {
let service_key = context.service_key();
let deployments: Vec<_> = {
let schema = Schema::new(context.service_data());
schema
.pending_deployments
.values()
.filter(|request| {
let confirmation = DeployConfirmation::from(request.clone());
!schema
.deploy_confirmations
.confirmed_by(&confirmation, &service_key)
})
.collect()
};
for unconfirmed_request in deployments {
let artifact = unconfirmed_request.artifact.clone();
let spec = unconfirmed_request.spec.clone();
let tx_sender = context.broadcaster().map(Broadcaster::into_owned);
let mut extensions = context.supervisor_extensions().expect(NOT_SUPERVISOR_MSG);
extensions.start_deploy(artifact, spec, move || {
if let Some(tx_sender) = tx_sender {
log::trace!(
"Sending confirmation for deployment request {:?}",
unconfirmed_request
);
let confirmation = DeployConfirmation::from(unconfirmed_request);
if let Err(e) = tx_sender.send(confirmation) {
log::error!("Cannot send confirmation: {}", e);
}
}
Ok(())
});
}
}
fn wire_api(&self, builder: &mut ServiceApiBuilder) {
api::wire(builder)
}
}
impl<Mode: mode::SupervisorMode> DefaultInstance for Supervisor<Mode> {
const INSTANCE_ID: u32 = SUPERVISOR_INSTANCE_ID;
const INSTANCE_NAME: &'static str = Self::NAME;
}