Skip to main content

spodes_rs/service/
acse.rs

1//! ACSE association establishment: the AARQ and AARE APDUs (IEC 62056-5-3, 7.2).
2//!
3//! These are BER-encoded (not A-XDR). The AARQ ([APPLICATION 0], tag 0x60) is
4//! sent by the client to open an application association; the AARE
5//! ([APPLICATION 1], tag 0x61) is the server's response.
6//!
7//! The `user_information` field carries the xDLMS InitiateRequest /
8//! InitiateResponse APDU; it is treated here as an opaque octet string.
9//!
10//! Validated against the LLS AARQ of IEC 62056-5-3 Annex D.4.
11
12use super::ServiceError;
13
14/// AARQ APDU tag ([APPLICATION 0], constructed).
15pub const AARQ_TAG: u8 = 0x60;
16/// AARE APDU tag ([APPLICATION 1], constructed).
17pub const AARE_TAG: u8 = 0x61;
18/// RLRQ APDU tag ([APPLICATION 2], constructed).
19pub const RLRQ_TAG: u8 = 0x62;
20/// RLRE APDU tag ([APPLICATION 3], constructed).
21pub const RLRE_TAG: u8 = 0x63;
22
23/// Release-request/response reason values (ACSE field `[0]`).
24pub mod release_reason {
25    /// Normal release (both RLRQ and RLRE).
26    pub const NORMAL: u8 = 0;
27    /// Urgent (RLRQ only; not used in DLMS/COSEM).
28    pub const URGENT: u8 = 1;
29    /// Not-finished (RLRE only).
30    pub const NOT_FINISHED: u8 = 1;
31    /// User-defined.
32    pub const USER_DEFINED: u8 = 30;
33}
34
35/// Association result (AARE field `[2]`).
36pub mod result {
37    /// The association was accepted.
38    pub const ACCEPTED: u8 = 0;
39    /// The association was rejected permanently (retrying will not help).
40    pub const REJECTED_PERMANENT: u8 = 1;
41    /// The association was rejected transiently (a retry may succeed).
42    pub const REJECTED_TRANSIENT: u8 = 2;
43}
44
45/// COSEM application-context-name identifiers (last arc of the OID
46/// `2.16.756.5.8.1.x`).
47pub mod application_context {
48    /// Logical name referencing, no ciphering.
49    pub const LN: u8 = 1;
50    /// Short name referencing, no ciphering.
51    pub const SN: u8 = 2;
52    /// Logical name referencing with ciphering.
53    pub const LN_CIPHERING: u8 = 3;
54    /// Short name referencing with ciphering.
55    pub const SN_CIPHERING: u8 = 4;
56}
57
58/// COSEM authentication-mechanism-name identifiers (last arc of the OID
59/// `2.16.756.5.8.2.x`).
60pub mod mechanism {
61    /// Mechanism 0: lowest-level security (no authentication).
62    pub const LOWEST: u8 = 0;
63    /// Mechanism 1: Low-Level Security (password authentication).
64    pub const LLS: u8 = 1;
65    /// Mechanism 3: High-Level Security using MD5.
66    pub const HLS_MD5: u8 = 3;
67    /// Mechanism 4: High-Level Security using SHA-1.
68    pub const HLS_SHA1: u8 = 4;
69    /// Mechanism 5: High-Level Security using GMAC.
70    pub const HLS_GMAC: u8 = 5;
71    /// Mechanism 6: High-Level Security using SHA-256.
72    pub const HLS_SHA256: u8 = 6;
73    /// Mechanism 7: High-Level Security using ECDSA.
74    pub const HLS_ECDSA: u8 = 7;
75    /// Mechanism 8: HLS CMAC — Kuznyechik CMAC (GOST, Р 1323565.1).
76    pub const HLS_GOST_CMAC: u8 = 8;
77    /// Mechanism 9: HLS GOST34112018-256 — Streebog-256 (GOST, Р 1323565.1).
78    pub const HLS_GOST_STREEBOG: u8 = 9;
79    /// Mechanism 10: HLS GOST34102018-256 — GOST 34.10 signature (Р 1323565.1).
80    pub const HLS_GOST_SIGNATURE: u8 = 10;
81}
82
83/// ACSE `result-source-diagnostic` values of the acse-service-user CHOICE
84/// (ISO 8650 / IEC 62056-5-3, Table 74), reported in a rejecting AARE.
85pub mod acse_diagnostic {
86    /// No reason given.
87    pub const NULL: u8 = 0;
88    /// The proposed application context is not supported.
89    pub const APPLICATION_CONTEXT_NAME_NOT_SUPPORTED: u8 = 2;
90    /// The calling-AP-title (client system title) was not recognized.
91    pub const CALLING_AP_TITLE_NOT_RECOGNIZED: u8 = 3;
92    /// The proposed authentication mechanism is not recognised.
93    pub const AUTHENTICATION_MECHANISM_NAME_NOT_RECOGNISED: u8 = 11;
94    /// Authentication failed (wrong secret / challenge).
95    pub const AUTHENTICATION_FAILURE: u8 = 13;
96    /// Authentication is required but the AARQ carried none.
97    pub const AUTHENTICATION_REQUIRED: u8 = 14;
98}
99
100/// ACSE `result-source-diagnostic` values of the acse-service-provider CHOICE.
101pub mod acse_provider_diagnostic {
102    /// No common ACSE version (AARQ.protocol-version not version1).
103    pub const NO_COMMON_ACSE_VERSION: u8 = 2;
104}
105
106/// BER BIT STRING value for ACSE protocol-version `{version1 (0)}`.
107pub const PROTOCOL_VERSION_1: [u8; 2] = [0x02, 0x84];
108
109const OID_PREFIX_APP_CONTEXT: [u8; 6] = [0x60, 0x85, 0x74, 0x05, 0x08, 0x01];
110const OID_PREFIX_MECHANISM: [u8; 6] = [0x60, 0x85, 0x74, 0x05, 0x08, 0x02];
111
112/// An AARQ (application association request) APDU.
113#[derive(Debug, Clone, PartialEq, Default)]
114pub struct AssociationRequest {
115    /// Protocol-version BIT STRING contents (`[unused-bits, bits…]`), when present.
116    pub protocol_version: Option<[u8; 2]>,
117    /// Application-context-name identifier (see [`application_context`]).
118    pub application_context: u8,
119    /// Calling-AP-title (client system title), present when ciphering is used.
120    pub calling_ap_title: Option<Vec<u8>>,
121    /// Sender-acse-requirements authentication bit (0x80 when set), when present.
122    pub sender_acse_requirements: Option<u8>,
123    /// Authentication-mechanism-name identifier, present for LLS/HLS.
124    pub mechanism_name: Option<u8>,
125    /// Calling-authentication-value (LLS password or HLS CtoS challenge).
126    pub calling_authentication_value: Option<Vec<u8>>,
127    /// User-information: the xDLMS InitiateRequest APDU (opaque).
128    pub user_information: Vec<u8>,
129}
130
131impl AssociationRequest {
132    /// Encodes the AARQ APDU.
133    pub fn encode(&self) -> Vec<u8> {
134        let mut content = Vec::new();
135        // `[0]` protocol-version (IMPLICIT BIT STRING).
136        if let Some(pv) = self.protocol_version {
137            content.extend_from_slice(&[0x80, 0x02, pv[0], pv[1]]);
138        }
139        // `[1]` application-context-name (OBJECT IDENTIFIER).
140        ber_tlv(0xA1, &object_identifier(OID_PREFIX_APP_CONTEXT, self.application_context), &mut content);
141        // `[6]` calling-AP-title (OCTET STRING) — only with ciphering.
142        if let Some(title) = &self.calling_ap_title {
143            ber_tlv(0xA6, &octet_string(title), &mut content);
144        }
145        // Authentication functional unit (`[10]`, `[11]`, `[12]`) — for LLS/HLS.
146        if let Some(mech) = self.mechanism_name {
147            // `[10]` sender-acse-requirements: BIT STRING { authentication(0) }.
148            let acse_req = self.sender_acse_requirements.unwrap_or(0x80);
149            content.extend_from_slice(&[0x8A, 0x02, 0x07, acse_req]);
150            // `[11]` mechanism-name (OBJECT IDENTIFIER, IMPLICIT → raw 7 octets).
151            content.push(0x8B);
152            let oid = raw_oid(OID_PREFIX_MECHANISM, mech);
153            push_length(oid.len(), &mut content);
154            content.extend_from_slice(&oid);
155            // `[12]` calling-authentication-value (EXPLICIT CHOICE charstring `[0]`).
156            if let Some(auth) = &self.calling_authentication_value {
157                let mut inner = vec![0x80];
158                push_length(auth.len(), &mut inner);
159                inner.extend_from_slice(auth);
160                ber_tlv(0xAC, &inner, &mut content);
161            }
162        } else if let Some(acse_req) = self.sender_acse_requirements {
163            content.extend_from_slice(&[0x8A, 0x02, 0x07, acse_req]);
164            if let Some(auth) = &self.calling_authentication_value {
165                let mut inner = vec![0x80];
166                push_length(auth.len(), &mut inner);
167                inner.extend_from_slice(auth);
168                ber_tlv(0xAC, &inner, &mut content);
169            }
170        } else if let Some(auth) = &self.calling_authentication_value {
171            let mut inner = vec![0x80];
172            push_length(auth.len(), &mut inner);
173            inner.extend_from_slice(auth);
174            ber_tlv(0xAC, &inner, &mut content);
175        }
176        // `[30]` user-information (OCTET STRING carrying the InitiateRequest).
177        ber_tlv(0xBE, &octet_string(&self.user_information), &mut content);
178
179        let mut apdu = vec![AARQ_TAG];
180        push_length(content.len(), &mut apdu);
181        apdu.extend_from_slice(&content);
182        apdu
183    }
184
185    /// Decodes an AARQ APDU.
186    pub fn decode(bytes: &[u8]) -> Result<AssociationRequest, ServiceError> {
187        let content = outer_content(bytes, AARQ_TAG)?;
188        let mut req = AssociationRequest::default();
189        for (tag, value) in TlvIter::new(content) {
190            match tag {
191                0x80 if value.len() >= 2 => req.protocol_version = Some([value[0], value[1]]),
192                0xA1 => req.application_context = parse_oid_last_arc(value)?,
193                0xA6 => req.calling_ap_title = Some(parse_octet_string(value)?),
194                0x8A if value.len() >= 2 => req.sender_acse_requirements = Some(value[1]),
195                0x8B => req.mechanism_name = Some(*value.last().ok_or(ServiceError::Truncated)?),
196                0xAC => req.calling_authentication_value = Some(parse_auth_value(value)?),
197                0xBE => req.user_information = parse_octet_string(value)?,
198                _ => {} // ignore other/optional fields
199            }
200        }
201        Ok(req)
202    }
203}
204
205/// An AARE (application association response) APDU.
206#[derive(Debug, Clone, PartialEq, Default)]
207pub struct AssociationResponse {
208    /// Protocol-version BIT STRING contents, when present.
209    pub protocol_version: Option<[u8; 2]>,
210    /// Application-context-name identifier.
211    pub application_context: u8,
212    /// Association result (see [`result`]).
213    pub result: u8,
214    /// Result source diagnostic value.
215    pub diagnostic: u8,
216    /// When true, diagnostic is acse-service-provider (`[2]`); otherwise user (`[1]`).
217    pub diagnostic_is_provider: bool,
218    /// Responding-AP-title (server system title), present with ciphering.
219    pub responding_ap_title: Option<Vec<u8>>,
220    /// Mechanism-name echoed for HLS (IMPLICIT OID last arc).
221    pub mechanism_name: Option<u8>,
222    /// Responding-authentication-value (HLS StoC challenge).
223    pub responding_authentication_value: Option<Vec<u8>>,
224    /// User-information: the xDLMS InitiateResponse APDU (opaque).
225    pub user_information: Vec<u8>,
226}
227
228impl AssociationResponse {
229    /// Encodes the AARE APDU.
230    pub fn encode(&self) -> Vec<u8> {
231        let mut content = Vec::new();
232        // `[0]` protocol-version.
233        if let Some(pv) = self.protocol_version {
234            content.extend_from_slice(&[0x80, 0x02, pv[0], pv[1]]);
235        }
236        // `[1]` application-context-name.
237        ber_tlv(0xA1, &object_identifier(OID_PREFIX_APP_CONTEXT, self.application_context), &mut content);
238        // `[2]` result (INTEGER).
239        ber_tlv(0xA2, &[0x02, 0x01, self.result], &mut content);
240        // `[3]` result-source-diagnostic (CHOICE user `[1]` / provider `[2]`).
241        let diag_choice = if self.diagnostic_is_provider { 0xA2 } else { 0xA1 };
242        ber_tlv(0xA3, &[diag_choice, 0x03, 0x02, 0x01, self.diagnostic], &mut content);
243        // `[4]` responding-AP-title (OCTET STRING) — with ciphering.
244        if let Some(title) = &self.responding_ap_title {
245            ber_tlv(0xA4, &octet_string(title), &mut content);
246        }
247        // HLS authentication functional unit: `[8]` / `[9]` / `[10]`.
248        if self.responding_authentication_value.is_some() {
249            content.extend_from_slice(&[0x88, 0x02, 0x07, 0x80]);
250            if let Some(mech) = self.mechanism_name {
251                content.push(0x89);
252                let oid = raw_oid(OID_PREFIX_MECHANISM, mech);
253                push_length(oid.len(), &mut content);
254                content.extend_from_slice(&oid);
255            }
256            if let Some(auth) = &self.responding_authentication_value {
257                let mut inner = vec![0x80];
258                push_length(auth.len(), &mut inner);
259                inner.extend_from_slice(auth);
260                ber_tlv(0xAA, &inner, &mut content);
261            }
262        }
263        // `[30]` user-information.
264        ber_tlv(0xBE, &octet_string(&self.user_information), &mut content);
265
266        let mut apdu = vec![AARE_TAG];
267        push_length(content.len(), &mut apdu);
268        apdu.extend_from_slice(&content);
269        apdu
270    }
271
272    /// Decodes an AARE APDU.
273    pub fn decode(bytes: &[u8]) -> Result<AssociationResponse, ServiceError> {
274        let content = outer_content(bytes, AARE_TAG)?;
275        let mut resp = AssociationResponse { result: result::REJECTED_PERMANENT, ..AssociationResponse::default() };
276        for (tag, value) in TlvIter::new(content) {
277            match tag {
278                0x80 if value.len() >= 2 => resp.protocol_version = Some([value[0], value[1]]),
279                0xA1 => resp.application_context = parse_oid_last_arc(value)?,
280                0xA2 => resp.result = *value.last().ok_or(ServiceError::Truncated)?,
281                0xA3 => {
282                    resp.diagnostic_is_provider = value.first() == Some(&0xA2);
283                    resp.diagnostic = *value.last().ok_or(ServiceError::Truncated)?;
284                }
285                0xA4 => resp.responding_ap_title = Some(parse_octet_string(value)?),
286                0x89 => resp.mechanism_name = Some(*value.last().ok_or(ServiceError::Truncated)?),
287                0xAA => resp.responding_authentication_value = Some(parse_auth_value(value)?),
288                0xBE => resp.user_information = parse_octet_string(value)?,
289                _ => {}
290            }
291        }
292        Ok(resp)
293    }
294}
295
296/// An RLRQ (association release request) or RLRE (release response) APDU. Both
297/// share the same shape: an optional reason and optional user-information (which
298/// carries a ciphered InitiateRequest/Response when the AA used ciphering).
299#[derive(Debug, Clone, PartialEq)]
300pub struct ReleaseRequest {
301    /// Release reason (see [`release_reason`]).
302    pub reason: Option<u8>,
303    /// User-information: the xDLMS InitiateRequest APDU (opaque), if any.
304    pub user_information: Option<Vec<u8>>,
305}
306
307/// An RLRE (association release response) APDU.
308pub type ReleaseResponse = ReleaseRequest;
309
310impl ReleaseRequest {
311    /// Encodes the RLRQ APDU (tag [`RLRQ_TAG`]).
312    pub fn encode_rlrq(&self) -> Vec<u8> {
313        self.encode(RLRQ_TAG)
314    }
315
316    /// Encodes the RLRE APDU (tag [`RLRE_TAG`]).
317    pub fn encode_rlre(&self) -> Vec<u8> {
318        self.encode(RLRE_TAG)
319    }
320
321    fn encode(&self, apdu_tag: u8) -> Vec<u8> {
322        let mut content = Vec::new();
323        // `[0]` reason (IMPLICIT ENUMERATED → primitive context tag 0x80).
324        if let Some(reason) = self.reason {
325            content.extend_from_slice(&[0x80, 0x01, reason]);
326        }
327        // `[30]` user-information (OCTET STRING carrying the InitiateRequest/Response).
328        if let Some(info) = &self.user_information {
329            ber_tlv(0xBE, &octet_string(info), &mut content);
330        }
331        let mut apdu = vec![apdu_tag];
332        push_length(content.len(), &mut apdu);
333        apdu.extend_from_slice(&content);
334        apdu
335    }
336
337    /// Decodes an RLRQ APDU.
338    pub fn decode_rlrq(bytes: &[u8]) -> Result<ReleaseRequest, ServiceError> {
339        Self::decode(bytes, RLRQ_TAG)
340    }
341
342    /// Decodes an RLRE APDU.
343    pub fn decode_rlre(bytes: &[u8]) -> Result<ReleaseResponse, ServiceError> {
344        Self::decode(bytes, RLRE_TAG)
345    }
346
347    fn decode(bytes: &[u8], apdu_tag: u8) -> Result<ReleaseRequest, ServiceError> {
348        let content = outer_content(bytes, apdu_tag)?;
349        let mut req = ReleaseRequest { reason: None, user_information: None };
350        for (tag, value) in TlvIter::new(content) {
351            match tag {
352                0x80 => req.reason = Some(*value.last().ok_or(ServiceError::Truncated)?),
353                0xBE => req.user_information = Some(parse_octet_string(value)?),
354                _ => {}
355            }
356        }
357        Ok(req)
358    }
359}
360
361// --- BER helpers -----------------------------------------------------------
362
363/// Builds an OBJECT IDENTIFIER TLV value: `06 07 <prefix(6) last_arc>`.
364fn object_identifier(prefix: [u8; 6], last_arc: u8) -> Vec<u8> {
365    let mut v = vec![0x06, 0x07];
366    v.extend_from_slice(&prefix);
367    v.push(last_arc);
368    v
369}
370
371/// The raw 7-octet OID value (no tag), for IMPLICIT contexts.
372fn raw_oid(prefix: [u8; 6], last_arc: u8) -> Vec<u8> {
373    let mut v = prefix.to_vec();
374    v.push(last_arc);
375    v
376}
377
378/// Builds an OCTET STRING TLV value: `04 <len> <bytes>`.
379fn octet_string(bytes: &[u8]) -> Vec<u8> {
380    let mut v = vec![0x04];
381    push_length(bytes.len(), &mut v);
382    v.extend_from_slice(bytes);
383    v
384}
385
386fn ber_tlv(tag: u8, value: &[u8], out: &mut Vec<u8>) {
387    out.push(tag);
388    push_length(value.len(), out);
389    out.extend_from_slice(value);
390}
391
392/// Writes a BER length octet (short or long form).
393#[allow(clippy::cast_possible_truncation)] // length < 128 and n in 1..=8 always fit u8
394fn push_length(length: usize, out: &mut Vec<u8>) {
395    if length < 128 {
396        out.push(length as u8);
397    } else {
398        let bytes = (length as u64).to_be_bytes();
399        let first = bytes.iter().position(|&b| b != 0).unwrap_or(7);
400        let n = 8 - first;
401        out.push(0x80 | n as u8);
402        out.extend_from_slice(&bytes[first..]);
403    }
404}
405
406/// Reads a BER length, returning the length and the number of octets it took.
407fn read_length(bytes: &[u8]) -> Result<(usize, usize), ServiceError> {
408    let first = *bytes.first().ok_or(ServiceError::Truncated)?;
409    if first < 128 {
410        Ok((first as usize, 1))
411    } else {
412        let n = (first & 0x7F) as usize;
413        let slice = bytes.get(1..1 + n).ok_or(ServiceError::Truncated)?;
414        let mut len = 0usize;
415        for &b in slice {
416            len = (len << 8) | b as usize;
417        }
418        Ok((len, 1 + n))
419    }
420}
421
422/// Verifies the outer APDU tag and returns its content octets.
423fn outer_content(bytes: &[u8], expected_tag: u8) -> Result<&[u8], ServiceError> {
424    let tag = *bytes.first().ok_or(ServiceError::Truncated)?;
425    if tag != expected_tag {
426        return Err(ServiceError::UnexpectedTag(tag));
427    }
428    let (len, header) = read_length(&bytes[1..])?;
429    let start = 1 + header;
430    bytes.get(start..start + len).ok_or(ServiceError::Truncated)
431}
432
433/// Extracts the last arc of an application-context or mechanism OID from an
434/// `A1`/context value `06 07 <prefix> <arc>`.
435fn parse_oid_last_arc(value: &[u8]) -> Result<u8, ServiceError> {
436    // value = 06 07 <7 octets>. The arc is the final octet.
437    value.last().copied().ok_or(ServiceError::Truncated)
438}
439
440/// Extracts the bytes of an inner OCTET STRING (`04 <len> <bytes>`).
441fn parse_octet_string(value: &[u8]) -> Result<Vec<u8>, ServiceError> {
442    if value.first() != Some(&0x04) {
443        return Err(ServiceError::InvalidData);
444    }
445    let (len, header) = read_length(&value[1..])?;
446    let start = 1 + header;
447    value.get(start..start + len).map(|s| s.to_vec()).ok_or(ServiceError::Truncated)
448}
449
450/// Extracts the authentication value from a ``[12]``/``[10]`` CHOICE
451/// (`80 <len> <bytes>`).
452fn parse_auth_value(value: &[u8]) -> Result<Vec<u8>, ServiceError> {
453    if value.first() != Some(&0x80) {
454        return Err(ServiceError::InvalidData);
455    }
456    let (len, header) = read_length(&value[1..])?;
457    let start = 1 + header;
458    value.get(start..start + len).map(|s| s.to_vec()).ok_or(ServiceError::Truncated)
459}
460
461/// Iterates over the top-level BER TLVs of a content buffer, yielding
462/// `(tag, value)` pairs. Malformed trailing bytes stop the iteration.
463struct TlvIter<'a> {
464    rest: &'a [u8],
465}
466
467impl<'a> TlvIter<'a> {
468    fn new(rest: &'a [u8]) -> Self {
469        TlvIter { rest }
470    }
471}
472
473impl<'a> Iterator for TlvIter<'a> {
474    type Item = (u8, &'a [u8]);
475
476    fn next(&mut self) -> Option<Self::Item> {
477        if self.rest.is_empty() {
478            return None;
479        }
480        let tag = self.rest[0];
481        let (len, header) = read_length(&self.rest[1..]).ok()?;
482        let start = 1 + header;
483        let value = self.rest.get(start..start + len)?;
484        self.rest = &self.rest[start + len..];
485        Some((tag, value))
486    }
487}
488
489#[cfg(test)]
490mod tests {
491    use super::*;
492
493    #[test]
494    fn aarq_lls_matches_reference_bytes() {
495        // IEC 62056-5-3 Annex D.4, LN referencing, LLS.
496        let initiate_request = vec![0x01, 0x00, 0x00, 0x00, 0x06, 0x5F, 0x1F, 0x04, 0x00, 0x00, 0x7E, 0x1F, 0x04, 0xB0];
497        let aarq = AssociationRequest {
498            protocol_version: None,
499            application_context: application_context::LN,
500            calling_ap_title: None,
501            sender_acse_requirements: Some(0x80),
502            mechanism_name: Some(mechanism::LLS),
503            calling_authentication_value: Some(b"12345678".to_vec()),
504            user_information: initiate_request,
505        };
506        let encoded = aarq.encode();
507        let expected = vec![
508            0x60, 0x36, // AARQ, length 54
509            0xA1, 0x09, 0x06, 0x07, 0x60, 0x85, 0x74, 0x05, 0x08, 0x01, 0x01, // app-context LN
510            0x8A, 0x02, 0x07, 0x80, // sender-acse-requirements
511            0x8B, 0x07, 0x60, 0x85, 0x74, 0x05, 0x08, 0x02, 0x01, // mechanism LLS
512            0xAC, 0x0A, 0x80, 0x08, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, // '12345678'
513            0xBE, 0x10, 0x04, 0x0E, // user-information
514            0x01, 0x00, 0x00, 0x00, 0x06, 0x5F, 0x1F, 0x04, 0x00, 0x00, 0x7E, 0x1F, 0x04, 0xB0,
515        ];
516        assert_eq!(encoded, expected);
517        assert_eq!(AssociationRequest::decode(&encoded).unwrap(), aarq);
518    }
519
520    #[test]
521    fn aarq_no_security_round_trips() {
522        let aarq = AssociationRequest {
523            application_context: application_context::LN,
524            calling_ap_title: None,
525            mechanism_name: None,
526            calling_authentication_value: None,
527            user_information: vec![0x01, 0x00, 0x00, 0x00, 0x06, 0x5F, 0x1F, 0x04, 0x00, 0x00, 0x7E, 0x1F, 0x04, 0xB0],
528            ..Default::default()
529        };
530        assert_eq!(AssociationRequest::decode(&aarq.encode()).unwrap(), aarq);
531    }
532
533    #[test]
534    fn aare_accepted_round_trips() {
535        let aare = AssociationResponse {
536            application_context: application_context::LN,
537            result: result::ACCEPTED,
538            diagnostic: 0,
539            responding_ap_title: None,
540            responding_authentication_value: None,
541            user_information: vec![0x08, 0x00, 0x06, 0x5F, 0x1F, 0x04, 0x00, 0x00, 0x7E, 0x1F, 0x04, 0xB0],
542            ..Default::default()
543        };
544        let encoded = aare.encode();
545        assert_eq!(encoded[0], AARE_TAG);
546        assert_eq!(AssociationResponse::decode(&encoded).unwrap(), aare);
547    }
548
549    #[test]
550    fn rlrq_normal_round_trips() {
551        let rlrq = ReleaseRequest { reason: Some(release_reason::NORMAL), user_information: None };
552        // 62 03 80 01 00.
553        assert_eq!(rlrq.encode_rlrq(), vec![0x62, 0x03, 0x80, 0x01, 0x00]);
554        assert_eq!(ReleaseRequest::decode_rlrq(&rlrq.encode_rlrq()).unwrap(), rlrq);
555    }
556
557    #[test]
558    fn rlre_with_user_information_round_trips() {
559        let rlre = ReleaseResponse {
560            reason: Some(release_reason::NORMAL),
561            user_information: Some(vec![0x08, 0x00, 0x06, 0x5F, 0x1F, 0x04, 0x00, 0x00, 0x7E, 0x1F, 0x04, 0xB0]),
562        };
563        let bytes = rlre.encode_rlre();
564        assert_eq!(bytes[0], RLRE_TAG);
565        assert_eq!(ReleaseResponse::decode_rlre(&bytes).unwrap(), rlre);
566    }
567
568    #[test]
569    fn aare_hls_carries_stoc_and_server_title() {
570        let aare = AssociationResponse {
571            application_context: application_context::LN_CIPHERING,
572            result: result::ACCEPTED,
573            diagnostic: 0,
574            responding_ap_title: Some(vec![0x4D, 0x4D, 0x4D, 0x00, 0x00, 0xBC, 0x61, 0x4E]),
575            responding_authentication_value: Some(b"P6wRJ21F".to_vec()),
576            user_information: vec![0x08, 0x00],
577            ..Default::default()
578        };
579        let decoded = AssociationResponse::decode(&aare.encode()).unwrap();
580        assert_eq!(decoded, aare);
581        assert_eq!(decoded.responding_authentication_value.unwrap(), b"P6wRJ21F");
582    }
583}