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
//! [`Agent`]s represent communication participants like Alice, Bob or Eve.
//!
//! Note that attackers are usually not represented by these [`Agent`]s but instead through a recipe
//! term (see [`crate::trace::InputAction`]).
//!
//! Each [`Agent`] has an *inbound* and an *outbound* channel (see [`crate::stream`])

use core::fmt;
use std::fmt::Debug;
use std::hash::Hash;

use serde::{Deserialize, Serialize};

use crate::algebra::ConcreteMessage;
use crate::error::Error;
use crate::protocol::{ProtocolBehavior, ProtocolTypes};
use crate::put::Put;
use crate::stream::Stream;

/// Copyable reference to an [`Agent`]. It identifies exactly one agent.
#[derive(Serialize, Deserialize, Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub struct AgentName(u8);

impl AgentName {
    #[must_use]
    pub const fn new() -> Self {
        const FIRST: AgentName = AgentName(0u8);
        FIRST
    }

    #[must_use]
    pub const fn next(&self) -> Self {
        Self(self.0 + 1)
    }

    #[must_use]
    pub const fn first() -> Self {
        Self::new()
    }
}

impl Default for AgentName {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Display for AgentName {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<AgentName> for u8 {
    fn from(value: AgentName) -> Self {
        value.0
    }
}

/// Contains the protocol specific configuration of an agent
pub trait ProtocolDescriptorConfig:
    Default + Debug + Clone + Serialize + Hash + for<'a> Deserialize<'a>
{
    /// Indicates wheter a agent is reusable, ie. it's configuration is compatible with the new
    /// agent to spawn
    fn is_reusable_with(&self, other: &Self) -> bool;
}

/// [`AgentDescriptor`]s act like a blueprint to spawn [`Agent`]s with a corresponding server or
/// client role and a specific TLs version. Essentially they are an [`Agent`] without a stream.
///
/// The difference between an [`AgentDescriptor`] and a [`crate::put::PutDescriptor`] is that
/// values of the [`AgentDescriptor`] are required for seed traces to succeed. They are the same for
/// every invocation of the seed. Values in the [`crate::put::PutDescriptor`] are supposed to
/// differ between invocations.
#[derive(Debug, Clone, Deserialize, Serialize, Eq, PartialEq, Hash)]
#[serde(bound = "C: ProtocolDescriptorConfig")]
pub struct AgentDescriptor<C: ProtocolDescriptorConfig> {
    pub name: AgentName,

    /// Contains the protocol specific configuration of the Agent
    pub protocol_config: C,
}

impl<C: ProtocolDescriptorConfig> AgentDescriptor<C> {
    pub fn from_config(name: AgentName, put_config: C) -> Self {
        Self {
            name,
            protocol_config: put_config,
        }
    }

    pub fn from_name(name: AgentName) -> Self {
        Self {
            name,
            protocol_config: C::default(),
        }
    }
}

impl<C: ProtocolDescriptorConfig> Default for AgentDescriptor<C> {
    fn default() -> Self {
        Self {
            name: AgentName::first(),
            protocol_config: C::default(),
        }
    }
}

/// An [`Agent`] holds a non-cloneable reference to a Stream.
pub struct Agent<PB: ProtocolBehavior> {
    descriptor:
        AgentDescriptor<<<PB as ProtocolBehavior>::ProtocolTypes as ProtocolTypes>::PUTConfig>,
    put: Box<dyn Put<PB>>,
}

impl<PB: ProtocolBehavior> fmt::Debug for Agent<PB> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Agent")
            .field("descriptor", &self.descriptor)
            .field("put", &self.put.describe_state())
            .finish()
    }
}

impl<PB: ProtocolBehavior> PartialEq for Agent<PB> {
    fn eq(&self, other: &Self) -> bool {
        self.descriptor.name.eq(&other.descriptor.name)
            && self.put.describe_state() == other.put.describe_state()
    }
}

impl<PB: ProtocolBehavior> Agent<PB> {
    #[must_use]
    pub fn new(
        descriptor: AgentDescriptor<<PB::ProtocolTypes as ProtocolTypes>::PUTConfig>,
        put: Box<dyn Put<PB>>,
    ) -> Self {
        Self { descriptor, put }
    }

    pub fn progress(&mut self) -> Result<(), Error> {
        self.put.progress()
    }

    pub fn reset(&mut self, new_name: AgentName) -> Result<(), Error> {
        self.descriptor.name = new_name;
        self.put.reset(new_name)
    }

    /// Shut down the agent by consuming it and returning a string that summarizes the execution.
    pub fn shutdown(&mut self) -> String {
        self.put.shutdown()
    }

    /// Checks whether the agent is in a good state.
    #[must_use]
    pub fn is_state_successful(&self) -> bool {
        self.put.is_state_successful()
    }

    /// Checks whether the agent is reusable with the descriptor.
    #[must_use]
    pub fn is_reusable_with(
        &self,
        other: &AgentDescriptor<<PB::ProtocolTypes as ProtocolTypes>::PUTConfig>,
    ) -> bool {
        self.descriptor
            .protocol_config
            .is_reusable_with(&other.protocol_config)
    }

    #[must_use]
    pub const fn name(&self) -> AgentName {
        self.descriptor.name
    }

    #[must_use]
    pub fn put(&self) -> &dyn Put<PB> {
        self.put.as_ref()
    }

    pub fn put_mut(&mut self) -> &mut dyn Put<PB> {
        self.put.as_mut()
    }
}

impl<PB: ProtocolBehavior> Stream<PB> for Agent<PB> {
    fn add_to_inbound(&mut self, message: &ConcreteMessage) {
        self.put.add_to_inbound(message);
    }

    fn take_message_from_outbound(
        &mut self,
    ) -> Result<Option<PB::OpaqueProtocolMessageFlight>, Error> {
        self.put.take_message_from_outbound()
    }
}