Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add ripemd160 hash function with permutation #1120

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 82 additions & 0 deletions std/hash/ripemd160/ripemd160.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
// Package ripemd160 implements in-circuit ripemd160 hash function.
//
// This package extends the permutation function [ripemd160.Permute] into a full
// hash function with padding computation and [hash.BinaryHasher] interface
// implementation.
package ripemd160

import (
"encoding/binary"
"fmt"

"github.com/consensys/gnark/frontend"
"github.com/consensys/gnark/std/hash"
"github.com/consensys/gnark/std/math/uints"
"github.com/consensys/gnark/std/permutation/ripemd160"
)

var _seed = uints.NewU32Array([]uint32{
0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,
})

type digest struct {
uapi *uints.BinaryField[uints.U32]
in []uints.U8
}

// New returns a new ripemd160 hasher.
func New(api frontend.API) (hash.BinaryHasher, error) {
uapi, err := uints.New[uints.U32](api)
if err != nil {
return nil, fmt.Errorf("new uapi: %w", err)
}
return &digest{uapi: uapi}, nil
}

func (d *digest) Write(data []uints.U8) {
d.in = append(d.in, data...)
}

func (d *digest) padded(bytesLen int) []uints.U8 {
zeroPadLen := 55 - bytesLen%64
if zeroPadLen < 0 {
zeroPadLen += 64
}
if cap(d.in) < len(d.in)+9+zeroPadLen {
// in case this is the first time this method is called increase the
// capacity of the slice to fit the padding.
d.in = append(d.in, make([]uints.U8, 9+zeroPadLen)...)
d.in = d.in[:len(d.in)-9-zeroPadLen]
}
buf := d.in
buf = append(buf, uints.NewU8(0x80))
buf = append(buf, uints.NewU8Array(make([]uint8, zeroPadLen))...)
lenbuf := make([]uint8, 8)
binary.LittleEndian.PutUint64(lenbuf, uint64(8*bytesLen))
buf = append(buf, uints.NewU8Array(lenbuf)...)
return buf
}

func (d *digest) Sum() []uints.U8 {
var runningDigest [5]uints.U32
var buf [64]uints.U8
copy(runningDigest[:], _seed)
padded := d.padded(len(d.in))
for i := 0; i < len(padded)/64; i++ {
copy(buf[:], padded[i*64:(i+1)*64])
runningDigest = ripemd160.Permute(d.uapi, runningDigest, buf)
}
var ret []uints.U8
for i := range runningDigest {
ret = append(ret, d.uapi.UnpackLSB(runningDigest[i])...)
}
return ret
}

func (d *digest) Reset() {
d.in = nil
}

func (d *digest) Size() int {
return 20
}
52 changes: 52 additions & 0 deletions std/hash/ripemd160/ripemd160_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package ripemd160

import (
"fmt"
"testing"

"github.com/consensys/gnark-crypto/ecc"
"github.com/consensys/gnark/frontend"
"github.com/consensys/gnark/std/math/uints"
"github.com/consensys/gnark/test"
"golang.org/x/crypto/ripemd160" //nolint staticcheck, backwards compatiblity
)

type ripemd160Circuit struct {
In []uints.U8
Expected [20]uints.U8
}

func (c *ripemd160Circuit) Define(api frontend.API) error {
h, err := New(api) //nolint G406, false positive, the current package name collides with "golang.org/x/crypto/ripemd160"
if err != nil {
return err
}
uapi, err := uints.New[uints.U32](api)
if err != nil {
return err
}
h.Write(c.In)
res := h.Sum()
if len(res) != len(c.Expected) {
return fmt.Errorf("not 20 bytes")
}
for i := range c.Expected {
uapi.ByteAssertEq(c.Expected[i], res[i])
}
return nil
}

func TestRipemd160(t *testing.T) {
bts := make([]byte, 310)
h := ripemd160.New() //nolint G406, false positive, we implement it for EVM compatibility
h.Write(bts)
dgst := h.Sum(nil)
witness := ripemd160Circuit{
In: uints.NewU8Array(bts),
}
copy(witness.Expected[:], uints.NewU8Array(dgst[:]))
err := test.IsSolved(&ripemd160Circuit{In: make([]uints.U8, len(bts))}, &witness, ecc.BN254.ScalarField())
if err != nil {
t.Fatal(err)
}
}
6 changes: 6 additions & 0 deletions std/math/uints/hints.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ func GetHints() []solver.Hint {
return []solver.Hint{
andHint,
xorHint,
orHint,
toBytes,
}
}
Expand All @@ -29,6 +30,11 @@ func andHint(_ *big.Int, inputs, outputs []*big.Int) error {
return nil
}

func orHint(_ *big.Int, inputs, outputs []*big.Int) error {
outputs[0].Or(inputs[0], inputs[1])
return nil
}

func toBytes(m *big.Int, inputs []*big.Int, outputs []*big.Int) error {
if len(inputs) != 2 {
return fmt.Errorf("input must be 2 elements")
Expand Down
14 changes: 10 additions & 4 deletions std/math/uints/uint8.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,10 +84,10 @@ type U32 [4]U8
type Long interface{ U32 | U64 }

type BinaryField[T U32 | U64] struct {
api frontend.API
xorT, andT *logderivprecomp.Precomputed
rchecker frontend.Rangechecker
allOne U8
api frontend.API
xorT, andT, orT *logderivprecomp.Precomputed
rchecker frontend.Rangechecker
allOne U8
}

func New[T Long](api frontend.API) (*BinaryField[T], error) {
Expand All @@ -99,11 +99,16 @@ func New[T Long](api frontend.API) (*BinaryField[T], error) {
if err != nil {
return nil, fmt.Errorf("new and table: %w", err)
}
orT, err := logderivprecomp.New(api, orHint, []uint{8})
if err != nil {
return nil, fmt.Errorf("new or table: %w", err)
}
rchecker := rangecheck.New(api)
bf := &BinaryField[T]{
api: api,
xorT: xorT,
andT: andT,
orT: orT,
rchecker: rchecker,
}
// TODO: this is const. add way to init constants
Expand Down Expand Up @@ -244,6 +249,7 @@ func (bf *BinaryField[T]) twoArgWideFn(tbl *logderivprecomp.Precomputed, a ...T)

func (bf *BinaryField[T]) And(a ...T) T { return bf.twoArgWideFn(bf.andT, a...) }
func (bf *BinaryField[T]) Xor(a ...T) T { return bf.twoArgWideFn(bf.xorT, a...) }
func (bf *BinaryField[T]) Or(a ...T) T { return bf.twoArgWideFn(bf.orT, a...) }

func (bf *BinaryField[T]) not(a U8) U8 {
ret := bf.xorT.Query(a.Val, bf.allOne.Val)
Expand Down
Loading