// kosa8 post-quantum checkpoint reference verifier.
//
// An independent re-implementation of the checkpoint format in kosa8 Labs
// Technical Report K8-TR-2026-01 v1.1, Appendix B. It uses only the Go
// standard library and Cloudflare CIRCL (ML-DSA-65, FIPS 204). It does not
// import any kosa8 code. Released for verification and review; see LICENSE
// terms in the report.
//
//	go run . vectors.json          verify the published vectors
//	go run . -demo vectors.json    also run eight tampering attempts and show each is caught
//
// Scope: format-3 audit entries without refs (the vectors), checkpoints in
// format kosa8.audit.pq-checkpoint/v1, Ed25519 classical keys. It checks the
// checkpoint layer only. Per-entry signatures and the HMAC chain are out of
// its scope (the HMAC key is never given to outside verifiers).
package main

import (
	"bytes"
	"crypto/ed25519"
	"crypto/rand"
	"crypto/sha256"
	"crypto/x509"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"os"
	"strconv"
	"time"

	"github.com/cloudflare/circl/sign/mldsa/mldsa65"
)

type Entry struct {
	Seq      int64           `json:"seq"`
	Time     time.Time       `json:"time"`
	Actor    string          `json:"actor"`
	Action   string          `json:"action"`
	Target   string          `json:"target,omitempty"`
	Detail   string          `json:"detail,omitempty"`
	Status   int             `json:"status,omitempty"`
	Format   int             `json:"format,omitempty"`
	Refs     json.RawMessage `json:"refs,omitempty"`
	PrevHash string          `json:"prev_hash"`
	Hash     string          `json:"hash"`
	Alg      string          `json:"alg,omitempty"`
	Kid      string          `json:"kid,omitempty"`
	Sig      string          `json:"sig,omitempty"`
}

type Sig struct {
	Alg string `json:"alg"`
	Kid string `json:"kid"`
	Sig string `json:"sig"`
}

type Checkpoint struct {
	Format    string    `json:"format"`
	Chain     string    `json:"chain"`
	From      int64     `json:"from"`
	FromHash  string    `json:"from_hash"`
	Seq       int64     `json:"seq"`
	Hash      string    `json:"hash"`
	Acc       string    `json:"acc"`
	Time      time.Time `json:"time"`
	Classical Sig       `json:"classical"`
	PQ        Sig       `json:"pq"`
}

type Key struct {
	Alg    string `json:"alg"`
	Kid    string `json:"kid"`
	Public string `json:"public"`
}

type Vectors struct {
	Chain         string       `json:"chain"`
	Entries       []Entry      `json:"entries"`
	Checkpoints   []Checkpoint `json:"checkpoints"`
	ClassicalKeys []Key        `json:"classical_keys"`
	PQKeys        []Key        `json:"pq_keys"`
}

// field is F(x): decimal length, ':', the bytes, '\n'.
func field(b *bytes.Buffer, x string) {
	b.WriteString(strconv.Itoa(len(x)))
	b.WriteByte(':')
	b.WriteString(x)
	b.WriteByte('\n')
}

const timeLayout = time.RFC3339Nano

// entryContent is the v3 HMAC input of an entry without refs.
func entryContent(e Entry) ([]byte, error) {
	if e.Format != 3 {
		return nil, fmt.Errorf("entry %d: format %d is outside this verifier's scope", e.Seq, e.Format)
	}
	if len(e.Refs) != 0 {
		return nil, fmt.Errorf("entry %d: refs are outside this verifier's scope", e.Seq)
	}
	var b bytes.Buffer
	b.WriteString("kosa8.audit/v3\n")
	field(&b, strconv.FormatInt(e.Seq, 10))
	field(&b, e.Time.UTC().Format(timeLayout))
	field(&b, e.Actor)
	field(&b, e.Action)
	field(&b, e.Target)
	field(&b, e.Detail)
	field(&b, strconv.Itoa(e.Status))
	field(&b, e.PrevHash)
	field(&b, "") // canonical refs: empty
	field(&b, e.Alg)
	field(&b, e.Kid)
	return b.Bytes(), nil
}

// leaf(e) = SHA-256("kosa8.audit.pq.leaf/v1\n" + F(format) + content + F(hash))
func leaf(e Entry) ([32]byte, error) {
	c, err := entryContent(e)
	if err != nil {
		return [32]byte{}, err
	}
	var b bytes.Buffer
	b.WriteString("kosa8.audit.pq.leaf/v1\n")
	field(&b, strconv.Itoa(e.Format))
	b.Write(c)
	field(&b, e.Hash)
	return sha256.Sum256(b.Bytes()), nil
}

// acc(From) = SHA-256("kosa8.audit.pq.acc/v1\n" + F(From) + F(FromHash))
func accStart(from int64, fromHash string) [32]byte {
	var b bytes.Buffer
	b.WriteString("kosa8.audit.pq.acc/v1\n")
	field(&b, strconv.FormatInt(from, 10))
	field(&b, fromHash)
	return sha256.Sum256(b.Bytes())
}

// message is what both signatures cover.
func (c Checkpoint) message() []byte {
	var b bytes.Buffer
	b.WriteString(c.Format + "\n")
	field(&b, c.Chain)
	field(&b, strconv.FormatInt(c.From, 10))
	field(&b, c.FromHash)
	field(&b, strconv.FormatInt(c.Seq, 10))
	field(&b, c.Hash)
	field(&b, c.Acc)
	field(&b, c.Time.UTC().Format(timeLayout))
	field(&b, c.Classical.Alg)
	field(&b, c.Classical.Kid)
	field(&b, c.PQ.Alg)
	field(&b, c.PQ.Kid)
	return b.Bytes()
}

const pqContext = "kosa8.audit" // FIPS 204 context string

func pqKey(k Key) (*mldsa65.PublicKey, error) {
	raw, err := base64.StdEncoding.DecodeString(k.Public)
	if err != nil || len(raw) != mldsa65.PublicKeySize {
		return nil, errors.New("ML-DSA-65 public key is not 1952 bytes of base64")
	}
	sum := sha256.Sum256(append([]byte("kosa8.mldsa65\n"), raw...))
	if "SHA256:"+hex.EncodeToString(sum[:]) != k.Kid {
		return nil, errors.New("ML-DSA-65 key id does not match the key")
	}
	pub := new(mldsa65.PublicKey)
	return pub, pub.UnmarshalBinary(raw)
}

func edKey(k Key) (ed25519.PublicKey, error) {
	der, err := base64.StdEncoding.DecodeString(k.Public)
	if err != nil {
		return nil, err
	}
	sum := sha256.Sum256(der)
	if "SHA256:"+hex.EncodeToString(sum[:]) != k.Kid {
		return nil, errors.New("classical key id does not match the key")
	}
	p, err := x509.ParsePKIXPublicKey(der)
	if err != nil {
		return nil, err
	}
	ed, ok := p.(ed25519.PublicKey)
	if !ok || k.Alg != "ed25519" {
		return nil, errors.New("only Ed25519 classical keys are in scope")
	}
	return ed, nil
}

// Verify checks every checkpoint against the entries and the pinned keys.
// It returns how many entries are covered.
func Verify(v Vectors) (int, error) {
	bySeq := map[int64]Entry{}
	for i, e := range v.Entries {
		if i > 0 && e.Seq != v.Entries[i-1].Seq+1 {
			return 0, fmt.Errorf("entry %d does not follow entry %d", e.Seq, v.Entries[i-1].Seq)
		}
		if i > 0 && e.PrevHash != v.Entries[i-1].Hash {
			return 0, fmt.Errorf("entry %d does not link to entry %d", e.Seq, v.Entries[i-1].Seq)
		}
		bySeq[e.Seq] = e
	}
	eds, pqs := map[string]ed25519.PublicKey{}, map[string]*mldsa65.PublicKey{}
	for _, k := range v.ClassicalKeys {
		p, err := edKey(k)
		if err != nil {
			return 0, err
		}
		eds[k.Kid] = p
	}
	for _, k := range v.PQKeys {
		p, err := pqKey(k)
		if err != nil {
			return 0, err
		}
		pqs[k.Kid] = p
	}
	covered := map[int64]bool{}
	for _, c := range v.Checkpoints {
		at := fmt.Sprintf("checkpoint of entries %d-%d", c.From+1, c.Seq)
		if c.Format != "kosa8.audit.pq-checkpoint/v1" {
			return 0, fmt.Errorf("%s: unknown format %q", at, c.Format)
		}
		if c.PQ.Alg != "ml-dsa-65" || c.PQ.Sig == "" || c.Classical.Sig == "" {
			return 0, fmt.Errorf("%s: missing one half of the hybrid signature", at)
		}
		msg := c.message()
		pp, ok := pqs[c.PQ.Kid]
		ps, _ := base64.StdEncoding.DecodeString(c.PQ.Sig)
		if !ok || len(ps) != mldsa65.SignatureSize || !mldsa65.Verify(pp, msg, []byte(pqContext), ps) {
			return 0, fmt.Errorf("%s: ML-DSA-65 signature does not verify under a pinned key", at)
		}
		cp, ok := eds[c.Classical.Kid]
		cs, _ := base64.StdEncoding.DecodeString(c.Classical.Sig)
		if !ok || !ed25519.Verify(cp, msg, cs) {
			return 0, fmt.Errorf("%s: Ed25519 signature does not verify under a pinned key", at)
		}
		if c.Chain != v.Chain {
			return 0, fmt.Errorf("%s: names chain %s, not %s", at, c.Chain, v.Chain)
		}
		acc := accStart(c.From, c.FromHash)
		for s := c.From + 1; s <= c.Seq; s++ {
			e, ok := bySeq[s]
			if !ok {
				return 0, fmt.Errorf("%s: entry %d is missing", at, s)
			}
			if s == c.From+1 && e.PrevHash != c.FromHash {
				return 0, fmt.Errorf("%s: starts from a different entry", at)
			}
			l, err := leaf(e)
			if err != nil {
				return 0, err
			}
			acc = sha256.Sum256(append(acc[:], l[:]...))
		}
		if bySeq[c.Seq].Hash != c.Hash {
			return 0, fmt.Errorf("%s: ends on a different entry", at)
		}
		if hex.EncodeToString(acc[:]) != c.Acc {
			return 0, fmt.Errorf("%s: accumulator does not match the entries", at)
		}
		for s := c.From + 1; s <= c.Seq; s++ {
			covered[s] = true
		}
	}
	return len(covered), nil
}

func clone(v Vectors) Vectors {
	b, _ := json.Marshal(v)
	var w Vectors
	_ = json.Unmarshal(b, &w)
	return w
}

// recomputeAcc is what a forger does after editing entries: refold the
// accumulator so the checkpoint's acc matches the forged log.
func recomputeAcc(v *Vectors) {
	c := &v.Checkpoints[0]
	acc := accStart(c.From, c.FromHash)
	for _, e := range v.Entries {
		if e.Seq > c.From && e.Seq <= c.Seq {
			l, _ := leaf(e)
			acc = sha256.Sum256(append(acc[:], l[:]...))
		}
	}
	c.Acc = hex.EncodeToString(acc[:])
}

func demos(v Vectors) []struct {
	name string
	v    Vectors
} {
	var out []struct {
		name string
		v    Vectors
	}
	add := func(name string, f func(*Vectors)) {
		w := clone(v)
		f(&w)
		out = append(out, struct {
			name string
			v    Vectors
		}{name, w})
	}
	add("edit an entry's content", func(w *Vectors) { w.Entries[4].Detail = "nothing happened" })
	add("delete an entry (and relink the next one)", func(w *Vectors) {
		w.Entries[5].PrevHash = w.Entries[3].Hash
		w.Entries = append(w.Entries[:4], w.Entries[5:]...)
		for i := 4; i < len(w.Entries); i++ {
			w.Entries[i].Seq--
		}
	})
	add("reorder two entries (renumber and relink)", func(w *Vectors) {
		w.Entries[2], w.Entries[3] = w.Entries[3], w.Entries[2]
		for i := range w.Entries {
			w.Entries[i].Seq = int64(i + 1)
			if i > 0 {
				w.Entries[i].PrevHash = w.Entries[i-1].Hash
			}
		}
	})
	add("truncate the tail", func(w *Vectors) { w.Entries = w.Entries[:len(w.Entries)-2] })
	add("strip the ML-DSA-65 half", func(w *Vectors) { w.Checkpoints[0].PQ.Sig = "" })
	add("replay the checkpoint onto another chain", func(w *Vectors) { w.Chain = "0123456789abcdef" })
	add("move the checkpoint to a shorter range", func(w *Vectors) {
		w.Checkpoints[0].Seq--
		w.Checkpoints[0].Hash = w.Entries[len(w.Entries)-2].Hash
	})
	// The quantum forger: can produce valid Ed25519 signatures under the
	// pinned classical key (modelled here by swapping in a key the forger
	// holds), edits an entry, refolds the accumulator and re-signs the
	// classical half. The ML-DSA-65 half no longer matches.
	add("quantum forger: edit, refold, re-sign the classical half", func(w *Vectors) {
		w.Entries[4].Detail = "nothing happened"
		recomputeAcc(w)
		pub, priv, _ := ed25519.GenerateKey(rand.Reader)
		der, _ := x509.MarshalPKIXPublicKey(pub)
		sum := sha256.Sum256(der)
		kid := "SHA256:" + hex.EncodeToString(sum[:])
		w.ClassicalKeys = []Key{{Alg: "ed25519", Kid: kid, Public: base64.StdEncoding.EncodeToString(der)}}
		c := &w.Checkpoints[0]
		c.Classical.Kid = kid
		c.Classical.Sig = base64.StdEncoding.EncodeToString(ed25519.Sign(priv, c.message()))
	})
	return out
}

func main() {
	demo := flag.Bool("demo", false, "also run tampering attempts")
	flag.Parse()
	if flag.NArg() != 1 {
		fmt.Fprintln(os.Stderr, "usage: go run . [-demo] vectors.json")
		os.Exit(2)
	}
	b, err := os.ReadFile(flag.Arg(0))
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(2)
	}
	var v Vectors
	if err := json.Unmarshal(b, &v); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(2)
	}
	n, err := Verify(v)
	if err != nil {
		fmt.Println("FAIL:", err)
		os.Exit(1)
	}
	fmt.Printf("OK: %d checkpoint(s), %d of %d entries covered, ML-DSA-65 and Ed25519 both verified\n",
		len(v.Checkpoints), n, len(v.Entries))
	if !*demo {
		return
	}
	bad := 0
	for _, d := range demos(v) {
		if _, err := Verify(d.v); err != nil {
			fmt.Printf("caught   %-58s %v\n", d.name+":", err)
		} else {
			fmt.Printf("MISSED   %s\n", d.name)
			bad++
		}
	}
	if bad > 0 {
		os.Exit(1)
	}
}
