Compare commits

..

6 Commits

Author SHA1 Message Date
arnaucube
6d75396b4b Upgrade linters 2020-12-16 15:07:19 +01:00
Eduard S
821a601d20 Merge pull request #31 from iden3/feature/update-bbjjeddsa
Update BabyJubJub EdDSA to last circomlib version
2020-12-03 10:52:29 +01:00
arnaucube
5dd19b46dd Update BabyJubJub EdDSA to last circomlib version
- Update BabyJubJub EdDSA signature to last circomlib version (Poseidon
usage)
- Remove panic on hash error inside verification, to avoid panic due
field overflow of BabyJubJub signature verification
2020-12-02 19:57:27 +01:00
arnau
94e92e88fb Merge pull request #30 from iden3/feature/signaturecomp-scanner
Add scanner/valuer interface to babyjub.SignatureComp
2020-10-16 16:24:44 +02:00
Arnau B
5ef832f175 Add scanner/valuer interface to babyjub.SignatureComp 2020-10-16 16:22:18 +02:00
arnau
59d8c7a4ca Merge pull request #29 from iden3/feature/babyjubjub-optimization
- Add `add-2008-bbjlp` for point addition
- Add `goff` to BabyJubJub point addition

```
Benchmarks (On a Intel(R) Core(TM) i7-8705G CPU @ 3.10GHz, with 32 GB of RAM):

- Old (commit: e04ca5764a):
BenchmarkBabyjub/AddConst-8              1000000              1072 ns/op
BenchmarkBabyjub/AddRnd-8                  93417             12943 ns/op
BenchmarkBabyjub/MulRnd-8                    252           4797810 ns/op
BenchmarkBabyjub/Compress-8              7291580               166 ns/op
BenchmarkBabyjub/InCurve-8                611137              1999 ns/op
BenchmarkBabyjub/InSubGroup-8             615792              2021 ns/op
BenchmarkBabyjubEddsa/SignMimc7-8            126           9358542 ns/op
BenchmarkBabyjubEddsa/VerifyMimc7-8          124           9484005 ns/op
BenchmarkBabyjubEddsa/SignPoseidon-8                 126           9486484 ns/op
BenchmarkBabyjubEddsa/VerifyPoseidon-8               126           9622807 ns/op

- With new point addition algorithm (commit: aab1a681dd):
BenchmarkBabyjub/AddConst-8              1356836               881 ns/op
BenchmarkBabyjub/AddRnd-8                 274112              4220 ns/op
BenchmarkBabyjub/MulRnd-8                    492           2474412 ns/op
BenchmarkBabyjub/Compress-8              6964855               197 ns/op
BenchmarkBabyjub/InCurve-8                608169              2008 ns/op
BenchmarkBabyjub/InSubGroup-8             618772              1954 ns/op
BenchmarkBabyjubEddsa/SignMimc7-8            238           4962397 ns/op
BenchmarkBabyjubEddsa/VerifyMimc7-8          235           5234883 ns/op
BenchmarkBabyjubEddsa/SignPoseidon-8                 240           5028720 ns/op
BenchmarkBabyjubEddsa/VerifyPoseidon-8               243           5226654 ns/op

Point Addition: ~3x
Point scalar Mul: ~1.9x
Signature (poseidon): ~1.88x
Verification (poseidon): ~1.84x

- With new point addition algorithm & goff (current commit):
BenchmarkBabyjub/AddConst-8              3000531               400 ns/op
BenchmarkBabyjub/AddRnd-8                2770335               428 ns/op
BenchmarkBabyjub/MulRnd-8                   6636            175522 ns/op
BenchmarkBabyjub/Compress-8              7358768               180 ns/op
BenchmarkBabyjub/InCurve-8                539193              1950 ns/op
BenchmarkBabyjub/InSubGroup-8             601402              1958 ns/op
BenchmarkBabyjubEddsa/SignMimc7-8           2940            409487 ns/op
BenchmarkBabyjubEddsa/VerifyMimc7-8         2908            414407 ns/op
BenchmarkBabyjubEddsa/SignPoseidon-8                2395            493165 ns/op
BenchmarkBabyjubEddsa/VerifyPoseidon-8              2491            494849 ns/op

Point Addition: ~9.86x
Point scalar Mul: ~14x
Signature (poseidon): ~10.2x
Verification (poseidon): ~10.56x

---

Total improvement (from old to current):
Point Addition: ~30.24x
Point scalar Mul: ~27.33x
Signature (poseidon): ~19.24x
Verification (poseidon): ~19.44x
```
2020-09-13 20:05:04 +02:00
15 changed files with 238 additions and 118 deletions

View File

@@ -1,5 +1,5 @@
on: [ push, pull_request ]
name: Lint
on: [ push, pull_request ]
jobs:
lint:
runs-on: ubuntu-latest
@@ -12,5 +12,5 @@ jobs:
uses: actions/checkout@v2
- name: Lint
run: |
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.24.0
$(go env GOPATH)/bin/golangci-lint run
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.30.0
$(go env GOPATH)/bin/golangci-lint run --timeout=5m -c .golangci.yml

17
.golangci.yml Normal file
View File

@@ -0,0 +1,17 @@
issues:
max-same-issues: 0
exclude-use-default: false
linters:
enable:
- whitespace
- gosec
- gci
- misspell
- gomnd
- gofmt
- goimports
- lll
- golint
linters-settings:
lll:
line-length: 100

View File

@@ -59,7 +59,8 @@ type PointProjective struct {
// NewPointProjective creates a new Point in projective coordinates.
func NewPointProjective() *PointProjective {
return &PointProjective{X: ff.NewElement().SetZero(), Y: ff.NewElement().SetOne(), Z: ff.NewElement().SetOne()}
return &PointProjective{X: ff.NewElement().SetZero(),
Y: ff.NewElement().SetOne(), Z: ff.NewElement().SetOne()}
}
// Affine returns the Point from the projective representation
@@ -84,19 +85,21 @@ func (p *PointProjective) Affine() *Point {
}
}
// Add computes the addition of two points in projective coordinates representation
func (res *PointProjective) Add(p *PointProjective, q *PointProjective) *PointProjective {
// add-2008-bbjlp https://hyperelliptic.org/EFD/g1p/auto-twisted-projective.html#doubling-dbl-2008-bbjlp
a := ff.NewElement().Mul(p.Z, q.Z)
// Add computes the addition of two points in projective coordinates
// representation
func (p *PointProjective) Add(q *PointProjective, o *PointProjective) *PointProjective {
// add-2008-bbjlp
// https://hyperelliptic.org/EFD/g1p/auto-twisted-projective.html#doubling-dbl-2008-bbjlp
a := ff.NewElement().Mul(q.Z, o.Z)
b := ff.NewElement().Square(a)
c := ff.NewElement().Mul(p.X, q.X)
d := ff.NewElement().Mul(p.Y, q.Y)
c := ff.NewElement().Mul(q.X, o.X)
d := ff.NewElement().Mul(q.Y, o.Y)
e := ff.NewElement().Mul(Dff, c)
e.MulAssign(d)
f := ff.NewElement().Sub(b, e)
g := ff.NewElement().Add(b, e)
x1y1 := ff.NewElement().Add(p.X, p.Y)
x2y2 := ff.NewElement().Add(q.X, q.Y)
x1y1 := ff.NewElement().Add(q.X, q.Y)
x2y2 := ff.NewElement().Add(o.X, o.Y)
x3 := ff.NewElement().Mul(x1y1, x2y2)
x3.SubAssign(c)
x3.SubAssign(d)
@@ -108,10 +111,10 @@ func (res *PointProjective) Add(p *PointProjective, q *PointProjective) *PointPr
y3.MulAssign(g)
z3 := ff.NewElement().Mul(f, g)
res.X = x3
res.Y = y3
res.Z = z3
return res
p.X = x3
p.Y = y3
p.Z = z3
return p
}
// Point represents a point of the babyjub curve.
@@ -141,15 +144,15 @@ func (p *Point) Projective() *PointProjective {
}
}
// Mul multiplies the Point p by the scalar s and stores the result in res,
// Mul multiplies the Point q by the scalar s and stores the result in p,
// which is also returned.
func (res *Point) Mul(s *big.Int, p *Point) *Point {
func (p *Point) Mul(s *big.Int, q *Point) *Point {
resProj := &PointProjective{
X: ff.NewElement().SetZero(),
Y: ff.NewElement().SetOne(),
Z: ff.NewElement().SetOne(),
}
exp := p.Projective()
exp := q.Projective()
for i := 0; i < s.BitLen(); i++ {
if s.Bit(i) == 1 {
@@ -157,8 +160,8 @@ func (res *Point) Mul(s *big.Int, p *Point) *Point {
}
exp = exp.Add(exp, exp)
}
res = resProj.Affine()
return res
p = resProj.Affine()
return p
}
// InCurve returns true when the Point p is in the babyjub curve.
@@ -200,10 +203,11 @@ func PointCoordSign(c *big.Int) bool {
return c.Cmp(new(big.Int).Rsh(constants.Q, 1)) == 1
}
// PackPoint packs a point into a 32 byte array
func PackPoint(ay *big.Int, sign bool) [32]byte {
leBuf := utils.BigIntLEBytes(ay)
if sign {
leBuf[31] = leBuf[31] | 0x80
leBuf[31] = leBuf[31] | 0x80 //nolint:gomnd
}
return leBuf
}
@@ -219,9 +223,9 @@ func (p *Point) Compress() [32]byte {
// Point. Returns error if the compressed Point is invalid.
func (p *Point) Decompress(leBuf [32]byte) (*Point, error) {
sign := false
if (leBuf[31] & 0x80) != 0x00 {
if (leBuf[31] & 0x80) != 0x00 { //nolint:gomnd
sign = true
leBuf[31] = leBuf[31] & 0x7F
leBuf[31] = leBuf[31] & 0x7F //nolint:gomnd
}
utils.SetBigIntFromLEBytes(p.Y, leBuf[:])
return PointFromSignAndY(sign, p.Y)

View File

@@ -44,7 +44,9 @@ func TestAdd2(t *testing.T) {
c.Y.String())
d := NewPointProjective().Add(c.Projective(), c.Projective()).Affine()
assert.Equal(t, "2f6458832049e917c95867185a96621336df33e13c98e81d1ef4928cdbb77772", hex.EncodeToString(d.X.Bytes()))
assert.Equal(t,
"2f6458832049e917c95867185a96621336df33e13c98e81d1ef4928cdbb77772",
hex.EncodeToString(d.X.Bytes()))
// Projective
aP := a.Projective()
@@ -52,7 +54,6 @@ func TestAdd2(t *testing.T) {
cP := NewPointProjective().Add(aP, bP)
c2 := cP.Affine()
assert.Equal(t, c, c2)
}
func TestAdd3(t *testing.T) {
@@ -225,7 +226,9 @@ func TestCompressDecompress1(t *testing.T) {
p := &Point{X: x, Y: y}
buf := p.Compress()
assert.Equal(t, "53b81ed5bffe9545b54016234682e7b2f699bd42a5e9eae27ff4051bc698ce85", hex.EncodeToString(buf[:]))
assert.Equal(t,
"53b81ed5bffe9545b54016234682e7b2f699bd42a5e9eae27ff4051bc698ce85",
hex.EncodeToString(buf[:]))
p2, err := NewPoint().Decompress(buf)
assert.Equal(t, nil, err)
@@ -241,7 +244,9 @@ func TestCompressDecompress2(t *testing.T) {
p := &Point{X: x, Y: y}
buf := p.Compress()
assert.Equal(t, "e114eb17eddf794f063a68fecac515e3620e131976108555735c8b0773929709", hex.EncodeToString(buf[:]))
assert.Equal(t,
"e114eb17eddf794f063a68fecac515e3620e131976108555735c8b0773929709",
hex.EncodeToString(buf[:]))
p2, err := NewPoint().Decompress(buf)
assert.Equal(t, nil, err)
@@ -263,7 +268,7 @@ func TestCompressDecompressRnd(t *testing.T) {
func BenchmarkBabyjub(b *testing.B) {
const n = 256
rnd := rand.New(rand.NewSource(42))
rnd := rand.New(rand.NewSource(42)) //nolint:gosec
var badpoints [n]*Point
for i := 0; i < n; i++ {

View File

@@ -1,15 +1,16 @@
// Package babyjub eddsa implements the EdDSA over the BabyJubJub curve
//nolint:gomnd
package babyjub
import (
"crypto/rand"
"database/sql/driver"
"fmt"
"math/big"
"github.com/iden3/go-iden3-crypto/mimc7"
"github.com/iden3/go-iden3-crypto/poseidon"
"github.com/iden3/go-iden3-crypto/utils"
"math/big"
)
// pruneBuffer prunes the buffer during key generation according to RFC 8032.
@@ -55,7 +56,7 @@ func SkToBigInt(k *PrivateKey) *big.Int {
return s
}
// Pub returns the public key corresponding to a private key.
// Public returns the public key corresponding to a private key.
func (k *PrivateKey) Public() *PublicKey {
return k.Scalar().Public()
}
@@ -69,8 +70,8 @@ func NewPrivKeyScalar(s *big.Int) *PrivKeyScalar {
return &sk
}
// Pub returns the public key corresponding to the scalar value s of a private
// key.
// Public returns the public key corresponding to the scalar value s of a
// private key.
func (s *PrivKeyScalar) Public() *PublicKey {
p := NewPoint().Mul((*big.Int)(s), B8)
pk := PublicKey(*p)
@@ -85,16 +86,19 @@ func (s *PrivKeyScalar) BigInt() *big.Int {
// PublicKey represents an EdDSA public key, which is a curve point.
type PublicKey Point
// MarshalText implements the marshaler for PublicKey
func (pk PublicKey) MarshalText() ([]byte, error) {
pkc := pk.Compress()
return utils.Hex(pkc[:]).MarshalText()
}
// String returns the string representation of the PublicKey
func (pk PublicKey) String() string {
pkc := pk.Compress()
return utils.Hex(pkc[:]).String()
}
// UnmarshalText implements the unmarshaler for the PublicKey
func (pk *PublicKey) UnmarshalText(h []byte) error {
var pkc PublicKeyComp
if err := utils.HexDecodeInto(pkc[:], h); err != nil {
@@ -109,24 +113,35 @@ func (pk *PublicKey) UnmarshalText(h []byte) error {
}
// Point returns the Point corresponding to a PublicKey.
func (p *PublicKey) Point() *Point {
return (*Point)(p)
func (pk *PublicKey) Point() *Point {
return (*Point)(pk)
}
// PublicKeyComp represents a compressed EdDSA Public key; it's a compressed curve
// point.
type PublicKeyComp [32]byte
func (buf PublicKeyComp) MarshalText() ([]byte, error) { return utils.Hex(buf[:]).MarshalText() }
func (buf PublicKeyComp) String() string { return utils.Hex(buf[:]).String() }
func (buf *PublicKeyComp) UnmarshalText(h []byte) error { return utils.HexDecodeInto(buf[:], h) }
func (p *PublicKey) Compress() PublicKeyComp {
return PublicKeyComp((*Point)(p).Compress())
// MarshalText implements the marshaler for the PublicKeyComp
func (pkComp PublicKeyComp) MarshalText() ([]byte, error) {
return utils.Hex(pkComp[:]).MarshalText()
}
func (p *PublicKeyComp) Decompress() (*PublicKey, error) {
point, err := NewPoint().Decompress(*p)
// String returns the string representation of the PublicKeyComp
func (pkComp PublicKeyComp) String() string { return utils.Hex(pkComp[:]).String() }
// UnmarshalText implements the unmarshaler for the PublicKeyComp
func (pkComp *PublicKeyComp) UnmarshalText(h []byte) error {
return utils.HexDecodeInto(pkComp[:], h)
}
// Compress returns the PublicKeyCompr for the given PublicKey
func (pk *PublicKey) Compress() PublicKeyComp {
return PublicKeyComp((*Point)(pk).Compress())
}
// Decompress returns the PublicKey for the given PublicKeyComp
func (pkComp *PublicKeyComp) Decompress() (*PublicKey, error) {
point, err := NewPoint().Decompress(*pkComp)
if err != nil {
return nil, err
}
@@ -143,9 +158,18 @@ type Signature struct {
// SignatureComp represents a compressed EdDSA signature.
type SignatureComp [64]byte
func (buf SignatureComp) MarshalText() ([]byte, error) { return utils.Hex(buf[:]).MarshalText() }
func (buf SignatureComp) String() string { return utils.Hex(buf[:]).String() }
func (buf *SignatureComp) UnmarshalText(h []byte) error { return utils.HexDecodeInto(buf[:], h) }
// MarshalText implements the marshaler for the SignatureComp
func (sComp SignatureComp) MarshalText() ([]byte, error) {
return utils.Hex(sComp[:]).MarshalText()
}
// String returns the string representation of the SignatureComp
func (sComp SignatureComp) String() string { return utils.Hex(sComp[:]).String() }
// UnmarshalText implements the unmarshaler for the SignatureComp
func (sComp *SignatureComp) UnmarshalText(h []byte) error {
return utils.HexDecodeInto(sComp[:], h)
}
// Compress an EdDSA signature by concatenating the compression of
// the point R8 and the Little-Endian encoding of S.
@@ -173,8 +197,26 @@ func (s *Signature) Decompress(buf [64]byte) (*Signature, error) {
// Decompress a compressed signature. Returns error if the Point decompression
// fails.
func (s *SignatureComp) Decompress() (*Signature, error) {
return new(Signature).Decompress(*s)
func (sComp *SignatureComp) Decompress() (*Signature, error) {
return new(Signature).Decompress(*sComp)
}
// Scan implements Scanner for database/sql.
func (sComp *SignatureComp) Scan(src interface{}) error {
srcB, ok := src.([]byte)
if !ok {
return fmt.Errorf("can't scan %T into Signature", src)
}
if len(srcB) != 64 {
return fmt.Errorf("can't scan []byte of len %d into Signature, want %d", len(srcB), 64)
}
copy(sComp[:], srcB[:])
return nil
}
// Value implements valuer for database/sql.
func (sComp SignatureComp) Value() (driver.Value, error) {
return sComp[:], nil
}
// Scan implements Scanner for database/sql.
@@ -225,17 +267,17 @@ func (k *PrivateKey) SignMimc7(msg *big.Int) *Signature {
// VerifyMimc7 verifies the signature of a message encoded as a big.Int in Zq
// using blake-512 hash for buffer hashing and mimc7 for big.Int hashing.
func (p *PublicKey) VerifyMimc7(msg *big.Int, sig *Signature) bool {
hmInput := []*big.Int{sig.R8.X, sig.R8.Y, p.X, p.Y, msg}
func (pk *PublicKey) VerifyMimc7(msg *big.Int, sig *Signature) bool {
hmInput := []*big.Int{sig.R8.X, sig.R8.Y, pk.X, pk.Y, msg}
hm, err := mimc7.Hash(hmInput, nil) // hm = H1(8*R.x, 8*R.y, A.x, A.y, msg)
if err != nil {
panic(err)
return false
}
left := NewPoint().Mul(sig.S, B8) // left = s * 8 * B
r1 := big.NewInt(8)
r1.Mul(r1, hm)
right := NewPoint().Mul(r1, p.Point())
right := NewPoint().Mul(r1, pk.Point())
rightProj := right.Projective()
rightProj.Add(sig.R8.Projective(), rightProj) // right = 8 * R + 8 * hm * A
right = rightProj.Affine()
@@ -255,7 +297,7 @@ func (k *PrivateKey) SignPoseidon(msg *big.Int) *Signature {
R8 := NewPoint().Mul(r, B8) // R8 = r * 8 * B
A := k.Public().Point()
hmInput := []*big.Int{R8.X, R8.Y, A.X, A.Y, msg, big.NewInt(int64(0))}
hmInput := []*big.Int{R8.X, R8.Y, A.X, A.Y, msg}
hm, err := poseidon.Hash(hmInput) // hm = H1(8*R.x, 8*R.y, A.x, A.y, msg)
if err != nil {
panic(err)
@@ -271,17 +313,17 @@ func (k *PrivateKey) SignPoseidon(msg *big.Int) *Signature {
// VerifyPoseidon verifies the signature of a message encoded as a big.Int in Zq
// using blake-512 hash for buffer hashing and Poseidon for big.Int hashing.
func (p *PublicKey) VerifyPoseidon(msg *big.Int, sig *Signature) bool {
hmInput := []*big.Int{sig.R8.X, sig.R8.Y, p.X, p.Y, msg, big.NewInt(int64(0))}
func (pk *PublicKey) VerifyPoseidon(msg *big.Int, sig *Signature) bool {
hmInput := []*big.Int{sig.R8.X, sig.R8.Y, pk.X, pk.Y, msg}
hm, err := poseidon.Hash(hmInput) // hm = H1(8*R.x, 8*R.y, A.x, A.y, msg)
if err != nil {
panic(err)
return false
}
left := NewPoint().Mul(sig.S, B8) // left = s * 8 * B
r1 := big.NewInt(8)
r1.Mul(r1, hm)
right := NewPoint().Mul(r1, p.Point())
right := NewPoint().Mul(r1, pk.Point())
rightProj := right.Projective()
rightProj.Add(sig.R8.Projective(), rightProj) // right = 8 * R + 8 * hm * A
right = rightProj.Affine()
@@ -289,7 +331,7 @@ func (p *PublicKey) VerifyPoseidon(msg *big.Int, sig *Signature) bool {
}
// Scan implements Scanner for database/sql.
func (p *PublicKey) Scan(src interface{}) error {
func (pk *PublicKey) Scan(src interface{}) error {
srcB, ok := src.([]byte)
if !ok {
return fmt.Errorf("can't scan %T into PublicKey", src)
@@ -303,12 +345,12 @@ func (p *PublicKey) Scan(src interface{}) error {
if err != nil {
return err
}
*p = *decomp
*pk = *decomp
return nil
}
// Value implements valuer for database/sql.
func (p PublicKey) Value() (driver.Value, error) {
comp := p.Compress()
func (pk PublicKey) Value() (driver.Value, error) {
comp := pk.Compress()
return comp[:], nil
}

View File

@@ -1,14 +1,13 @@
package babyjub
import (
"database/sql"
"database/sql/driver"
"encoding/hex"
"fmt"
"math/big"
"testing"
"database/sql"
"database/sql/driver"
"github.com/iden3/go-iden3-crypto/constants"
"github.com/iden3/go-iden3-crypto/utils"
"github.com/stretchr/testify/assert"
@@ -27,7 +26,8 @@ func TestPublicKey(t *testing.T) {
func TestSignVerifyMimc7(t *testing.T) {
var k PrivateKey
_, err := hex.Decode(k[:], []byte("0001020304050607080900010203040506070809000102030405060708090001"))
_, err := hex.Decode(k[:],
[]byte("0001020304050607080900010203040506070809000102030405060708090001"))
require.Nil(t, err)
msgBuf, err := hex.DecodeString("00010203040506070809")
if err != nil {
@@ -72,7 +72,8 @@ func TestSignVerifyMimc7(t *testing.T) {
func TestSignVerifyPoseidon(t *testing.T) {
var k PrivateKey
_, err := hex.Decode(k[:], []byte("0001020304050607080900010203040506070809000102030405060708090001"))
_, err := hex.Decode(k[:],
[]byte("0001020304050607080900010203040506070809000102030405060708090001"))
require.Nil(t, err)
msgBuf, err := hex.DecodeString("00010203040506070809")
if err != nil {
@@ -96,7 +97,7 @@ func TestSignVerifyPoseidon(t *testing.T) {
"15383486972088797283337779941324724402501462225528836549661220478783371668959",
sig.R8.Y.String())
assert.Equal(t,
"1662463587877312619203503803508234533733252768380479199263194005796068211378",
"1398758333392199195742243841591064350253744445503462896781493968760929513778",
sig.S.String())
ok := pk.VerifyPoseidon(msg, sig)
@@ -108,7 +109,7 @@ func TestSignVerifyPoseidon(t *testing.T) {
assert.Equal(t, ""+
"dfedb4315d3f2eb4de2d3c510d7a987dcab67089c8ace06308827bf5bcbe02a2"+
"b23a1f04909fc088dec7e4835d85a326f7c0d0b2a3d0232d84448ca7c9ebac03",
"32f16b0f2f4c4e1169aa59685637e1429b6581a9531d058d65f4ab224eab1703",
hex.EncodeToString(sigBuf[:]))
ok = pk.VerifyPoseidon(msg, sig2)
@@ -117,7 +118,8 @@ func TestSignVerifyPoseidon(t *testing.T) {
func TestCompressDecompress(t *testing.T) {
var k PrivateKey
_, err := hex.Decode(k[:], []byte("0001020304050607080900010203040506070809000102030405060708090001"))
_, err := hex.Decode(k[:],
[]byte("0001020304050607080900010203040506070809000102030405060708090001"))
require.Nil(t, err)
pk := k.Public()
for i := 0; i < 64; i++ {
@@ -135,6 +137,17 @@ func TestCompressDecompress(t *testing.T) {
}
}
func TestSignatureCompScannerValuer(t *testing.T) {
privK := NewRandPrivKey()
var value driver.Valuer //nolint:gosimple this is done to ensure interface compability
value = privK.SignPoseidon(big.NewInt(674238462)).Compress()
scan := privK.SignPoseidon(big.NewInt(1)).Compress()
fromDB, err := value.Value()
assert.Nil(t, err)
assert.Nil(t, scan.Scan(fromDB))
assert.Equal(t, value, scan)
}
func TestSignatureScannerValuer(t *testing.T) {
privK := NewRandPrivKey()
var value driver.Valuer
@@ -142,8 +155,8 @@ func TestSignatureScannerValuer(t *testing.T) {
value = privK.SignPoseidon(big.NewInt(674238462))
scan = privK.SignPoseidon(big.NewInt(1))
fromDB, err := value.Value()
assert.NoError(t, err)
assert.NoError(t, scan.Scan(fromDB))
assert.Nil(t, err)
assert.Nil(t, scan.Scan(fromDB))
assert.Equal(t, value, scan)
}
@@ -157,14 +170,15 @@ func TestPubKeyScannerValuer(t *testing.T) {
value = pubKValue
scan = pubKScan
fromDB, err := value.Value()
assert.NoError(t, err)
assert.NoError(t, scan.Scan(fromDB))
assert.Nil(t, err)
assert.Nil(t, scan.Scan(fromDB))
assert.Equal(t, value, scan)
}
func BenchmarkBabyjubEddsa(b *testing.B) {
var k PrivateKey
_, err := hex.Decode(k[:], []byte("0001020304050607080900010203040506070809000102030405060708090001"))
_, err := hex.Decode(k[:],
[]byte("0001020304050607080900010203040506070809000102030405060708090001"))
require.Nil(b, err)
pk := k.Public()

View File

@@ -1,9 +1,13 @@
package babyjub
import (
"github.com/dchest/blake512" // I have personally reviewed that this module doesn't do anything suspicious
"github.com/dchest/blake512"
)
// Note on dchest/blake512: This specific blake512 module is compatible with
// the version of Blake512 used at circomlib, and this module has been reviewed
// to don't be doing do anything suspicious.
// Blake512 performs the blake-512 hash over the buffer m. Note that this is
// the original blake from the SHA3 competition and not the new blake2 version.
func Blake512(m []byte) []byte {

View File

@@ -3,13 +3,10 @@ package constants
import (
"fmt"
"math/big"
"github.com/iden3/go-iden3-crypto/ff"
)
// Q is the order of the integer field (Zq) that fits inside the SNARK.
var Q *big.Int
var QE *ff.Element
// Zero is 0.
var Zero *big.Int

View File

@@ -1,5 +1,6 @@
package ff
// NewElement returns a new empty *Element
func NewElement() *Element {
return &Element{}
}

1
go.sum
View File

@@ -126,6 +126,7 @@ github.com/steakknife/bloomfilter v0.0.0-20180922174646-6819c0d2a570 h1:gIlAHnH1
github.com/steakknife/bloomfilter v0.0.0-20180922174646-6819c0d2a570/go.mod h1:8OR4w3TdeIHIh1g6EMY5p0gVNOovcWC+1vpc7naMuAw=
github.com/steakknife/hamming v0.0.0-20180906055917-c99c65617cd3 h1:njlZPzLwU639dk2kqnCPPv+wNjq7Xb6EfUxe/oX0/NM=
github.com/steakknife/hamming v0.0.0-20180906055917-c99c65617cd3/go.mod h1:hpGUWaI9xL8pRQCTXQgocU38Qw1g0Us7n5PxxTwTCYU=
github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=

View File

@@ -10,6 +10,7 @@ import (
"github.com/iden3/go-iden3-crypto/utils"
)
// SEED defines the seed used to constants
const SEED = "mimc"
var constants = generateConstantsData()
@@ -47,8 +48,9 @@ func getConstants(seed string, nRounds int) []*ff.Element {
return cts
}
// MIMC7HashGeneric performs the MIMC7 hash over a *big.Int, in a generic way, where it can be specified the Finite Field over R, and the number of rounds
func MIMC7HashGeneric(xInBI, kBI *big.Int, nRounds int) *big.Int {
// MIMC7HashGeneric performs the MIMC7 hash over a *big.Int, in a generic way,
// where it can be specified the Finite Field over R, and the number of rounds
func MIMC7HashGeneric(xInBI, kBI *big.Int, nRounds int) *big.Int { //nolint:golint
xIn := ff.NewElement().SetBigInt(xInBI)
k := ff.NewElement().SetBigInt(kBI)
@@ -72,7 +74,8 @@ func MIMC7HashGeneric(xInBI, kBI *big.Int, nRounds int) *big.Int {
return res
}
// HashGeneric performs the MIMC7 hash over a *big.Int array, in a generic way, where it can be specified the Finite Field over R, and the number of rounds
// HashGeneric performs the MIMC7 hash over a *big.Int array, in a generic way,
// where it can be specified the Finite Field over R, and the number of rounds
func HashGeneric(iv *big.Int, arr []*big.Int, nRounds int) (*big.Int, error) {
if !utils.CheckBigIntArrayInField(arr) {
return nil, errors.New("inputs values not inside Finite Field")
@@ -88,8 +91,9 @@ func HashGeneric(iv *big.Int, arr []*big.Int, nRounds int) (*big.Int, error) {
return r, nil
}
// MIMC7Hash performs the MIMC7 hash over a *big.Int, using the Finite Field over R and the number of rounds setted in the `constants` variable
func MIMC7Hash(xInBI, kBI *big.Int) *big.Int {
// MIMC7Hash performs the MIMC7 hash over a *big.Int, using the Finite Field
// over R and the number of rounds setted in the `constants` variable
func MIMC7Hash(xInBI, kBI *big.Int) *big.Int { //nolint:golint
xIn := ff.NewElement().SetBigInt(xInBI)
k := ff.NewElement().SetBigInt(kBI)

View File

@@ -11,9 +11,13 @@ import (
func TestKeccak256(t *testing.T) {
res := crypto.Keccak256([]byte(SEED))
assert.Equal(t, "b6e489e6b37224a50bebfddbe7d89fa8fdcaa84304a70bd13f79b5d9f7951e9e", hex.EncodeToString(res))
assert.Equal(t,
"b6e489e6b37224a50bebfddbe7d89fa8fdcaa84304a70bd13f79b5d9f7951e9e",
hex.EncodeToString(res))
c := new(big.Int).SetBytes(crypto.Keccak256([]byte(SEED)))
assert.Equal(t, "82724731331859054037315113496710413141112897654334566532528783843265082629790", c.String())
assert.Equal(t,
"82724731331859054037315113496710413141112897654334566532528783843265082629790",
c.String())
}
func TestMIMC7Generic(t *testing.T) {
@@ -25,10 +29,14 @@ func TestMIMC7Generic(t *testing.T) {
// Generic Hash
mhg := MIMC7HashGeneric(b1, b2, 91)
assert.Equal(t, "10594780656576967754230020536574539122676596303354946869887184401991294982664", mhg.String())
assert.Equal(t,
"10594780656576967754230020536574539122676596303354946869887184401991294982664",
mhg.String())
hg, err := HashGeneric(big.NewInt(0), bigArray, 91)
assert.Nil(t, err)
assert.Equal(t, "6464402164086696096195815557694604139393321133243036833927490113253119343397", (*big.Int)(hg).String())
assert.Equal(t,
"6464402164086696096195815557694604139393321133243036833927490113253119343397",
(*big.Int)(hg).String())
}
func TestMIMC7(t *testing.T) {
@@ -43,7 +51,8 @@ func TestMIMC7(t *testing.T) {
h1, err := Hash(bigArray1, nil)
assert.Nil(t, err)
// same hash value than the iden3js and circomlib tests:
assert.Equal(t, "0x"+hex.EncodeToString((*big.Int)(h1).Bytes()), "0x237c92644dbddb86d8a259e0e923aaab65a93f1ec5758b8799988894ac0958fd")
assert.Equal(t, "0x"+hex.EncodeToString((*big.Int)(h1).Bytes()),
"0x237c92644dbddb86d8a259e0e923aaab65a93f1ec5758b8799988894ac0958fd")
// h2a, hash of 2 elements
bigArray2a := []*big.Int{b78, b41}
@@ -51,19 +60,22 @@ func TestMIMC7(t *testing.T) {
h2a, err := Hash(bigArray2a, nil)
assert.Nil(t, err)
// same hash value than the iden3js and circomlib tests:
assert.Equal(t, "0x"+hex.EncodeToString((*big.Int)(h2a).Bytes()), "0x067f3202335ea256ae6e6aadcd2d5f7f4b06a00b2d1e0de903980d5ab552dc70")
assert.Equal(t, "0x"+hex.EncodeToString((*big.Int)(h2a).Bytes()),
"0x067f3202335ea256ae6e6aadcd2d5f7f4b06a00b2d1e0de903980d5ab552dc70")
// h2b, hash of 2 elements
bigArray2b := []*big.Int{b12, b45}
mh2b := MIMC7Hash(b12, b45)
assert.Nil(t, err)
assert.Equal(t, "0x"+hex.EncodeToString((*big.Int)(mh2b).Bytes()), "0x2ba7ebad3c6b6f5a20bdecba2333c63173ca1a5f2f49d958081d9fa7179c44e4")
assert.Equal(t, "0x"+hex.EncodeToString((*big.Int)(mh2b).Bytes()),
"0x2ba7ebad3c6b6f5a20bdecba2333c63173ca1a5f2f49d958081d9fa7179c44e4")
h2b, err := Hash(bigArray2b, nil)
assert.Nil(t, err)
// same hash value than the iden3js and circomlib tests:
assert.Equal(t, "0x"+hex.EncodeToString((*big.Int)(h2b).Bytes()), "0x15ff7fe9793346a17c3150804bcb36d161c8662b110c50f55ccb7113948d8879")
assert.Equal(t, "0x"+hex.EncodeToString((*big.Int)(h2b).Bytes()),
"0x15ff7fe9793346a17c3150804bcb36d161c8662b110c50f55ccb7113948d8879")
// h4, hash of 4 elements
bigArray4 := []*big.Int{b12, b45, b78, b41}
@@ -71,11 +83,14 @@ func TestMIMC7(t *testing.T) {
h4, err := Hash(bigArray4, nil)
assert.Nil(t, err)
// same hash value than the iden3js and circomlib tests:
assert.Equal(t, "0x"+hex.EncodeToString((*big.Int)(h4).Bytes()), "0x284bc1f34f335933a23a433b6ff3ee179d682cd5e5e2fcdd2d964afa85104beb")
assert.Equal(t, "0x"+hex.EncodeToString((*big.Int)(h4).Bytes()),
"0x284bc1f34f335933a23a433b6ff3ee179d682cd5e5e2fcdd2d964afa85104beb")
msg := []byte("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.")
msg := []byte("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.") //nolint:lll
hmsg := HashBytes(msg)
assert.Equal(t, "16855787120419064316734350414336285711017110414939748784029922801367685456065", hmsg.String())
assert.Equal(t,
"16855787120419064316734350414336285711017110414939748784029922801367685456065",
hmsg.String())
}
func BenchmarkMIMC7(b *testing.B) {
@@ -86,6 +101,6 @@ func BenchmarkMIMC7(b *testing.B) {
bigArray4 := []*big.Int{b12, b45, b78, b41}
for i := 0; i < b.N; i++ {
Hash(bigArray4, nil) //nolint:errcheck
Hash(bigArray4, nil) //nolint:errcheck,gosec
}
}

View File

@@ -9,9 +9,9 @@ import (
"github.com/iden3/go-iden3-crypto/utils"
)
const NROUNDSF = 8
const NROUNDSF = 8 //nolint:golint
var NROUNDSP = []int{56, 57, 56, 60, 60, 63, 64, 63}
var NROUNDSP = []int{56, 57, 56, 60, 60, 63, 64, 63} //nolint:golint
func zero() *ff.Element {
return ff.NewElement()

View File

@@ -12,7 +12,9 @@ import (
func TestBlake2bVersion(t *testing.T) {
h := blake2b.Sum256([]byte("poseidon_constants"))
assert.Equal(t, "e57ba154fb2c47811dc1a2369b27e25a44915b4e4ece4eb8ec74850cb78e01b1", hex.EncodeToString(h[:]))
assert.Equal(t,
"e57ba154fb2c47811dc1a2369b27e25a44915b4e4ece4eb8ec74850cb78e01b1",
hex.EncodeToString(h[:]))
}
func TestPoseidonHash(t *testing.T) {
@@ -22,33 +24,47 @@ func TestPoseidonHash(t *testing.T) {
h, err := Hash([]*big.Int{b1})
assert.Nil(t, err)
assert.Equal(t, "11043376183861534927536506085090418075369306574649619885724436265926427398571", h.String())
assert.Equal(t,
"11043376183861534927536506085090418075369306574649619885724436265926427398571",
h.String())
h, err = Hash([]*big.Int{b1, b2})
assert.Nil(t, err)
assert.Equal(t, "17117985411748610629288516079940078114952304104811071254131751175361957805920", h.String())
assert.Equal(t,
"17117985411748610629288516079940078114952304104811071254131751175361957805920",
h.String())
h, err = Hash([]*big.Int{b1, b2, b0, b0, b0})
assert.Nil(t, err)
assert.Equal(t, "3975478831357328722254985704342968745327876719981393787143845259590563829094", h.String())
assert.Equal(t,
"3975478831357328722254985704342968745327876719981393787143845259590563829094",
h.String())
h, err = Hash([]*big.Int{b1, b2, b0, b0, b0, b0})
assert.Nil(t, err)
assert.Equal(t, "19772360636270345724087386688434825760738403416279047262510528378903625000110", h.String())
assert.Equal(t,
"19772360636270345724087386688434825760738403416279047262510528378903625000110",
h.String())
b3 := big.NewInt(3)
b4 := big.NewInt(4)
h, err = Hash([]*big.Int{b3, b4, b0, b0, b0})
assert.Nil(t, err)
assert.Equal(t, "3181200837746671699652342497997860344148947482942465819251904554707352676086", h.String())
assert.Equal(t,
"3181200837746671699652342497997860344148947482942465819251904554707352676086",
h.String())
h, err = Hash([]*big.Int{b3, b4, b0, b0, b0, b0})
assert.Nil(t, err)
assert.Equal(t, "8386348873272147968934270337233829407378789978142456170950021426339096575008", h.String())
assert.Equal(t,
"8386348873272147968934270337233829407378789978142456170950021426339096575008",
h.String())
b5 := big.NewInt(5)
b6 := big.NewInt(6)
h, err = Hash([]*big.Int{b1, b2, b3, b4, b5, b6})
assert.Nil(t, err)
assert.Equal(t, "5202465217520500374834597824465244016759843635092906214933648999760272616044", h.String())
assert.Equal(t,
"5202465217520500374834597824465244016759843635092906214933648999760272616044",
h.String())
}
func TestErrorInputs(t *testing.T) {
@@ -70,12 +86,12 @@ func TestErrorInputs(t *testing.T) {
func BenchmarkPoseidonHash(b *testing.B) {
b0 := big.NewInt(0)
b1 := utils.NewIntFromString("12242166908188651009877250812424843524687801523336557272219921456462821518061")
b2 := utils.NewIntFromString("12242166908188651009877250812424843524687801523336557272219921456462821518061")
b1 := utils.NewIntFromString("12242166908188651009877250812424843524687801523336557272219921456462821518061") //nolint:lll
b2 := utils.NewIntFromString("12242166908188651009877250812424843524687801523336557272219921456462821518061") //nolint:lll
bigArray4 := []*big.Int{b1, b2, b0, b0, b0, b0}
for i := 0; i < b.N; i++ {
Hash(bigArray4) //nolint:errcheck
Hash(bigArray4) //nolint:errcheck,gosec
}
}

View File

@@ -77,7 +77,7 @@ func HexDecodeInto(dst []byte, h []byte) error {
h = h[2:]
}
if len(h)/2 != len(dst) {
return fmt.Errorf("expected %v bytes in hex string, got %v", len(dst), len(h)/2)
return fmt.Errorf("expected %v bytes in hex string, got %v", len(dst), len(h)/2) //nolint:gomnd
}
n, err := hex.Decode(dst, h)
if err != nil {