/* MIT License Copyright (c) 2023 OKX.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // Modified by coolbitx in 2024 export function checksumToArray(checksum: number) { const result = []; for (let i = 0; i < 8; ++i) { result.push(checksum & 31); checksum /= 32; } return result.reverse(); } const GENERATOR1 = [0x98, 0x79, 0xf3, 0xae, 0x1e]; const GENERATOR2 = [0xf2bc8e61, 0xb76d99e2, 0x3e5fb3c4, 0x2eabe2a8, 0x4f43e470]; export function polymod(data: Uint8Array) { // Treat c as 8 bits + 32 bits let c0 = 0, c1 = 1, C = 0; for (let j = 0; j < data.length; j++) { // Set C to c shifted by 35 C = c0 >>> 3; // 0x[07]ffffffff c0 &= 0x07; // Shift as a whole number c0 <<= 5; c0 |= c1 >>> 27; // 0xffffffff >>> 5 c1 &= 0x07ffffff; c1 <<= 5; // xor the last 5 bits c1 ^= data[j]; for (let i = 0; i < GENERATOR1.length; ++i) { if (C & (1 << i)) { c0 ^= GENERATOR1[i]; c1 ^= GENERATOR2[i]; } } } c1 ^= 1; // Negative numbers -> large positive numbers if (c1 < 0) { c1 ^= 1 << 31; c1 += (1 << 30) * 2; } // Unless bitwise operations are used, // numbers are consisting of 52 bits, except // the sign bit. The result is max 40 bits, // so it fits perfectly in one number! return c0 * (1 << 30) * 4 + c1; }