
// uC includes
#include "../common/io.c"
#include "../common/lib.c"

typedef unsigned char u8;
typedef unsigned short u16;

int main () {
    u8 *ed25519_pubkey = (mem + 0x2440);
    u8 *buf            = (mem + 0x2460); // >=> 0x2460

    u8 sig_buf[64]; // >=> sp

    puts ("Welcome to the secure program loader.");

    while (1) {
        u16 loadaddr; // >=> r11
        u8 len;       // >=> r10
        puts ("Please enter debug payload.");

        memset (buf, 0, 0x400);
        getsn (buf, 0x3ff);

        loadaddr = (buf[0] << 8) + (buf[1]);
        len      = buf[3];

        if (0x8000 > loadaddr || loadaddr >= 0xf001) {
            puts ("Load address outside allowed range of 0x8000-0xF000");
            continue;
        }
        if (loadaddr & 1) {
            puts ("Load address unaligned");
            continue;
        }
        if (len - 6 > 0x3bb) {
            puts ("Invalid payload length");
            continue;
        }

        u8 *signature = buf + len;
        memcpy (sig_buf, buf + len, 0x40);

        if (verify_ed25519 (ed25519_pubkey, buf, len, sig_buf) != 0x1) {
            puts ("Incorrect signature, continuing");
            continue;
        }

        puts ("Signature valid, executing payload");
        printf ("LA:%p, BF:%p, LEN:%x\n", mem + loadaddr, buf, len);
        memcpy (mem + loadaddr, buf + 0x4, len);
    }
}
