paysec 0.1.1

Rust library related to payment security standards.
Documentation
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
//! Module for TR-31 Optional Blocks.
//!
//! This module defines the `OptBlock` struct which represents an optional block
//! in a TR-31 key block. In TR-31, optional blocks are used to store additional,
//! non-standard data within a key block. These blocks are identified by unique
//! identifiers and can be linked together to form a chain of optional data segments.
//!
//! # Format
//!
//! An optional block consists of:
//! - An identifier (`id`): A two-character ASCII string identifying the type of data.
//! - A length field: Indicating the length of the optional block and varies depending on the size of the block:
//!   - A two-byte hex-ASCII value of the length it it is below 256 bytes
//!   - An extended length field for largers sized blocks
//! - A data field (`data`): A variable-length string of ASCII printable characters.
//!
//! # Usage
//!
//! Optional blocks are used in various contexts within a TR-31 key block, such as for
//! additional metadata, custom fields, or other supplementary information that does not
//! fit into the standard key block structure.
//!
//! # Example Usage
//!
//! ```
//! use paysec::keyblock::OptBlock;
//!
//! // Creating a new OptBlock with an identifier, data, and no subsequent blocks
//! let opt_block = OptBlock::new("CT", "ExampleData", None);
//! assert!(opt_block.is_ok());
//! let opt_block = opt_block.unwrap();
//!
//! // Displaying the identifier and data
//! println!("ID: {}, Data: {}", opt_block.id(), opt_block.data());
//!
//! // Exporting the OptBlock to a string
//! let exported_string = opt_block.export_str();
//! assert!(exported_string.is_ok());
//! println!("Exported OptBlock: {}", exported_string.unwrap());
//!
//! // Creating another OptBlock and appending it to the first one
//! let next_block = OptBlock::new("PB", "PaddingData", None).unwrap();
//! let mut opt_block_chain = opt_block;
//! opt_block_chain.append(next_block);
//!
//! // Exporting the chained OptBlocks to a string
//! let exported_chain = opt_block_chain.export_str().unwrap();
//! println!("Exported OptBlock Chain: {}", exported_chain);
//! ```
//!
//! # References
//!
//! TR-31: 2018, p. 17-18, 27-33.

use std::error::Error;
use std::fmt::Write;

use super::header_constants::ALLOWED_OPT_BLOCK_IDS;

/// Represent an optional block as defined in the TR-31 specification.
///
/// Each `OptBlock` is identified by a two-character ASCII `id`, followed by a length field
/// indicating the size of the data, and the `data` itself which consists of ASCII printable characters.
/// The `length` field is a `usize` and represents the byte size of the `data` field.
/// The `next` field allows for the chaining of multiple `OptBlock`s to store a sequence of data.
///
/// # Fields
///
/// - `id`: A two-character ASCII string identifier for the optional block.
/// - `data`: A string containing the data of the block, composed of ASCII printable characters.
/// - `length`: The size of the `data` field in bytes, represented as a `usize`.
/// - `next`: An optional pointer to the next `OptBlock` in the chain.
#[derive(Debug, PartialEq, Clone)]
pub struct OptBlock {
    id: String,
    data: String,
    length: usize,
    next: Option<Box<OptBlock>>,
}

impl OptBlock {
    /// Create a new `OptBlock` instance with the specified `id`, `data`, and optional `next` block.
    ///
    /// # Arguments
    ///
    /// * `id` - The identifier for the new block, which must be one of the valid values defined in `ALLOWED_IDS`.
    /// * `data` - The data associated with the block, which must consist entirely of ASCII characters.
    /// * `next` - An optional `OptBlock` instance representing the next block in a linked list of blocks.
    ///
    /// # Returns
    ///
    /// A `Result` containing either an `OptBlock` instance or a boxed error.
    ///
    /// # Errors
    ///
    /// Returns an error in the following cases:
    /// - If the specified `id` is not one of the valid values defined in `ALLOWED_IDS`.
    /// - If the specified `data` contains non-ASCII characters.
    /// - If the total length of the `OptBlock` instance exceeds 65535 characters.
    pub fn new(id: &str, data: &str, next: Option<OptBlock>) -> Result<Self, Box<dyn Error>> {
        let mut opt_block = Self::new_empty();
        opt_block.set_id(id)?;
        opt_block.set_data(data)?;
        opt_block.set_next(next);
        Ok(opt_block)
    }

    /// Create a new empty `OptBlock`.
    ///
    /// This function creates a new `OptBlock` instance with empty `id`, `data`, and `next`
    /// fields and `length` set to zero.
    pub fn new_empty() -> Self {
        Self {
            id: String::new(),
            data: String::new(),
            length: 0,
            next: None,
        }
    }

    /// Construct a new `OptBlock` instance by parsing an input string.
    ///
    /// # Arguments
    ///
    /// * `s` - The input string to parse.
    /// * `num_opt_blocks` - The expected number of opt blocks to parse.
    ///
    /// # Returns
    ///
    /// A `Result` containing either the parsed `OptBlock` instance or a boxed error.
    ///
    /// # Errors
    ///
    /// Returns an error in the following cases:
    /// - If the input string is too short or does not meet the expected format.
    /// - If the length field is invalid or the string is too short for the given length.
    /// - If `set_id` or `set_data` fails.
    /// - If there are any errors while constructing the linked list of `OptBlock` instances.
    pub fn new_from_str(s: &str, num_opt_blocks: usize) -> Result<Self, Box<dyn Error>> {
        if s.len() < 4 {
            return Err(
                "ERROR TR-31 OPT BLOCK: String too short. Expected at least 4 characters".into(),
            );
        }

        let mut opt_block = Self::new_empty();
        opt_block.set_id(&s[..2])?;

        let data_start_offset: usize;
        if &s[2..4] == "00" {
            if s.len() < 256 {
                return Err("ERROR TR-31 OPT BLOCK: String containing extended length too short. Expected at least 256 characters".into());
            }
            let ext_block_len = &s[4..10];
            opt_block.length = Self::ext_len_from_str(ext_block_len)?;
            data_start_offset = 10;
        } else {
            opt_block.length = Self::len_from_str(&s[2..4])?;
            data_start_offset = 4;
        }

        if s.len() < opt_block.length {
            return Err(format!(
                "ERROR TR-31 OPT BLOCK: String too short for given length. Expected at least {} characters.",
                opt_block.length
            ).into());
        }

        opt_block.set_data(&s[data_start_offset..opt_block.length])?;

        // Parsing the next block if more than one block is expected
        if num_opt_blocks > 1 {
            // Recursively parse the next block
            let next_block_str = &s[opt_block.length..];
            let next_block = OptBlock::new_from_str(next_block_str, num_opt_blocks - 1)?;

            // Set the next block
            opt_block.set_next(Some(next_block));
        }

        Ok(opt_block)
    }

    /// Return a string representation of the `OptBlock` and its contents.
    ///
    /// # Returns
    ///
    /// A `Result` containing either the string representation of the `OptBlock` or a boxed error.
    ///
    /// # Errors
    ///
    /// Returns an error in the following cases:
    /// - If the length of the `OptBlock` is less than 4, indicating an uninitialized `OptBlock`.
    /// - If there are any errors while formatting the length field.
    pub fn export_str(&self) -> Result<String, Box<dyn Error>> {
        if self.length < 4 {
            return Err("ERROR TR-31 OPT BLOCK: Length must be greater than 4, indicating uninitialized OptBlock".into());
        }

        let mut res = String::new();

        // Optional Block ID
        res.push_str(&self.id);

        // Optional Block Length
        if self.length < 256 {
            write!(&mut res, "{:02X}", self.length)?;
        } else {
            write!(&mut res, "0002{:04X}", self.length)?;
        }

        // Optional Block Data
        res.push_str(&self.data);

        // Additional Optional Blocks, if present
        if let Some(next) = &self.next {
            res.push_str(&next.export_str()?);
        }

        Ok(res)
    }

    /// Set the identifier for this `OptBlock` instance.
    ///
    /// # Arguments
    ///
    /// * `id` - The identifier to set for this `OptBlock` instance.
    ///
    /// # Returns
    ///
    /// A `Result` indicating success (`Ok`) or containing a boxed error (`Err`) if an error occurs.
    ///
    /// # Errors
    ///
    /// This function returns an error if the input identifier is not valid. The identifier must be
    /// included in the list of allowed identifiers.
    pub fn set_id(&mut self, id: &str) -> Result<(), Box<dyn Error>> {
        if Self::is_allowed_id(id) {
            self.id = id.to_string();
            Ok(())
        } else {
            Err(format!("ERROR TR-31 OPT BLOCK: Invalid ID: {}", id).into())
        }
    }

    /// Return the ID of the `OptBlock`
    pub fn id(&self) -> &str {
        &self.id
    }

    /// Set the data field of the `OptBlock` instance to the given value and update the length of
    /// the block.
    ///
    /// # Arguments
    ///
    /// * `data` - The value to set as the data field.
    ///
    /// # Returns
    ///
    /// A `Result` indicating success (`Ok`) or containing a boxed error (`Err`) if an error occurs.
    ///
    /// # Errors
    ///
    /// This function returns an error in the following cases:
    /// - If the ID has not been set before calling this function. The ID must be a two-character
    ///   ASCII string and must be set prior to setting the data.
    /// - If the input `data` string contains non-ASCII characters. The data field must consist only
    ///   of ASCII printable characters.
    pub fn set_data(&mut self, data: &str) -> Result<(), Box<dyn Error>> {
        if self.id.len() != 2 {
            return Err("ERROR TR-31 OPT BLOCK: ID not set (has to be set before data)".into());
        }
        if !data.chars().all(|c| c.is_ascii()) {
            return Err(format!(
                "ERROR TR-31 OPT BLOCK: Data has non ASCII characters: {}",
                data
            )
            .into());
        }
        self.data = data.to_string();
        self.set_length()?;
        Ok(())
    }

    /// Returns the data of the `OptBlock`
    pub fn data(&self) -> &str {
        &self.data
    }

    /// Set the length of the current `OptBlock` instance based on the length of its ID and data
    /// fields. If the total length of the block exceeds 255 characters, an additional extended
    /// length field is added. If the total length exceeds 65535 characters, an error is
    /// returned. The length is stored in the `length` field of the `OptBlock` instance.
    ///
    /// # Returns
    ///
    /// A `Result` containing either `Ok(())` if the length is successfully set, or a boxed error.
    ///
    /// # Errors
    ///
    /// This function returns an error in the form of a `Box<dyn Error>` if the total length of the
    /// `OptBlock` instance exceeds 65535 characters.
    fn set_length(&mut self) -> Result<(), Box<dyn Error>> {
        // Minimum length containing ID length, length field length and data length
        let min_len: usize = self.id.len() + 2 + self.data.len();
        if min_len < 256 {
            self.length = min_len;
        } else {
            // If length of the optional header exceeds 255, additional extended length field of
            // length 6 is needed.
            self.length = min_len + 6;
        }
        if self.length > 65535 {
            let old_length = self.length;
            self.length = 0;
            return Err(format!(
                "ERROR TR-31 OPT BLOCK: Block size '{}' is too long (must be max. 65535)",
                old_length
            )
            .into());
        }
        Ok(())
    }

    /// Returns a reference to the length of the `OptBlock` instance.
    pub fn length(&self) -> &usize {
        &self.length
    }

    /// Set the next optional block.
    ///
    /// # Arguments
    ///
    /// * `next_block` - An optional `OptBlock` to be set as the next block.
    pub fn set_next(&mut self, next_block: Option<OptBlock>) {
        self.next = next_block.map(Box::new);
    }

    /// Return a reference to the next `OptBlock` instance in the linked list or `None` if there is
    /// no next `OptBlock`.
    pub fn next(&self) -> Option<&OptBlock> {
        self.next.as_deref()
    }

    /// Append an `OptBlock` to the end of the linked list of optional blocks.
    ///
    /// This method takes an `OptBlock` and appends it to the end of the current chain of `OptBlock`s.
    /// If the current `OptBlock` already has a next block linked, the method recursively traverses
    /// the chain until it finds the last block, to which the new block is then appended.
    ///
    /// # Arguments
    ///
    /// * `opt_block_to_append` - The `OptBlock` to be appended to the end of the current chain.
    pub fn append(&mut self, opt_block_to_append: OptBlock) {
        match &mut self.next {
            Some(ref mut next_block) => next_block.append(opt_block_to_append),
            None => self.set_next(Some(opt_block_to_append)),
        }
    }

    /// Determines whether the given `id` string is allowed.
    ///
    /// # Arguments
    ///
    /// * `id` - The ID string to check.
    ///
    /// # Returns
    ///
    /// `true` if the ID is allowed, `false` otherwise.
    ///
    pub fn is_allowed_id(id: &str) -> bool {
        ALLOWED_OPT_BLOCK_IDS.contains(&id)
    }

    /// Returns the total length of the `OptBlock`, including its own length and the lengths of all
    /// subsequent `OptBlock`s in the linked list.
    ///
    /// # Returns
    ///
    /// The total length of the `OptBlock` as a `usize` value..
    ///
    pub fn total_length(&self) -> usize {
        let mut total = self.length;
        if let Some(next) = &self.next {
            total += next.total_length();
        }
        total
    }

    /// Parse the length of an `OptBlock` from a hexadecimal-encoded string.
    ///
    /// # Arguments
    ///
    /// * `s` - A hexadecimal-encoded string representing the length of the `OptBlock`.
    ///
    /// # Returns
    ///
    /// A `Result` containing either the length of the `OptBlock` as a `usize` value or a boxed error.
    ///
    /// # Errors
    ///
    /// Returns an error in the following cases:
    /// - If the length string is not exactly 2 characters long.
    /// - If the string cannot be parsed as a hexadecimal number.
    /// - If the resulting length is less than 4.
    /// Errors are returned as a `Box<dyn Error>`, which can encompass various error types.
    fn len_from_str(s: &str) -> Result<usize, Box<dyn Error>> {
        if s.len() != 2 {
            return Err(Box::<dyn Error>::from(format!(
            "ERROR TR-31 OPT BLOCK: Invalid length field: Expected a string with 2 characters, found '{}'",
            s
        )));
        }

        let len = usize::from_str_radix(s, 16).map_err(|_| { 
            Box::<dyn Error>::from(format!("ERROR TR-31 OPT BLOCK: Invalid length field: '{}' is not a valid hexadecimal number", s)) 
        })?;

        if len < 4 {
            return Err(Box::<dyn Error>::from(format!(
            "ERROR TR-31 OPT BLOCK: Invalid length field: value {} is too small (must be at least 4)",
            len
        )));
        }

        Ok(len)
    }

    /// Convert the extended length field of a TR-31 message from a hexadecimal string to a `usize`.
    ///
    /// # Arguments
    ///
    /// * `s` - The input string to parse.
    ///
    /// # Returns
    ///
    /// A `Result` containing either the parsed extended length as a `usize` or a boxed error.
    ///
    /// # Errors
    ///
    /// This function returns an error in the following cases:
    /// - If the input string does not have a length of 6 characters.
    /// - If the first two characters are not `02`.
    /// - If the resulting `usize` is less than or equal to 255.
    fn ext_len_from_str(s: &str) -> Result<usize, String> {
        if s.len() != 6 {
            return Err(format!(
                "ERROR TR-31 OPT BLOCK: Invalid extended length field: {}",
                s
            ));
        }
        if &s[0..2] != "02" {
            return Err(format!(
                "ERROR TR-31 OPT BLOCK: Invalid length of length field: {}",
                &s[0..2]
            ));
        }
        let res = usize::from_str_radix(&s[2..6], 16).map_err(|e| e.to_string())?;
        if res <= 255 {
            return Err(format!(
                "ERROR TR-31 OPT BLOCK: Extended length is not greater than 255: {}",
                &s[2..6]
            ));
        }
        Ok(res)
    }
}