github.com/consensys/gnark-crypto@v0.14.0/ecc/bn254/fr/mimc/mimc_test.go (about)

     1  package mimc_test
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/consensys/gnark-crypto/ecc/bn254/fr"
     7  	"github.com/consensys/gnark-crypto/ecc/bn254/fr/mimc"
     8  	fiatshamir "github.com/consensys/gnark-crypto/fiat-shamir"
     9  	"github.com/stretchr/testify/assert"
    10  	"github.com/stretchr/testify/require"
    11  )
    12  
    13  func TestMiMCFiatShamir(t *testing.T) {
    14  	fs := fiatshamir.NewTranscript(mimc.NewMiMC(), "c0")
    15  	zero := make([]byte, mimc.BlockSize)
    16  	err := fs.Bind("c0", zero)
    17  	assert.NoError(t, err)
    18  	_, err = fs.ComputeChallenge("c0")
    19  	assert.NoError(t, err)
    20  }
    21  
    22  func TestByteOrder(t *testing.T) {
    23  	assert := require.New(t)
    24  
    25  	var buf [fr.Bytes]byte
    26  	// if the 31 first bytes are FF, it's a valid FF in little endian, but not in big endian
    27  	for i := 0; i < fr.Bytes-1; i++ {
    28  		buf[i] = 0xFF
    29  	}
    30  	_, err := fr.BigEndian.Element(&buf)
    31  	assert.Error(err)
    32  	_, err = fr.LittleEndian.Element(&buf)
    33  	assert.NoError(err)
    34  
    35  	{
    36  		// hashing buf with big endian should fail
    37  		mimcHash := mimc.NewMiMC(mimc.WithByteOrder(fr.BigEndian))
    38  		_, err := mimcHash.Write(buf[:])
    39  		assert.Error(err)
    40  	}
    41  
    42  	{
    43  		// hashing buf with little endian should succeed
    44  		mimcHash := mimc.NewMiMC(mimc.WithByteOrder(fr.LittleEndian))
    45  		_, err := mimcHash.Write(buf[:])
    46  		assert.NoError(err)
    47  	}
    48  
    49  	buf = [fr.Bytes]byte{}
    50  	// if the 31 bytes are FF, it's a valid FF in big endian, but not in little endian
    51  	for i := 1; i < fr.Bytes; i++ {
    52  		buf[i] = 0xFF
    53  	}
    54  	_, err = fr.BigEndian.Element(&buf)
    55  	assert.NoError(err)
    56  	_, err = fr.LittleEndian.Element(&buf)
    57  	assert.Error(err)
    58  
    59  	{
    60  		// hashing buf with big endian should succeed
    61  		mimcHash := mimc.NewMiMC(mimc.WithByteOrder(fr.BigEndian))
    62  		_, err := mimcHash.Write(buf[:])
    63  		assert.NoError(err)
    64  	}
    65  
    66  	{
    67  		// hashing buf with little endian should fail
    68  		mimcHash := mimc.NewMiMC(mimc.WithByteOrder(fr.LittleEndian))
    69  		_, err := mimcHash.Write(buf[:])
    70  		assert.Error(err)
    71  	}
    72  
    73  }