// RSW-0003 vectors: independent signature check with Go crypto/ed25519.
// Go 1.20+, standard library only. Run from this directory: go run verify.go
//
// crypto/ed25519 is a library verifier, not the RSW-0003 strict profile:
// it does not reject small-order public keys. The strict expectations live in
// ../expected.json; this program shows where the library agrees and where a
// strict reader needs its own checks.
package main

import (
	"archive/zip"
	"bytes"
	"crypto/ed25519"
	"encoding/base32"
	"encoding/binary"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"strings"
)

var prefix = []byte("RSW/1:cartridge-manifest\x00")

func entries(path string) map[string][]byte {
	png, err := os.ReadFile(path)
	must(err)
	var payload []byte
	for i := 8; i < len(png); {
		n := int(binary.BigEndian.Uint32(png[i:]))
		if string(png[i+4:i+8]) == "rsWT" {
			payload = png[i+8 : i+8+n]
		}
		i += 12 + n
	}
	zr, err := zip.NewReader(bytes.NewReader(payload), int64(len(payload)))
	must(err)
	out := map[string][]byte{}
	for _, f := range zr.File {
		rc, err := f.Open()
		must(err)
		var b bytes.Buffer
		_, err = b.ReadFrom(rc)
		must(err)
		rc.Close()
		out[f.Name] = b.Bytes()
	}
	return out
}

func keyOf(manifest []byte) []byte {
	var m struct {
		PublicKey string `json:"public_key"`
	}
	must(json.Unmarshal(manifest, &m))
	k, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(strings.TrimPrefix(m.PublicKey, "ed25519:"))
	must(err)
	return k
}

func must(err error) {
	if err != nil {
		panic(err)
	}
}

func readHex(path string) []byte {
	b, err := os.ReadFile(path)
	must(err)
	h, err := hex.DecodeString(strings.TrimSpace(strings.SplitN(string(b), "\n", 2)[0]))
	must(err)
	return h
}

func main() {
	base := ".."
	cart := func(name string) map[string][]byte { return entries(filepath.Join(base, "cartridges", name+".rsw.png")) }
	C, err := os.ReadFile(filepath.Join(base, "reference", "canonical-manifest.json"))
	must(err)
	M := append(append([]byte{}, prefix...), C...)
	seed := readHex(filepath.Join(base, "reference", "test-seed.hex"))
	priv := ed25519.NewKeyFromSeed(seed)
	pub := priv.Public().(ed25519.PublicKey)

	failures := 0
	check := func(cond bool, what string) {
		if cond {
			fmt.Println("ok   " + what)
		} else {
			fmt.Println("FAIL " + what)
			failures++
		}
	}

	p1 := cart("RSW-0003-exemplo")
	check(bytes.Equal(ed25519.Sign(priv, M), p1["signature.sig"]), "seed re-derives the p1 signature byte for byte")
	check(bytes.Equal(keyOf(p1["manifest.json"]), pub), "p1 public_key matches the test seed")
	check(ed25519.Verify(pub, M, p1["signature.sig"]), "p1 signature verifies over prefix || C")
	check(ed25519.Verify(pub, M, cart("p2-reformatted-manifest")["signature.sig"]), "p2 signature verifies over prefix || C (C from reference)")

	n1 := cart("n1-altered-manifest")
	check(!ed25519.Verify(pub, append(append([]byte{}, prefix...), n1["manifest.json"]...), n1["signature.sig"]), "n1 altered manifest rejected")
	check(!ed25519.Verify(pub, M, cart("n3-altered-signature")["signature.sig"]), "n3 altered signature rejected")
	check(!ed25519.Verify(pub, M, cart("n4-truncated-signature")["signature.sig"]), "n4 63-byte signature rejected")
	check(!ed25519.Verify(pub, M, cart("n8-wrong-domain")["signature.sig"]), "n8 wrong-domain signature rejected")

	n7 := ed25519.Verify(pub, M, cart("n7-s-out-of-range")["signature.sig"])
	fmt.Printf("info n7 (S + L): crypto/ed25519 returns %v; strict profile expects INVALID_SIGNATURE_ENCODING\n", n7)

	n5 := cart("n5-degenerate-key")
	n5ok := ed25519.Verify(keyOf(n5["manifest.json"]), append(append([]byte{}, prefix...), n5["manifest.json"]...), n5["signature.sig"])
	fmt.Printf("info n5 (identity key, R = identity, S = 0): crypto/ed25519 returns %v; strict profile expects INVALID_PUBLIC_KEY\n", n5ok)

	if failures > 0 {
		fmt.Printf("%d check(s) failed\n", failures)
		os.Exit(1)
	}
	fmt.Println("all signature checks passed")
}
