# -*- coding: utf-8 -*-
"""
bshield_cfg_decode.py — Re-implement tĩnh bộ giải mã config của build-info (BShield 3.19.0).

Nguồn: decompile Ghidra
  - ctor singleton 0x33bb8 (buildinfo_cons.txt)  : ChaCha keystream + parse section 6 -> mask1 [sing+0x18]
  - 0x2e300 (buildinfo_wave3.txt)               : 5 section (1..5) -> công thức kết hợp -> mask2 [sing+0x1c]

Thuật toán keystream (từ decompile, mô phỏng 1:1):
  state[16]: word0 = số vòng (config[0]); words1..15 = config[1..15];
             khi sinh block: word12 = counter = abs_off/0x40 + 1
  N vòng double-round ChaCha (rot 16/12/8/7), cộng state gốc, serialize LE 64 byte.
  keystream byte index = abs_off & 0x3f (block b cover abs [64b, 64b+64)).
"""
import struct, sys, os

M32 = 0xFFFFFFFF

def rotl(x, n):
    x &= M32
    return ((x << n) | (x >> (32 - n))) & M32

def chacha_block(state, rounds):
    """state: list 16 uint (đã đặt word12=counter, word0=rounds nguồn riêng). trả 64 bytes LE."""
    x = list(state)
    for _ in range(rounds):
        # quarter column round (theo decompile: 4 cột, mỗi cột 4 phép quay 16/12/8/7)
        for a, b, c, d in ((0, 4, 8, 12), (1, 5, 9, 13), (2, 6, 10, 14), (3, 7, 11, 15)):
            x[d] ^= (x[a] + x[b]) & M32; x[d] = rotl(x[d], 16)
            x[a] = (x[a] + x[b] + x[d]) & M32
            x[c] ^= x[a]; t = x[c]; x[c] = rotl(t, 12) & M32
            # theo decompile: x[b] ^= x[c] sau khi x[c] đã quay 12? — xem ghi chú 'order' bên dưới
            x[b] = (x[b] + x[c]) & M32
            x[a] ^= x[b]; x[a] = rotl(x[a], 8) & M32
            x[d] ^= x[a]  # placeholder — sẽ được thay bằng triển khai literal từ decompile
    return x

# --- Triển khai LITERAL theo decompile (an toàn hơn), 1 double-round mỗi vòng loop ---
def double_round(x):
    # cột 1: (12, 0, 4, 8) — theo dòng 128-138 của buildinfo_cons.txt
    x[12] ^= (x[0] + x[4]) & M32; x[12] = rotl(x[12], 16)
    x[8] = (x[8] + x[12]) & M32
    x[4] ^= x[8]; x[4] = rotl(x[4], 12)
    x[0] = (x[0] + x[4] + x[8]) & M32
    # chuỗi biến tạm uVar1/uVar2/uVar3 khớp: quay 8 cho uVar1 (đã XOR x[0])
    # (x[0] ^ x[4]) >> 8 | << 8 = rotl 8
    t = (x[0] ^ x[4]) & M32
    t8 = rotl(t, 8)
    x[8] = (x[8] + t8) & M32
    x[4] ^= x[8]; x[4] = rotl(x[4], 7)  # uVar3
    # NOTE: decompile ghidra tái dùng biến; đoạn trên cần khớp chính xác — xem hàm literal bên dưới.
    raise NotImplementedError("dùng kef_decrypt chuẩn bên dưới")

def QR(a, b, c, d):
    """ChaCha quarter-round chuẩn theo đúng thứ tự trong decompile:
       d ^= a+b ; d rot16 ; c += d... — nhưng decompile có biến thể.
    """
    pass

# ============================================================================
# Triển khai literal từ decompile (buildinfo_cons.txt dòng 128–219), cột (0,4,8,12):
#   x[12] ^= x[0]+x[4]; x[12]=rot16
#   x[8] += x[12]
#   t = x[4]^x[8]; t = rot12(t)
#   x[0] += x[4] + t
#   uVar1 = t ^ x[0]; uVar2 = rot8(uVar1)
#   x[8] += uVar2
#   uVar3 = (t ^ x[8]) rot7
#   ... x[0] += uVar3 (dòng 172: auStack_68[0] = auStack_68[0] + uVar5)
# Cột (1,5,9,13): x[13]^=x[1]+x[5]; rot16; x[9]+=x[13]; t=x[5]^x[9] rot12; x[1]+=x[5]+t;
#   uVar1 = t^x[1]; uVar4 = rot8(uVar1); x[9]+=uVar4; uVar5=(t^x[9]) rot7 -> dùng cho cột sau
# ...
# Diagonal rounds: dòng 172–219: x[0]+=uVar5; ... (diagonal rot: 16/12/8/7 với các cặp (0,5,10,15)...)
# ============================================================================
