# Integrity and Checksums

This reference describes the mathematical checksums used to validate data integrity when communicating over the serial connection.

## Longitudinal redundancy check (LRC)

Every single operational message exchanged between the SP and the PP (e.g., `Y19`, `Y15`, `Y02`) must be appended with an LRC validation byte to ensure the payload was not corrupted during serial transmission.

### LRC validation scope

The LRC byte calculation must cover all characters in the active payload starting immediately *after* the `<STX>` control character, and concluding immediately *after* the `<ETX>` control character.

* **Included**: Payload characters, `<FS>` separators, `<ETX>`.
* **Excluded**: `<STX>`, `<ACK>`, `<NAK>`, and the previously calculated `{LRC}` byte itself.

### LRC algorithm

The LRC is a straightforward exclusive OR (XOR) calculation executed sequentially over each byte in the targeted string.

**Pseudocode Logic**:

```python
def calculate_lrc(payload_string, etx_char):
    lrc = 0
    # Process the entire payload string
    for byte in payload_string:
        lrc = lrc ^ ord(byte)
    
    # Process the ETX character 
    lrc = lrc ^ ord(etx_char)
    
    return lrc
```

### Action on LRC failure

Upon receiving a message:

1. The receiving party (either SP or PP) must independently calculate the LRC of the incoming data block up to the `<ETX>`.
2. Compare the calculated LRC against the `{LRC}` byte provided at the end of the message.
3. If they match, the receiver returns an `<ACK>` (Acknowledge) character.
4. If they differ, the receiver returns a `<NAK>` (Negative Acknowledge) character. The sender should then immediately retransmit the entire identical packet.

## Cyclic redundancy check (CRC-16)

While the LRC byte ensures the integrity of short operational commands, the terminal requires a more robust validation framework for massive data transfers, specifically during remote application downloads over the `YDL` command.

### CRC scope

During a `YDL` file download, the file is split into numerous manageable blocks. The SP must calculate a CRC over the data payload `[DDA]` for *every individual chunk*, and send that CRC alongside the chunk.

### CRC algorithm (CRC-16/CCITT-FALSE)

The system utilizes a 16-bit CRC based on the CCITT standard polynomial. Below is the list of standard parameters:

* **Width**: 16 bits
* **Polynomial**: `0x1021` (`X^16 + X^12 + X^5 + 1`)
* **Initial Value**: `0xFFFF`
* **Input Reflected**: False
* **Result Reflected**: False
* **Final XOR Value**: `0x0000`

### Implementation note

Because the CRC acts on the `YDL` package data block, the `YDL` message itself *still requires a standard `{LRC}` byte at the end of its frame* to validate the transmission string. Therefore, a YDL transmission contains two distinct integrity layers: the CRC verifying the binary chunk of the APK, and the LRC verifying the ascii serial frame transmitting that chunk.