#include <stddef.h>
#include <limits.h>
#include <stdio.h>

#include <unistd.h>
#include <sys/mman.h>

#include <rpm/rpmpgp.h>

static unsigned char data_eddsa_asc[] = {
  0x88, 0x75, 0x04, 0x00, 0x16, 0x08, 0x00, 0x1d, 0x16, 0x21, 0x04, 0xe8,
  0x3a, 0x38, 0x0b, 0x85, 0x75, 0x56, 0x2b, 0x3c, 0x6f, 0x41, 0xca, 0x28,
  0xa4, 0x5c, 0x93, 0xb0, 0xb5, 0xb6, 0xe0, 0x05, 0x02, 0x60, 0x0f, 0x77,
  0x1a, 0x00, 0x0a, 0x09, 0x10, 0x28, 0xa4, 0x5c, 0x93, 0xb0, 0xb5, 0xb6,
  0xe0, 0x61, 0x58, 0x00, 0xff, 0x7a, 0xb7, 0xaf, 0xa7, 0x82, 0x3a, 0x1e,
  0xd3, 0x0b, 0x1f, 0xbe, 0xee, 0x50, 0x6c, 0xa0, 0xa7, 0xb1, 0x89, 0x7a,
  0x97, 0x69, 0xb8, 0x6d, 0x84, 0x44, 0x09, 0x77, 0x8c, 0xfa, 0xfe, 0x10,
  0xf6, 0x01, 0x00, 0xcb, 0x53, 0xd9, 0xc5, 0xc1, 0x0e, 0x2c, 0x84, 0x62,
  0x20, 0x65, 0xb0, 0xb9, 0x1a, 0x46, 0xf7, 0xf9, 0xb4, 0xfe, 0xfd, 0x2c,
  0x1e, 0x99, 0x72, 0x58, 0x48, 0xc0, 0x22, 0x63, 0x47, 0x12, 0x0a
};
static long data_eddsa_asc_len = 119;

int main(void)
{
    long s = sysconf(_SC_PAGE_SIZE);
    if (!(s > data_eddsa_asc_len && s < LONG_MAX / 2))
	return 1;

    uint8_t *addr = mmap(NULL, 2 * s, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
    if (addr == MAP_FAILED) {
	perror("mmap");
	return 1;
    }
    if (mprotect(addr + s, (size_t)s, PROT_NONE)) {
	perror("mprotect");
	return 1;
    }
    memcpy(addr + (s - data_eddsa_asc_len), data_eddsa_asc, data_eddsa_asc_len);
    pgpDigParams params = NULL;
    addr += s - data_eddsa_asc_len;
    if (pgpPrtParams(addr, data_eddsa_asc_len, PGPTAG_SIGNATURE, &params)) {
	fprintf(stderr, "Valid old-format signature not properly accepted\n");
	return 1;
    }
    params = pgpDigParamsFree(params);
    addr[0] = 0xC2;
    if (pgpPrtParams(addr, data_eddsa_asc_len, PGPTAG_SIGNATURE, &params)) {
	fprintf(stderr, "Valid new-format signature not properly accepted\n");
	return 1;
    }
    params = pgpDigParamsFree(params);
    addr[0] = 0x88;
    addr[1] += 5;
    if (pgpPrtParams(addr, data_eddsa_asc_len, 0, &params) != -1) {
	fprintf(stderr, "Invalid old-format signature packet not properly rejected\n");
	return 1;
    }
    params = pgpDigParamsFree(params);
    addr[0] = 0xC2;
    if (pgpPrtParams(addr, data_eddsa_asc_len, 0, &params) != -1) {
	fprintf(stderr, "Invalid new-format signature packet not properly rejected\n");
	return 1;
    }
    params = pgpDigParamsFree(params);
    return 0;
}
