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
//! The *term* module defines typed[`Term`]s of the form `fn_add(x: u8, fn_square(y: u16)) → u16`.
//!
//! Each function like `fn_add` or `fn_square` has a shape. The variables `x` and `y` each have a
//! type. These types allow type checks during the runtime of the fuzzer.
//! These checks restrict how[`Term`]scan be mutated in the *fuzzer* module.

// Code in this directory is derived from https://github.com/joshrule/term-rewriting-rs/
// and is licensed under:
//
// The MIT License (MIT)
// Copyright (c) 2018--2021
// Maximilian Ammann <max@maxammann.org>, Joshua S. Rule <joshua.s.rule@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

use std::fmt;
use std::hash::Hash;

use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};

pub use self::term::*;

pub mod atoms;
pub mod dynamic_function;
pub mod error;
pub mod macros;
pub mod signature;
pub mod term;

impl<T> Matcher for Option<T>
where
    T: Matcher,
{
    fn matches(&self, matcher: &Self) -> bool {
        match (self, matcher) {
            (Some(inner), Some(inner_matcher)) => inner.matches(inner_matcher),
            (Some(_), None) => true, // None matches everything as query -> True
            (None, None) => true,    // None == None => True
            (None, Some(_)) => false, // None != Some => False
        }
    }

    fn specificity(&self) -> u32 {
        if let Some(matcher) = self {
            1 + matcher.specificity()
        } else {
            0
        }
    }
}

/// Determines whether two instances match. We can also ask it how specific it is.
pub trait Matcher:
    fmt::Debug + Clone + Hash + serde::Serialize + DeserializeOwned + PartialEq
{
    fn matches(&self, matcher: &Self) -> bool;

    fn specificity(&self) -> u32;
}

#[derive(Debug, Clone, Hash, PartialEq, Serialize, Deserialize)]
pub struct AnyMatcher;

impl Matcher for AnyMatcher {
    fn matches(&self, _matcher: &Self) -> bool {
        true
    }

    fn specificity(&self) -> u32 {
        0
    }
}

#[cfg(test)]
#[allow(clippy::ptr_arg)]
pub mod test_signature {
    use std::any::{Any, TypeId};
    use std::fmt;
    use std::fmt::{Debug, Display};
    use std::io::Read;

    use serde::{Deserialize, Serialize};

    use crate::agent::{AgentDescriptor, AgentName, TLSVersion};
    use crate::algebra::dynamic_function::TypeShape;
    use crate::algebra::error::FnError;
    use crate::algebra::{AnyMatcher, Term};
    use crate::claims::{Claim, GlobalClaimList, SecurityViolationPolicy};
    use crate::codec::{Codec, Reader};
    use crate::error::Error;
    use crate::protocol::{
        EvaluatedTerm, OpaqueProtocolMessage, OpaqueProtocolMessageFlight, ProtocolBehavior,
        ProtocolMessage, ProtocolMessageDeframer, ProtocolMessageFlight, ProtocolTypes,
    };
    use crate::put::{Put, PutOptions};
    use crate::put_registry::{Factory, PutKind};
    use crate::trace::{Action, InputAction, Knowledge, Source, Step, Trace};
    use crate::variable_data::VariableData;
    use crate::{define_signature, dummy_extract_knowledge, term, VERSION_STR};

    #[derive(Debug)]
    pub struct HmacKey;
    #[derive(Debug)]
    pub struct HandshakeMessage;
    #[derive(Debug)]
    pub struct Encrypted;
    #[derive(Debug)]
    pub struct ProtocolVersion;
    #[derive(Debug)]
    pub struct Random;
    #[derive(Debug)]
    pub struct ClientExtension;
    #[derive(Debug)]
    pub struct ClientExtensions;
    #[derive(Debug)]
    pub struct Group;
    #[derive(Debug)]
    pub struct SessionID;
    #[derive(Debug)]
    pub struct CipherSuites;
    #[derive(Debug)]
    pub struct CipherSuite;
    #[derive(Debug)]
    pub struct Compression;
    #[derive(Debug)]
    pub struct Compressions;

    dummy_extract_knowledge!(TestProtocolTypes, HmacKey);
    dummy_extract_knowledge!(TestProtocolTypes, HandshakeMessage);
    dummy_extract_knowledge!(TestProtocolTypes, Encrypted);
    dummy_extract_knowledge!(TestProtocolTypes, ProtocolVersion);
    dummy_extract_knowledge!(TestProtocolTypes, Random);
    dummy_extract_knowledge!(TestProtocolTypes, ClientExtension);
    dummy_extract_knowledge!(TestProtocolTypes, ClientExtensions);
    dummy_extract_knowledge!(TestProtocolTypes, Group);
    dummy_extract_knowledge!(TestProtocolTypes, SessionID);
    dummy_extract_knowledge!(TestProtocolTypes, CipherSuites);
    dummy_extract_knowledge!(TestProtocolTypes, CipherSuite);
    dummy_extract_knowledge!(TestProtocolTypes, Compression);
    dummy_extract_knowledge!(TestProtocolTypes, Compressions);
    dummy_extract_knowledge!(TestProtocolTypes, u8);
    dummy_extract_knowledge!(TestProtocolTypes, u16);
    dummy_extract_knowledge!(TestProtocolTypes, u32);
    dummy_extract_knowledge!(TestProtocolTypes, u64);

    impl<T: std::fmt::Debug + Clone + 'static> EvaluatedTerm<TestProtocolTypes> for Vec<T> {
        fn extract_knowledge<'a>(
            &'a self,
            knowledges: &mut Vec<Knowledge<'a, TestProtocolTypes>>,
            matcher: Option<<TestProtocolTypes as ProtocolTypes>::Matcher>,
            source: &'a Source,
        ) -> Result<(), Error> {
            knowledges.push(Knowledge {
                source,
                matcher,
                data: self,
            });

            Ok(())
        }
    }

    pub fn fn_hmac256_new_key() -> Result<HmacKey, FnError> {
        Ok(HmacKey)
    }

    pub fn fn_hmac256(_key: &HmacKey, _msg: &Vec<u8>) -> Result<Vec<u8>, FnError> {
        Ok(Vec::new())
    }

    pub fn fn_client_hello(
        _version: &ProtocolVersion,
        _random: &Random,
        _id: &SessionID,
        _suites: &CipherSuites,
        _compressions: &Compressions,
        _extensions: &ClientExtensions,
    ) -> Result<HandshakeMessage, FnError> {
        Ok(HandshakeMessage)
    }

    pub fn fn_finished() -> Result<HandshakeMessage, FnError> {
        Ok(HandshakeMessage)
    }

    pub fn fn_protocol_version12() -> Result<ProtocolVersion, FnError> {
        Ok(ProtocolVersion)
    }
    pub fn fn_new_session_id() -> Result<SessionID, FnError> {
        Ok(SessionID)
    }

    pub fn fn_new_random() -> Result<Random, FnError> {
        Ok(Random)
    }

    pub fn fn_client_extensions_append(
        _extensions: &ClientExtensions,
        _extension: &ClientExtension,
    ) -> Result<ClientExtensions, FnError> {
        Ok(ClientExtensions)
    }

    pub fn fn_client_extensions_new() -> Result<ClientExtensions, FnError> {
        Ok(ClientExtensions)
    }
    pub fn fn_support_group_extension(_group: &Group) -> Result<ClientExtension, FnError> {
        Ok(ClientExtension)
    }

    pub fn fn_signature_algorithm_extension() -> Result<ClientExtension, FnError> {
        Ok(ClientExtension)
    }
    pub fn fn_ec_point_formats_extension() -> Result<ClientExtension, FnError> {
        Ok(ClientExtension)
    }
    pub fn fn_signed_certificate_timestamp_extension() -> Result<ClientExtension, FnError> {
        Ok(ClientExtension)
    }
    pub fn fn_renegotiation_info_extension(_info: &Vec<u8>) -> Result<ClientExtension, FnError> {
        Ok(ClientExtension)
    }
    pub fn fn_signature_algorithm_cert_extension() -> Result<ClientExtension, FnError> {
        Ok(ClientExtension)
    }

    pub fn fn_empty_bytes_vec() -> Result<Vec<u8>, FnError> {
        Ok(Vec::new())
    }

    pub fn fn_named_group_secp384r1() -> Result<Group, FnError> {
        Ok(Group)
    }

    pub fn fn_client_key_exchange() -> Result<HandshakeMessage, FnError> {
        Ok(HandshakeMessage)
    }

    pub fn fn_new_cipher_suites() -> Result<CipherSuites, FnError> {
        Ok(CipherSuites)
    }

    pub fn fn_append_cipher_suite(
        _suites: &CipherSuites,
        _suite: &CipherSuite,
    ) -> Result<CipherSuites, FnError> {
        Ok(CipherSuites)
    }
    pub fn fn_cipher_suite12() -> Result<CipherSuite, FnError> {
        Ok(CipherSuite)
    }

    pub fn fn_compressions() -> Result<Compressions, FnError> {
        Ok(Compressions)
    }

    pub fn fn_encrypt12(_finished: &HandshakeMessage, _seq: &u32) -> Result<Encrypted, FnError> {
        Ok(Encrypted)
    }

    pub fn fn_seq_0() -> Result<u32, FnError> {
        Ok(0)
    }

    pub fn fn_seq_1() -> Result<u32, FnError> {
        Ok(1)
    }

    pub fn example_op_c(a: &u8) -> Result<u16, FnError> {
        Ok((a + 1) as u16)
    }

    fn create_client_hello() -> TestTerm {
        term! {
              fn_client_hello(
                fn_protocol_version12,
                fn_new_random,
                fn_new_session_id,
                (fn_append_cipher_suite(
                    (fn_new_cipher_suites()),
                    fn_cipher_suite12
                )),
                fn_compressions,
                (fn_client_extensions_append(
                    (fn_client_extensions_append(
                        (fn_client_extensions_append(
                            (fn_client_extensions_append(
                                (fn_client_extensions_append(
                                    (fn_client_extensions_append(
                                        fn_client_extensions_new,
                                        (fn_support_group_extension(fn_named_group_secp384r1))
                                    )),
                                    fn_signature_algorithm_extension
                                )),
                                fn_ec_point_formats_extension
                            )),
                            fn_signed_certificate_timestamp_extension
                        )),
                         // Enable Renegotiation
                        (fn_renegotiation_info_extension(fn_empty_bytes_vec))
                    )),
                    // Add signature cert extension
                    fn_signature_algorithm_cert_extension
                ))
            )
        }
    }

    pub fn setup_simple_trace() -> TestTrace {
        let server = AgentName::first();
        let client_hello = create_client_hello();

        Trace {
            prior_traces: vec![],
            descriptors: vec![AgentDescriptor::new_server(server, TLSVersion::V1_2)],
            steps: vec![
                Step {
                    agent: server,
                    action: Action::Input(InputAction {
                        precomputations: vec![],
                        recipe: client_hello,
                    }),
                },
                Step {
                    agent: server,
                    action: Action::Input(InputAction {
                        precomputations: vec![],
                        recipe: term! {fn_client_key_exchange},
                    }),
                },
                Step {
                    agent: server,
                    action: Action::Input(InputAction {
                        precomputations: vec![],
                        recipe: term! {fn_encrypt12(fn_finished,fn_seq_0)},
                    }),
                },
            ],
        }
    }

    define_signature!(
        TEST_SIGNATURE<TestProtocolTypes>,
        fn_hmac256_new_key
        fn_hmac256
        fn_client_hello
        fn_finished
        fn_protocol_version12
        fn_new_session_id
        fn_new_random
        fn_client_extensions_append
        fn_client_extensions_new
        fn_support_group_extension
        fn_signature_algorithm_extension
        fn_ec_point_formats_extension
        fn_signed_certificate_timestamp_extension
        fn_renegotiation_info_extension
        fn_signature_algorithm_cert_extension
        fn_empty_bytes_vec
        fn_named_group_secp384r1
        fn_client_key_exchange
        fn_new_cipher_suites
        fn_append_cipher_suite
        fn_cipher_suite12
        fn_compressions
        fn_encrypt12
        fn_seq_0
        fn_seq_1
    );

    pub type TestTrace = Trace<TestProtocolTypes>;
    pub type TestTerm = Term<TestProtocolTypes>;

    pub struct TestClaim;

    dummy_extract_knowledge!(TestProtocolTypes, TestClaim);

    impl VariableData<TestProtocolTypes> for TestClaim {
        fn boxed(&self) -> Box<dyn VariableData<TestProtocolTypes>> {
            panic!("Not implemented for test stub");
        }

        fn boxed_any(&self) -> Box<dyn Any> {
            panic!("Not implemented for test stub");
        }

        fn type_id(&self) -> TypeId {
            panic!("Not implemented for test stub");
        }

        fn type_name(&self) -> &'static str {
            panic!("Not implemented for test stub");
        }

        fn boxed_term(&self) -> Box<dyn EvaluatedTerm<TestProtocolTypes>> {
            panic!("Not implemented for test stub");
        }
    }

    impl fmt::Debug for TestClaim {
        fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> std::fmt::Result {
            panic!("Not implemented for test stub");
        }
    }

    impl Claim<TestProtocolTypes> for TestClaim {
        fn agent_name(&self) -> AgentName {
            panic!("Not implemented for test stub");
        }

        fn id(&self) -> TypeShape<TestProtocolTypes> {
            panic!("Not implemented for test stub");
        }

        fn inner(&self) -> Box<dyn EvaluatedTerm<TestProtocolTypes>> {
            panic!("Not implemented for test stub");
        }
    }

    pub struct TestOpaqueMessage;

    impl Clone for TestOpaqueMessage {
        fn clone(&self) -> Self {
            panic!("Not implemented for test stub");
        }
    }

    impl fmt::Debug for TestOpaqueMessage {
        fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> std::fmt::Result {
            panic!("Not implemented for test stub");
        }
    }

    impl Codec for TestOpaqueMessage {
        fn encode(&self, _bytes: &mut Vec<u8>) {
            panic!("Not implemented for test stub");
        }

        fn read(_: &mut Reader) -> Option<Self> {
            panic!("Not implemented for test stub");
        }
    }

    impl OpaqueProtocolMessage<TestProtocolTypes> for TestOpaqueMessage {
        fn debug(&self, _info: &str) {
            panic!("Not implemented for test stub");
        }
    }

    dummy_extract_knowledge!(TestProtocolTypes, TestOpaqueMessage);

    pub struct TestMessage;

    impl Clone for TestMessage {
        fn clone(&self) -> Self {
            panic!("Not implemented for test stub");
        }
    }

    impl fmt::Debug for TestMessage {
        fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> std::fmt::Result {
            panic!("Not implemented for test stub");
        }
    }

    impl ProtocolMessage<TestProtocolTypes, TestOpaqueMessage> for TestMessage {
        fn create_opaque(&self) -> TestOpaqueMessage {
            panic!("Not implemented for test stub");
        }

        fn debug(&self, _info: &str) {
            panic!("Not implemented for test stub");
        }
    }

    dummy_extract_knowledge!(TestProtocolTypes, TestMessage);

    pub struct TestMessageDeframer;

    impl ProtocolMessageDeframer<TestProtocolTypes> for TestMessageDeframer {
        type OpaqueProtocolMessage = TestOpaqueMessage;

        fn pop_frame(&mut self) -> Option<TestOpaqueMessage> {
            panic!("Not implemented for test stub");
        }

        fn read(&mut self, _rd: &mut dyn Read) -> std::io::Result<usize> {
            panic!("Not implemented for test stub");
        }
    }

    pub struct TestSecurityViolationPolicy;
    impl SecurityViolationPolicy<TestProtocolTypes, TestClaim> for TestSecurityViolationPolicy {
        fn check_violation(_claims: &[TestClaim]) -> Option<&'static str> {
            panic!("Not implemented for test stub");
        }
    }

    #[derive(Debug, Clone)]
    pub struct TestMessageFlight;

    impl
        ProtocolMessageFlight<
            TestProtocolTypes,
            TestMessage,
            TestOpaqueMessage,
            TestOpaqueMessageFlight,
        > for TestMessageFlight
    {
        fn new() -> Self {
            Self {}
        }

        fn push(&mut self, _msg: TestMessage) {
            panic!("Not implemented for test stub");
        }

        fn debug(&self, _info: &str) {
            panic!("Not implemented for test stub");
        }
    }

    impl TryFrom<TestOpaqueMessageFlight> for TestMessageFlight {
        type Error = ();

        fn try_from(_value: TestOpaqueMessageFlight) -> Result<Self, Self::Error> {
            Ok(Self)
        }
    }

    dummy_extract_knowledge!(TestProtocolTypes, TestMessageFlight);

    impl From<TestMessage> for TestMessageFlight {
        fn from(_value: TestMessage) -> Self {
            Self {}
        }
    }

    #[derive(Debug, Clone)]
    pub struct TestOpaqueMessageFlight;

    impl OpaqueProtocolMessageFlight<TestProtocolTypes, TestOpaqueMessage> for TestOpaqueMessageFlight {
        fn new() -> Self {
            Self {}
        }

        fn push(&mut self, _msg: TestOpaqueMessage) {
            panic!("Not implemented for test stub");
        }

        fn debug(&self, _info: &str) {
            panic!("Not implemented for test stub");
        }
    }

    dummy_extract_knowledge!(TestProtocolTypes, TestOpaqueMessageFlight);

    impl From<TestOpaqueMessage> for TestOpaqueMessageFlight {
        fn from(_value: TestOpaqueMessage) -> Self {
            Self {}
        }
    }

    impl Codec for TestOpaqueMessageFlight {
        fn encode(&self, _bytes: &mut Vec<u8>) {
            panic!("Not implemented for test stub");
        }

        fn read(_: &mut Reader) -> Option<Self> {
            panic!("Not implemented for test stub");
        }
    }

    impl From<TestMessageFlight> for TestOpaqueMessageFlight {
        fn from(_value: TestMessageFlight) -> Self {
            Self {}
        }
    }

    #[derive(Clone, Debug, Hash, Serialize, Deserialize)]
    pub struct TestProtocolTypes;

    impl ProtocolTypes for TestProtocolTypes {
        type Matcher = AnyMatcher;

        fn signature() -> &'static Signature<Self> {
            panic!("Not implemented for test stub");
        }
    }

    impl Display for TestProtocolTypes {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "")
        }
    }

    #[derive(Debug, PartialEq)]
    pub struct TestProtocolBehavior;

    impl ProtocolBehavior for TestProtocolBehavior {
        type Claim = TestClaim;
        type OpaqueProtocolMessage = TestOpaqueMessage;
        type OpaqueProtocolMessageFlight = TestOpaqueMessageFlight;
        type ProtocolMessage = TestMessage;
        type ProtocolMessageFlight = TestMessageFlight;
        type ProtocolTypes = TestProtocolTypes;
        type SecurityViolationPolicy = TestSecurityViolationPolicy;

        fn create_corpus() -> Vec<(Trace<Self::ProtocolTypes>, &'static str)> {
            panic!("Not implemented for test stub");
        }
    }

    pub struct TestFactory;

    impl Factory<TestProtocolBehavior> for TestFactory {
        fn create(
            &self,
            _agent_descriptor: &AgentDescriptor,
            _claims: &GlobalClaimList<
                TestProtocolTypes,
                <TestProtocolBehavior as ProtocolBehavior>::Claim,
            >,
            _options: &PutOptions,
        ) -> Result<Box<dyn Put<TestProtocolBehavior>>, Error> {
            panic!("Not implemented for test stub");
        }

        fn kind(&self) -> PutKind {
            PutKind::Rust
        }

        fn name(&self) -> String {
            String::from("TESTSTUB_RUST_PUT")
        }

        fn versions(&self) -> Vec<(String, String)> {
            vec![(
                "harness".to_string(),
                format!("{} ({})", self.name(), VERSION_STR),
            )]
        }

        fn clone_factory(&self) -> Box<dyn Factory<TestProtocolBehavior>> {
            Box::new(TestFactory {})
        }
    }
}

#[cfg(test)]
mod tests {
    use super::test_signature::*;
    use crate::agent::AgentName;
    use crate::algebra::atoms::Variable;
    use crate::algebra::dynamic_function::TypeShape;
    use crate::algebra::signature::Signature;
    use crate::algebra::{AnyMatcher, Term};
    use crate::put_registry::{Factory, PutRegistry};
    use crate::term;
    use crate::trace::{Source, Spawner, TraceContext};

    #[allow(dead_code)]
    fn test_compilation() {
        // reminds me of Lisp, lol
        let client = AgentName::first();
        let _test_nested_with_variable: TestTerm = term! {
           fn_client_hello(
                (fn_client_hello(
                    fn_protocol_version12,
                    fn_new_random,
                    (fn_client_hello(fn_protocol_version12,
                        fn_new_random,
                        fn_new_random,
                        ((client,0)/ProtocolVersion)
                    ))
                )),
                fn_new_random
            )
        };

        let _set_simple_function2: TestTerm = term! {
           fn_client_hello((fn_protocol_version12()), fn_new_random, fn_new_random)
        };

        let _test_simple_function2: TestTerm = term! {
           fn_new_random(((client,0)))
        };
        let _test_simple_function1: TestTerm = term! {
           fn_protocol_version12
        };
        let _test_simple_function: TestTerm = term! {
           fn_new_random(((client,0)/ProtocolVersion))
        };
        let _test_variable: TestTerm = term! {
            (client,0)/ProtocolVersion
        };
        let _set_nested_function: TestTerm = term! {
           fn_client_extensions_append(
                (fn_client_extensions_append(
                    fn_client_extensions_new,
                    (fn_support_group_extension(fn_named_group_secp384r1))
                )),
                (fn_support_group_extension(fn_named_group_secp384r1))
            )
        };
    }

    #[test_log::test]
    fn example() {
        let hmac256_new_key = Signature::new_function(&fn_hmac256_new_key);
        let hmac256 = Signature::new_function(&fn_hmac256);
        let _client_hello = Signature::new_function(&fn_client_hello);

        let data = "hello".as_bytes().to_vec();

        //println!("TypeId of vec array {:?}", data.type_id());

        let variable: Variable<TestProtocolTypes> = Signature::new_var(
            TypeShape::of::<Vec<u8>>(),
            Some(Source::Agent(AgentName::first())),
            None,
            0,
        );

        let generated_term = Term::Application(
            hmac256,
            vec![
                Term::Application(hmac256_new_key, vec![]),
                Term::Variable(variable),
            ],
        );

        //println!("{}", generated_term);

        fn dummy_factory() -> Box<dyn Factory<TestProtocolBehavior>> {
            Box::new(TestFactory)
        }

        let registry =
            PutRegistry::<TestProtocolBehavior>::new([("teststub", dummy_factory())], "teststub");

        let spawner = Spawner::new(registry.clone());
        let mut context = TraceContext::new(spawner);
        context
            .knowledge_store
            .add_raw_knowledge(data, Source::Agent(AgentName::first()), None);

        println!("{:?}", context.knowledge_store);

        let _string = generated_term
            .evaluate(&context)
            .as_ref()
            .unwrap()
            .as_any()
            .downcast_ref::<Vec<u8>>();
        //println!("{:?}", string);
    }

    #[test_log::test]
    fn playground() {
        let _var_data = fn_new_session_id();

        //println!("vec {:?}", TypeId::of::<Vec<u8>>());
        //println!("vec {:?}", TypeId::of::<Vec<u16>>());

        ////println!("{:?}", var_data.type_id());

        let func = Signature::new_function(&example_op_c);
        let dynamic_fn = func.dynamic_fn();
        let _string = dynamic_fn(&vec![Box::new(1u8)])
            .unwrap()
            .as_any()
            .downcast_ref::<u16>()
            .unwrap();
        //println!("{:?}", string);
        let _string = Signature::new_function(&example_op_c).shape();
        //println!("{}", string);

        let constructed_term = Term::<TestProtocolTypes>::Application(
            Signature::new_function(&example_op_c),
            vec![
                Term::Application(
                    Signature::new_function(&example_op_c),
                    vec![
                        Term::Application(
                            Signature::new_function(&example_op_c),
                            vec![
                                Term::Application(Signature::new_function(&example_op_c), vec![]),
                                Term::Variable(
                                    Signature::new_var_with_type::<SessionID, AnyMatcher>(
                                        Some(Source::Agent(AgentName::first())),
                                        None,
                                        0,
                                    ),
                                ),
                            ],
                        ),
                        Term::Variable(Signature::new_var_with_type::<SessionID, AnyMatcher>(
                            Some(Source::Agent(AgentName::first())),
                            None,
                            0,
                        )),
                    ],
                ),
                Term::Application(
                    Signature::new_function(&example_op_c),
                    vec![
                        Term::Application(
                            Signature::new_function(&example_op_c),
                            vec![
                                Term::Variable(Signature::new_var_with_type::<SessionID, _>(
                                    Some(Source::Agent(AgentName::first())),
                                    None,
                                    0,
                                )),
                                Term::Application(Signature::new_function(&example_op_c), vec![]),
                            ],
                        ),
                        Term::Variable(Signature::new_var_with_type::<SessionID, _>(
                            Some(Source::Agent(AgentName::first())),
                            None,
                            0,
                        )),
                    ],
                ),
            ],
        );

        //println!("{}", constructed_term);
        let _graph = constructed_term.dot_subgraph(true, 0, "test");
        //println!("{}", graph);
    }
}