Skip to content
go-libfossil Artifact [f789193111]
Login

Artifact [f789193111]

Artifact f789193111c0e12f252b1f5a5a62c545e437a6bd217132a5ddd8304fcaf20355:


package shun

import (
	"crypto/ed25519"
	"database/sql"
	"errors"
	"fmt"
	"sort"

	"github.com/danmestas/go-libfossil/db"
)

const erasuresSchema = `CREATE TABLE IF NOT EXISTS erasures(
  uuid TEXT NOT NULL,
  mtime INTEGER NOT NULL,
  scom TEXT NOT NULL,
  PRIMARY KEY(uuid, mtime, scom)
) WITHOUT ROWID`

// PinnedKey reads the repository's pinned erasure-key setting, returning
// (nil, false, nil) when absent or malformed.
func PinnedKey(q db.Querier) (ed25519.PublicKey, bool, error) {
	if q == nil {
		panic("shun.PinnedKey: q must not be nil")
	}
	var value sql.NullString
	err := q.QueryRow("SELECT value FROM config WHERE name=?", SettingErasureKey).Scan(&value)
	if errors.Is(err, sql.ErrNoRows) {
		return nil, false, nil
	}
	if err != nil {
		return nil, false, fmt.Errorf("shun.PinnedKey: %w", err)
	}
	if !value.Valid {
		return nil, false, nil
	}
	pub, err := ParsePublicKey(value.String)
	if err != nil {
		return nil, false, nil
	}
	return pub, true, nil
}

// SetPinnedKey stores pub in the repository's erasure-key config setting.
func SetPinnedKey(q db.Querier, pub ed25519.PublicKey, mtime int64) error {
	if q == nil {
		panic("shun.SetPinnedKey: q must not be nil")
	}
	if len(pub) != ed25519.PublicKeySize {
		return fmt.Errorf("%w: length %d", ErrBadErasureKey, len(pub))
	}
	_, err := q.Exec(
		"REPLACE INTO config(name, value, mtime) VALUES(?, ?, ?)",
		SettingErasureKey, FormatPublicKey(pub), mtime,
	)
	return err
}

func hasErasuresTable(q db.Querier) (bool, error) {
	var n int
	err := q.QueryRow(
		"SELECT count(*) FROM sqlite_master WHERE type='table' AND name='erasures'",
	).Scan(&n)
	if err != nil {
		return false, fmt.Errorf("shun.hasErasuresTable: %w", err)
	}
	return n > 0, nil
}

// RecordSigned persists one syntactically valid signed erasure row in the
// repository's erasures table (lazily created on first write).
func RecordSigned(q db.Querier, row Row) (bool, error) {
	if q == nil {
		panic("shun.RecordSigned: q must not be nil")
	}
	if !isLowerHash(row.UUID) || row.MTime < 0 {
		return false, fmt.Errorf("%w: row %q @ %d", ErrBadErasureInput, row.UUID, row.MTime)
	}
	if form, _ := Classify(row.Comment); form != FormSigned {
		return false, fmt.Errorf("%w: not a signed erasure statement", ErrBadErasureInput)
	}
	if _, err := q.Exec(erasuresSchema); err != nil {
		return false, fmt.Errorf("shun.RecordSigned schema: %w", err)
	}
	res, err := q.Exec(
		"INSERT OR IGNORE INTO erasures(uuid, mtime, scom) VALUES(?, ?, ?)",
		row.UUID, row.MTime, row.Comment,
	)
	if err != nil {
		return false, fmt.Errorf("shun.RecordSigned insert: %w", err)
	}
	n, _ := res.RowsAffected()
	return n > 0, nil
}

// ListSigned returns all stored signed erasure rows, or nil when the erasures
// table does not exist.
func ListSigned(q db.Querier) ([]Row, error) {
	if q == nil {
		panic("shun.ListSigned: q must not be nil")
	}
	ok, err := hasErasuresTable(q)
	if err != nil || !ok {
		return nil, err
	}
	rows, err := q.Query(
		"SELECT uuid, CAST(mtime AS INTEGER), scom FROM erasures ORDER BY mtime ASC, uuid ASC, scom ASC",
	)
	if err != nil {
		return nil, fmt.Errorf("shun.ListSigned: %w", err)
	}
	defer rows.Close()
	var out []Row
	for rows.Next() {
		var r Row
		if err := rows.Scan(&r.UUID, &r.MTime, &r.Comment); err != nil {
			return nil, fmt.Errorf("shun.ListSigned scan: %w", err)
		}
		out = append(out, r)
	}
	return out, rows.Err()
}

// ListVerifiedSigned returns all stored signed rows that verify against the
// repository's pinned erasure-key and projectCode.
func ListVerifiedSigned(q db.Querier, projectCode string) ([]Row, error) {
	pub, ok, err := PinnedKey(q)
	if err != nil || !ok {
		return nil, err
	}
	all, err := ListSigned(q)
	if err != nil || len(all) == 0 {
		return nil, err
	}
	var out []Row
	for _, row := range all {
		if v, _ := Judge(pub, projectCode, row); v == VerdictVerified {
			out = append(out, row)
		}
	}
	return out, nil
}

type judgedRow struct {
	row Row
	st  Statement
}

// FoldRows computes the §9.3.1 folded status of every UUID appearing in rows
// against pub, projectCode, and nowUnix.
func FoldRows(
	pub ed25519.PublicKey, projectCode string, rows []Row, nowUnix int64,
) map[string]FoldResult {
	byUUID := make(map[string][]Row)
	for _, r := range rows {
		byUUID[r.UUID] = append(byUUID[r.UUID], r)
	}
	out := make(map[string]FoldResult, len(byUUID))
	for uuid, group := range byUUID {
		out[uuid] = foldUUID(pub, projectCode, group, nowUnix)
	}
	return out
}

func foldUUID(pub ed25519.PublicKey, projectCode string, group []Row, nowUnix int64) FoldResult {
	var hasPlain, hasApplied bool
	var verified []judgedRow
	for _, r := range group {
		v, st := Judge(pub, projectCode, r)
		switch v {
		case VerdictPlain:
			if r.Comment == AppliedReason {
				hasApplied = true
			} else {
				hasPlain = true
			}
		case VerdictVerified:
			verified = append(verified, judgedRow{row: r, st: st})
		}
	}
	if hasPlain {
		return FoldResult{Status: StatusShunned}
	}
	if hasApplied {
		return FoldResult{Status: StatusErased}
	}
	winner, ok := newestVerified(verified, false, 0)
	if !ok {
		return FoldResult{Status: StatusInert}
	}
	erase := winner
	if winner.st.Kind == KindCancel {
		before, ok := newestVerified(verified, true, winner.row.MTime)
		if !ok || winner.row.MTime < before.st.NotBefore {
			return FoldResult{Status: StatusInert}
		}
		erase = before
	}
	if nowUnix >= erase.st.NotBefore {
		return FoldResult{Status: StatusErased, NotBefore: erase.st.NotBefore}
	}
	return FoldResult{Status: StatusPending, NotBefore: erase.st.NotBefore}
}

// newestVerified mirrors zit's logstore.newestVerified: highest mtime wins;
// ties break in favor of erase over cancel, then earlier not-before. When
// erasesBefore is true, only erase rows strictly older than limitMTime qualify.
func newestVerified(rows []judgedRow, erasesBefore bool, limitMTime int64) (judgedRow, bool) {
	var best judgedRow
	found := false
	for _, cur := range rows {
		if erasesBefore && (cur.st.Kind != KindErase || cur.row.MTime >= limitMTime) {
			continue
		}
		if !found || newerJudged(cur, best) {
			best, found = cur, true
		}
	}
	return best, found
}

func newerJudged(a, b judgedRow) bool {
	if a.row.MTime != b.row.MTime {
		return a.row.MTime > b.row.MTime
	}
	if a.st.Kind != b.st.Kind {
		return a.st.Kind == KindErase
	}
	return a.st.NotBefore < b.st.NotBefore
}

// ApplyDue folds stored signed erasures at nowUnix and records a plain
// "erasure applied" row in the shun table for each UUID whose erasure has
// taken effect (§9.3.1). Returns the newly applied UUIDs, sorted.
func ApplyDue(q db.Querier, projectCode string, nowUnix int64) ([]string, error) {
	if q == nil {
		panic("shun.ApplyDue: q must not be nil")
	}
	pub, ok, err := PinnedKey(q)
	if err != nil || !ok {
		return nil, err
	}
	signed, err := ListSigned(q)
	if err != nil || len(signed) == 0 {
		return nil, err
	}
	plainEntries, err := List(q)
	if err != nil {
		return nil, err
	}
	existing := make(map[string]bool, len(plainEntries))
	all := make([]Row, 0, len(plainEntries)+len(signed))
	for _, e := range plainEntries {
		existing[e.UUID] = true
		all = append(all, Row{UUID: e.UUID, MTime: e.MTime, Comment: e.Comment})
	}
	all = append(all, signed...)
	folded := FoldRows(pub, projectCode, all, nowUnix)
	var applied []string
	for uuid, res := range folded {
		if res.Status != StatusErased || existing[uuid] {
			continue
		}
		if _, err := q.Exec(
			"INSERT OR IGNORE INTO shun(uuid, mtime, scom) VALUES(?, ?, ?)",
			uuid, nowUnix, AppliedReason,
		); err != nil {
			return nil, fmt.Errorf("shun.ApplyDue insert %s: %w", uuid, err)
		}
		applied = append(applied, uuid)
	}
	sort.Strings(applied)
	return applied, nil
}