Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

digest.gno

package rulecalc

import (
	"crypto/sha256"
	"encoding/hex"
	"strings"
)

// App is one grant application. Its ID is its index in the revealed list.
type App struct {
	Title   string
	PkgPath string
	Payout  address
}

// AppsDigest is the commitment to an application list, published before the
// rule phase and checked at reveal: hex(sha256) of one "Title|PkgPath|Payout\n"
// line per app, in order, followed by salt.
// It panics if a field contains "|" or a newline, or the salt contains a
// newline, since the same digest could then open to a different list.
//
// Off-chain equivalent:
//
//	printf 'Title|PkgPath|Payout\n...salt' | sha256sum
func AppsDigest(apps []App, salt string) string {
	if strings.Contains(salt, "\n") {
		panic("rulecalc: salt contains newline")
	}
	var b strings.Builder
	for _, a := range apps {
		fields := []string{a.Title, a.PkgPath, string(a.Payout)}
		for _, f := range fields {
			if strings.ContainsAny(f, "|\n") {
				panic("rulecalc: application field contains | or newline")
			}
		}
		b.WriteString(strings.Join(fields, "|"))
		b.WriteString("\n")
	}
	b.WriteString(salt)
	sum := sha256.Sum256([]byte(b.String()))
	return hex.EncodeToString(sum[:])
}

digest_test.gno

package rulecalc

import "testing"

func apps2() []App {
	return []App{
		{Title: "Alpha", PkgPath: "gno.land/r/x/alpha", Payout: address("g1alpha")},
		{Title: "Beta", PkgPath: "gno.land/r/x/beta", Payout: address("g1beta")},
	}
}

func TestAppsDigestStable(t *testing.T) {
	a := AppsDigest(apps2(), "salt")
	b := AppsDigest(apps2(), "salt")
	if a != b {
		t.Fatal("same input, different digest")
	}
	if len(a) != 64 {
		t.Fatalf("want 64 hex chars, got %d", len(a))
	}
}

func TestAppsDigestKnownVector(t *testing.T) {
	// sha256("Alpha|gno.land/r/x/alpha|g1alpha\nBeta|gno.land/r/x/beta|g1beta\nsalt")
	// computed independently: printf 'Alpha|...\nBeta|...\nsalt' | sha256sum
	want := "451fc91dfae0103fc7f9a91c168aa15c290f0bbe7217e9acfc900c32ababe09a"
	if got := AppsDigest(apps2(), "salt"); got != want {
		t.Fatalf("digest mismatch: got %s", got)
	}
}

func TestAppsDigestSensitive(t *testing.T) {
	base := AppsDigest(apps2(), "salt")

	swapped := apps2()
	swapped[0], swapped[1] = swapped[1], swapped[0]
	if AppsDigest(swapped, "salt") == base {
		t.Error("order change not detected")
	}

	payout := apps2()
	payout[1].Payout = address("g1other")
	if AppsDigest(payout, "salt") == base {
		t.Error("payout change not detected")
	}

	if AppsDigest(apps2(), "pepper") == base {
		t.Error("salt change not detected")
	}
}

func TestAppsDigestRejectsSeparators(t *testing.T) {
	bad := [][]App{
		{{Title: "A|B", PkgPath: "p", Payout: address("g1")}},
		{{Title: "A", PkgPath: "p\nq", Payout: address("g1")}},
		{{Title: "A", PkgPath: "p", Payout: address("g1|x")}},
	}
	for i, apps := range bad {
		func() {
			defer func() {
				if recover() == nil {
					t.Errorf("case %d: expected panic", i)
				}
			}()
			AppsDigest(apps, "salt")
		}()
	}
}

// A salt holding application lines would let the same digest open to a shorter
// list: [A, B]+salt and [A]+"B|...\nsalt" hash the same bytes.
func TestAppsDigestRejectsSaltHidingApps(t *testing.T) {
	full := AppsDigest(apps2(), "salt")
	defer func() {
		if recover() == nil {
			t.Error("expected panic for a salt with a newline")
		}
	}()
	got := AppsDigest(apps2()[:1], "Beta|gno.land/r/x/beta|g1beta\nsalt")
	if got == full {
		t.Error("the same digest opens to a shorter application list")
	}
}

gnomod.toml

module = "gno.land/p/g1dxg6leh2vsde83qxcpprvj2xljqz6fg2jp2t08/rulecalc/v1"
gno = "0.9"

[addpkg]
  creator = "g1dxg6leh2vsde83qxcpprvj2xljqz6fg2jp2t08"
  height = 1363233
  max_deposit = "20000000ugnot"

rule.gno

// Package rulecalc holds the evaluation rule schema for a grant round and the
// deterministic computation of its outcome. It has no state and moves no coins.
package rulecalc

import (
	"errors"
	"strconv"
)

// Method is how evaluator score sheets are aggregated into a winner.
type Method int

const (
	// WeightedSum: the winner has the highest sum of weight*score over all sheets.
	WeightedSum Method = iota + 1
	// MajorityFirst: each sheet's first place is its highest weighted app;
	// the winner has the most first places.
	MajorityFirst
)

// TieBreak decides a top-level tie.
type TieBreak int

const (
	// LowestID: the tied app with the lowest ID wins.
	LowestID TieBreak = iota + 1
	// Refund: no winner; the grant returns to the customer.
	Refund
)

const (
	MinCriteria = 1
	MaxCriteria = 4
	MinWeight   = 1
	MaxWeight   = 10
	MinScore    = 0
	MaxScore    = 10
)

// Criterion is one named, weighted evaluation axis.
type Criterion struct {
	Name   string
	Weight int
}

// Rule is the procedure the evaluators agree on before applications are revealed.
// Rationale is shown to readers and never affects computation.
type Rule struct {
	Method    Method
	Criteria  []Criterion
	Quorum    int
	Tie       TieBreak
	Rationale string
}

// Validate checks the rule against the schema for a round with nEvaluators joined evaluators.
func (r Rule) Validate(nEvaluators int) error {
	if r.Method != WeightedSum && r.Method != MajorityFirst {
		return errors.New("rulecalc: unknown method " + strconv.Itoa(int(r.Method)))
	}
	if r.Tie != LowestID && r.Tie != Refund {
		return errors.New("rulecalc: unknown tie-break " + strconv.Itoa(int(r.Tie)))
	}
	n := len(r.Criteria)
	if n < MinCriteria || n > MaxCriteria {
		return errors.New("rulecalc: need 1-4 criteria, got " + strconv.Itoa(n))
	}
	seen := map[string]bool{}
	for _, c := range r.Criteria {
		if c.Name == "" {
			return errors.New("rulecalc: criterion name is empty")
		}
		if seen[c.Name] {
			return errors.New("rulecalc: duplicate criterion " + c.Name)
		}
		seen[c.Name] = true
		if c.Weight < MinWeight || c.Weight > MaxWeight {
			return errors.New("rulecalc: weight of " + c.Name + " must be 1-10")
		}
	}
	if r.Quorum < 1 || r.Quorum > nEvaluators {
		return errors.New("rulecalc: quorum must be between 1 and " + strconv.Itoa(nEvaluators))
	}
	return nil
}

rule_test.gno

package rulecalc

import "testing"

func validRule() Rule {
	return Rule{
		Method:   WeightedSum,
		Criteria: []Criterion{{Name: "security", Weight: 3}},
		Quorum:   2,
		Tie:      LowestID,
	}
}

func TestValidateOK(t *testing.T) {
	if err := validRule().Validate(3); err != nil {
		t.Fatalf("valid rule rejected: %v", err)
	}
	r := validRule()
	r.Method = MajorityFirst
	r.Tie = Refund
	r.Criteria = []Criterion{{"a", 1}, {"b", 10}, {"c", 5}, {"d", 2}}
	r.Quorum = 3
	if err := r.Validate(3); err != nil {
		t.Fatalf("valid rule (4 criteria, quorum == evaluators) rejected: %v", err)
	}
}

func TestValidateRejects(t *testing.T) {
	cases := []struct {
		name string
		mod  func(r *Rule)
	}{
		{"no criteria", func(r *Rule) { r.Criteria = nil }},
		{"five criteria", func(r *Rule) {
			r.Criteria = []Criterion{{"a", 1}, {"b", 1}, {"c", 1}, {"d", 1}, {"e", 1}}
		}},
		{"weight 0", func(r *Rule) { r.Criteria = []Criterion{{"a", 0}} }},
		{"weight 11", func(r *Rule) { r.Criteria = []Criterion{{"a", 11}} }},
		{"empty name", func(r *Rule) { r.Criteria = []Criterion{{"", 1}} }},
		{"duplicate name", func(r *Rule) { r.Criteria = []Criterion{{"a", 1}, {"a", 2}} }},
		{"quorum 0", func(r *Rule) { r.Quorum = 0 }},
		{"quorum above evaluators", func(r *Rule) { r.Quorum = 4 }},
		{"unknown method", func(r *Rule) { r.Method = Method(0) }},
		{"unknown method high", func(r *Rule) { r.Method = Method(3) }},
		{"unknown tie", func(r *Rule) { r.Tie = TieBreak(0) }},
		{"unknown tie high", func(r *Rule) { r.Tie = TieBreak(3) }},
	}
	for _, c := range cases {
		r := validRule()
		c.mod(&r)
		if err := r.Validate(3); err == nil {
			t.Errorf("%s: expected error, got nil", c.name)
		}
	}
}

tally.gno

package rulecalc

import (
	"errors"
	"strconv"
)

// Sheet is one evaluator's scores: Scores[app][criterion], apps ordered by ID 0..n-1,
// criteria in the order of Rule.Criteria.
type Sheet struct {
	Evaluator address
	Scores    [][]int
}

// ValidateSheet checks that s scores every app on every criterion within 0-10.
func ValidateSheet(r Rule, nApps int, s Sheet) error {
	if len(s.Scores) != nApps {
		return errors.New("rulecalc: sheet must score " + strconv.Itoa(nApps) + " apps")
	}
	for i, row := range s.Scores {
		if len(row) != len(r.Criteria) {
			return errors.New("rulecalc: app " + strconv.Itoa(i) + " needs " + strconv.Itoa(len(r.Criteria)) + " scores")
		}
		for _, v := range row {
			if v < MinScore || v > MaxScore {
				return errors.New("rulecalc: score out of range 0-10 for app " + strconv.Itoa(i))
			}
		}
	}
	return nil
}

func weighted(r Rule, row []int) int {
	sum := 0
	for c, v := range row {
		sum += r.Criteria[c].Weight * v
	}
	return sum
}

// argmax returns the lowest index holding the maximum and whether that maximum is shared.
func argmax(xs []int) (best int, tied bool) {
	for i := 1; i < len(xs); i++ {
		if xs[i] > xs[best] {
			best = i
			tied = false
		} else if xs[i] == xs[best] {
			tied = true
		}
	}
	return best, tied
}

// Totals returns the per-app figure the rule's method ranks by:
// weighted score sums for WeightedSum, first-place counts for MajorityFirst.
// Sheets must already pass ValidateSheet.
func Totals(r Rule, nApps int, sheets []Sheet) []int {
	tot := make([]int, nApps)
	for _, s := range sheets {
		switch r.Method {
		case WeightedSum:
			for app, row := range s.Scores {
				tot[app] += weighted(r, row)
			}
		case MajorityFirst:
			per := make([]int, nApps)
			for app, row := range s.Scores {
				per[app] = weighted(r, row)
			}
			first, _ := argmax(per) // in-sheet tie -> lowest ID
			tot[first]++
		}
	}
	return tot
}

// Compute returns the winning app ID. paid == false means the grant is refunded:
// no apps, fewer sheets than the quorum, or a top-level tie under the Refund tie-break.
// Sheets must already pass ValidateSheet.
func Compute(r Rule, nApps int, sheets []Sheet) (winner int, paid bool) {
	if nApps < 1 || len(sheets) < r.Quorum {
		return 0, false
	}
	best, tied := argmax(Totals(r, nApps, sheets))
	if tied && r.Tie == Refund {
		return 0, false
	}
	return best, true
}

tally_test.gno

package rulecalc

import "testing"

// two criteria, weights 3 and 1
func ws(tie TieBreak, quorum int) Rule {
	return Rule{Method: WeightedSum, Criteria: []Criterion{{"a", 3}, {"b", 1}}, Quorum: quorum, Tie: tie}
}

func sheet(ev string, scores ...[]int) Sheet {
	return Sheet{Evaluator: address(ev), Scores: scores}
}

func TestComputeWeightedSum(t *testing.T) {
	// app0: 3*5+1*5=20 and 3*4+1*0=12 -> 32 ; app1: 3*6+1*0=18 and 3*6+1*2=20 -> 38
	sheets := []Sheet{
		sheet("e1", []int{5, 5}, []int{6, 0}),
		sheet("e2", []int{4, 0}, []int{6, 2}),
	}
	w, paid := Compute(ws(LowestID, 2), 2, sheets)
	if !paid || w != 1 {
		t.Fatalf("want winner 1 paid, got %d %v", w, paid)
	}
	tot := Totals(ws(LowestID, 2), 2, sheets)
	if len(tot) != 2 || tot[0] != 32 || tot[1] != 38 {
		t.Fatalf("totals: want [32 38], got %v", tot)
	}
}

func TestComputeMajorityFirst(t *testing.T) {
	r := ws(LowestID, 3)
	r.Method = MajorityFirst
	// sheet firsts: e1 -> 0, e2 -> 1, e3 -> 1. Weighted sums would favor 0 heavily.
	sheets := []Sheet{
		sheet("e1", []int{10, 10}, []int{0, 0}),
		sheet("e2", []int{5, 0}, []int{6, 0}),
		sheet("e3", []int{5, 0}, []int{6, 0}),
	}
	w, paid := Compute(r, 2, sheets)
	if !paid || w != 1 {
		t.Fatalf("want winner 1 paid, got %d %v", w, paid)
	}
	tot := Totals(r, 2, sheets)
	if tot[0] != 1 || tot[1] != 2 {
		t.Fatalf("first-place counts: want [1 2], got %v", tot)
	}
}

func TestComputeMajorityFirstInSheetTieLowestID(t *testing.T) {
	r := ws(LowestID, 1)
	r.Method = MajorityFirst
	// in-sheet tie between app0 and app1 -> first place is app0
	w, paid := Compute(r, 2, []Sheet{sheet("e1", []int{2, 2}, []int{2, 2})})
	if !paid || w != 0 {
		t.Fatalf("want winner 0 paid, got %d %v", w, paid)
	}
}

func TestComputeTieLowestID(t *testing.T) {
	sheets := []Sheet{sheet("e1", []int{2, 0}, []int{1, 3})} // 6 vs 6
	w, paid := Compute(ws(LowestID, 1), 2, sheets)
	if !paid || w != 0 {
		t.Fatalf("want winner 0 paid, got %d %v", w, paid)
	}
}

func TestComputeTieRefund(t *testing.T) {
	sheets := []Sheet{sheet("e1", []int{2, 0}, []int{1, 3})} // 6 vs 6
	_, paid := Compute(ws(Refund, 1), 2, sheets)
	if paid {
		t.Fatal("tie with Refund must not pay")
	}
}

func TestComputeQuorum(t *testing.T) {
	sheets := []Sheet{
		sheet("e1", []int{5, 5}, []int{6, 0}),
		sheet("e2", []int{4, 0}, []int{6, 2}),
	}
	_, paid := Compute(ws(LowestID, 3), 2, sheets)
	if paid {
		t.Fatal("below quorum must not pay")
	}
}

func TestComputeNoSheets(t *testing.T) {
	_, paid := Compute(ws(LowestID, 1), 2, nil)
	if paid {
		t.Fatal("no sheets must not pay")
	}
}

func TestComputeNoApps(t *testing.T) {
	_, paid := Compute(ws(LowestID, 1), 0, []Sheet{sheet("e1")})
	if paid {
		t.Fatal("no apps must not pay")
	}
}

func TestValidateSheet(t *testing.T) {
	r := ws(LowestID, 1)
	if err := ValidateSheet(r, 2, sheet("e1", []int{0, 10}, []int{10, 0})); err != nil {
		t.Fatalf("valid sheet rejected: %v", err)
	}
	bad := []Sheet{
		sheet("e1", []int{11, 0}, []int{0, 0}),           // score 11
		sheet("e1", []int{-1, 0}, []int{0, 0}),           // score -1
		sheet("e1", []int{1, 1}),                         // too few apps
		sheet("e1", []int{1, 1}, []int{1, 1}, []int{1, 1}), // too many apps
		sheet("e1", []int{1}, []int{1, 1}),               // too few criteria
		sheet("e1", []int{1, 1, 1}, []int{1, 1}),         // too many criteria
	}
	for i, s := range bad {
		if err := ValidateSheet(r, 2, s); err == nil {
			t.Errorf("bad sheet %d accepted", i)
		}
	}
}