commitreveal.gno
1.44 Kb · 49 lines
1// Package commitreveal implements a minimal commit-reveal scheme.
2//
3// A commitment is the hex-encoded SHA-256 of the exact byte string
4//
5// salt + ":" + payload
6//
7// The payload stays secret until the revealer publishes payload and salt;
8// anyone can then recompute the commitment and check it matches the value
9// that was committed earlier. The salt keeps short or guessable payloads
10// from being brute-forced against a bare hash of the payload alone.
11//
12// The package is pure and stateless: it is safe to import from any realm.
13package commitreveal
14
15import (
16 "crypto/sha256"
17 "encoding/hex"
18)
19
20// Commit returns the commitment for payload under salt: the lowercase
21// hex encoding of SHA-256(salt + ":" + payload).
22func Commit(payload string, salt string) string {
23 sum := sha256.Sum256([]byte(salt + ":" + payload))
24 return hex.EncodeToString(sum[:])
25}
26
27// IsCommitment reports whether s has the canonical commitment format:
28// exactly 64 lowercase hexadecimal characters.
29func IsCommitment(s string) bool {
30 if len(s) != 64 {
31 return false
32 }
33 for i := 0; i < len(s); i++ {
34 c := s[i]
35 if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
36 return false
37 }
38 }
39 return true
40}
41
42// Verify reports whether commitment is well-formed and equals the
43// commitment recomputed from payload and salt.
44func Verify(commitment string, payload string, salt string) bool {
45 if !IsCommitment(commitment) {
46 return false
47 }
48 return Commit(payload, salt) == commitment
49}