splinter 0.3.14

Splinter is a privacy-focused platform for distributed applications that provides a blockchain-inspired networking environment for communication and transactions between organizations.
Documentation
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
// Copyright 2018-2020 Cargill Incorporated
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::convert::{TryFrom, TryInto};
use std::sync::mpsc::{channel, Sender};
use std::sync::{Arc, Mutex};
use std::thread::{Builder, JoinHandle};
use std::time::Duration;

use protobuf::Message;
use transact::protos::IntoBytes;

use crate::consensus::two_phase::TwoPhaseEngine;
use crate::consensus::{
    error::{ConsensusSendError, ProposalManagerError},
    ConsensusEngine, ConsensusMessage, ConsensusNetworkSender, PeerId, Proposal, ProposalId,
    ProposalManager, ProposalUpdate, StartupState,
};
use crate::protos::scabbard::{ProposedBatch, ScabbardMessage, ScabbardMessage_Type};

use super::error::{ScabbardConsensusManagerError, ScabbardError};
use super::shared::ScabbardShared;
use super::state::ScabbardState;

/// Component used by the service to manage and interact with consenus
pub struct ScabbardConsensusManager {
    consensus_msg_tx: Sender<ConsensusMessage>,
    proposal_update_tx: Sender<ProposalUpdate>,
    thread_handle: JoinHandle<()>,
}

impl ScabbardConsensusManager {
    /// Create the proposal manager, network sender, and channels used to communicate with
    /// consensus, and start consensus in a separate thread.
    pub fn new(
        service_id: String,
        shared: Arc<Mutex<ScabbardShared>>,
        state: Arc<Mutex<ScabbardState>>,
        // The coordinator timeout for the two-phase commit consensus engine
        coordinator_timeout: Duration,
    ) -> Result<Self, ScabbardConsensusManagerError> {
        let peer_ids = shared
            .lock()
            .map_err(|_| ScabbardConsensusManagerError(Box::new(ScabbardError::LockPoisoned)))?
            .peer_services()
            .iter()
            .map(|id| id.as_bytes().into())
            .collect();

        let (consensus_msg_tx, consensus_msg_rx) = channel();
        let (proposal_update_tx, proposal_update_rx) = channel();

        let proposal_manager = ScabbardProposalManager::new(
            service_id.clone(),
            proposal_update_tx.clone(),
            shared.clone(),
            state,
        );
        let consensus_network_sender =
            ScabbardConsensusNetworkSender::new(service_id.clone(), shared);
        let startup_state = StartupState {
            id: service_id.as_bytes().into(),
            peer_ids,
            last_proposal: None,
        };

        let thread_handle = Builder::new()
            .name(format!("consensus-{}", service_id))
            .spawn(move || {
                let mut two_phase_engine = TwoPhaseEngine::new(coordinator_timeout);
                if let Err(err) = two_phase_engine.run(
                    consensus_msg_rx,
                    proposal_update_rx,
                    Box::new(consensus_network_sender),
                    Box::new(proposal_manager),
                    startup_state,
                ) {
                    error!("two phase consensus exited with an error: {}", err)
                }
            })
            .map_err(|err| ScabbardConsensusManagerError(Box::new(err)))?;

        Ok(ScabbardConsensusManager {
            consensus_msg_tx,
            proposal_update_tx,
            thread_handle,
        })
    }

    /// Consumes self and shuts down the consensus thread.
    pub fn shutdown(self) -> Result<(), ScabbardConsensusManagerError> {
        self.send_update(ProposalUpdate::Shutdown)?;

        self.thread_handle
            .join()
            .unwrap_or_else(|err| error!("consensus thread failed: {:?}", err));

        Ok(())
    }

    pub fn handle_message(
        &self,
        message_bytes: &[u8],
    ) -> Result<(), ScabbardConsensusManagerError> {
        let consensus_message = ConsensusMessage::try_from(message_bytes)
            .map_err(|err| ScabbardConsensusManagerError(Box::new(err)))?;

        self.consensus_msg_tx
            .send(consensus_message)
            .map_err(|err| ScabbardConsensusManagerError(Box::new(err)))?;

        Ok(())
    }

    pub fn send_update(&self, update: ProposalUpdate) -> Result<(), ScabbardConsensusManagerError> {
        self.proposal_update_tx
            .send(update)
            .map_err(|err| ScabbardConsensusManagerError(Box::new(err)))
    }
}

pub struct ScabbardProposalManager {
    service_id: String,
    proposal_update_sender: Sender<ProposalUpdate>,
    shared: Arc<Mutex<ScabbardShared>>,
    state: Arc<Mutex<ScabbardState>>,
}

impl ScabbardProposalManager {
    pub fn new(
        service_id: String,
        proposal_update_sender: Sender<ProposalUpdate>,
        shared: Arc<Mutex<ScabbardShared>>,
        state: Arc<Mutex<ScabbardState>>,
    ) -> Self {
        ScabbardProposalManager {
            service_id,
            proposal_update_sender,
            shared,
            state,
        }
    }
}

impl ProposalManager for ScabbardProposalManager {
    fn create_proposal(
        &self,
        // Ignoring previous proposal ID and consensus data, because this service and two phase
        // consensus don't care about it.
        _previous_proposal_id: Option<ProposalId>,
        _consensus_data: Vec<u8>,
    ) -> Result<(), ProposalManagerError> {
        let mut shared = self
            .shared
            .lock()
            .map_err(|_| ProposalManagerError::Internal(Box::new(ScabbardError::LockPoisoned)))?;

        if let Some(batch) = shared.pop_batch_from_queue() {
            let expected_hash = self
                .state
                .lock()
                .map_err(|_| ProposalManagerError::Internal(Box::new(ScabbardError::LockPoisoned)))?
                .prepare_change(batch.clone())
                .map_err(|err| ProposalManagerError::Internal(Box::new(err)))?;

            // Intentionally leaving out the previous_id and proposal_height fields, since this
            // service and two phase consensus don't use them. This means the proposal ID can just
            // be the summary.
            let mut proposal = Proposal::default();
            proposal.id = expected_hash.as_bytes().into();
            proposal.summary = expected_hash.as_bytes().into();

            shared.add_proposed_batch(proposal.id.clone(), batch.clone());

            // Send the proposal to the other services
            let mut proposed_batch = ProposedBatch::new();
            proposed_batch.set_proposal(
                proposal
                    .clone()
                    .try_into()
                    .map_err(|err| ProposalManagerError::Internal(Box::new(err)))?,
            );
            proposed_batch.set_batch(
                batch
                    .into_bytes()
                    .map_err(|err| ProposalManagerError::Internal(Box::new(err)))?,
            );
            proposed_batch.set_service_id(self.service_id.clone());

            let mut msg = ScabbardMessage::new();
            msg.set_message_type(ScabbardMessage_Type::PROPOSED_BATCH);
            msg.set_proposed_batch(proposed_batch);
            let msg_bytes = msg
                .write_to_bytes()
                .map_err(|err| ProposalManagerError::Internal(Box::new(err)))?;

            let sender = shared
                .network_sender()
                .ok_or(ProposalManagerError::NotReady)?;

            for service in shared.peer_services() {
                sender
                    .send(service, msg_bytes.as_slice())
                    .map_err(|err| ProposalManagerError::Internal(Box::new(err)))?;
            }

            self.proposal_update_sender
                .send(ProposalUpdate::ProposalCreated(Some(proposal)))?;
        } else {
            self.proposal_update_sender
                .send(ProposalUpdate::ProposalCreated(None))?;
        }

        Ok(())
    }

    fn check_proposal(&self, id: &ProposalId) -> Result<(), ProposalManagerError> {
        let batch = self
            .shared
            .lock()
            .map_err(|_| ProposalManagerError::Internal(Box::new(ScabbardError::LockPoisoned)))?
            .get_proposed_batch(id)
            .ok_or_else(|| ProposalManagerError::UnknownProposal(id.clone()))?
            .clone();

        let hash = self
            .state
            .lock()
            .map_err(|_| ProposalManagerError::Internal(Box::new(ScabbardError::LockPoisoned)))?
            .prepare_change(batch)
            .map_err(|err| ProposalManagerError::Internal(Box::new(err)))?;

        if hash.as_bytes() != id.as_ref() {
            warn!("Hash mismatch: expected {} but was {}", id, hash);

            self.proposal_update_sender
                .send(ProposalUpdate::ProposalInvalid(id.clone()))?;
        } else {
            self.proposal_update_sender
                .send(ProposalUpdate::ProposalValid(id.clone()))?;
        }

        Ok(())
    }

    fn accept_proposal(
        &self,
        id: &ProposalId,
        // Ignoring consensus data, because this service and two phase consensus don't care about
        // it.
        _consensus_data: Option<Vec<u8>>,
    ) -> Result<(), ProposalManagerError> {
        let mut shared = self
            .shared
            .lock()
            .map_err(|_| ProposalManagerError::Internal(Box::new(ScabbardError::LockPoisoned)))?;

        shared
            .remove_proposed_batch(id)
            .ok_or_else(|| ProposalManagerError::UnknownProposal(id.clone()))?;

        self.state
            .lock()
            .map_err(|_| ProposalManagerError::Internal(Box::new(ScabbardError::LockPoisoned)))?
            .commit()
            .map_err(|err| ProposalManagerError::Internal(Box::new(err)))?;

        self.proposal_update_sender
            .send(ProposalUpdate::ProposalAccepted(id.clone()))?;

        info!("Committed proposal {}", id);

        Ok(())
    }

    fn reject_proposal(&self, id: &ProposalId) -> Result<(), ProposalManagerError> {
        let mut shared = self
            .shared
            .lock()
            .map_err(|_| ProposalManagerError::Internal(Box::new(ScabbardError::LockPoisoned)))?;

        shared
            .remove_proposed_batch(id)
            .ok_or_else(|| ProposalManagerError::UnknownProposal(id.clone()))?;

        self.state
            .lock()
            .map_err(|_| ProposalManagerError::Internal(Box::new(ScabbardError::LockPoisoned)))?
            .rollback()
            .map_err(|err| ProposalManagerError::Internal(Box::new(err)))?;

        info!("Rolled back proposal {}", id);

        Ok(())
    }
}

pub struct ScabbardConsensusNetworkSender {
    service_id: String,
    shared: Arc<Mutex<ScabbardShared>>,
}

impl ScabbardConsensusNetworkSender {
    pub fn new(service_id: String, shared: Arc<Mutex<ScabbardShared>>) -> Self {
        ScabbardConsensusNetworkSender { service_id, shared }
    }
}

impl ConsensusNetworkSender for ScabbardConsensusNetworkSender {
    fn send_to(&self, peer_id: &PeerId, message: Vec<u8>) -> Result<(), ConsensusSendError> {
        let peer_id_string = String::from_utf8(peer_id.clone().into())
            .map_err(|err| ConsensusSendError::Internal(Box::new(err)))?;

        let consensus_message = ConsensusMessage::new(message, self.service_id.as_bytes().into());
        let mut msg = ScabbardMessage::new();
        msg.set_message_type(ScabbardMessage_Type::CONSENSUS_MESSAGE);
        msg.set_consensus_message(consensus_message.try_into()?);

        let shared = self
            .shared
            .lock()
            .map_err(|_| ConsensusSendError::Internal(Box::new(ScabbardError::LockPoisoned)))?;

        if !shared.peer_services().contains(&peer_id_string) {
            return Err(ConsensusSendError::UnknownPeer(peer_id.clone()));
        }

        let network_sender = shared
            .network_sender()
            .ok_or(ConsensusSendError::NotReady)?;

        network_sender
            .send(&peer_id_string, msg.write_to_bytes()?.as_slice())
            .map_err(|err| ConsensusSendError::Internal(Box::new(err)))?;

        Ok(())
    }

    fn broadcast(&self, message: Vec<u8>) -> Result<(), ConsensusSendError> {
        let consensus_message = ConsensusMessage::new(message, self.service_id.as_bytes().into());
        let mut msg = ScabbardMessage::new();
        msg.set_message_type(ScabbardMessage_Type::CONSENSUS_MESSAGE);
        msg.set_consensus_message(consensus_message.try_into()?);

        let shared = self
            .shared
            .lock()
            .map_err(|_| ConsensusSendError::Internal(Box::new(ScabbardError::LockPoisoned)))?;

        let network_sender = shared
            .network_sender()
            .ok_or(ConsensusSendError::NotReady)?;

        for service in shared.peer_services() {
            network_sender
                .send(service, msg.write_to_bytes()?.as_slice())
                .map_err(|err| ConsensusSendError::Internal(Box::new(err)))?;
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use std::collections::{HashSet, VecDeque};

    use crate::service::tests::*;
    use crate::signing::hash::HashVerifier;

    /// Tests that the network sender properly creates messages and sends them using the
    /// `ServiceNetworkSender`.
    #[test]
    fn network_sender() {
        let service_sender = MockServiceNetworkSender::new();
        let mut peer_services = HashSet::new();
        peer_services.insert("1".to_string());
        peer_services.insert("2".to_string());

        let shared = Arc::new(Mutex::new(ScabbardShared::new(
            VecDeque::new(),
            Some(Box::new(service_sender.clone())),
            peer_services.clone(),
            Box::new(HashVerifier),
        )));
        let consensus_sender = ScabbardConsensusNetworkSender::new("0".into(), shared);

        // Test send_to
        consensus_sender
            .send_to(&"1".as_bytes().into(), vec![0])
            .expect("failed to send");

        let (recipient, message) = service_sender
            .sent
            .lock()
            .expect("sent lock poisoned")
            .get(0)
            .expect("1st message not sent")
            .clone();
        assert_eq!(recipient, "1".to_string());

        let scabbard_message: ScabbardMessage =
            protobuf::parse_from_bytes(&message).expect("failed to parse 1st scabbard message");
        assert_eq!(
            scabbard_message.get_message_type(),
            ScabbardMessage_Type::CONSENSUS_MESSAGE
        );

        let consensus_message =
            ConsensusMessage::try_from(scabbard_message.get_consensus_message())
                .expect("failed to parse 1st consensus message");
        assert_eq!(consensus_message.message, vec![0]);
        assert_eq!(consensus_message.origin_id, "0".as_bytes().into());

        // Test broadcast
        consensus_sender.broadcast(vec![1]).expect("failed to send");

        // First broadcast message
        let (recipient, message) = service_sender
            .sent
            .lock()
            .expect("sent lock poisoned")
            .get(1)
            .expect("2nd message not sent")
            .clone();
        assert!(peer_services.remove(&recipient));

        let scabbard_message: ScabbardMessage =
            protobuf::parse_from_bytes(&message).expect("failed to parse 2nd scabbard message");
        assert_eq!(
            scabbard_message.get_message_type(),
            ScabbardMessage_Type::CONSENSUS_MESSAGE
        );

        let consensus_message =
            ConsensusMessage::try_from(scabbard_message.get_consensus_message())
                .expect("failed to parse 2nd consensus message");
        assert_eq!(consensus_message.message, vec![1]);
        assert_eq!(consensus_message.origin_id, "0".as_bytes().into());

        // Second broadcast message
        let (recipient, message) = service_sender
            .sent
            .lock()
            .expect("sent lock poisoned")
            .get(2)
            .expect("3rd message not sent")
            .clone();
        assert!(peer_services.remove(&recipient));

        let scabbard_message: ScabbardMessage =
            protobuf::parse_from_bytes(&message).expect("failed to parse 3rd scabbard message");
        assert_eq!(
            scabbard_message.get_message_type(),
            ScabbardMessage_Type::CONSENSUS_MESSAGE
        );

        let consensus_message =
            ConsensusMessage::try_from(scabbard_message.get_consensus_message())
                .expect("failed to parse 3rd consensus message");
        assert_eq!(consensus_message.message, vec![1]);
        assert_eq!(consensus_message.origin_id, "0".as_bytes().into());
    }
}