# btc16m.py
# Generates fully folded 16,777,216-vector HDGL covenant
# Uses 64 seed vectors with logarithmic doubling (folding)
# Conservatively saturates r_dim + Ω to avoid overflow

MAX_SEED_VECTORS = 64
TARGET_VECTORS = 16_777_216  # 2^24
BLOCK_SIZE = 4  # 4 vectors per block
SAFE_ZERO = "0x0"

# Example r_dim & Ω per initial seed block (powers-of-2 scaled)
PARAMS = {
    1: ("0x3000", "0x812"),
    2: ("0x4000", "0x502"),
    3: ("0x5000", "0x310"),
    4: ("0x6000", "0x192"),
    5: ("0x7000", "0x119"),
    6: ("0x8000", "0x73"),
    7: ("0x9000", "0x45"),
    8: ("0xA000", "0x28"),
}

def generate_hdgl_covenant(pubkey="<YOUR_PUBLIC_KEY>"):
    script = [f"{pubkey} OP_CHECKSIGVERIFY\n"]

    # 1️⃣ Generate 64 seed vectors
    num_blocks = MAX_SEED_VECTORS // BLOCK_SIZE
    for block_idx in range(1, num_blocks + 1):
        # vectors
        v_line = " ".join([SAFE_ZERO]*BLOCK_SIZE) + " OP_HDGL_VEC_ADD OP_EQUALVERIFY"
        script.append(v_line)

        # OP_ADD + OP_EQUALVERIFY
        idx_base = 100 + (block_idx-1)*BLOCK_SIZE
        add_line = f"{idx_base} {idx_base+1} OP_ADD {idx_base+2} OP_EQUALVERIFY"
        script.append(add_line)

        # OP_WITHINVERIFY
        within_line = f"{idx_base+3} {idx_base+4} {idx_base+5} OP_WITHINVERIFY"
        script.append(within_line)

        # embed r_dim + Ω if defined
        if block_idx in PARAMS:
            param_line = f"{PARAMS[block_idx][0]} {PARAMS[block_idx][1]} OP_HDGL_PARAM_ADD OP_EQUALVERIFY"
            script.append(param_line)

        script.append("")  # spacing

    # 2️⃣ Logarithmic folding to reach TARGET_VECTORS
    seed_count = MAX_SEED_VECTORS
    fold_index = 0
    while seed_count < TARGET_VECTORS:
        fold_index += 1
        prev_count = seed_count
        seed_count *= 2  # double vectors each fold

        v_line = f"OP_VEC_DUP {prev_count} OP_HDGL_VEC_ADD OP_EQUALVERIFY"
        script.append(v_line)

        idx_base = 100 + prev_count  # approximate OP indices (safe conservative)
        add_line = f"{idx_base} {idx_base+1} OP_ADD {idx_base+2} OP_EQUALVERIFY"
        script.append(add_line)
        within_line = f"{idx_base+3} {idx_base+4} {idx_base+5} OP_WITHINVERIFY"
        script.append(within_line)

        script.append("")  # spacing

    # Final covenant check
    script.append("OP_CHECKTEMPLATEVERIFY")
    return "\n".join(script)

if __name__ == "__main__":
    covenant_script = generate_hdgl_covenant()
    print("=== Fully Folded 16,777,216-Vector HDGL Covenant ===")
    print(covenant_script)
