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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
pub mod multi;
pub mod parallel;
pub mod serial;
use std::error::Error;
use crate::context::ContextId;
use crate::protocol::batch::BatchPair;
use crate::protocol::receipt::{TransactionReceipt, TransactionResult};
use crate::protocol::transaction::TransactionPair;
pub struct ExecutionTask {
pair: TransactionPair,
context_id: ContextId,
}
impl ExecutionTask {
pub fn new(pair: TransactionPair, context_id: ContextId) -> Self {
ExecutionTask { pair, context_id }
}
pub fn pair(&self) -> &TransactionPair {
&self.pair
}
pub fn context_id(&self) -> &ContextId {
&self.context_id
}
pub fn take(self) -> (TransactionPair, ContextId) {
(self.pair, self.context_id)
}
}
#[derive(Debug, Clone, Eq, Hash, PartialEq)]
pub struct BatchExecutionResult {
pub batch: BatchPair,
pub receipts: Vec<TransactionReceipt>,
}
#[derive(Debug, Clone, Eq, Hash, PartialEq)]
pub struct InvalidTransactionResult {
pub transaction_id: String,
pub error_message: String,
pub error_data: Vec<u8>,
}
impl From<InvalidTransactionResult> for TransactionReceipt {
fn from(result: InvalidTransactionResult) -> Self {
TransactionReceipt {
transaction_id: result.transaction_id,
transaction_result: TransactionResult::Invalid {
error_message: result.error_message,
error_data: result.error_data,
},
}
}
}
#[derive(Debug, PartialEq)]
pub enum ExecutionTaskCompletionNotification {
Invalid(ContextId, InvalidTransactionResult),
Valid(ContextId, String),
}
#[derive(Clone, Debug)]
pub enum SchedulerError {
DuplicateBatch(String),
Internal(String),
NoTaskIterator,
SchedulerFinalized,
UnexpectedNotification(String),
}
impl Error for SchedulerError {}
impl std::fmt::Display for SchedulerError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match *self {
SchedulerError::DuplicateBatch(ref batch_id) => {
write!(f, "duplicate batch added to scheduler: {}", batch_id)
}
SchedulerError::Internal(ref err) => {
write!(f, "scheduler encountered an internal error: {}", err)
}
SchedulerError::NoTaskIterator => write!(f, "task iterator already taken"),
SchedulerError::SchedulerFinalized => write!(f, "batch added to finalized scheduler"),
SchedulerError::UnexpectedNotification(ref txn_id) => write!(
f,
"scheduler received an unexpected notification: {}",
txn_id
),
}
}
}
pub trait Scheduler: Send {
fn set_result_callback(
&mut self,
callback: Box<dyn Fn(Option<BatchExecutionResult>) + Send>,
) -> Result<(), SchedulerError>;
fn set_error_callback(
&mut self,
callback: Box<dyn Fn(SchedulerError) + Send>,
) -> Result<(), SchedulerError>;
fn add_batch(&mut self, batch: BatchPair) -> Result<(), SchedulerError>;
fn cancel(&mut self) -> Result<Vec<BatchPair>, SchedulerError>;
fn finalize(&mut self) -> Result<(), SchedulerError>;
fn take_task_iterator(
&mut self,
) -> Result<Box<dyn Iterator<Item = ExecutionTask> + Send>, SchedulerError>;
fn new_notifier(&mut self) -> Result<Box<dyn ExecutionTaskCompletionNotifier>, SchedulerError>;
}
pub trait SchedulerFactory: Send {
fn create_scheduler(&self, state_id: String) -> Result<Box<dyn Scheduler>, SchedulerError>;
}
pub trait ExecutionTaskCompletionNotifier: Send {
fn notify(&self, notification: ExecutionTaskCompletionNotification);
fn clone_box(&self) -> Box<dyn ExecutionTaskCompletionNotifier>;
}
impl Clone for Box<dyn ExecutionTaskCompletionNotifier> {
fn clone(&self) -> Self {
self.clone_box()
}
}
fn default_result_callback(batch_result: Option<BatchExecutionResult>) {
warn!(
"No result callback set; dropping batch execution result: {}",
match batch_result {
Some(ref result) => result.batch.batch().header_signature(),
None => "None",
}
);
}
fn default_error_callback(error: SchedulerError) {
error!("No error callback set; SchedulerError: {}", error);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::context::manager::ContextManagerError;
use crate::context::ContextLifecycle;
use crate::protocol::batch::BatchBuilder;
use crate::protocol::receipt::TransactionReceiptBuilder;
use crate::protocol::transaction::{HashMethod, Transaction, TransactionBuilder};
use std::sync::mpsc;
use cylinder::{secp256k1::Secp256k1Context, Context, Signer};
pub fn mock_transactions(num: u8) -> Vec<Transaction> {
let signer = new_signer();
(0..num)
.map(|i| {
TransactionBuilder::new()
.with_family_name("mock".into())
.with_family_version("0.1".into())
.with_inputs(vec![])
.with_outputs(vec![])
.with_nonce(vec![i])
.with_payload(vec![])
.with_payload_hash_method(HashMethod::SHA512)
.build(&*signer)
.expect("Failed to build transaction")
})
.collect()
}
pub fn mock_batch(transactions: Vec<Transaction>) -> BatchPair {
let signer = new_signer();
BatchBuilder::new()
.with_transactions(transactions)
.build_pair(&*signer)
.expect("Failed to build batch pair")
}
pub fn mock_batch_with_num_txns(num: u8) -> BatchPair {
mock_batch(mock_transactions(num))
}
pub fn mock_batches_with_one_transaction(num_batches: u8) -> Vec<BatchPair> {
mock_transactions(num_batches)
.into_iter()
.map(|txn| mock_batch(vec![txn]))
.collect()
}
fn new_signer() -> Box<dyn Signer> {
let context = Secp256k1Context::new();
let key = context.new_random_private_key();
context.new_signer(key)
}
pub fn valid_receipt_from_batch(batch: BatchPair) -> Option<BatchExecutionResult> {
let receipts = batch
.batch()
.transactions()
.iter()
.map(|txn| TransactionReceipt {
transaction_id: txn.header_signature().into(),
transaction_result: TransactionResult::Valid {
state_changes: vec![],
events: vec![],
data: vec![],
},
})
.collect();
Some(BatchExecutionResult { batch, receipts })
}
pub fn invalid_receipt_from_batch(batch: BatchPair) -> Option<BatchExecutionResult> {
let receipts = batch
.batch()
.transactions()
.iter()
.map(|txn| TransactionReceipt {
transaction_id: txn.header_signature().into(),
transaction_result: TransactionResult::Invalid {
error_message: String::new(),
error_data: vec![],
},
})
.collect();
Some(BatchExecutionResult { batch, receipts })
}
pub fn mock_context_id() -> ContextId {
[
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
0x0f, 0x10,
]
}
#[derive(Clone)]
pub struct MockContextLifecycle {}
impl MockContextLifecycle {
pub fn new() -> Self {
MockContextLifecycle {}
}
}
impl ContextLifecycle for MockContextLifecycle {
fn create_context(
&mut self,
_dependent_contexts: &[ContextId],
_state_id: &str,
) -> ContextId {
[
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x01,
]
}
fn get_transaction_receipt(
&self,
_context_id: &ContextId,
transaction_id: &str,
) -> Result<TransactionReceipt, ContextManagerError> {
TransactionReceiptBuilder::new()
.valid()
.with_transaction_id(transaction_id.into())
.build()
.map_err(|err| ContextManagerError::from(err))
}
fn drop_context(&mut self, _context_id: ContextId) {}
fn clone_box(&self) -> Box<dyn ContextLifecycle> {
Box::new(self.clone())
}
}
pub fn test_scheduler_add_batch(scheduler: &mut dyn Scheduler) -> BatchPair {
let batch = mock_batch_with_num_txns(1);
scheduler
.add_batch(batch.clone())
.expect("Failed to add batch");
match scheduler.add_batch(batch.clone()) {
Err(SchedulerError::DuplicateBatch(batch_id)) => {
assert_eq!(batch_id, batch.batch().header_signature())
}
res => panic!("Did not get DuplicateBatch; got {:?}", res),
}
batch
}
pub fn test_scheduler_cancel(scheduler: &mut dyn Scheduler) {
let batches = mock_batches_with_one_transaction(2);
scheduler
.add_batch(batches[0].clone())
.expect("Failed to add 1st batch");
scheduler
.add_batch(batches[1].clone())
.expect("Failed to add 2nd batch");
for batch in scheduler.cancel().expect("Failed 1st cancel") {
assert!(batches.contains(&batch));
}
assert!(scheduler.cancel().expect("Failed 2nd cancel").is_empty());
}
pub fn test_scheduler_finalize(scheduler: &mut dyn Scheduler) {
let (tx, rx) = mpsc::channel();
scheduler
.set_result_callback(Box::new(move |result| {
tx.send(result).expect("Failed to send result");
}))
.expect("Failed to set result callback");
let mut task_iterator = scheduler
.take_task_iterator()
.expect("Failed to get task iterator");
scheduler.finalize().expect("Failed to finalize");
assert!(rx.recv().expect("Failed to receive result").is_none());
match scheduler.add_batch(mock_batch_with_num_txns(1)) {
Err(SchedulerError::SchedulerFinalized) => (),
res => panic!("Did not get SchedulerFinalized; got {:?}", res),
}
assert!(task_iterator.next().is_none());
}
pub fn test_scheduler_flow_with_one_transaction(scheduler: &mut dyn Scheduler) {
let (tx, rx) = mpsc::channel();
scheduler
.set_result_callback(Box::new(move |result| {
if result.is_some() {
tx.send(result).expect("Failed to send result");
}
}))
.expect("Failed to set result callback");
let batch = mock_batch_with_num_txns(1);
scheduler
.add_batch(batch.clone())
.expect("Failed to add batch");
let mut task_iterator = scheduler
.take_task_iterator()
.expect("Failed to get task iterator");
let notifier = scheduler
.new_notifier()
.expect("Failed to get new notifier");
notifier.notify(ExecutionTaskCompletionNotification::Invalid(
mock_context_id(),
InvalidTransactionResult {
transaction_id: task_iterator
.next()
.expect("Failed to get task")
.pair()
.transaction()
.header_signature()
.into(),
error_message: String::new(),
error_data: vec![],
},
));
let result = rx.recv().expect("Failed to receive result");
assert_eq!(result, invalid_receipt_from_batch(batch));
}
pub fn test_scheduler_flow_with_two_batches(scheduler: &mut dyn Scheduler) {
let (tx, rx) = mpsc::channel();
scheduler
.set_result_callback(Box::new(move |result| {
tx.send(result).expect("Failed to send result");
}))
.expect("Failed to set result callback");
let batches = mock_batches_with_one_transaction(2);
for batch in batches.iter() {
scheduler
.add_batch(batch.clone())
.expect("Failed to add batch");
}
scheduler.finalize().expect("Unable to finalize scheduler");
let mut task_iterator = scheduler
.take_task_iterator()
.expect("Failed to get task iterator");
let notifier = scheduler
.new_notifier()
.expect("Failed to get new notifier");
notifier.notify(ExecutionTaskCompletionNotification::Invalid(
mock_context_id(),
InvalidTransactionResult {
transaction_id: task_iterator
.next()
.expect("Failed to get task")
.pair()
.transaction()
.header_signature()
.into(),
error_message: String::new(),
error_data: vec![],
},
));
notifier.notify(ExecutionTaskCompletionNotification::Invalid(
mock_context_id(),
InvalidTransactionResult {
transaction_id: task_iterator
.next()
.expect("Failed to get task")
.pair()
.transaction()
.header_signature()
.into(),
error_message: String::new(),
error_data: vec![],
},
));
for batch in batches {
let result = rx.recv().expect("Failed to receive result");
assert_eq!(result, invalid_receipt_from_batch(batch));
}
let result = rx.recv().expect("Failed to receive result");
assert_eq!(result, None);
}
pub fn test_scheduler_flow_with_multiple_transactions(scheduler: &mut dyn Scheduler) {
let (tx, rx) = mpsc::channel();
scheduler
.set_result_callback(Box::new(move |result| {
if result.is_some() {
tx.send(result).expect("Failed to send result");
}
}))
.expect("Failed to set result callback");
let original_batch = mock_batch_with_num_txns(3);
scheduler
.add_batch(original_batch.clone())
.expect("Failed to add batch");
let mut task_iterator = scheduler
.take_task_iterator()
.expect("Failed to get task iterator");
let notifier = scheduler
.new_notifier()
.expect("Failed to get new notifier");
notifier.notify(ExecutionTaskCompletionNotification::Valid(
mock_context_id(),
task_iterator
.next()
.expect("Failed to get task")
.pair()
.transaction()
.header_signature()
.into(),
));
notifier.notify(ExecutionTaskCompletionNotification::Valid(
mock_context_id(),
task_iterator
.next()
.expect("Failed to get task")
.pair()
.transaction()
.header_signature()
.into(),
));
notifier.notify(ExecutionTaskCompletionNotification::Valid(
mock_context_id(),
task_iterator
.next()
.expect("Failed to get task")
.pair()
.transaction()
.header_signature()
.into(),
));
let BatchExecutionResult { batch, receipts } = rx
.recv()
.expect("Failed to receive result")
.expect("Got None result");
assert_eq!(batch, original_batch);
let original_batch_txn_ids = original_batch
.batch()
.transactions()
.iter()
.map(|txn| txn.header_signature())
.collect::<Vec<_>>()
.sort_unstable();
let receipt_txn_ids = receipts
.iter()
.map(|receipt| match &receipt.transaction_result {
TransactionResult::Valid { .. } => &receipt.transaction_id,
res => panic!("Did not get valid receipt; got {:?}", res),
})
.collect::<Vec<_>>()
.sort_unstable();
assert_eq!(original_batch_txn_ids, receipt_txn_ids);
}
pub fn test_scheduler_invalid_transaction_invalidates_batch(scheduler: &mut dyn Scheduler) {
let (tx, rx) = mpsc::channel();
scheduler
.set_result_callback(Box::new(move |result| {
if result.is_some() {
tx.send(result).expect("Failed to send result");
}
}))
.expect("Failed to set result callback");
let original_batch = mock_batch_with_num_txns(3);
scheduler
.add_batch(original_batch.clone())
.expect("Failed to add batch");
let mut task_iterator = scheduler
.take_task_iterator()
.expect("Failed to get task iterator");
let notifier = scheduler
.new_notifier()
.expect("Failed to get new notifier");
notifier.notify(ExecutionTaskCompletionNotification::Valid(
mock_context_id(),
task_iterator
.next()
.expect("Failed to get task")
.pair()
.transaction()
.header_signature()
.into(),
));
notifier.notify(ExecutionTaskCompletionNotification::Invalid(
mock_context_id(),
InvalidTransactionResult {
transaction_id: task_iterator
.next()
.expect("Failed to get task")
.pair()
.transaction()
.header_signature()
.into(),
error_message: String::new(),
error_data: vec![],
},
));
let BatchExecutionResult { batch, receipts } = rx
.recv()
.expect("Failed to receive result")
.expect("Got None result");
assert_eq!(batch, original_batch);
let original_batch_txn_ids = original_batch
.batch()
.transactions()
.iter()
.map(|txn| txn.header_signature())
.collect::<Vec<_>>()
.sort_unstable();
let receipt_txn_ids = receipts
.iter()
.map(|receipt| match &receipt.transaction_result {
TransactionResult::Invalid { .. } => &receipt.transaction_id,
res => panic!("Did not get invalid receipt; got {:?}", res),
})
.collect::<Vec<_>>()
.sort_unstable();
assert_eq!(original_batch_txn_ids, receipt_txn_ids);
}
}