Search Apps Documentation Source Content File Folder Download Copy Actions Download State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

commit.gno

1.43 Kb · 51 lines
 1// Package commit provides small, deterministic commitment helpers shared by
 2// the agent demos. On-chain realms store *commitments* to off-chain data
 3// (reports, patches, verdicts) rather than the data itself; this package is
 4// the one place that defines how those commitments are computed, so several
 5// realms agree on the scheme.
 6package commit
 7
 8import (
 9	"crypto/sha256"
10	"encoding/hex"
11)
12
13// Hash returns the hex-encoded SHA-256 over its parts, length-prefixed so
14// that Hash("ab","c") != Hash("a","bc"). Use it to commit to structured
15// off-chain material without revealing it.
16func Hash(parts ...string) string {
17	var buf []byte
18	for _, p := range parts {
19		buf = appendUvarint(buf, uint64(len(p)))
20		buf = append(buf, p...)
21	}
22	sum := sha256.Sum256(buf)
23	return hex.EncodeToString(sum[:])
24}
25
26// Verdict is the canonical commitment used by commit-reveal voting: a hidden
27// boolean plus a salt. Reveal the same (verdict, salt) later and any observer
28// can recompute this and confirm the vote was not changed after the fact.
29func Verdict(verdict bool, salt string) string {
30	v := "no"
31	if verdict {
32		v = "yes"
33	}
34	return Hash("verdict", v, salt)
35}
36
37// Short abbreviates a hex commitment for display.
38func Short(h string) string {
39	if len(h) <= 12 {
40		return h
41	}
42	return h[:6] + "…" + h[len(h)-4:]
43}
44
45func appendUvarint(buf []byte, x uint64) []byte {
46	for x >= 0x80 {
47		buf = append(buf, byte(x)|0x80)
48		x >>= 7
49	}
50	return append(buf, byte(x))
51}