Repository Public
1// SP Wallet Core2// File: Sources/SPWalletCore/Crypto/Checksums.swift3// Description: Small non-cryptographic checksums and the double SHA-256 of Base58Check. CRC-16/XMODEM (polynomial 0x1021,4// initial value 0) protects Stellar strkeys (stored little-endian) and TON user-friendly addresses (big-endian).5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import CryptoKit9import Foundation1011public enum CRC16 {12 /** CRC-16/XMODEM: poly 0x1021, init 0x0000, no reflection, no final XOR. Check value of "123456789" is 0x31C3. */13 public static func xmodem(_ bytes: some Sequence<UInt8>) -> UInt16 {14 var crc: UInt16 = 015 for byte in bytes {16 crc ^= UInt16(byte) << 817 for _ in 0..<8 { crc = (crc & 0x8000) != 0 ? (crc << 1) ^ 0x1021 : crc << 1 }18 }19 return crc20 }21}2223enum SHA2 {24 static func sha256(_ bytes: [UInt8]) -> [UInt8] { [UInt8](SHA256.hash(data: bytes)) }25 /** SHA-256 applied twice: the checksum of Base58Check and of XRP Ledger addresses. */26 static func doubleSHA256(_ bytes: [UInt8]) -> [UInt8] { sha256(sha256(bytes)) }27}28