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
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
/*
 * Copyright 2019-2021 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.
 * -----------------------------------------------------------------------------
 */
//! The static execution adapter provides a way to execute transaction handlers directly.
//!
//! This module provides the `StaticExecutionAdapter`, an implementation of `ExecutionAdapter`
//! which execute transactions via `TransactionHandler` instances directly.
use std::sync::mpsc::{channel, Sender};
use std::thread;

use crate::context::manager::sync::ContextManager;
use crate::context::manager::ContextManagerError;
use crate::context::ContextId;
use crate::execution::adapter::{ExecutionAdapter, ExecutionAdapterError, ExecutionOperationError};
use crate::execution::{ExecutionRegistry, TransactionFamily};
use crate::handler::{ApplyError, ContextError, TransactionContext, TransactionHandler};
use crate::protocol::receipt::Event;
use crate::protocol::transaction::TransactionPair;
use crate::scheduler::{ExecutionTaskCompletionNotification, InvalidTransactionResult};

// A type declaration to make the use of this complicated type-bounded box easier to work with
type OnDoneCallback =
    Box<dyn Fn(Result<ExecutionTaskCompletionNotification, ExecutionAdapterError>) + Send>;

/// The StaticExecutionAdapter to wrap TransactionHandlers
///
/// This struct takes a series of transaction handlers which can be used to execution transactions.
/// These transactions are executed on a single background thread.
pub struct StaticExecutionAdapter {
    join_handle: thread::JoinHandle<bool>,
    sender: Sender<StaticAdapterCommand>,
}

impl StaticExecutionAdapter {
    /// Creates a new adapter, if possible.
    ///
    /// Creates a `StaticExecutionAdapter` wrapping the given `TransactionHandler` vector and a
    /// `ContextManager` instance. This adapter will dispatch transaction pairs to the appropriate
    /// handler, if found.
    ///
    /// # Errors
    ///
    /// `ExecutionAdapterError` is returned if the background thread cannot be created.
    pub fn new_adapter(
        handlers: Vec<Box<dyn TransactionHandler>>,
        context_manager: ContextManager,
    ) -> Result<Self, ExecutionAdapterError> {
        let (sender, receiver) = channel();
        let join_handle = thread::Builder::new()
            .name("StaticExecutionAdapter".into())
            .spawn(move || {
                while let Ok(cmd) = receiver.recv() {
                    match cmd {
                        StaticAdapterCommand::Execute(execute_cmd) => {
                            let (txn_pair, context_id, on_done) = *execute_cmd;
                            debug!("Executing {:?} in context {:?}", &txn_pair, &context_id);
                            execute_transaction(
                                &handlers,
                                txn_pair,
                                &context_manager,
                                context_id,
                                on_done,
                            );
                        }
                        StaticAdapterCommand::Start(mut execution_registry) => {
                            register_handlers(&handlers, &mut *execution_registry);
                        }
                        StaticAdapterCommand::Stop => {
                            break;
                        }
                    }
                }
                true
            })
            .map_err(|err| ExecutionAdapterError::GeneralExecutionError(Box::new(err)))?;

        Ok(StaticExecutionAdapter {
            join_handle,
            sender,
        })
    }
}

fn execute_transaction(
    handlers: &[Box<dyn TransactionHandler>],
    transaction_pair: TransactionPair,
    context_manager: &ContextManager,
    context_id: ContextId,
    on_done: OnDoneCallback,
) {
    let family = TransactionFamily::from_pair(&transaction_pair);
    match handlers.iter().find(|handler| {
        handler.family_name() == family.family_name()
            && handler
                .family_versions()
                .iter()
                .any(|v| v == family.family_version())
    }) {
        Some(handler) => {
            let mut static_context = StaticContext::new(context_manager, &context_id);

            match handler.apply(&transaction_pair, &mut static_context) {
                Ok(_) => on_done(Ok(ExecutionTaskCompletionNotification::Valid(
                    context_id,
                    transaction_pair.transaction().header_signature().to_owned(),
                ))),
                Err(ApplyError::InvalidTransaction(error_message)) => {
                    on_done(Ok(ExecutionTaskCompletionNotification::Invalid(
                        context_id,
                        InvalidTransactionResult {
                            transaction_id: transaction_pair
                                .transaction()
                                .header_signature()
                                .to_owned(),
                            error_message,
                            error_data: vec![],
                        },
                    )))
                }
                Err(err) => on_done(Err(ExecutionAdapterError::GeneralExecutionError(Box::new(
                    err,
                )))),
            }
        }
        None => on_done(Err(ExecutionAdapterError::RoutingError(Box::new(
            transaction_pair,
        )))),
    };
}

fn register_handlers(
    handlers: &[Box<dyn TransactionHandler>],
    execution_registry: &mut dyn ExecutionRegistry,
) {
    for handler in handlers {
        for version in handler.family_versions() {
            execution_registry.register_transaction_family(TransactionFamily::new(
                handler.family_name().to_owned(),
                version.clone(),
            ));
        }
    }
}

impl ExecutionAdapter for StaticExecutionAdapter {
    fn start(
        &mut self,
        execution_registry: Box<dyn ExecutionRegistry>,
    ) -> Result<(), ExecutionOperationError> {
        self.sender
            .send(StaticAdapterCommand::Start(execution_registry))
            .map_err(|err| {
                ExecutionOperationError::StartError(format!(
                    "Unable to start static execution adapter: {}",
                    err
                ))
            })
    }

    fn execute(
        &self,
        transaction_pair: TransactionPair,
        context_id: ContextId,
        on_done: OnDoneCallback,
    ) -> Result<(), ExecutionOperationError> {
        self.sender
            .send(StaticAdapterCommand::Execute(Box::new((
                transaction_pair,
                context_id,
                on_done,
            ))))
            .map_err(|err| {
                ExecutionOperationError::ExecuteError(format!(
                    "Unable to send transaction for static execution: {}",
                    err
                ))
            })
    }

    fn stop(self: Box<Self>) -> Result<(), ExecutionOperationError> {
        self.sender
            .send(StaticAdapterCommand::Stop)
            .map_err(|err| {
                ExecutionOperationError::StopError(format!("Unable to send stop command: {}", err))
            })?;

        self.join_handle.join().map_err(|_| {
            ExecutionOperationError::StopError("Unable to join internal thread.".into())
        })?;

        Ok(())
    }
}

enum StaticAdapterCommand {
    Start(Box<dyn ExecutionRegistry>),
    Stop,
    Execute(Box<(TransactionPair, ContextId, OnDoneCallback)>),
}

struct StaticContext<'a, 'b> {
    context_manager: &'a ContextManager,
    context_id: &'b ContextId,
}

impl<'a, 'b> StaticContext<'a, 'b> {
    fn new(context_manager: &'a ContextManager, context_id: &'b ContextId) -> Self {
        StaticContext {
            context_manager,
            context_id,
        }
    }
}

impl<'a, 'b> TransactionContext for StaticContext<'a, 'b> {
    fn get_state_entries(
        &self,
        addresses: &[String],
    ) -> Result<Vec<(String, Vec<u8>)>, ContextError> {
        self.context_manager
            .get(self.context_id, addresses)
            .map_err(ContextError::from)
    }

    fn set_state_entries(&self, entries: Vec<(String, Vec<u8>)>) -> Result<(), ContextError> {
        for (address, value) in entries.into_iter() {
            self.context_manager
                .set_state(self.context_id, address, value)?;
        }

        Ok(())
    }

    fn delete_state_entries(&self, addresses: &[String]) -> Result<Vec<String>, ContextError> {
        let mut results = vec![];
        for address in addresses.iter() {
            if self
                .context_manager
                .delete_state(self.context_id, address.as_str())?
                .is_some()
            {
                results.push(address.clone());
            }
        }
        Ok(results)
    }

    fn add_receipt_data(&self, data: Vec<u8>) -> Result<(), ContextError> {
        self.context_manager
            .add_data(self.context_id, data)
            .map_err(ContextError::from)
    }

    fn add_event(
        &self,
        event_type: String,
        attributes: Vec<(String, String)>,
        data: Vec<u8>,
    ) -> Result<(), ContextError> {
        self.context_manager
            .add_event(
                self.context_id,
                Event {
                    event_type,
                    attributes,
                    data,
                },
            )
            .map_err(ContextError::from)
    }
}

impl From<ContextManagerError> for ContextError {
    fn from(err: ContextManagerError) -> Self {
        // Error's should be addressed in the handler::error module.
        ContextError::SendError(Box::new(err))
    }
}

#[cfg(all(test, feature = "family-command-transaction-builder"))]
mod test {
    use super::*;

    use std::collections::HashMap;
    use std::sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    };
    use std::time;

    use cylinder::{secp256k1::Secp256k1Context, Context, Signer};

    use crate::context::ContextLifecycle;
    use crate::families::command::{CommandTransactionBuilder, CommandTransactionHandler};
    use crate::protocol::command::{
        AddEvent, AddReceiptData, BytesEntry, Command, DeleteState, GetState, ReturnInternalError,
        ReturnInvalid, SetState, Sleep, SleepType,
    };
    use crate::protocol::receipt::TransactionResult;
    use crate::scheduler::{ExecutionTaskCompletionNotification, InvalidTransactionResult};
    use crate::state::hashmap::HashMapState;

    fn create_bytes_entry(state_writes: Vec<(String, Vec<u8>)>) -> Vec<BytesEntry> {
        state_writes
            .into_iter()
            .map(|(k, v)| BytesEntry::new(k.to_string(), v.to_vec()))
            .collect()
    }

    /// Apply the static adapter with a simple transaction that sets a value successfully.
    #[test]
    fn apply_static_adapter_simple_set() {
        let registry = MockRegistry::default();

        let state = HashMapState::new();
        let state_id = HashMapState::state_id(&HashMap::new());

        let mut context_manager: ContextManager = ContextManager::new(Box::new(state));

        let handler = CommandTransactionHandler::new();

        let mut static_adapter =
            StaticExecutionAdapter::new_adapter(vec![Box::new(handler)], context_manager.clone())
                .expect("Could not create adapter");

        assert!(static_adapter.start(Box::new(registry.clone())).is_ok());

        // Create and execute a simple transaction.
        let txn_pair = CommandTransactionBuilder::new()
            .with_commands(vec![Command::SetState(SetState::new(create_bytes_entry(
                vec![("abc".into(), b"abc".to_vec())],
            )))])
            .into_transaction_builder()
            .expect("Failed to get transaction builder")
            .build_pair(&*new_signer())
            .expect("Failed to build transaction pair");
        let txn_id = txn_pair.transaction().header_signature().into();
        let context_id = context_manager.create_context(&[], &state_id);

        let (send, recv) = std::sync::mpsc::channel();
        assert!(static_adapter
            .execute(
                txn_pair,
                context_id.clone(),
                Box::new(move |res| {
                    send.send(res).expect("Unable to send result");
                }),
            )
            .is_ok());
        let result = recv.recv().unwrap();

        assert_eq!(
            ExecutionTaskCompletionNotification::Valid(context_id.clone(), txn_id),
            result.unwrap()
        );
        assert_eq!(
            vec![("abc".to_owned(), b"abc".to_vec())],
            context_manager
                .get(&context_id, &["abc".to_owned()])
                .unwrap()
        );

        assert!(Box::new(static_adapter).stop().is_ok());
    }

    /// Apply the static adapter with a failing transaction which returns an invalid error.
    #[test]
    fn apply_static_adapter_invalid_txn() {
        let registry = MockRegistry::default();

        let state = HashMapState::new();
        let state_id = HashMapState::state_id(&HashMap::new());

        let mut context_manager: ContextManager = ContextManager::new(Box::new(state));

        let handler = CommandTransactionHandler::new();

        let mut static_adapter =
            StaticExecutionAdapter::new_adapter(vec![Box::new(handler)], context_manager.clone())
                .expect("Could not create adapter");

        assert!(static_adapter.start(Box::new(registry.clone())).is_ok());

        // Create and execute a failing transaction, resulting in an invalid error.
        let txn_pair = CommandTransactionBuilder::new()
            .with_commands(vec![
                Command::GetState(GetState::new(vec!["abc".into()])),
                Command::ReturnInvalid(ReturnInvalid::new("Test Fail Succeeded".into())),
            ])
            .into_transaction_builder()
            .expect("Failed to get transaction builder")
            .build_pair(&*new_signer())
            .expect("Failed to build transaction pair");

        let txn_id = txn_pair.transaction().header_signature().to_owned();
        let context_id = context_manager.create_context(&[], &state_id);

        let (send, recv) = std::sync::mpsc::channel();
        assert!(static_adapter
            .execute(
                txn_pair,
                context_id.clone(),
                Box::new(move |res| {
                    send.send(res).expect("Unable to send result");
                }),
            )
            .is_ok());
        let result = recv.recv().unwrap();

        assert_eq!(
            ExecutionTaskCompletionNotification::Invalid(
                context_id,
                InvalidTransactionResult {
                    transaction_id: txn_id,
                    error_message: "Test Fail Succeeded".into(),
                    error_data: vec![],
                }
            ),
            result.unwrap()
        );

        assert!(Box::new(static_adapter).stop().is_ok());
    }

    /// Apply the static adapter with a failing transaction which returns an internal error.
    #[test]
    fn apply_static_adapter_internal_error() {
        let registry = MockRegistry::default();

        let state = HashMapState::new();
        let state_id = HashMapState::state_id(&HashMap::new());

        let mut context_manager: ContextManager = ContextManager::new(Box::new(state));

        let handler = CommandTransactionHandler::new();

        let mut static_adapter =
            StaticExecutionAdapter::new_adapter(vec![Box::new(handler)], context_manager.clone())
                .expect("Could not create adapter");

        assert!(static_adapter.start(Box::new(registry.clone())).is_ok());

        // Create and execute a failing transaction, resulting in an internal error.
        let txn_pair = CommandTransactionBuilder::new()
            .with_commands(vec![
                Command::GetState(GetState::new(vec!["abc".into()])),
                Command::ReturnInternalError(ReturnInternalError::new(
                    "Test Internal Fail Succeeded".into(),
                )),
            ])
            .into_transaction_builder()
            .expect("Failed to get transaction builder")
            .build_pair(&*new_signer())
            .expect("Failed to build transaction pair");

        let context_id = context_manager.create_context(&[], &state_id);

        let (send, recv) = std::sync::mpsc::channel();
        assert!(static_adapter
            .execute(
                txn_pair,
                context_id.clone(),
                Box::new(move |res| {
                    send.send(res).expect("Unable to send result");
                }),
            )
            .is_ok());
        let result = recv.recv().unwrap();

        assert!(result.is_err());

        assert!(Box::new(static_adapter).stop().is_ok());
    }

    /// Apply the static adapter with a valid delete transaction.
    #[test]
    fn apply_static_adapter_valid_delete() {
        let registry = MockRegistry::default();

        let state = HashMapState::new();
        let state_id = HashMapState::state_id(&HashMap::new());

        let mut context_manager: ContextManager = ContextManager::new(Box::new(state));

        let handler = CommandTransactionHandler::new();

        let mut static_adapter =
            StaticExecutionAdapter::new_adapter(vec![Box::new(handler)], context_manager.clone())
                .expect("Could not create adapter");

        assert!(static_adapter.start(Box::new(registry.clone())).is_ok());

        // Create and execute a valid delete transaction.
        let txn_pair = CommandTransactionBuilder::new()
            .with_commands(vec![
                Command::SetState(SetState::new(create_bytes_entry(vec![(
                    "abc".into(),
                    b"abc".to_vec(),
                )]))),
                Command::GetState(GetState::new(vec!["abc".into()])),
                Command::DeleteState(DeleteState::new(vec!["abc".into()])),
            ])
            .into_transaction_builder()
            .expect("Failed to get transaction builder")
            .build_pair(&*new_signer())
            .expect("Failed to build transaction pair");
        let txn_id = txn_pair.transaction().header_signature().to_owned();
        let context_id = context_manager.create_context(&[], &state_id);

        let (send, recv) = std::sync::mpsc::channel();
        assert!(static_adapter
            .execute(
                txn_pair,
                context_id.clone(),
                Box::new(move |res| {
                    send.send(res).expect("Unable to send result");
                }),
            )
            .is_ok());
        let result = recv.recv().unwrap();

        assert_eq!(
            ExecutionTaskCompletionNotification::Valid(context_id.clone(), txn_id),
            result.unwrap()
        );
        assert_eq!(
            context_manager
                .get(&context_id, &["abc".to_owned()])
                .unwrap(),
            vec![],
        );

        assert!(Box::new(static_adapter).stop().is_ok());
    }

    /// Apply the static adapter with a valid busy wait command.
    #[test]
    fn apply_static_adapter_busy_wait_sleep() {
        let registry = MockRegistry::default();

        let state = HashMapState::new();
        let state_id = HashMapState::state_id(&HashMap::new());

        let mut context_manager: ContextManager = ContextManager::new(Box::new(state));

        let handler = CommandTransactionHandler::new();

        let mut static_adapter =
            StaticExecutionAdapter::new_adapter(vec![Box::new(handler)], context_manager.clone())
                .expect("Could not create adapter");

        assert!(static_adapter.start(Box::new(registry.clone())).is_ok());

        // Create and execute a busy wait transaction.
        let txn_pair = CommandTransactionBuilder::new()
            .with_commands(vec![Command::Sleep(Sleep::new(100, SleepType::BusyWait))])
            .into_transaction_builder()
            .expect("Failed to get transaction builder")
            .build_pair(&*new_signer())
            .expect("Failed to build transaction pair");
        let txn_id = txn_pair.transaction().header_signature().to_owned();
        let context_id = context_manager.create_context(&[], &state_id);

        let time_before_execution = time::Instant::now();

        let (send, recv) = std::sync::mpsc::channel();
        assert!(static_adapter
            .execute(
                txn_pair,
                context_id.clone(),
                Box::new(move |res| {
                    send.send(res).expect("Unable to send result");
                }),
            )
            .is_ok());
        let result = recv.recv().unwrap();

        let elapsed = time_before_execution.elapsed();
        assert!(elapsed.ge(&time::Duration::from_millis(100)));

        assert_eq!(
            ExecutionTaskCompletionNotification::Valid(context_id.clone(), txn_id),
            result.unwrap()
        );

        assert!(Box::new(static_adapter).stop().is_ok());
    }

    /// Apply the static adapter with a valid wait command.
    #[test]
    fn apply_static_adapter_wait_sleep() {
        let registry = MockRegistry::default();

        let state = HashMapState::new();
        let state_id = HashMapState::state_id(&HashMap::new());

        let mut context_manager: ContextManager = ContextManager::new(Box::new(state));

        let handler = CommandTransactionHandler::new();

        let mut static_adapter =
            StaticExecutionAdapter::new_adapter(vec![Box::new(handler)], context_manager.clone())
                .expect("Could not create adapter");

        assert!(static_adapter.start(Box::new(registry.clone())).is_ok());

        // Create and execute a sleep transaction.
        let txn_pair = CommandTransactionBuilder::new()
            .with_commands(vec![Command::Sleep(Sleep::new(100, SleepType::Wait))])
            .into_transaction_builder()
            .expect("Failed to get transaction builder")
            .build_pair(&*new_signer())
            .expect("Failed to build transaction pair");
        let txn_id = txn_pair.transaction().header_signature().to_owned();
        let context_id = context_manager.create_context(&[], &state_id);

        let time_before_execution = time::Instant::now();

        let (send, recv) = std::sync::mpsc::channel();
        assert!(static_adapter
            .execute(
                txn_pair,
                context_id.clone(),
                Box::new(move |res| {
                    send.send(res).expect("Unable to send result");
                }),
            )
            .is_ok());
        let result = recv.recv().unwrap();

        let elapsed = time_before_execution.elapsed();
        assert!(elapsed.ge(&time::Duration::from_millis(100)));

        assert_eq!(
            ExecutionTaskCompletionNotification::Valid(context_id.clone(), txn_id),
            result.unwrap()
        );

        assert!(Box::new(static_adapter).stop().is_ok());
    }

    /// Apply the static adapter with a list of commands that will return early with an internal
    /// error.
    #[test]
    fn apply_static_adapter_early_internal_error() {
        let registry = MockRegistry::default();

        let state = HashMapState::new();
        let state_id = HashMapState::state_id(&HashMap::new());

        let mut context_manager: ContextManager = ContextManager::new(Box::new(state));

        let handler = CommandTransactionHandler::new();

        let mut static_adapter =
            StaticExecutionAdapter::new_adapter(vec![Box::new(handler)], context_manager.clone())
                .expect("Could not create adapter");

        assert!(static_adapter.start(Box::new(registry.clone())).is_ok());

        // Create and execute a Set transaction, followed by an Internal error. This will cause
        // the rest of the commands to be short-circuited.
        let txn_pair = CommandTransactionBuilder::new()
            .with_commands(vec![
                Command::SetState(SetState::new(create_bytes_entry(vec![(
                    "abc".into(),
                    b"abc".to_vec(),
                )]))),
                Command::ReturnInternalError(ReturnInternalError::new(
                    "Return internal error between transactions".into(),
                )),
                Command::SetState(SetState::new(create_bytes_entry(vec![(
                    "def".into(),
                    b"def".to_vec(),
                )]))),
            ])
            .into_transaction_builder()
            .expect("Failed to get transaction builder")
            .build_pair(&*new_signer())
            .expect("Failed to build transaction pair");

        let context_id = context_manager.create_context(&[], &state_id);

        let (send, recv) = std::sync::mpsc::channel();
        assert!(static_adapter
            .execute(
                txn_pair,
                context_id.clone(),
                Box::new(move |res| {
                    send.send(res).expect("Unable to send result");
                }),
            )
            .is_ok());
        let result = recv.recv().unwrap();

        assert!(result.is_err());
        assert_eq!(
            vec![("abc".to_owned(), b"abc".to_vec())],
            context_manager
                .get(&context_id, &["abc".to_owned()])
                .unwrap(),
        );
        assert_eq!(
            context_manager
                .get(&context_id, &["def".to_owned()])
                .unwrap(),
            vec![],
        );

        assert!(Box::new(static_adapter).stop().is_ok());
    }

    /// Apply the static adapter with several commands to add Events.
    #[test]
    fn apply_static_adapter_add_events() {
        let registry = MockRegistry::default();

        let state = HashMapState::new();
        let state_id = HashMapState::state_id(&HashMap::new());

        let mut context_manager: ContextManager = ContextManager::new(Box::new(state));

        let handler = CommandTransactionHandler::new();

        let mut static_adapter =
            StaticExecutionAdapter::new_adapter(vec![Box::new(handler)], context_manager.clone())
                .expect("Could not create adapter");

        assert!(static_adapter.start(Box::new(registry.clone())).is_ok());

        // Create and execute an Add Event transaction.
        let txn_pair = CommandTransactionBuilder::new()
            .with_commands(vec![
                Command::AddEvent(AddEvent::new(
                    "First event".to_string(),
                    create_bytes_entry(vec![
                        ("key1".to_string(), "value1".as_bytes().to_vec()),
                        ("key2".to_string(), "value2".as_bytes().to_vec()),
                    ]),
                    b"abc".to_vec(),
                )),
                Command::AddEvent(AddEvent::new(
                    "Second event".to_string(),
                    create_bytes_entry(vec![
                        ("key1".to_string(), "value1".as_bytes().to_vec()),
                        ("key2".to_string(), "value2".as_bytes().to_vec()),
                    ]),
                    b"def".to_vec(),
                )),
            ])
            .into_transaction_builder()
            .expect("Failed to get transaction builder")
            .build_pair(&*new_signer())
            .expect("Failed to build transaction pair");
        let txn_id = txn_pair.transaction().header_signature().to_owned();
        let context_id = context_manager.create_context(&[], &state_id);

        let (send, recv) = std::sync::mpsc::channel();
        assert!(static_adapter
            .execute(
                txn_pair,
                context_id.clone(),
                Box::new(move |res| {
                    send.send(res).expect("Unable to send result");
                }),
            )
            .is_ok());
        let result = recv.recv().unwrap();

        assert_eq!(
            ExecutionTaskCompletionNotification::Valid(context_id.clone(), txn_id.clone()),
            result.unwrap()
        );

        let txn_receipt = context_manager
            .get_transaction_receipt(&context_id, &txn_id)
            .unwrap();
        let events = match txn_receipt.transaction_result {
            TransactionResult::Valid { events, .. } => events,
            _ => panic!("transaction is invalid"),
        };
        let first_event = events.first().unwrap();
        assert_eq!(first_event.event_type, "First event".to_string());
        assert_eq!(
            first_event.attributes,
            vec![
                ("key1".to_string(), "value1".to_string()),
                ("key2".to_string(), "value2".to_string())
            ]
        );
        assert_eq!(first_event.data, b"abc".to_vec());

        let second_event = events.last().unwrap();
        assert_eq!(second_event.event_type, "Second event".to_string());
        assert_eq!(
            second_event.attributes,
            vec![
                ("key1".to_string(), "value1".to_string()),
                ("key2".to_string(), "value2".to_string())
            ]
        );
        assert_eq!(second_event.data, b"def".to_vec());

        assert!(Box::new(static_adapter).stop().is_ok());
    }

    /// Apply the static adapter with several commands to add Transaction Receipt data.
    #[test]
    fn apply_static_adapter_add_receipt_data() {
        let registry = MockRegistry::default();

        let state = HashMapState::new();
        let state_id = HashMapState::state_id(&HashMap::new());

        let mut context_manager: ContextManager = ContextManager::new(Box::new(state));

        let handler = CommandTransactionHandler::new();

        let mut static_adapter =
            StaticExecutionAdapter::new_adapter(vec![Box::new(handler)], context_manager.clone())
                .expect("Could not create adapter");

        assert!(static_adapter.start(Box::new(registry.clone())).is_ok());

        // Create and execute an Add Receipt Data transaction.
        let txn_pair = CommandTransactionBuilder::new()
            .with_commands(vec![
                Command::AddReceiptData(AddReceiptData::new(b"abc".to_vec())),
                Command::AddReceiptData(AddReceiptData::new(b"def".to_vec())),
            ])
            .into_transaction_builder()
            .expect("Failed to get transaction builder")
            .build_pair(&*new_signer())
            .expect("Failed to build transaction pair");

        let txn_id = txn_pair.transaction().header_signature().to_owned();
        let context_id = context_manager.create_context(&[], &state_id);

        let (send, recv) = std::sync::mpsc::channel();
        assert!(static_adapter
            .execute(
                txn_pair,
                context_id.clone(),
                Box::new(move |res| {
                    send.send(res).expect("Unable to send result");
                }),
            )
            .is_ok());
        let result = recv.recv().unwrap();

        assert_eq!(
            ExecutionTaskCompletionNotification::Valid(context_id.clone(), txn_id.clone()),
            result.unwrap()
        );

        let txn_receipt = context_manager
            .get_transaction_receipt(&context_id, &txn_id)
            .unwrap();
        let receipt_data = match txn_receipt.transaction_result {
            TransactionResult::Valid { data, .. } => data,
            _ => panic!("transaction is invalid"),
        };
        assert_eq!(receipt_data.first().unwrap(), &b"abc".to_vec());
        assert_eq!(receipt_data.last().unwrap(), &b"def".to_vec());

        assert!(Box::new(static_adapter).stop().is_ok());
    }

    fn new_signer() -> Box<dyn Signer> {
        let context = Secp256k1Context::new();
        let key = context.new_random_private_key();
        context.new_signer(key)
    }

    #[derive(Clone, Default)]
    struct MockRegistry {
        registered: Arc<AtomicBool>,
    }

    impl ExecutionRegistry for MockRegistry {
        fn register_transaction_family(&mut self, _family: TransactionFamily) {
            self.registered.store(true, Ordering::Relaxed);
        }

        fn unregister_transaction_family(&mut self, _family: &TransactionFamily) {
            self.registered.store(false, Ordering::Relaxed);
        }
    }
}