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

commitreveal.gno

// Package commitreveal implements the commit-then-reveal scheme as a pure,
// reusable package.
//
// The problem it solves: anything submitted to a chain is public before it is
// executed, so a naive sealed-bid auction or simultaneous-move game lets the
// last player read everyone else's move and win for free. Commit-reveal splits
// the action in two — first publish H(value || salt), later publish the value
// and salt. The commitment binds you to a choice without disclosing it.
//
// The SALT is not optional and this package refuses to let a caller skip it.
// Without one, a commitment over a small domain is trivially brute-forced: a
// rock-paper-scissors move has three possible hashes, so hashing all three
// breaks the scheme entirely. MinSaltLen is enforced at commit time rather than
// left as advice in a comment.
//
// Verification is CONSTANT-TIME over the digest. A short-circuiting comparison
// leaks, through timing, how many leading bytes of a guess were right, which is
// enough to reconstruct a commitment byte by byte.
//
// This package computes and checks commitments; it stores nothing and knows
// nothing about phases or deadlines. The realm owns that.
//
// A live demo of this package is at
// [r/moul/x/daily/commitrevealdemo](/r/nym-moultest123/x/daily/commitrevealdemo/v0).
package commitreveal

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

// MinSaltLen is the shortest salt accepted. Short salts make a small-domain
// commitment brute-forceable, which defeats the whole scheme.
const MinSaltLen = 16

// MaxValueLen bounds the committed value so gas stays predictable.
const MaxValueLen = 4096

var (
	ErrShortSalt   = errors.New("commitreveal: salt is shorter than MinSaltLen")
	ErrLongValue   = errors.New("commitreveal: value exceeds MaxValueLen")
	ErrMismatch    = errors.New("commitreveal: reveal does not match the commitment")
	ErrBadHexDigest = errors.New("commitreveal: commitment is not a valid hex digest")
)

// DigestLen is the length in bytes of a commitment digest (SHA-256).
const DigestLen = 32

// Commit returns the hex-encoded commitment for value and salt.
//
// The salt is length-prefixed rather than simply concatenated: with plain
// concatenation, ("ab","cd") and ("a","bcd") hash identically, so one
// commitment could be opened two different ways.
func Commit(value, salt string) (string, error) {
	if len(salt) < MinSaltLen {
		return "", ErrShortSalt
	}
	if len(value) > MaxValueLen {
		return "", ErrLongValue
	}
	return hex.EncodeToString(digest(value, salt)), nil
}

// MustCommit is Commit, panicking on invalid input. For tests and for callers
// that have already validated.
func MustCommit(value, salt string) string {
	c, err := Commit(value, salt)
	if err != nil {
		panic(err.Error())
	}
	return c
}

// Verify reports whether value and salt open the given commitment. The digest
// comparison is constant-time.
func Verify(commitment, value, salt string) bool {
	if len(salt) < MinSaltLen || len(value) > MaxValueLen {
		return false
	}
	want, err := hex.DecodeString(commitment)
	if err != nil || len(want) != DigestLen {
		return false
	}
	return equalConstantTime(want, digest(value, salt))
}

// Open verifies and reports why it failed, for callers wanting a reason rather
// than a bool.
func Open(commitment, value, salt string) error {
	if len(salt) < MinSaltLen {
		return ErrShortSalt
	}
	if len(value) > MaxValueLen {
		return ErrLongValue
	}
	want, err := hex.DecodeString(commitment)
	if err != nil || len(want) != DigestLen {
		return ErrBadHexDigest
	}
	if !equalConstantTime(want, digest(value, salt)) {
		return ErrMismatch
	}
	return nil
}

// ValidCommitment reports whether s is well-formed as a commitment: hex, and
// exactly DigestLen bytes. It says nothing about what it commits to.
func ValidCommitment(s string) bool {
	b, err := hex.DecodeString(s)
	return err == nil && len(b) == DigestLen
}

// digest computes SHA-256 over a length-prefixed encoding of value and salt.
// gno's crypto/sha256 exposes only Sum256, so the message is assembled first
// rather than streamed through a hash.Hash.
func digest(value, salt string) []byte {
	buf := make([]byte, 0, 8+len(value)+len(salt))
	buf = append(buf, lengthPrefix(len(value))...)
	buf = append(buf, value...)
	buf = append(buf, lengthPrefix(len(salt))...)
	buf = append(buf, salt...)
	sum := sha256.Sum256(buf)
	return sum[:]
}

// lengthPrefix encodes n as 4 big-endian bytes.
func lengthPrefix(n int) []byte {
	return []byte{
		byte(n >> 24), byte(n >> 16), byte(n >> 8), byte(n),
	}
}

// equalConstantTime compares two byte slices without short-circuiting, so the
// time taken does not reveal how many leading bytes matched.
func equalConstantTime(a, b []byte) bool {
	if len(a) != len(b) {
		return false
	}
	var diff byte
	for i := range a {
		diff |= a[i] ^ b[i]
	}
	return diff == 0
}

commitreveal_test.gno

package commitreveal

import (
	"strings"
	"testing"

	"gno.land/p/nt/uassert/v0"
)

const goodSalt = "0123456789abcdef" // exactly MinSaltLen

func TestCommitAndVerify(t *testing.T) {
	c, err := Commit("rock", goodSalt)
	uassert.NoError(t, err)
	uassert.True(t, ValidCommitment(c), "a commitment is a 32-byte hex digest")
	uassert.Equal(t, 64, len(c), "32 bytes hex-encoded")

	uassert.True(t, Verify(c, "rock", goodSalt), "the correct opening verifies")
}

func TestCommitIsDeterministic(t *testing.T) {
	a, _ := Commit("paper", goodSalt)
	b, _ := Commit("paper", goodSalt)
	uassert.Equal(t, a, b, "same input, same commitment")
}

func TestDifferentValuesDiffer(t *testing.T) {
	a, _ := Commit("rock", goodSalt)
	b, _ := Commit("paper", goodSalt)
	uassert.False(t, a == b)
}

// TestSameValueDifferentSaltDiffers is why the salt exists: two players
// choosing the same move must not publish the same commitment.
func TestSameValueDifferentSaltDiffers(t *testing.T) {
	a, _ := Commit("rock", "salt-one-0123456789")
	b, _ := Commit("rock", "salt-two-0123456789")
	uassert.False(t, a == b, "the same move must not be recognisable across players")
}

func TestWrongOpeningFails(t *testing.T) {
	c, _ := Commit("rock", goodSalt)

	uassert.False(t, Verify(c, "paper", goodSalt), "wrong value")
	uassert.False(t, Verify(c, "rock", "a-different-salt-value"), "wrong salt")
	uassert.False(t, Verify(c, "", goodSalt), "empty value")
}

// TestShortSaltRefused is the enforced-not-advised part: a three-move game with
// a short salt is brute-forceable, so the package will not produce one.
func TestShortSaltRefused(t *testing.T) {
	_, err := Commit("rock", "tooshort")
	uassert.ErrorIs(t, err, ErrShortSalt)

	_, err = Commit("rock", strings.Repeat("x", MinSaltLen-1))
	uassert.ErrorIs(t, err, ErrShortSalt, "one byte under the minimum is still refused")

	_, err = Commit("rock", strings.Repeat("x", MinSaltLen))
	uassert.NoError(t, err, "exactly MinSaltLen is accepted")
}

func TestShortSaltNeverVerifies(t *testing.T) {
	// Even a digest that would match cannot be opened with a short salt.
	uassert.False(t, Verify(MustCommit("rock", goodSalt), "rock", "short"),
		"Verify enforces the salt floor too")
}

func TestLongValueRefused(t *testing.T) {
	_, err := Commit(strings.Repeat("x", MaxValueLen+1), goodSalt)
	uassert.ErrorIs(t, err, ErrLongValue)

	_, err = Commit(strings.Repeat("x", MaxValueLen), goodSalt)
	uassert.NoError(t, err, "exactly MaxValueLen is accepted")
}

// TestLengthPrefixPreventsAmbiguity is the subtle one: with plain
// concatenation, ("ab","cdefghijklmnopq") and ("abc","defghijklmnopq") produce
// the same bytes, so one commitment could be opened two ways.
func TestLengthPrefixPreventsAmbiguity(t *testing.T) {
	a, err := Commit("ab", "cdefghijklmnopqr")
	uassert.NoError(t, err)
	b, err := Commit("abc", "defghijklmnopqr0")
	uassert.NoError(t, err)

	uassert.False(t, a == b, "a split ambiguity must not collide")
	uassert.False(t, Verify(a, "abc", "defghijklmnopqr0"), "and must not cross-verify")
}

func TestOpenReportsReasons(t *testing.T) {
	c := MustCommit("rock", goodSalt)

	uassert.NoError(t, Open(c, "rock", goodSalt))
	uassert.ErrorIs(t, Open(c, "paper", goodSalt), ErrMismatch)
	uassert.ErrorIs(t, Open(c, "rock", "short"), ErrShortSalt)
	uassert.ErrorIs(t, Open(c, strings.Repeat("x", MaxValueLen+1), goodSalt), ErrLongValue)
	uassert.ErrorIs(t, Open("not-hex!!", "rock", goodSalt), ErrBadHexDigest)
	uassert.ErrorIs(t, Open("abcd", "rock", goodSalt), ErrBadHexDigest, "right charset, wrong length")
}

func TestMalformedCommitments(t *testing.T) {
	uassert.False(t, Verify("", "rock", goodSalt))
	uassert.False(t, Verify("zz", "rock", goodSalt), "not hex")
	uassert.False(t, Verify(strings.Repeat("ab", 16), "rock", goodSalt), "16 bytes, not 32")
}

func TestValidCommitment(t *testing.T) {
	uassert.True(t, ValidCommitment(MustCommit("x", goodSalt)))
	uassert.False(t, ValidCommitment(""))
	uassert.False(t, ValidCommitment("nothex"))
	uassert.False(t, ValidCommitment(strings.Repeat("a", 63)), "odd length")
	uassert.False(t, ValidCommitment(strings.Repeat("a", 66)), "too long")
	uassert.True(t, ValidCommitment(strings.Repeat("A", 64)), "uppercase hex is fine")
}

func TestMustCommitPanicsOnBadInput(t *testing.T) {
	defer func() {
		r := recover()
		uassert.True(t, r != nil, "MustCommit must panic on a short salt")
	}()
	MustCommit("rock", "short")
}

func TestEqualConstantTime(t *testing.T) {
	a := []byte{1, 2, 3}
	uassert.True(t, equalConstantTime(a, []byte{1, 2, 3}))
	uassert.False(t, equalConstantTime(a, []byte{1, 2, 4}), "differs in the last byte")
	uassert.False(t, equalConstantTime(a, []byte{9, 2, 3}), "differs in the first byte")
	uassert.False(t, equalConstantTime(a, []byte{1, 2}), "different lengths")
	uassert.True(t, equalConstantTime(nil, nil))
}

// TestFullRoundTrip walks the two phases the scheme is made of.
func TestFullRoundTrip(t *testing.T) {
	// Phase 1: both players publish only a commitment.
	aliceSalt := "alice-secret-salt-1"
	bobSalt := "bob-secret-salt-0001"
	aliceCommit := MustCommit("rock", aliceSalt)
	bobCommit := MustCommit("paper", bobSalt)

	uassert.False(t, aliceCommit == bobCommit)
	uassert.True(t, ValidCommitment(aliceCommit))

	// Phase 2: reveals are checked against the earlier commitments.
	uassert.NoError(t, Open(aliceCommit, "rock", aliceSalt))
	uassert.NoError(t, Open(bobCommit, "paper", bobSalt))

	// Bob cannot change his move after seeing Alice's.
	uassert.ErrorIs(t, Open(bobCommit, "scissors", bobSalt), ErrMismatch)
	// Nor can he claim Alice's commitment as his own.
	uassert.ErrorIs(t, Open(aliceCommit, "rock", bobSalt), ErrMismatch)
}

gnomod.toml

module = "gno.land/p/nym-moultest123/x/daily/commitreveal/v0"
gno = "0.9"

[addpkg]
  creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv"
  height = 186405
  max_deposit = "6000000ugnot"