Skip to content
pi-c Documentation
Login

Documentation

/* Remote control's cryptography against test/pic/remote-vectors.json (docs/design/remote-protocol.md,
 * section 8): the file's hash, the derivations, both handshakes in both roles, the transport, VAPID
 * and Web Push; and the refusals: a flipped bit anywhere in a message 1, the wrong psk, a key off
 * the curve, the wrong channel, a replayed or reordered counter. Usage: test_noise VECTORS.JSON */
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "bearssl.h"
#include "noise.h"
#include "sqlite3.h"

#define VECTORS_SHA256 "fa895483624944e6f7e36b690bc3344a19e6755c270d49d10c4a876869e0e4ab"

static sqlite3 *mem;
static char *doc;

/* The vectors' string at PATH (static until the next call). */
static const char *v(const char *path) {
    static char out[65536];
    sqlite3_stmt *q = NULL;
    assert(sqlite3_prepare_v2(mem, "SELECT json_extract(?1, ?2)", -1, &q, NULL) == SQLITE_OK);
    sqlite3_bind_text(q, 1, doc, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 2, path, -1, SQLITE_STATIC);
    assert(sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0));
    (void)snprintf(out, sizeof out, "%s", (const char *)sqlite3_column_text(q, 0));
    sqlite3_finalize(q);
    return out;
}

static size_t unhex(const char *s, unsigned char *out) {
    size_t n = 0;
    for (; s[0] && s[1]; s += 2) {
        unsigned x;
        assert(sscanf(s, "%2x", &x) == 1);
        out[n++] = (unsigned char)x;
    }
    return n;
}

static void hexs(const unsigned char *b, size_t n, char *out) {
    for (size_t i = 0; i < n; i++) {
        (void)snprintf(out + 2 * i, 3, "%02x", b[i]);
    }
    out[2 * n] = '\0';
}

static void same_hex(const char *what, const unsigned char *b, size_t n, const char *path) {
    char got[2 * PIC_NOISE_RECORD_CAP + 1];
    hexs(b, n, got);
    if (strcmp(got, v(path)) != 0) {
        fprintf(stderr, "%s: got %s\n    want %s\n", what, got, v(path));
        exit(1);
    }
}

static void seqkey(unsigned char *b, int first) {
    for (int i = 0; i < 32; i++) {
        b[i] = (unsigned char)(first + i);
    }
}

static void test_file_hash(const char *text, size_t n) {
    unsigned char d[32];
    char h[65];
    pic_noise_sha256(d, text, n, NULL, 0);
    hexs(d, 32, h);
    if (strcmp(h, VECTORS_SHA256) != 0) {
        fprintf(stderr, "remote-vectors.json changed: sha256 %s, the tests expect %s\n", h, VECTORS_SHA256);
        exit(1);
    }
    puts("ok vectors file hash");
}

static void test_derive(void) {
    unsigned char owner[32], dev[32], ps[32], psk[32], tok[32], ch[16], mb[16], dc[16], offer[PIC_NOISE_OFFER], back[16];
    unsigned char pub[65], ps2[32];
    pic_noise_keypair pic;
    uint64_t exp = 0;
    char url[512], b64[200];
    seqkey(owner, 0x10);
    seqkey(dev, 0x30);
    seqkey(ps, 0xc1);
    pic_noise_id(mb, "pic-rc/1 mailbox", owner);
    same_hex("mailbox", mb, 16, "$.derive.mailbox");
    pic_noise_pair_derive(ps, psk, tok, ch);
    same_hex("psk", psk, 32, "$.derive.psk");
    same_hex("pair token", tok, 32, "$.derive.pair_token");
    same_hex("pair channel", ch, 16, "$.derive.pair_channel");
    pic_noise_id(dc, "pic-rc/1 channel", dev);
    same_hex("device channel", dc, 16, "$.derive.device_channel");
    {
        unsigned char k[32];
        seqkey(k, 0x01);
        assert(pic_noise_keypair_make(&pic, k) == 0);
    }
    same_hex("pic static public", pic.pub, 65, "$.keys.pic_static_public");
    pic_noise_offer(mb, pic.pub, ps, 1800000000u, offer);
    same_hex("offer", offer, sizeof offer, "$.offer.bytes");
    pic_b64u_enc(offer, sizeof offer, b64);
    (void)snprintf(url, sizeof url, "https://relay.example/#p1.%s", b64);
    assert(strcmp(url, v("$.offer.url")) == 0);
    assert(pic_noise_offer_read(offer, sizeof offer, back, pub, ps2, &exp) == 0);
    assert(memcmp(back, mb, 16) == 0 && memcmp(pub, pic.pub, 65) == 0 && memcmp(ps2, ps, 32) == 0 && exp == 1800000000u);
    offer[0] = 2;
    assert(pic_noise_offer_read(offer, sizeof offer, back, pub, ps2, &exp) == -1);
    puts("ok derivations and the offer");
}

/* One handshake of the vectors, at PFX ("$.pairing" or "$.session"): both roles reproduce both
 * records, the hash and the keys, and each reads the vector's record of the other. */
static void handshake(const char *pfx, int psk_mode, pic_noise_transport *up_t, pic_noise_transport *down_t) {
    unsigned char picp[32], php[32], ie[32], re[32], prologue[64], psk[32], sid[8], m[2048], rec[2048], pl[512];
    unsigned char up[32], down[32], up2[32], down2[32];
    pic_noise_keypair pic, phone;
    pic_noise_hs I, R;
    size_t pn, mn, rn, n;
    char path[96], p1[512], p2[512];
    seqkey(picp, 0x01);
    seqkey(php, 0x21);
    assert(pic_noise_keypair_make(&pic, picp) == 0 && pic_noise_keypair_make(&phone, php) == 0);
#define P(x) ((void)snprintf(path, sizeof path, "%s.%s", pfx, x), path)
    pn = unhex(v(P("prologue")), prologue);
    unhex(v(P("phone_ephemeral_private")), ie);
    unhex(v(P("pic_ephemeral_private")), re);
    unhex(v(P("sid")), sid);
    unhex(v("$.derive.psk"), psk);
    (void)snprintf(p1, sizeof p1, "%s", v(P("payload1")));
    (void)snprintf(p2, sizeof p2, "%s", v(P("payload2")));
    pic_noise_hs_init(&I, 1, &phone, pic.pub, psk_mode ? psk : NULL, prologue, pn);
    pic_noise_hs_init(&R, 0, &pic, NULL, psk_mode ? psk : NULL, prologue, pn);
    assert(pic_noise_hs_ephemeral(&I, ie) == 0 && pic_noise_hs_ephemeral(&R, re) == 0);
    assert(pic_noise_write1(&I, p1, strlen(p1), m, sizeof m, &mn) == 0);
    rn = pic_noise_head(PIC_NOISE_REC_M1, sid, m, mn, rec);
    same_hex("record1", rec, rn, P("record1"));
    /* the responder reads the vector's record, not ours */
    rn = unhex(v(P("record1")), rec);
    assert(pic_noise_read1(&R, rec + 9, rn - 9, pl, sizeof pl, &n) == 0);
    assert(n == strlen(p1) && memcmp(pl, p1, n) == 0 && memcmp(R.rs, phone.pub, 65) == 0);
    assert(pic_noise_write2(&R, p2, strlen(p2), m, sizeof m, &mn) == 0);
    rn = pic_noise_head(PIC_NOISE_REC_M2, sid, m, mn, rec);
    same_hex("record2", rec, rn, P("record2"));
    rn = unhex(v(P("record2")), rec);
    assert(pic_noise_read2(&I, rec + 9, rn - 9, pl, sizeof pl, &n) == 0);
    assert(n == strlen(p2) && memcmp(pl, p2, n) == 0);
    same_hex("handshake hash", I.h, 32, P("handshake_hash"));
    assert(memcmp(I.h, R.h, 32) == 0);
    assert(pic_noise_split(&I, up, down) == 0 && pic_noise_split(&R, up2, down2) == 0);
    assert(memcmp(up, up2, 32) == 0 && memcmp(down, down2, 32) == 0);
    same_hex("key up", up, 32, P("key_up"));
    same_hex("key down", down, 32, P("key_down"));
    if (psk_mode) {
        char sas[7];
        pic_noise_sas(I.h, sas);
        assert(strcmp(sas, v("$.pairing.sas")) == 0);
    }
    pic_noise_transport_init(up_t, 1, sid, up, down);   /* the phone's */
    pic_noise_transport_init(down_t, 0, sid, up, down); /* pic's */
    pic_noise_hs_wipe(&I);
    pic_noise_hs_wipe(&R);
#undef P
}

static void transport_pair(const char *pfx, const char *name, pic_noise_transport *sender, pic_noise_transport *reader) {
    unsigned char rec[PIC_NOISE_RECORD_CAP], out[PIC_NOISE_CHUNK];
    char path[96], plain[512];
    size_t rn, n;
    int flag, gap;
    (void)snprintf(path, sizeof path, "%s.%s_plain", pfx, name);
    (void)snprintf(plain, sizeof plain, "%s", v(path));
    rn = pic_noise_record(sender, 1, plain, strlen(plain), rec);
    (void)snprintf(path, sizeof path, "%s.%s", pfx, name);
    same_hex(path, rec, rn, path);
    rn = unhex(v(path), rec);
    assert(pic_noise_open_record(reader, rec, rn, &flag, out, &n, &gap) == 0);
    assert(flag == 1 && n == strlen(plain) && memcmp(out, plain, n) == 0);
    /* the same record again is a replay, dropped */
    assert(pic_noise_open_record(reader, rec, rn, &flag, out, &n, &gap) == -1);
}

/* A reader writes only the plaintext's bytes: OUT sized exactly for the payload (on the heap, so
 * AddressSanitizer sees one byte past it) must hold, for both handshake messages. */
static void test_exact_capacity(void) {
    pic_noise_keypair pic, phone;
    pic_noise_hs I, R;
    unsigned char picp[32], php[32], ie[32], re[32], m[1024], prologue[9] = "exact-ca";
    char p1[300], p2[200];
    size_t mn, n;
    unsigned char *out;
    seqkey(picp, 0x41);
    seqkey(php, 0x61);
    seqkey(ie, 0x11);
    seqkey(re, 0x31);
    memset(p1, 'a', sizeof p1);
    memset(p2, 'b', sizeof p2);
    assert(pic_noise_keypair_make(&pic, picp) == 0 && pic_noise_keypair_make(&phone, php) == 0);
    pic_noise_hs_init(&I, 1, &phone, pic.pub, NULL, prologue, sizeof prologue - 1);
    pic_noise_hs_init(&R, 0, &pic, NULL, NULL, prologue, sizeof prologue - 1);
    assert(pic_noise_hs_ephemeral(&I, ie) == 0 && pic_noise_hs_ephemeral(&R, re) == 0);
    assert(pic_noise_write1(&I, p1, sizeof p1, m, sizeof m, &mn) == 0);
    out = malloc(sizeof p1);
    assert(out && pic_noise_read1(&R, m, mn, out, sizeof p1, &n) == 0);
    assert(n == sizeof p1 && memcmp(out, p1, n) == 0);
    free(out);
    assert(pic_noise_write2(&R, p2, sizeof p2, m, sizeof m, &mn) == 0);
    out = malloc(sizeof p2);
    assert(out && pic_noise_read2(&I, m, mn, out, sizeof p2, &n) == 0);
    assert(n == sizeof p2 && memcmp(out, p2, n) == 0);
    free(out);
    pic_noise_hs_wipe(&I);
    pic_noise_hs_wipe(&R);
}

/* ---- the prekey variant of IK message 1 (tools/noise-prekey-vectors.js) ------------------------ */

#define PK_PLAIN_PROLOGUE "7069632d6e6f6973652d7072656b65792f3100"
#define PK_PLAIN_M1                                                                                        \
    "04ecb6a2f86c7825ee71d022c29b9f8aa35971520ec3f9739855635765ead1bd14adad028bfba628ed75b72e3cbeb1ef192e6" \
    "0f52b3e2021497df3afb3006550df705dc3c1d937c536021301dd7fd942b9036e335004e99e297bea2bc7cd5a22230351ad33" \
    "dc29e5ca0f0704dceb3cd44553876357e2aae0a6b34e6b113144c8176a9c869b95efc7d715414754766dddd3eee95d90e99fb" \
    "a26faab70974aa612a3b068985ef99b925cc2811ab16c4da310d93b9f4696fe416ccb0ffc04a93b27"
#define PK_PLAIN_H1 "a5bf865f9019f2c810281d77507a83d3d5527f41477e85ed48b113df6c6ea01c"
#define PK_PLAIN_M2                                                                                        \
    "04ad137f7ef829eef8a8571bf4d307664ea8e024e05bda4e26da8f7ae884456058a88e48c9a1d9386471f13f2559758edc4bc" \
    "1e11394eb415d63e2d33e4d38519d405aa9b8657a0e8e9e15602e93fdf21a9beb"
#define PK_PLAIN_H2 "2ab75715d5d7592a4d5178ffcb50c9cc123b66c128468aeb621e011fded09e20"
#define PK_PROLOGUE "7069632d6e6f6973652d7072656b65792f3101"
#define PK_BIND                                                                                            \
    "01e1e2e3e4e5e6e7e8043c06b1c7fc699ccd77641f46f0c0492cfd76bf784e4ed1968f13ae1d646568cbae90b48f7cf4acfde" \
    "4fc09b124c424aeba66f604aef18c7201be06272b905899"
#define PK_PUB                                                                                             \
    "043c06b1c7fc699ccd77641f46f0c0492cfd76bf784e4ed1968f13ae1d646568cbae90b48f7cf4acfde4fc09b124c424aeba6" \
    "6f604aef18c7201be06272b905899"
#define PK_M1                                                                                              \
    "04ecb6a2f86c7825ee71d022c29b9f8aa35971520ec3f9739855635765ead1bd14adad028bfba628ed75b72e3cbeb1ef192e6" \
    "0f52b3e2021497df3afb3006550df705dc3c1d937c536021301dd7fd942b9036e335004e99e297bea2bc7cd5a22230351ad33" \
    "dc29e5ca0f0704dceb3cd44553876357e2aae0a6b34e6b113144c8176a1439264f1245806bf0dd3d24259573caf331f75b161" \
    "b451ff2b76d0302a3e8b6e47458fe8e9f320ae2f4e2194d028a87d7f2ab7be42963243edc1674954f"
#define PK_H1 "b4ef776ec45ca8422b4d4a0e904baadd1592cf945d174f4aef84549574430437"
#define PK_M2                                                                                              \
    "04ad137f7ef829eef8a8571bf4d307664ea8e024e05bda4e26da8f7ae884456058a88e48c9a1d9386471f13f2559758edc4bc" \
    "1e11394eb415d63e2d33e4d38519d495ff331fc0f3f0ef81c6f4e8eacc40ca292"
#define PK_H2 "ce8d99d811818e6ea54fd4c01df35119cf3780c7bb72b23ba38670c00522fa37"
#define PK_FORGED_M1                                                                                       \
    "04ecb6a2f86c7825ee71d022c29b9f8aa35971520ec3f9739855635765ead1bd14adad028bfba628ed75b72e3cbeb1ef192e6" \
    "0f52b3e2021497df3afb3006550df705dc3c1d937c536021301dd7fd942b9036e335004e99e297bea2bc7cd5a22230351ad33" \
    "dc29e5ca0f0704dceb3cd44553876357e2aae0a6b34e6b113144c8176a1439264f1245806bf0dd3d24259573caf331f75b161" \
    "b451ff2b76d0302a3e8b650736ce79edc041b4cb1617eb911da4aab533261782b0a2f54c368cc6bce"
/* DH(initiator ephemeral, this point) is all zeros: e^-1 times the point (0, y) */
#define PK_ZERO_DH                                                                                         \
    "0499a4b3cd790b5edb682a338536928f0b3c27363ec6edeef6ad7261f8091dc7b553df73ff417210f3f83c9aa82808123ec42" \
    "2b8c567c4b5635e33f2e8c129a580"
/* IKpsk1's head without the psk: e mixed as a key, no MixKeyAndHash(psk), then the tag */
#define PK_PSK_WITHOUT_PSK_M1                                                                              \
    "04ecb6a2f86c7825ee71d022c29b9f8aa35971520ec3f9739855635765ead1bd14adad028bfba628ed75b72e3cbeb1ef192e" \
    "60f52b3e2021497df3afb3006550df036d6dd4af32665bd1242644cfb11b3efb601799ecd07041d4edd4a33635b5f33b1234" \
    "ff28a00f54f78fbf0c905d146e4d25725c00aca85cbac10f644d782478f3eb7ab356993602bd611d7f23788fdfe3a67097ff" \
    "450870a0202f43292d370bd2644b51180f6afb01a5db8b10944c257331a6ab08ed8b8d2dbb8ce988f070"
#define PK_PAYLOAD1 "set alpha beta"
#define PK_PAYLOAD2 "ok"
#define PK_HEAD (PIC_NOISE_PUB + PIC_NOISE_PUB + 16 + 16) /* e, s, the early tag */

static void hex_is(const char *what, const unsigned char *b, size_t n, const char *want) {
    char got[4096];
    assert(2 * n < sizeof got);
    hexs(b, n, got);
    if (strcmp(got, want) != 0) {
        fprintf(stderr, "%s: got %s\n    want %s\n", what, got, want);
        exit(1);
    }
}

typedef struct {
    pic_noise_keypair hub, dev, pre;
    unsigned char ie[32], re[32], prologue[32], bind[128];
    size_t prologue_n, bind_n;
} pk_keys;

static void pk_setup(pk_keys *k, int prekey) {
    unsigned char b[32];
    seqkey(b, 0x01);
    assert(pic_noise_keypair_make(&k->hub, b) == 0);
    seqkey(b, 0x21);
    assert(pic_noise_keypair_make(&k->dev, b) == 0);
    seqkey(b, 0xd1);
    assert(pic_noise_keypair_make(&k->pre, b) == 0);
    hex_is("prekey public", k->pre.pub, PIC_NOISE_PUB, PK_PUB);
    seqkey(k->ie, 0x81);
    seqkey(k->re, 0xa1);
    k->prologue_n = unhex(prekey ? PK_PROLOGUE : PK_PLAIN_PROLOGUE, k->prologue);
    k->bind_n = unhex(PK_BIND, k->bind);
}

static void pk_init(const pk_keys *k, pic_noise_hs *I, pic_noise_hs *R) {
    if (I) {
        pic_noise_hs_init(I, 1, &k->dev, k->hub.pub, NULL, k->prologue, k->prologue_n);
        assert(pic_noise_hs_ephemeral(I, k->ie) == 0);
    }
    if (R) {
        pic_noise_hs_init(R, 0, &k->hub, NULL, NULL, k->prologue, k->prologue_n);
        assert(pic_noise_hs_ephemeral(R, k->re) == 0);
    }
}

/* The responder's two halves on MSG; 0 when both pass. */
static int pk_read(const pk_keys *k, const unsigned char *msg, size_t mn, const pic_noise_keypair *pre,
                   const unsigned char *bind, size_t bind_n, unsigned char *out, size_t cap, size_t *n) {
    pic_noise_hs R;
    size_t used = 0;
    int rc;
    pk_init(k, NULL, &R);
    if (pic_noise_read1_begin(&R, msg, mn, &used) != 0) {
        pic_noise_hs_wipe(&R);
        return -2;
    }
    assert(used == PK_HEAD && memcmp(R.rs, k->dev.pub, PIC_NOISE_PUB) == 0);
    rc = pic_noise_read1_finish(&R, msg + used, mn - used, pre, bind, bind_n, out, cap, n);
    pic_noise_hs_wipe(&R);
    return rc;
}

/* Both vectors, with and without a prekey: message 1, h after it, message 2 and the final h, in
 * both roles, each side reading the vector's bytes rather than its own. */
static void pk_vector(int prekey) {
    pk_keys k;
    pic_noise_hs I, R;
    unsigned char m[1024], vec[1024], pl[256];
    size_t mn, vn, n, used = 0;
    const pic_noise_keypair *pre;
    pk_setup(&k, prekey);
    pre = prekey ? &k.pre : NULL;
    pk_init(&k, &I, &R);
    assert(pic_noise_write1_prekey(&I, prekey ? k.pre.pub : NULL, prekey ? k.bind : NULL, prekey ? k.bind_n : 0,
                                   PK_PAYLOAD1, strlen(PK_PAYLOAD1), m, sizeof m, &mn) == 0);
    hex_is("prekey message 1", m, mn, prekey ? PK_M1 : PK_PLAIN_M1);
    hex_is("prekey h1, initiator", I.h, 32, prekey ? PK_H1 : PK_PLAIN_H1);
    vn = unhex(prekey ? PK_M1 : PK_PLAIN_M1, vec);
    assert(pic_noise_read1_begin(&R, vec, vn, &used) == 0 && used == PK_HEAD);
    assert(memcmp(R.rs, k.dev.pub, PIC_NOISE_PUB) == 0);
    assert(pic_noise_read1_finish(&R, vec + used, vn - used, pre, prekey ? k.bind : NULL, prekey ? k.bind_n : 0, pl,
                                  sizeof pl, &n) == 0);
    assert(n == strlen(PK_PAYLOAD1) && memcmp(pl, PK_PAYLOAD1, n) == 0);
    hex_is("prekey h1, responder", R.h, 32, prekey ? PK_H1 : PK_PLAIN_H1);
    /* message 2 is IK's, continuing from the mixed state */
    assert(pic_noise_write2(&R, PK_PAYLOAD2, strlen(PK_PAYLOAD2), m, sizeof m, &mn) == 0);
    hex_is("prekey message 2", m, mn, prekey ? PK_M2 : PK_PLAIN_M2);
    vn = unhex(prekey ? PK_M2 : PK_PLAIN_M2, vec);
    assert(pic_noise_read2(&I, vec, vn, pl, sizeof pl, &n) == 0);
    assert(n == strlen(PK_PAYLOAD2) && memcmp(pl, PK_PAYLOAD2, n) == 0);
    hex_is("prekey h2", I.h, 32, prekey ? PK_H2 : PK_PLAIN_H2);
    assert(memcmp(I.h, R.h, 32) == 0);
    pic_noise_hs_wipe(&I);
    pic_noise_hs_wipe(&R);
}

/* Without a prekey the new calls are IK as it is, plus the early tag: the head they write is,
 * byte for byte, what today's write1 writes for an empty payload, and read1 reads that head. */
static void pk_ik_equivalence(void) {
    pk_keys k;
    pic_noise_hs I, R;
    unsigned char a[1024], b[1024], pl[64];
    size_t an, bn, n;
    pk_setup(&k, 0);
    pk_init(&k, &I, NULL);
    assert(pic_noise_write1_prekey(&I, NULL, NULL, 0, PK_PAYLOAD1, strlen(PK_PAYLOAD1), a, sizeof a, &an) == 0);
    pk_init(&k, &I, NULL);
    assert(pic_noise_write1(&I, NULL, 0, b, sizeof b, &bn) == 0);
    assert(bn == PK_HEAD && an == PK_HEAD + strlen(PK_PAYLOAD1) + 16 && memcmp(a, b, bn) == 0);
    pk_init(&k, NULL, &R);
    assert(pic_noise_read1(&R, a, PK_HEAD, pl, sizeof pl, &n) == 0 && n == 0);
    assert(memcmp(R.rs, k.dev.pub, PIC_NOISE_PUB) == 0);
    pic_noise_hs_wipe(&I);
    pic_noise_hs_wipe(&R);
}

/* Each failure of the reference message: it must not read. */
static void pk_failures(void) {
    pk_keys k;
    pic_noise_keypair other;
    unsigned char m[1024], pl[256], b[32], bind[128];
    size_t mn, n;
    pk_setup(&k, 1);
    mn = unhex(PK_M1, m);
    assert(pk_read(&k, m, mn, &k.pre, k.bind, k.bind_n, pl, sizeof pl, &n) == 0);
    /* the wrong prekey */
    seqkey(b, 0xd2);
    assert(pic_noise_keypair_make(&other, b) == 0);
    assert(pk_read(&k, m, mn, &other, k.bind, k.bind_n, pl, sizeof pl, &n) == -1);
    /* no prekey at all */
    assert(pk_read(&k, m, mn, NULL, NULL, 0, pl, sizeof pl, &n) == -1);
    /* the wrong bind: one bit, and a byte short */
    memcpy(bind, k.bind, k.bind_n);
    bind[1] ^= 1;
    assert(pk_read(&k, m, mn, &k.pre, bind, k.bind_n, pl, sizeof pl, &n) == -1);
    assert(pk_read(&k, m, mn, &k.pre, k.bind, k.bind_n - 1, pl, sizeof pl, &n) == -1);
    /* one bit flipped anywhere: in the head begin refuses it, after it finish does */
    for (size_t i = 0; i < mn; i++) {
        m[i] ^= 0x01;
        assert(pk_read(&k, m, mn, &k.pre, k.bind, k.bind_n, pl, sizeof pl, &n) == (i < PK_HEAD ? -2 : -1));
        m[i] ^= 0x01;
    }
    /* the early tag alone */
    m[PK_HEAD - 1] ^= 0x80;
    assert(pk_read(&k, m, mn, &k.pre, k.bind, k.bind_n, pl, sizeof pl, &n) == -2);
    m[PK_HEAD - 1] ^= 0x80;
    /* truncated: no room for the tag, or for the payload's */
    assert(pk_read(&k, m, PK_HEAD - 1, &k.pre, k.bind, k.bind_n, pl, sizeof pl, &n) == -2);
    assert(pk_read(&k, m, PK_HEAD + 15, &k.pre, k.bind, k.bind_n, pl, sizeof pl, &n) == -1);
    assert(pk_read(&k, m, mn, &k.pre, k.bind, k.bind_n, pl, sizeof pl, &n) == 0);
    puts("ok prekey failures: wrong prekey, wrong bind, flipped bits, the early tag, truncation");
}

/* Someone holding the responder's static private key passes the early tag for any initiator key,
 * but without P's private key cannot make a payload that finishes. */
static void pk_forged(void) {
    pk_keys k;
    pic_noise_hs R;
    unsigned char m[1024], pl[256];
    size_t mn, n, used = 0;
    pk_setup(&k, 1);
    mn = unhex(PK_FORGED_M1, m);
    pk_init(&k, NULL, &R);
    assert(pic_noise_read1_begin(&R, m, mn, &used) == 0 && used == PK_HEAD);
    assert(memcmp(R.rs, k.dev.pub, PIC_NOISE_PUB) == 0);
    memset(pl, 0x5a, sizeof pl);
    assert(pic_noise_read1_finish(&R, m + used, mn - used, &k.pre, k.bind, k.bind_n, pl, sizeof pl, &n) == -1);
    for (size_t i = 0; i < strlen(PK_PAYLOAD1); i++) {
        assert(pl[i] == 0); /* nothing of a forged plaintext is left */
    }
    /* the state is unusable afterwards */
    assert(pic_noise_write2(&R, PK_PAYLOAD2, 2, m, sizeof m, &mn) == -1);
    pic_noise_hs_wipe(&R);
    puts("ok prekey forgery with the responder's key: begin passes, finish fails");
}

static int all_zero(const void *p, size_t n) {
    const unsigned char *c = p;
    while (n--) {
        if (*c++) {
            return 0;
        }
    }
    return 1;
}

/* A prekey that is not a usable point: refused before anything is written, the state wiped. */
static void pk_invalid_point(void) {
    pk_keys k;
    pic_noise_hs I;
    unsigned char bad[PIC_NOISE_PUB], m[1024];
    size_t mn = 0;
    pk_setup(&k, 1);
    for (int c = 0; c < 5; c++) {
        memcpy(bad, k.pre.pub, sizeof bad);
        switch (c) {
        case 0: bad[64] ^= 1; break;                 /* off the curve */
        case 1: memset(bad + 1, 0, 64); break;       /* (0, 0): infinity's usual stand-in */
        case 2: bad[0] = 0x02; break;                /* compressed form */
        case 3: memset(bad + 1, 0xff, 64); break;    /* coordinates past p */
        default: unhex(PK_ZERO_DH, bad); break;      /* on the curve, but DH(e, P) is all zeros */
        }
        assert(c == 4 || !pic_noise_pub_valid(bad));
        pk_init(&k, &I, NULL);
        assert(pic_noise_write1_prekey(&I, bad, k.bind, k.bind_n, PK_PAYLOAD1, strlen(PK_PAYLOAD1), m, sizeof m, &mn) ==
               -1);
        assert(all_zero(I.ck, 32) && all_zero(I.k, 32) && all_zero(&I.e, sizeof I.e) && all_zero(&I.s, sizeof I.s));
        assert(pic_noise_write1(&I, PK_PAYLOAD1, 3, m, sizeof m, &mn) == -1);
    }
    {
        unsigned char z[PIC_NOISE_PUB];
        unhex(PK_ZERO_DH, z);
        assert(pic_noise_pub_valid(z));
    }
    puts("ok prekey invalid points: off the curve, zero, compressed, out of range, all-zero DH");
}

/* Misuse: each wrong order returns -1 and leaves the state unusable and wiped. */
static void pk_misuse(void) {
    pk_keys k;
    pic_noise_hs I, R;
    unsigned char m[1024], pl[256];
    size_t mn, n, used = 0;
    pk_setup(&k, 1);
    mn = unhex(PK_M1, m);
    /* finish without begin */
    pk_init(&k, NULL, &R);
    assert(pic_noise_read1_finish(&R, m + PK_HEAD, mn - PK_HEAD, &k.pre, k.bind, k.bind_n, pl, sizeof pl, &n) == -1);
    assert(all_zero(&R.s, sizeof R.s) && pic_noise_read1_begin(&R, m, mn, &used) == -1);
    assert(pic_noise_read1(&R, m, mn, pl, sizeof pl, &n) == -1);
    /* finish without begin and without a prekey: there is no key yet, so this would read the bytes
     * as clear text if the order were not checked */
    pk_init(&k, NULL, &R);
    memset(pl, 0x5a, sizeof pl);
    assert(pic_noise_read1_finish(&R, m + PK_HEAD, mn - PK_HEAD, NULL, NULL, 0, pl, sizeof pl, &n) == -1);
    assert(pl[0] == 0x5a);
    /* begin twice */
    pk_init(&k, NULL, &R);
    assert(pic_noise_read1_begin(&R, m, mn, &used) == 0);
    assert(pic_noise_read1_begin(&R, m, mn, &used) == -1);
    assert(all_zero(R.ck, 32) && all_zero(R.k, 32));
    assert(pic_noise_read1_finish(&R, m + PK_HEAD, mn - PK_HEAD, &k.pre, k.bind, k.bind_n, pl, sizeof pl, &n) == -1);
    /* finish twice */
    pk_init(&k, NULL, &R);
    assert(pic_noise_read1_begin(&R, m, mn, &used) == 0);
    assert(pic_noise_read1_finish(&R, m + used, mn - used, &k.pre, k.bind, k.bind_n, pl, sizeof pl, &n) == 0);
    assert(pic_noise_read1_finish(&R, m + used, mn - used, &k.pre, k.bind, k.bind_n, pl, sizeof pl, &n) == -1);
    assert(pic_noise_write2(&R, PK_PAYLOAD2, 2, pl, sizeof pl, &n) == -1);
    /* between the halves nothing else runs: not message 2, not read1 */
    pk_init(&k, NULL, &R);
    assert(pic_noise_read1_begin(&R, m, mn, &used) == 0);
    assert(pic_noise_write2(&R, PK_PAYLOAD2, 2, pl, sizeof pl, &n) == -1);
    assert(pic_noise_read1(&R, m, mn, pl, sizeof pl, &n) == -1);
    assert(pic_noise_read1_finish(&R, m + used, mn - used, &k.pre, k.bind, k.bind_n, pl, sizeof pl, &n) == 0);
    /* the wrong role: an initiator cannot read, a responder cannot write */
    pk_init(&k, &I, &R);
    assert(pic_noise_read1_begin(&I, m, mn, &used) == -1);
    assert(pic_noise_write1_prekey(&R, k.pre.pub, k.bind, k.bind_n, "x", 1, pl, sizeof pl, &n) == -1);
    /* write twice */
    pk_init(&k, &I, NULL);
    assert(pic_noise_write1_prekey(&I, k.pre.pub, k.bind, k.bind_n, "x", 1, pl, sizeof pl, &n) == 0);
    assert(pic_noise_write1_prekey(&I, k.pre.pub, k.bind, k.bind_n, "x", 1, pl, sizeof pl, &n) == -1);
    /* a bind without a prekey, or a length without a bind */
    pk_init(&k, &I, &R);
    assert(pic_noise_write1_prekey(&I, NULL, k.bind, k.bind_n, "x", 1, pl, sizeof pl, &n) == -1);
    pk_init(&k, &I, &R);
    assert(pic_noise_write1_prekey(&I, k.pre.pub, NULL, 3, "x", 1, pl, sizeof pl, &n) == -1);
    assert(pic_noise_read1_begin(&R, m, mn, &used) == 0);
    assert(pic_noise_read1_finish(&R, m + used, mn - used, NULL, k.bind, k.bind_n, pl, sizeof pl, &n) == -1);
    pic_noise_hs_wipe(&I);
    pic_noise_hs_wipe(&R);
    puts("ok prekey misuse: finish without begin, begin twice, finish twice, wrong role, bind rules");
}

/* IK only: on a state started for IKpsk1 the new calls refuse, and the pairing path is unchanged. */
static void pk_psk_refused(void) {
    pk_keys k;
    pic_noise_hs I, R;
    unsigned char psk[32], m[1024], pl[256];
    size_t mn, n, used = 0;
    pk_setup(&k, 1);
    seqkey(psk, 0x07);
    pic_noise_hs_init(&I, 1, &k.dev, k.hub.pub, psk, k.prologue, k.prologue_n);
    assert(pic_noise_write1_prekey(&I, k.pre.pub, k.bind, k.bind_n, "x", 1, m, sizeof m, &mn) == -1);
    pic_noise_hs_init(&I, 1, &k.dev, k.hub.pub, psk, k.prologue, k.prologue_n);
    assert(pic_noise_write1_prekey(&I, NULL, NULL, 0, "x", 1, m, sizeof m, &mn) == -1);
    /* a pairing message 1 written as today still reads as today, and not through begin */
    pic_noise_hs_init(&I, 1, &k.dev, k.hub.pub, psk, k.prologue, k.prologue_n);
    assert(pic_noise_write1(&I, "x", 1, m, sizeof m, &mn) == 0);
    pic_noise_hs_init(&R, 0, &k.hub, NULL, psk, k.prologue, k.prologue_n);
    assert(pic_noise_read1_begin(&R, m, mn, &used) == -1);
    pic_noise_hs_init(&R, 0, &k.hub, NULL, psk, k.prologue, k.prologue_n);
    assert(pic_noise_read1_finish(&R, m, mn, NULL, NULL, 0, pl, sizeof pl, &n) == -1);
    pic_noise_hs_init(&R, 0, &k.hub, NULL, psk, k.prologue, k.prologue_n);
    assert(pic_noise_read1(&R, m, mn, pl, sizeof pl, &n) == 0 && n == 1 && pl[0] == 'x');
    /* a message that skips the psk but otherwise matches IKpsk1's head is refused at begin, so a
     * responder started for pairing never reads a message from someone without the psk */
    {
        pk_keys p;
        pk_setup(&p, 0);
        mn = unhex(PK_PSK_WITHOUT_PSK_M1, m);
        pic_noise_hs_init(&R, 0, &p.hub, NULL, psk, p.prologue, p.prologue_n);
        assert(pic_noise_read1_begin(&R, m, mn, &used) == -1);
        assert(pic_noise_read1_finish(&R, m + PK_HEAD, mn - PK_HEAD, NULL, NULL, 0, pl, sizeof pl, &n) == -1);
    }
    pic_noise_hs_wipe(&I);
    pic_noise_hs_wipe(&R);
    puts("ok prekey refused on IKpsk1");
}

/* Buffers sized exactly, on the heap so AddressSanitizer sees one byte past them: the writer's
 * message and the reader's plaintext; one byte less is refused. Also a payload of zero bytes. */
static void pk_exact_capacity(void) {
    pk_keys k;
    pic_noise_hs I, R;
    char p1[300];
    size_t lens[2] = {sizeof p1, 0};
    pk_setup(&k, 1);
    memset(p1, 'a', sizeof p1);
    for (int t = 0; t < 2; t++) {
        size_t len = lens[t], want = PK_HEAD + len + 16, mn = 0, n = 0, used = 0;
        unsigned char *m = malloc(want), *out = malloc(len ? len : 1);
        assert(m && out);
        pk_init(&k, &I, NULL);
        assert(pic_noise_write1_prekey(&I, k.pre.pub, k.bind, k.bind_n, p1, len, m, want - 1, &mn) == -1);
        pk_init(&k, &I, NULL);
        assert(pic_noise_write1_prekey(&I, k.pre.pub, k.bind, k.bind_n, p1, len, m, want, &mn) == 0 && mn == want);
        pk_init(&k, NULL, &R);
        assert(pic_noise_read1_begin(&R, m, mn, &used) == 0);
        if (len) {
            assert(pic_noise_read1_finish(&R, m + used, mn - used, &k.pre, k.bind, k.bind_n, out, len - 1, &n) == -1);
            pk_init(&k, NULL, &R);
            assert(pic_noise_read1_begin(&R, m, mn, &used) == 0);
        }
        assert(pic_noise_read1_finish(&R, m + used, mn - used, &k.pre, k.bind, k.bind_n, out, len, &n) == 0);
        assert(n == len && memcmp(out, p1, n) == 0);
        /* the message holds exactly begin's bytes: no read past it */
        {
            unsigned char *head = malloc(PK_HEAD);
            assert(head);
            memcpy(head, m, PK_HEAD);
            pk_init(&k, NULL, &R);
            assert(pic_noise_read1_begin(&R, head, PK_HEAD, &used) == 0 && used == PK_HEAD);
            free(head);
        }
        free(m);
        free(out);
    }
    {
        /* a payload length that would wrap the size check */
        unsigned char m[256];
        size_t mn;
        pk_init(&k, &I, NULL);
        assert(pic_noise_write1_prekey(&I, k.pre.pub, k.bind, k.bind_n, p1, (size_t)-8, m, sizeof m, &mn) == -1);
    }
    pic_noise_hs_wipe(&I);
    pic_noise_hs_wipe(&R);
    puts("ok prekey exact capacity");
}

static void test_prekey(void) {
    pk_vector(0);
    pk_vector(1);
    puts("ok prekey vectors: message 1, h, message 2, with and without a prekey");
    pk_ik_equivalence();
    puts("ok prekey IK equivalence: the head is today's write1 of an empty payload");
    pk_failures();
    pk_forged();
    pk_invalid_point();
    pk_misuse();
    pk_psk_refused();
    pk_exact_capacity();
}

/* The writers' buffers sized exactly, on the heap, and one byte short; a payload length that would
 * wrap the size check; and Split, which refuses until message 2 has passed and zeroes its keys. */
static void test_write_capacity(void) {
    pic_noise_keypair pic, phone;
    pic_noise_hs I, R;
    unsigned char picp[32], php[32], ie[32], re[32], pl[64], up[32], down[32], small[256];
    char p1[300], p2[200];
    size_t mn = 0, n, w1 = 2 * PIC_NOISE_PUB + 16 + sizeof p1 + 16, w2 = PIC_NOISE_PUB + sizeof p2 + 16;
    unsigned char *m1 = malloc(w1), *m2 = malloc(w2), *out = malloc(sizeof p1);
    assert(m1 && m2 && out);
    seqkey(picp, 0x41);
    seqkey(php, 0x61);
    seqkey(ie, 0x11);
    seqkey(re, 0x31);
    memset(p1, 'a', sizeof p1);
    memset(p2, 'b', sizeof p2);
    assert(pic_noise_keypair_make(&pic, picp) == 0 && pic_noise_keypair_make(&phone, php) == 0);
#define FRESH()                                                                                            \
    (pic_noise_hs_init(&I, 1, &phone, pic.pub, NULL, (const unsigned char *)"w", 1),                       \
     pic_noise_hs_init(&R, 0, &pic, NULL, NULL, (const unsigned char *)"w", 1),                            \
     assert(pic_noise_hs_ephemeral(&I, ie) == 0 && pic_noise_hs_ephemeral(&R, re) == 0))
    FRESH();
    assert(pic_noise_write1(&I, p1, (size_t)-8, small, sizeof small, &mn) == -1);
    assert(pic_noise_write1(&I, p1, sizeof p1, m1, w1 - 1, &mn) == -1);
    memset(up, 0xaa, sizeof up);
    memset(down, 0xaa, sizeof down);
    assert(pic_noise_split(&I, up, down) == -1 && all_zero(up, 32) && all_zero(down, 32));
    assert(pic_noise_write1(&I, p1, sizeof p1, m1, w1, &mn) == 0 && mn == w1);
    assert(pic_noise_read1(&R, m1, mn, out, sizeof p1, &n) == 0 && n == sizeof p1);
    memset(up, 0xaa, sizeof up);
    assert(pic_noise_split(&R, up, down) == -1 && all_zero(up, 32)); /* after message 1 only */
    assert(pic_noise_write2(&R, p2, (size_t)-8, small, sizeof small, &mn) == -1);
    assert(pic_noise_write2(&R, p2, sizeof p2, m2, w2 - 1, &mn) == -1);
    assert(pic_noise_write2(&R, p2, sizeof p2, m2, w2, &mn) == 0 && mn == w2);
    assert(pic_noise_read2(&I, m2, mn, pl, sizeof pl, &n) == -1); /* a reader's OUT too small */
    FRESH();
    assert(pic_noise_write1(&I, p1, sizeof p1, m1, w1, &mn) == 0 && pic_noise_read1(&R, m1, mn, out, sizeof p1, &n) == 0);
    assert(pic_noise_write2(&R, p2, sizeof p2, m2, w2, &mn) == 0 && pic_noise_read2(&I, m2, mn, out, sizeof p2, &n) == 0);
    {
        unsigned char up2[32], down2[32];
        assert(pic_noise_split(&I, up, down) == 0 && pic_noise_split(&R, up2, down2) == 0);
        assert(memcmp(up, up2, 32) == 0 && memcmp(down, down2, 32) == 0 && !all_zero(up, 32));
    }
    /* a state a refused prekey call wiped cannot be split */
    pic_noise_hs_init(&R, 0, &pic, NULL, NULL, (const unsigned char *)"w", 1);
    assert(pic_noise_read1_begin(&R, small, 1, &n) == -1 && pic_noise_split(&R, up, down) == -1);
#undef FRESH
    pic_noise_hs_wipe(&I);
    pic_noise_hs_wipe(&R);
    free(m1);
    free(m2);
    free(out);
    puts("ok writers' exact capacity, wrapping lengths, Split only after message 2");
}

static void test_pairing(void) {
    pic_noise_transport phone, pic;
    handshake("$.pairing", 1, &phone, &pic);
    transport_pair("$.pairing", "up0", &phone, &pic);
    transport_pair("$.pairing", "down0", &pic, &phone);
    puts("ok pairing handshake, code and first transport records");
}

static void test_session(void) {
    pic_noise_transport phone, pic;
    unsigned char rec[PIC_NOISE_RECORD_CAP], out[PIC_NOISE_CHUNK], d[32], sid[8], big[20000];
    size_t rn, n;
    int flag, gap;
    handshake("$.session", 0, &phone, &pic);
    transport_pair("$.session", "up0", &phone, &pic);
    transport_pair("$.session", "down0", &pic, &phone);
    /* n 7 down: the phone sees a gap */
    pic.send_n = 7;
    transport_pair("$.session", "down7", &pic, &phone);
    /* a 20000-byte message as two records, n 1 and 2 up */
    memset(big, 0x61, sizeof big);
    rn = pic_noise_record(&phone, 0, big, PIC_NOISE_CHUNK, rec);
    pic_noise_sha256(d, rec, rn, NULL, 0);
    same_hex("fragment 1", d, 32, "$.session.fragmented.sha256_of_records[0]");
    assert(pic_noise_open_record(&pic, rec, rn, &flag, out, &n, &gap) == 0 && flag == 0 && n == PIC_NOISE_CHUNK && !gap);
    {
        unsigned char rec2[PIC_NOISE_RECORD_CAP];
        size_t rn2 = pic_noise_record(&phone, 1, big + PIC_NOISE_CHUNK, sizeof big - PIC_NOISE_CHUNK, rec2);
        pic_noise_sha256(d, rec2, rn2, NULL, 0);
        same_hex("fragment 2", d, 32, "$.session.fragmented.sha256_of_records[1]");
        assert(pic_noise_open_record(&pic, rec2, rn2, &flag, out, &n, &gap) == 0 && flag == 1 &&
               n == sizeof big - PIC_NOISE_CHUNK && !gap);
        /* reordered: the older record after the newer is dropped */
        assert(pic_noise_open_record(&pic, rec, rn, &flag, out, &n, &gap) == -1);
    }
    /* a gap: n 4 after 2 */
    phone.send_n = 4;
    rn = pic_noise_record(&phone, 1, "{}", 2, rec);
    assert(pic_noise_open_record(&pic, rec, rn, &flag, out, &n, &gap) == 0 && gap == 1);
    /* one bit changed anywhere in a transport record: dropped, nothing changed */
    rn = pic_noise_record(&phone, 1, "{\"type\":\"ping\"}", 15, rec);
    for (size_t i = 0; i < rn; i++) {
        for (int b = 0; b < 8; b++) {
            int64_t was = pic.last;
            rec[i] ^= (unsigned char)(1u << b);
            assert(pic_noise_open_record(&pic, rec, rn, &flag, out, &n, &gap) == -1);
            assert(pic.last == was);
            rec[i] ^= (unsigned char)(1u << b);
        }
    }
    assert(pic_noise_open_record(&pic, rec, rn, &flag, out, &n, &gap) == 0);
    /* counters stop at 2^32, as the page's do: 2^32 - 1 is taken, 2^32 is dropped */
    phone.send_n = (1ull << 32) - 1;
    rn = pic_noise_record(&phone, 1, "{}", 2, rec);
    assert(pic_noise_open_record(&pic, rec, rn, &flag, out, &n, &gap) == 0);
    rn = pic_noise_record(&phone, 1, "{}", 2, rec);
    assert(pic_noise_open_record(&pic, rec, rn, &flag, out, &n, &gap) == -1);
    unhex(v("$.session.sid"), sid);
    rn = pic_noise_head(PIC_NOISE_REC_RESET, sid, NULL, 0, rec);
    same_hex("reset", rec, rn, "$.session.reset");
    puts("ok session handshake, transport counters, fragments, gaps and reset");
}

/* The refusals of section 8 for message 1: each leaves a fresh responder unable to read it. */
static void test_refusals(void) {
    unsigned char picp[32], prologue[64], psk[32], rec[2048], pl[512], bad[32];
    pic_noise_keypair pic;
    pic_noise_hs R;
    size_t pn, rn, n;
    seqkey(picp, 0x01);
    assert(pic_noise_keypair_make(&pic, picp) == 0);
    pn = unhex(v("$.pairing.prologue"), prologue);
    unhex(v("$.derive.psk"), psk);
    rn = unhex(v("$.pairing.record1"), rec);
    /* one bit changed anywhere in the Noise message */
    for (size_t i = 9; i < rn; i++) {
        rec[i] ^= 0x10;
        pic_noise_hs_init(&R, 0, &pic, NULL, psk, prologue, pn);
        assert(pic_noise_read1(&R, rec + 9, rn - 9, pl, sizeof pl, &n) == -1);
        rec[i] ^= 0x10;
    }
    /* the wrong psk */
    memcpy(bad, psk, 32);
    bad[31] ^= 1;
    pic_noise_hs_init(&R, 0, &pic, NULL, bad, prologue, pn);
    assert(pic_noise_read1(&R, rec + 9, rn - 9, pl, sizeof pl, &n) == -1);
    /* the wrong channel: another prologue */
    prologue[pn - 1] ^= 1;
    pic_noise_hs_init(&R, 0, &pic, NULL, psk, prologue, pn);
    assert(pic_noise_read1(&R, rec + 9, rn - 9, pl, sizeof pl, &n) == -1);
    prologue[pn - 1] ^= 1;
    /* an ephemeral key not on the curve */
    rec[9 + 64] ^= 1;
    {
        unsigned char k[65];
        memcpy(k, rec + 9, 65);
        assert(!pic_noise_pub_valid(k));
    }
    pic_noise_hs_init(&R, 0, &pic, NULL, psk, prologue, pn);
    assert(pic_noise_read1(&R, rec + 9, rn - 9, pl, sizeof pl, &n) == -1);
    rec[9 + 64] ^= 1;
    /* a session message 1 (no psk) is not a pairing message 1 */
    pic_noise_hs_init(&R, 0, &pic, NULL, NULL, prologue, pn);
    assert(pic_noise_read1(&R, rec + 9, rn - 9, pl, sizeof pl, &n) == -1);
    /* and the untouched record still reads */
    pic_noise_hs_init(&R, 0, &pic, NULL, psk, prologue, pn);
    assert(pic_noise_read1(&R, rec + 9, rn - 9, pl, sizeof pl, &n) == 0);
    /* an initiator whose static key is off the curve cannot even be written to */
    {
        unsigned char off[65];
        memcpy(off, pic.pub, 65);
        off[64] ^= 1;
        assert(!pic_noise_pub_valid(off));
    }
    puts("ok refusals: flipped bits, wrong psk, wrong channel, off-curve key, wrong protocol");
}

static void test_vapid(void) {
    unsigned char vp[32], sig[64];
    pic_noise_keypair k;
    char input[512], jwt[700], b64[100], pubs[100];
    seqkey(vp, 0x51);
    assert(pic_noise_keypair_make(&k, vp) == 0);
    pic_b64u_enc(k.pub, 65, pubs);
    assert(strcmp(pubs, v("$.vapid.public")) == 0);
    {
        char h[100], c[300];
        const char *head = v("$.vapid.header");
        pic_b64u_enc((const unsigned char *)head, strlen(head), h);
        (void)snprintf(input, sizeof input, "%s.", h);
        {
            const char *claims = v("$.vapid.claims");
            pic_b64u_enc((const unsigned char *)claims, strlen(claims), c);
        }
        (void)snprintf(input + strlen(input), sizeof input - strlen(input), "%s", c);
    }
    assert(pic_noise_es256(vp, input, sig) == 0);
    pic_b64u_enc(sig, 64, b64);
    (void)snprintf(jwt, sizeof jwt, "%s.%s", input, b64);
    assert(strcmp(jwt, v("$.vapid.jwt")) == 0);
    puts("ok VAPID token");
}

static void b64(const char *s, unsigned char *out, size_t want) {
    long n = pic_b64u_dec(s, strlen(s), out, 4096);
    assert(n == (long)want);
}

static void test_push(void) {
    unsigned char ua[32], as[32], salt[16], auth[16], body[4096], t[32];
    pic_noise_keypair uak, ask;
    char enc[8192], topic[64];
    const char *pt;
    size_t n;
    seqkey(ua, 0x71);
    seqkey(as, 0x91);
    unhex(v("$.push.salt"), salt);
    b64(v("$.push.auth"), auth, 16);
    assert(pic_noise_keypair_make(&uak, ua) == 0 && pic_noise_keypair_make(&ask, as) == 0);
    pt = v("$.push.plaintext");
    {
        char copy[512];
        (void)snprintf(copy, sizeof copy, "%s", pt);
        n = pic_noise_webpush(&ask, salt, uak.pub, auth, copy, strlen(copy), body);
    }
    assert(n > 0);
    pic_b64u_enc(body, n, enc);
    assert(strcmp(enc, v("$.push.body")) == 0);
    {
        static const char label[] = "pic-rc/1 topic";
        unsigned char in[64];
        memcpy(in, label, sizeof label); /* with its NUL: the 0x00 */
        memcpy(in + sizeof label, "w1/c1", 5);
        pic_noise_hmac(t, auth, 16, in, sizeof label + 5, NULL, 0);
        pic_b64u_enc(t, 16, topic);
        assert(strcmp(topic, v("$.push.topic")) == 0);
    }
    /* RFC 8291 appendix A */
    {
        unsigned char uap[32], asp[32], rsalt[16], rauth[16];
        const char *msg = "When I grow up, I want to be a watermelon";
        b64("q1dXpw3UpT5VOmu_cf_v6ih07Aems3njxI-JWgLcM94", uap, 32);
        b64("yfWPiYE-n46HLnH0KqZOF1fJJU3MYrct3AELtAQ-oRw", asp, 32);
        b64("DGv6ra1nlYgDCS1FRnbzlw", rsalt, 16);
        b64("BTBZMqHH6r4Tts7J_aSIgg", rauth, 16);
        assert(pic_noise_keypair_make(&uak, uap) == 0 && pic_noise_keypair_make(&ask, asp) == 0);
        n = pic_noise_webpush(&ask, rsalt, uak.pub, rauth, msg, strlen(msg), body);
        pic_b64u_enc(body, n, enc);
        assert(strcmp(enc, v("$.rfc8291_appendix_a.body")) == 0);
    }
    puts("ok Web Push body, topic and RFC 8291 appendix A");
}

static void test_b64u(void) {
    unsigned char out[8];
    assert(pic_b64u_dec("AQ", 2, out, sizeof out) == 1 && out[0] == 1);
    assert(pic_b64u_dec("AR", 2, out, sizeof out) == -1); /* nonzero leftover bits */
    assert(pic_b64u_dec("A", 1, out, sizeof out) == -1);
    assert(pic_b64u_dec("A+", 2, out, sizeof out) == -1);
    assert(pic_b64u_dec("AAAAAAAAAAAA", 12, out, sizeof out) == -1); /* 9 bytes in 8 */
    puts("ok base64url");
}

int main(int argc, char **argv) {
    test_exact_capacity();
    FILE *f;
    long n;
    assert(argc == 2);
    assert((f = fopen(argv[1], "rb")) != NULL);
    assert(fseek(f, 0, SEEK_END) == 0 && (n = ftell(f)) > 0 && fseek(f, 0, SEEK_SET) == 0);
    assert((doc = malloc((size_t)n + 1)) != NULL && fread(doc, 1, (size_t)n, f) == (size_t)n);
    doc[n] = '\0';
    fclose(f);
    assert(sqlite3_open(":memory:", &mem) == SQLITE_OK);
    test_file_hash(doc, (size_t)n);
    test_b64u();
    test_derive();
    test_pairing();
    test_session();
    test_refusals();
    test_prekey();
    test_write_capacity();
    test_vapid();
    test_push();
    sqlite3_close(mem);
    free(doc);
    puts("ok all remote vectors");
    return 0;
}