Browse Source

Merge pull request #390 from hermeznetwork/feature/bjj-comp

Feature/bjj comp
feature/sql-semaphore1
a_bennassar 4 years ago
committed by GitHub
parent
commit
8a2df8de0d
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
47 changed files with 761 additions and 733 deletions
  1. +1
    -1
      api/accountcreationauths.go
  2. +7
    -13
      api/parsers.go
  3. +2
    -2
      api/parsers_test.go
  4. +14
    -4
      api/txspool.go
  5. +3
    -2
      api/txspool_test.go
  6. +17
    -18
      apitypes/apitypes.go
  7. +16
    -12
      apitypes/apitypes_test.go
  8. +12
    -18
      common/account.go
  9. +55
    -52
      common/account_test.go
  10. +5
    -5
      common/accountcreationauths.go
  11. +6
    -6
      common/fee_test.go
  12. +15
    -25
      common/l1tx.go
  13. +35
    -46
      common/l1tx_test.go
  14. +3
    -3
      common/l2tx_test.go
  15. +59
    -38
      common/pooll2tx.go
  16. +28
    -19
      common/pooll2tx_test.go
  17. +7
    -7
      common/tx.go
  18. +3
    -3
      common/tx_test.go
  19. +3
    -3
      common/utils.go
  20. +7
    -4
      common/utils_test.go
  21. +1
    -1
      common/zk_test.go
  22. +4
    -4
      db/historydb/historydb.go
  23. +6
    -6
      db/historydb/views.go
  24. +6
    -2
      db/l2db/l2db.go
  25. +21
    -21
      db/l2db/views.go
  26. +96
    -91
      db/statedb/statedb_test.go
  27. +37
    -26
      db/statedb/txprocessors.go
  28. +68
    -68
      db/statedb/txprocessors_test.go
  29. +10
    -12
      db/statedb/utils.go
  30. +19
    -19
      db/statedb/utils_test.go
  31. +119
    -120
      db/statedb/zkinputsgen_test.go
  32. +11
    -14
      eth/rollup.go
  33. +6
    -9
      eth/rollup_test.go
  34. +1
    -1
      go.mod
  35. +2
    -6
      go.sum
  36. +2
    -2
      synchronizer/synchronizer_test.go
  37. +1
    -1
      test/debugapi/debugapi_test.go
  38. +9
    -4
      test/ethclient.go
  39. +1
    -1
      test/ethclient_test.go
  40. +1
    -1
      test/historydb.go
  41. +1
    -1
      test/l2db.go
  42. +3
    -3
      test/til/lang_test.go
  43. +6
    -6
      test/til/sets_test.go
  44. +7
    -7
      test/til/txs.go
  45. +17
    -18
      test/til/txs_test.go
  46. +4
    -4
      txselector/txselector.go
  47. +4
    -4
      txselector/txselector_test.go

+ 1
- 1
api/accountcreationauths.go

@ -61,7 +61,7 @@ type receivedAuth struct {
func accountCreationAuthAPIToCommon(apiAuth *receivedAuth) *common.AccountCreationAuth {
return &common.AccountCreationAuth{
EthAddr: ethCommon.Address(apiAuth.EthAddr),
BJJ: (*babyjub.PublicKey)(&apiAuth.BJJ),
BJJ: (babyjub.PublicKeyComp)(apiAuth.BJJ),
Signature: []byte(apiAuth.Signature),
Timestamp: apiAuth.Timestamp,
}

+ 7
- 13
api/parsers.go

@ -87,7 +87,7 @@ func parseQueryHezEthAddr(c querier) (*ethCommon.Address, error) {
return hezStringToEthAddr(addrStr, name)
}
func parseQueryBJJ(c querier) (*babyjub.PublicKey, error) {
func parseQueryBJJ(c querier) (*babyjub.PublicKeyComp, error) {
const name = "BJJ"
bjjStr := c.Query(name)
if bjjStr == "" {
@ -146,7 +146,7 @@ func parseIdx(c querier) (*common.Idx, error) {
return stringToIdx(idxStr, name)
}
func parseExitFilters(c querier) (*common.TokenID, *ethCommon.Address, *babyjub.PublicKey, *common.Idx, error) {
func parseExitFilters(c querier) (*common.TokenID, *ethCommon.Address, *babyjub.PublicKeyComp, *common.Idx, error) {
// TokenID
tid, err := parseQueryUint("tokenId", nil, 0, maxUint32, c)
if err != nil {
@ -237,7 +237,7 @@ func parseSlotFilters(c querier) (*int64, *int64, *ethCommon.Address, *bool, err
return minSlotNum, maxSlotNum, wonByEthereumAddress, finishedAuction, nil
}
func parseAccountFilters(c querier) ([]common.TokenID, *ethCommon.Address, *babyjub.PublicKey, error) {
func parseAccountFilters(c querier) ([]common.TokenID, *ethCommon.Address, *babyjub.PublicKeyComp, error) {
// TokenID
idsStr := c.Query("tokenIds")
var tokenIDs []common.TokenID
@ -365,7 +365,7 @@ func hezStringToEthAddr(addrStr, name string) (*ethCommon.Address, error) {
return &addr, tracerr.Wrap(err)
}
func hezStringToBJJ(bjjStr, name string) (*babyjub.PublicKey, error) {
func hezStringToBJJ(bjjStr, name string) (*babyjub.PublicKeyComp, error) {
const decodedLen = 33
splitted := strings.Split(bjjStr, "hez:")
if len(splitted) != 2 || len(splitted[1]) != 44 {
@ -395,13 +395,7 @@ func hezStringToBJJ(bjjStr, name string) (*babyjub.PublicKey, error) {
name))
}
bjjComp := babyjub.PublicKeyComp(bjjBytes)
bjj, err := bjjComp.Decompress()
if err != nil {
return nil, tracerr.Wrap(fmt.Errorf(
"invalid %s, error decompressing public key: %s",
name, err.Error()))
}
return bjj, nil
return &bjjComp, nil
}
func parseQueryEthAddr(name string, c querier) (*ethCommon.Address, error) {
@ -436,8 +430,8 @@ type errorMsg struct {
Message string
}
func bjjToString(bjj *babyjub.PublicKey) string {
pkComp := [32]byte(bjj.Compress())
func bjjToString(bjj babyjub.PublicKeyComp) string {
pkComp := [32]byte(bjj)
sum := pkComp[0]
for i := 1; i < len(pkComp); i++ {
sum += pkComp[i]

+ 2
- 2
api/parsers_test.go

@ -214,10 +214,10 @@ func TestParseQueryBJJ(t *testing.T) {
assert.NoError(t, err)
assert.Nil(t, res)
// Correct
c.m[name] = bjjToString(pubK)
c.m[name] = bjjToString(pubK.Compress())
res, err = parseQueryBJJ(c)
assert.NoError(t, err)
assert.Equal(t, *pubK, *res)
assert.Equal(t, pubK.Compress(), *res)
}
func TestParseQueryTxType(t *testing.T) {

+ 14
- 4
api/txspool.go

@ -83,7 +83,7 @@ func (tx *receivedPoolTx) toPoolL2TxWrite() *l2db.PoolL2TxWrite {
FromIdx: common.Idx(tx.FromIdx),
ToIdx: (*common.Idx)(tx.ToIdx),
ToEthAddr: (*ethCommon.Address)(tx.ToEthAddr),
ToBJJ: (*babyjub.PublicKey)(tx.ToBJJ),
ToBJJ: (*babyjub.PublicKeyComp)(tx.ToBJJ),
TokenID: tx.TokenID,
Amount: (*big.Int)(&tx.Amount),
AmountFloat: amountF,
@ -94,7 +94,7 @@ func (tx *receivedPoolTx) toPoolL2TxWrite() *l2db.PoolL2TxWrite {
RqFromIdx: (*common.Idx)(tx.RqFromIdx),
RqToIdx: (*common.Idx)(tx.RqToIdx),
RqToEthAddr: (*ethCommon.Address)(tx.RqToEthAddr),
RqToBJJ: (*babyjub.PublicKey)(tx.RqToBJJ),
RqToBJJ: (*babyjub.PublicKeyComp)(tx.RqToBJJ),
RqTokenID: tx.RqTokenID,
RqAmount: (*big.Int)(tx.RqAmount),
RqFee: tx.RqFee,
@ -107,14 +107,12 @@ func (a *API) verifyPoolL2TxWrite(txw *l2db.PoolL2TxWrite) error {
poolTx := common.PoolL2Tx{
TxID: txw.TxID,
FromIdx: txw.FromIdx,
ToBJJ: txw.ToBJJ,
TokenID: txw.TokenID,
Amount: txw.Amount,
Fee: txw.Fee,
Nonce: txw.Nonce,
// State: txw.State,
Signature: txw.Signature,
RqToBJJ: txw.RqToBJJ,
RqAmount: txw.RqAmount,
Type: txw.Type,
}
@ -128,6 +126,12 @@ func (a *API) verifyPoolL2TxWrite(txw *l2db.PoolL2TxWrite) error {
} else {
poolTx.ToEthAddr = *txw.ToEthAddr
}
// ToBJJ
if txw.ToBJJ == nil {
poolTx.ToBJJ = common.EmptyBJJComp
} else {
poolTx.ToBJJ = *txw.ToBJJ
}
// RqFromIdx
if txw.RqFromIdx != nil {
poolTx.RqFromIdx = *txw.RqFromIdx
@ -142,6 +146,12 @@ func (a *API) verifyPoolL2TxWrite(txw *l2db.PoolL2TxWrite) error {
} else {
poolTx.RqToEthAddr = *txw.RqToEthAddr
}
// RqToBJJ
if txw.RqToBJJ == nil {
poolTx.RqToBJJ = common.EmptyBJJComp
} else {
poolTx.RqToBJJ = *txw.RqToBJJ
}
// RqTokenID
if txw.RqTokenID != nil {
poolTx.RqTokenID = *txw.RqTokenID

+ 3
- 2
api/txspool_test.go

@ -122,7 +122,7 @@ func genTestPoolTxs(
addr := ethAddrToHez(acc.EthAddr)
genReceiveTx.ToEthAddr = &addr
}
if poolTx.ToBJJ != nil {
if poolTx.ToBJJ != common.EmptyBJJComp {
toBJJ := bjjToString(poolTx.ToBJJ)
genSendTx.ToBJJ = &toBJJ
genReceiveTx.ToBJJ = &toBJJ
@ -151,12 +151,13 @@ func genTestPoolTxs(
genSendTx.RqToEthAddr = &rqToEth
genReceiveTx.RqToEthAddr = &rqToEth
}
if poolTx.RqToBJJ != nil {
if poolTx.RqToBJJ != common.EmptyBJJComp {
rqToBJJ := bjjToString(poolTx.RqToBJJ)
genSendTx.RqToBJJ = &rqToBJJ
genReceiveTx.RqToBJJ = &rqToBJJ
}
}
poolTxsToSend = append(poolTxsToSend, genSendTx)
poolTxsToReceive = append(poolTxsToReceive, genReceiveTx)
}

+ 17
- 18
apitypes/apitypes.go

@ -143,14 +143,13 @@ func (s *StrHezEthAddr) UnmarshalText(text []byte) error {
return nil
}
// HezBJJ is used to scan/value *babyjub.PublicKey directly into strings that follow the BJJ public key hez fotmat (^hez:[A-Za-z0-9_-]{44}$) from/to sql DBs.
// It assumes that *babyjub.PublicKey are inserted/fetched to/from the DB using the default Scan/Value interface
// HezBJJ is used to scan/value *babyjub.PublicKeyComp directly into strings that follow the BJJ public key hez fotmat (^hez:[A-Za-z0-9_-]{44}$) from/to sql DBs.
// It assumes that *babyjub.PublicKeyComp are inserted/fetched to/from the DB using the default Scan/Value interface
type HezBJJ string
// NewHezBJJ creates a HezBJJ from a *babyjub.PublicKey.
// NewHezBJJ creates a HezBJJ from a *babyjub.PublicKeyComp.
// Calling this method with a nil bjj causes panic
func NewHezBJJ(bjj *babyjub.PublicKey) HezBJJ {
pkComp := [32]byte(bjj.Compress())
func NewHezBJJ(pkComp babyjub.PublicKeyComp) HezBJJ {
sum := pkComp[0]
for i := 1; i < len(pkComp); i++ {
sum += pkComp[i]
@ -159,20 +158,20 @@ func NewHezBJJ(bjj *babyjub.PublicKey) HezBJJ {
return HezBJJ("hez:" + base64.RawURLEncoding.EncodeToString(bjjSum))
}
func hezStrToBJJ(s string) (*babyjub.PublicKey, error) {
func hezStrToBJJ(s string) (babyjub.PublicKeyComp, error) {
const decodedLen = 33
const encodedLen = 44
formatErr := errors.New("invalid BJJ format. Must follow this regex: ^hez:[A-Za-z0-9_-]{44}$")
encoded := strings.TrimPrefix(s, "hez:")
if len(encoded) != encodedLen {
return nil, formatErr
return common.EmptyBJJComp, formatErr
}
decoded, err := base64.RawURLEncoding.DecodeString(encoded)
if err != nil {
return nil, formatErr
return common.EmptyBJJComp, formatErr
}
if len(decoded) != decodedLen {
return nil, formatErr
return common.EmptyBJJComp, formatErr
}
bjjBytes := [decodedLen - 1]byte{}
copy(bjjBytes[:decodedLen-1], decoded[:decodedLen-1])
@ -181,27 +180,27 @@ func hezStrToBJJ(s string) (*babyjub.PublicKey, error) {
sum += bjjBytes[i]
}
if decoded[decodedLen-1] != sum {
return nil, tracerr.Wrap(errors.New("checksum verification failed"))
return common.EmptyBJJComp, tracerr.Wrap(errors.New("checksum verification failed"))
}
bjjComp := babyjub.PublicKeyComp(bjjBytes)
return bjjComp.Decompress()
return bjjComp, nil
}
// ToBJJ returns a *babyjub.PublicKey created from HezBJJ
func (b HezBJJ) ToBJJ() (*babyjub.PublicKey, error) {
// ToBJJ returns a babyjub.PublicKeyComp created from HezBJJ
func (b HezBJJ) ToBJJ() (babyjub.PublicKeyComp, error) {
return hezStrToBJJ(string(b))
}
// Scan implements Scanner for database/sql
func (b *HezBJJ) Scan(src interface{}) error {
bjj := &babyjub.PublicKey{}
bjj := &babyjub.PublicKeyComp{}
if err := bjj.Scan(src); err != nil {
return tracerr.Wrap(err)
}
if bjj == nil {
return nil
}
*b = NewHezBJJ(bjj)
*b = NewHezBJJ(*bjj)
return nil
}
@ -214,8 +213,8 @@ func (b HezBJJ) Value() (driver.Value, error) {
return bjj.Value()
}
// StrHezBJJ is used to unmarshal HezBJJ directly into an alias of babyjub.PublicKey
type StrHezBJJ babyjub.PublicKey
// StrHezBJJ is used to unmarshal HezBJJ directly into an alias of babyjub.PublicKeyComp
type StrHezBJJ babyjub.PublicKeyComp
// UnmarshalText unmarshals a StrHezBJJ
func (s *StrHezBJJ) UnmarshalText(text []byte) error {
@ -223,7 +222,7 @@ func (s *StrHezBJJ) UnmarshalText(text []byte) error {
if err != nil {
return tracerr.Wrap(err)
}
*s = StrHezBJJ(*bjj)
*s = StrHezBJJ(bjj)
return nil
}

+ 16
- 12
apitypes/apitypes_test.go

@ -157,11 +157,11 @@ func TestStrHezBJJ(t *testing.T) {
I StrHezBJJ
}
priv := babyjub.NewRandPrivKey()
hezBjj := NewHezBJJ(priv.Public())
hezBjj := NewHezBJJ(priv.Public().Compress())
from := []byte(`{"I":"` + hezBjj + `"}`)
to := &testStrHezBJJ{}
assert.NoError(t, json.Unmarshal(from, to))
assert.Equal(t, priv.Public(), (*babyjub.PublicKey)(&to.I))
assert.Equal(t, priv.Public().Compress(), (babyjub.PublicKeyComp)(to.I))
}
func TestStrHezIdx(t *testing.T) {
@ -262,20 +262,23 @@ func TestHezBJJ(t *testing.T) {
assert.NoError(t, err)
// Example structs
type bjjStruct struct {
I *babyjub.PublicKey `meddler:"i"`
I babyjub.PublicKeyComp `meddler:"i"`
}
type hezBJJStruct struct {
I HezBJJ `meddler:"i"`
}
type bjjStructNil struct {
I *babyjub.PublicKeyComp `meddler:"i"`
}
type hezBJJStructNil struct {
I *HezBJJ `meddler:"i"`
}
// Not nil case
// Insert into DB using *babyjub.PublicKey Scan/Value
// Insert into DB using *babyjub.PublicKeyComp Scan/Value
priv := babyjub.NewRandPrivKey()
fromBJJ := bjjStruct{
I: priv.Public(),
I: priv.Public().Compress(),
}
err = meddler.Insert(db, "test", &fromBJJ)
assert.NoError(t, err)
@ -289,11 +292,11 @@ func TestHezBJJ(t *testing.T) {
assert.NoError(t, err)
// Insert into DB using HezBJJ Scan/Value
fromHezBJJ := hezBJJStruct{
I: NewHezBJJ(priv.Public()),
I: NewHezBJJ(priv.Public().Compress()),
}
err = meddler.Insert(db, "test", &fromHezBJJ)
assert.NoError(t, err)
// Read from DB using *babyjub.PublicKey Scan/Value
// Read from DB using *babyjub.PublicKeyComp Scan/Value
toBJJ := bjjStruct{}
err = meddler.QueryRow(db, &toBJJ, "select * from test")
assert.NoError(t, err)
@ -303,8 +306,8 @@ func TestHezBJJ(t *testing.T) {
// Clean DB
_, err = db.Exec("delete from test")
assert.NoError(t, err)
// Insert into DB using *babyjub.PublicKey Scan/Value
fromBJJNil := bjjStruct{
// Insert into DB using *babyjub.PublicKeyComp Scan/Value
fromBJJNil := bjjStructNil{
I: nil,
}
err = meddler.Insert(db, "test", &fromBJJNil)
@ -326,9 +329,10 @@ func TestHezBJJ(t *testing.T) {
}
err = meddler.Insert(db, "test", &fromHezBJJNil)
assert.NoError(t, err)
// Read from DB using *babyjub.PublicKey Scan/Value
toBJJNil := bjjStruct{
I: priv.Public(), // check that this will be set to nil, not because of not being initialized
// Read from DB using *babyjub.PublicKeyComp Scan/Value
bjjComp := priv.Public().Compress()
toBJJNil := bjjStructNil{
I: &bjjComp, // check that this will be set to nil, not because of not being initialized
}
err = meddler.QueryRow(db, &toBJJNil, "select * from test")
assert.NoError(t, err)

+ 12
- 18
common/account.go

@ -115,13 +115,13 @@ func NonceFromBytes(b [5]byte) Nonce {
// Account is a struct that gives information of the holdings of an address and a specific token. Is the data structure that generates the Value stored in the leaf of the MerkleTree
type Account struct {
Idx Idx `meddler:"idx"`
TokenID TokenID `meddler:"token_id"`
BatchNum BatchNum `meddler:"batch_num"`
PublicKey *babyjub.PublicKey `meddler:"bjj"`
EthAddr ethCommon.Address `meddler:"eth_addr"`
Nonce Nonce `meddler:"-"` // max of 40 bits used
Balance *big.Int `meddler:"-"` // max of 192 bits used
Idx Idx `meddler:"idx"`
TokenID TokenID `meddler:"token_id"`
BatchNum BatchNum `meddler:"batch_num"`
PublicKey babyjub.PublicKeyComp `meddler:"bjj"`
EthAddr ethCommon.Address `meddler:"eth_addr"`
Nonce Nonce `meddler:"-"` // max of 40 bits used
Balance *big.Int `meddler:"-"` // max of 192 bits used
}
func (a *Account) String() string {
@ -158,15 +158,13 @@ func (a *Account) Bytes() ([32 * NLeafElems]byte, error) {
copy(b[28:32], a.TokenID.Bytes())
copy(b[23:28], nonceBytes[:])
if a.PublicKey == nil {
return b, tracerr.Wrap(fmt.Errorf("Account.PublicKey can not be nil"))
}
if babyjub.PointCoordSign(a.PublicKey.X) {
pkSign, pkY := babyjub.UnpackSignY(a.PublicKey)
if pkSign {
b[22] = 1
}
balanceBytes := a.Balance.Bytes()
copy(b[64-len(balanceBytes):64], balanceBytes)
ayBytes := a.PublicKey.Y.Bytes()
ayBytes := pkY.Bytes()
copy(b[96-len(ayBytes):96], ayBytes)
copy(b[108:128], a.EthAddr.Bytes())
@ -234,11 +232,7 @@ func AccountFromBytes(b [32 * NLeafElems]byte) (*Account, error) {
return nil, tracerr.Wrap(fmt.Errorf("%s Balance", ErrNumOverflow))
}
ay := new(big.Int).SetBytes(b[64:96])
pkPoint, err := babyjub.PointFromSignAndY(sign, ay)
if err != nil {
return nil, tracerr.Wrap(err)
}
publicKey := babyjub.PublicKey(*pkPoint)
publicKeyComp := babyjub.PackSignY(sign, ay)
ethAddr := ethCommon.BytesToAddress(b[108:128])
if !cryptoUtils.CheckBigIntInField(balance) {
@ -252,7 +246,7 @@ func AccountFromBytes(b [32 * NLeafElems]byte) (*Account, error) {
TokenID: TokenID(tokenID),
Nonce: nonce,
Balance: balance,
PublicKey: &publicKey,
PublicKey: publicKeyComp,
EthAddr: ethAddr,
}
return &a, nil

+ 55
- 52
common/account_test.go

@ -22,11 +22,11 @@ import (
func TestIdxParser(t *testing.T) {
i := Idx(1)
iBytes, err := i.Bytes()
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, 6, len(iBytes))
assert.Equal(t, "000000000001", hex.EncodeToString(iBytes[:]))
i2, err := IdxFromBytes(iBytes[:])
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, i, i2)
i = Idx(100)
@ -35,11 +35,11 @@ func TestIdxParser(t *testing.T) {
// value before overflow
i = Idx(281474976710655)
iBytes, err = i.Bytes()
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, 6, len(iBytes))
assert.Equal(t, "ffffffffffff", hex.EncodeToString(iBytes[:]))
i2, err = IdxFromBytes(iBytes[:])
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, i, i2)
// expect value overflow
@ -52,7 +52,7 @@ func TestIdxParser(t *testing.T) {
func TestNonceParser(t *testing.T) {
n := Nonce(1)
nBytes, err := n.Bytes()
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, 5, len(nBytes))
assert.Equal(t, "0000000001", hex.EncodeToString(nBytes[:]))
n2 := NonceFromBytes(nBytes)
@ -61,7 +61,7 @@ func TestNonceParser(t *testing.T) {
// value before overflow
n = Nonce(1099511627775)
nBytes, err = n.Bytes()
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, 5, len(nBytes))
assert.Equal(t, "ffffffffff", hex.EncodeToString(nBytes[:]))
n2 = NonceFromBytes(nBytes)
@ -77,25 +77,25 @@ func TestNonceParser(t *testing.T) {
func TestAccount(t *testing.T) {
var sk babyjub.PrivateKey
_, err := hex.Decode(sk[:], []byte("0001020304050607080900010203040506070809000102030405060708090001"))
assert.Nil(t, err)
assert.NoError(t, err)
pk := sk.Public()
account := &Account{
TokenID: TokenID(1),
Nonce: Nonce(1234),
Balance: big.NewInt(1000),
PublicKey: pk,
PublicKey: pk.Compress(),
EthAddr: ethCommon.HexToAddress("0xc58d29fA6e86E4FAe04DDcEd660d45BCf3Cb2370"),
}
b, err := account.Bytes()
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, byte(1), b[22])
a1, err := AccountFromBytes(b)
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, account, a1)
e, err := account.BigInts()
assert.Nil(t, err)
assert.NoError(t, err)
assert.True(t, cryptoUtils.CheckBigIntInField(e[0]))
assert.True(t, cryptoUtils.CheckBigIntInField(e[1]))
assert.True(t, cryptoUtils.CheckBigIntInField(e[2]))
@ -106,7 +106,7 @@ func TestAccount(t *testing.T) {
assert.Equal(t, new(big.Int).SetBytes(account.EthAddr.Bytes()).String(), e[3].String())
a2, err := AccountFromBigInts(e)
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, account, a2)
assert.Equal(t, a1, a2)
}
@ -116,35 +116,35 @@ func TestAccountLoop(t *testing.T) {
for i := 0; i < 256; i++ {
var sk babyjub.PrivateKey
_, err := hex.Decode(sk[:], []byte("0001020304050607080900010203040506070809000102030405060708090001"))
assert.Nil(t, err)
assert.NoError(t, err)
pk := sk.Public()
key, err := ethCrypto.GenerateKey()
assert.Nil(t, err)
assert.NoError(t, err)
address := ethCrypto.PubkeyToAddress(key.PublicKey)
account := &Account{
TokenID: TokenID(i),
Nonce: Nonce(i),
Balance: big.NewInt(1000),
PublicKey: pk,
PublicKey: pk.Compress(),
EthAddr: address,
}
b, err := account.Bytes()
assert.Nil(t, err)
assert.NoError(t, err)
a1, err := AccountFromBytes(b)
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, account, a1)
e, err := account.BigInts()
assert.Nil(t, err)
assert.NoError(t, err)
assert.True(t, cryptoUtils.CheckBigIntInField(e[0]))
assert.True(t, cryptoUtils.CheckBigIntInField(e[1]))
assert.True(t, cryptoUtils.CheckBigIntInField(e[2]))
assert.True(t, cryptoUtils.CheckBigIntInField(e[3]))
a2, err := AccountFromBigInts(e)
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, account, a2)
}
}
@ -157,31 +157,31 @@ func TestAccountLoopRandom(t *testing.T) {
pk := sk.Public()
key, err := ethCrypto.GenerateKey()
assert.Nil(t, err)
assert.NoError(t, err)
address := ethCrypto.PubkeyToAddress(key.PublicKey)
account := &Account{
TokenID: TokenID(i),
Nonce: Nonce(i),
Balance: big.NewInt(1000),
PublicKey: pk,
PublicKey: pk.Compress(),
EthAddr: address,
}
b, err := account.Bytes()
assert.Nil(t, err)
assert.NoError(t, err)
a1, err := AccountFromBytes(b)
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, account, a1)
e, err := account.BigInts()
assert.Nil(t, err)
assert.NoError(t, err)
assert.True(t, cryptoUtils.CheckBigIntInField(e[0]))
assert.True(t, cryptoUtils.CheckBigIntInField(e[1]))
assert.True(t, cryptoUtils.CheckBigIntInField(e[2]))
assert.True(t, cryptoUtils.CheckBigIntInField(e[3]))
a2, err := AccountFromBigInts(e)
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, account, a2)
}
}
@ -200,18 +200,18 @@ func bigFromStr(h string, u int) *big.Int {
func TestAccountHashValue(t *testing.T) {
var sk babyjub.PrivateKey
_, err := hex.Decode(sk[:], []byte("0001020304050607080900010203040506070809000102030405060708090001"))
assert.Nil(t, err)
assert.NoError(t, err)
pk := sk.Public()
account := &Account{
TokenID: TokenID(1),
Nonce: Nonce(1234),
Balance: big.NewInt(1000),
PublicKey: pk,
PublicKey: pk.Compress(),
EthAddr: ethCommon.HexToAddress("0xc58d29fA6e86E4FAe04DDcEd660d45BCf3Cb2370"),
}
v, err := account.HashValue()
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, "16297758255249203915951182296472515138555043617458222397753168518282206850764", v.String())
}
@ -219,67 +219,70 @@ func TestAccountHashValueTestVectors(t *testing.T) {
// values from js test vectors
ay := new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(253), nil), big.NewInt(1))
assert.Equal(t, "1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", (hex.EncodeToString(ay.Bytes())))
bjj, err := babyjub.PointFromSignAndY(true, ay)
require.Nil(t, err)
bjjPoint, err := babyjub.PointFromSignAndY(true, ay)
require.NoError(t, err)
bjj := babyjub.PublicKey(*bjjPoint)
account := &Account{
Idx: 1,
TokenID: 0xFFFFFFFF,
PublicKey: (*babyjub.PublicKey)(bjj),
PublicKey: bjj.Compress(),
EthAddr: ethCommon.HexToAddress("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"),
Nonce: Nonce(0xFFFFFFFFFF),
Balance: bigFromStr("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16),
}
e, err := account.BigInts()
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, "9444732965739290427391", e[0].String())
assert.Equal(t, "6277101735386680763835789423207666416102355444464034512895", e[1].String())
assert.Equal(t, "14474011154664524427946373126085988481658748083205070504932198000989141204991", e[2].String())
assert.Equal(t, "1461501637330902918203684832716283019655932542975", e[3].String())
h, err := poseidon.Hash(e[:])
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, "4550823210217540218403400309533329186487982452461145263910122718498735057257", h.String())
v, err := account.HashValue()
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, "4550823210217540218403400309533329186487982452461145263910122718498735057257", v.String())
// second account
ay = big.NewInt(0)
bjj, err = babyjub.PointFromSignAndY(false, ay)
require.Nil(t, err)
bjjPoint, err = babyjub.PointFromSignAndY(false, ay)
require.NoError(t, err)
bjj = babyjub.PublicKey(*bjjPoint)
account = &Account{
TokenID: 0,
PublicKey: (*babyjub.PublicKey)(bjj),
PublicKey: bjj.Compress(),
EthAddr: ethCommon.HexToAddress("0x00"),
Nonce: Nonce(0),
Balance: big.NewInt(0),
}
v, err = account.HashValue()
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, "7750253361301235345986002241352365187241910378619330147114280396816709365657", v.String())
// third account
ay = bigFromStr("21b0a1688b37f77b1d1d5539ec3b826db5ac78b2513f574a04c50a7d4f8246d7", 16)
bjj, err = babyjub.PointFromSignAndY(false, ay)
require.Nil(t, err)
bjjPoint, err = babyjub.PointFromSignAndY(false, ay)
require.NoError(t, err)
bjj = babyjub.PublicKey(*bjjPoint)
account = &Account{
TokenID: 3,
PublicKey: (*babyjub.PublicKey)(bjj),
PublicKey: bjj.Compress(),
EthAddr: ethCommon.HexToAddress("0xA3C88ac39A76789437AED31B9608da72e1bbfBF9"),
Nonce: Nonce(129),
Balance: bigFromStr("42000000000000000000", 10),
}
e, err = account.BigInts()
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, "554050781187", e[0].String())
assert.Equal(t, "42000000000000000000", e[1].String())
assert.Equal(t, "15238403086306505038849621710779816852318505119327426213168494964113886299863", e[2].String())
assert.Equal(t, "935037732739828347587684875151694054123613453305", e[3].String())
v, err = account.HashValue()
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, "10565754214047872850889045989683221123564392137456000481397520902594455245517", v.String())
}
@ -290,7 +293,7 @@ func TestAccountErrNotInFF(t *testing.T) {
r := new(big.Int).Sub(cryptoConstants.Q, big.NewInt(1))
e := [NLeafElems]*big.Int{z, z, r, r}
_, err := AccountFromBigInts(e)
assert.Nil(t, err)
assert.NoError(t, err)
// Q should give error
r = cryptoConstants.Q
@ -310,7 +313,7 @@ func TestAccountErrNotInFF(t *testing.T) {
func TestAccountErrNumOverflowNonce(t *testing.T) {
var sk babyjub.PrivateKey
_, err := hex.Decode(sk[:], []byte("0001020304050607080900010203040506070809000102030405060708090001"))
assert.Nil(t, err)
assert.NoError(t, err)
pk := sk.Public()
// check limit
@ -318,11 +321,11 @@ func TestAccountErrNumOverflowNonce(t *testing.T) {
TokenID: TokenID(1),
Nonce: Nonce(math.Pow(2, 40) - 1),
Balance: big.NewInt(1000),
PublicKey: pk,
PublicKey: pk.Compress(),
EthAddr: ethCommon.HexToAddress("0xc58d29fA6e86E4FAe04DDcEd660d45BCf3Cb2370"),
}
_, err = account.Bytes()
assert.Nil(t, err)
assert.NoError(t, err)
// force value overflow
account.Nonce = Nonce(math.Pow(2, 40))
@ -331,13 +334,13 @@ func TestAccountErrNumOverflowNonce(t *testing.T) {
assert.Equal(t, fmt.Errorf("%s Nonce", ErrNumOverflow), tracerr.Unwrap(err))
_, err = AccountFromBytes(b)
assert.Nil(t, err)
assert.NoError(t, err)
}
func TestAccountErrNumOverflowBalance(t *testing.T) {
var sk babyjub.PrivateKey
_, err := hex.Decode(sk[:], []byte("0001020304050607080900010203040506070809000102030405060708090001"))
assert.Nil(t, err)
assert.NoError(t, err)
pk := sk.Public()
// check limit
@ -345,13 +348,13 @@ func TestAccountErrNumOverflowBalance(t *testing.T) {
TokenID: TokenID(1),
Nonce: Nonce(math.Pow(2, 40) - 1),
Balance: new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(192), nil), big.NewInt(1)),
PublicKey: pk,
PublicKey: pk.Compress(),
EthAddr: ethCommon.HexToAddress("0xc58d29fA6e86E4FAe04DDcEd660d45BCf3Cb2370"),
}
assert.Equal(t, "6277101735386680763835789423207666416102355444464034512895", account.Balance.String())
_, err = account.Bytes()
assert.Nil(t, err)
assert.NoError(t, err)
// force value overflow
account.Balance = new(big.Int).Exp(big.NewInt(2), big.NewInt(192), nil)
@ -361,7 +364,7 @@ func TestAccountErrNumOverflowBalance(t *testing.T) {
assert.Equal(t, fmt.Errorf("%s Balance", ErrNumOverflow), tracerr.Unwrap(err))
_, err = AccountFromBytes(b)
assert.Nil(t, err)
assert.NoError(t, err)
b[39] = 1
_, err = AccountFromBytes(b)

+ 5
- 5
common/accountcreationauths.go

@ -11,17 +11,17 @@ import (
// AccountCreationAuth authorizations sent by users to the L2DB, to be used for account creations when necessary
type AccountCreationAuth struct {
EthAddr ethCommon.Address `meddler:"eth_addr"`
BJJ *babyjub.PublicKey `meddler:"bjj"`
Signature []byte `meddler:"signature"`
Timestamp time.Time `meddler:"timestamp,utctime"`
EthAddr ethCommon.Address `meddler:"eth_addr"`
BJJ babyjub.PublicKeyComp `meddler:"bjj"`
Signature []byte `meddler:"signature"`
Timestamp time.Time `meddler:"timestamp,utctime"`
}
// HashToSign builds the hash to be signed using BJJ pub key and the constant message
func (a *AccountCreationAuth) HashToSign() ([]byte, error) {
// Calculate message to be signed
const msg = "I authorize this babyjubjub key for hermez rollup account creation"
comp, err := a.BJJ.Compress().MarshalText()
comp, err := a.BJJ.MarshalText()
if err != nil {
return nil, tracerr.Wrap(err)
}

+ 6
- 6
common/fee_test.go

@ -23,27 +23,27 @@ func TestFeePercentage(t *testing.T) {
func TestCalcFeeAmount(t *testing.T) {
v := big.NewInt(1000)
feeAmount, err := CalcFeeAmount(v, FeeSelector(195)) // 800%
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, "8000", feeAmount.String())
feeAmount, err = CalcFeeAmount(v, FeeSelector(192)) // 100%
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, "1000", feeAmount.String())
feeAmount, err = CalcFeeAmount(v, FeeSelector(172)) // 50%
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, "500", feeAmount.String())
feeAmount, err = CalcFeeAmount(v, FeeSelector(126)) // 10.2%
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, "101", feeAmount.String())
feeAmount, err = CalcFeeAmount(v, FeeSelector(60)) // 1.03%
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, "10", feeAmount.String())
feeAmount, err = CalcFeeAmount(v, FeeSelector(31)) // 0.127%
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, "1", feeAmount.String())
}

+ 15
- 25
common/l1tx.go

@ -28,16 +28,16 @@ type L1Tx struct {
// where type:
// - L1UserTx: 0
// - L1CoordinatorTx: 1
TxID TxID `meddler:"id"`
ToForgeL1TxsNum *int64 `meddler:"to_forge_l1_txs_num"` // toForgeL1TxsNum in which the tx was forged / will be forged
Position int `meddler:"position"`
UserOrigin bool `meddler:"user_origin"` // true if the tx was originated by a user, false if it was aoriginated by a coordinator. Note that this differ from the spec for implementation simplification purpposes
FromIdx Idx `meddler:"from_idx,zeroisnull"` // FromIdx is used by L1Tx/Deposit to indicate the Idx receiver of the L1Tx.DepositAmount (deposit)
FromEthAddr ethCommon.Address `meddler:"from_eth_addr,zeroisnull"`
FromBJJ *babyjub.PublicKey `meddler:"from_bjj,zeroisnull"`
ToIdx Idx `meddler:"to_idx"` // ToIdx is ignored in L1Tx/Deposit, but used in the L1Tx/DepositAndTransfer
TokenID TokenID `meddler:"token_id"`
Amount *big.Int `meddler:"amount,bigint"`
TxID TxID `meddler:"id"`
ToForgeL1TxsNum *int64 `meddler:"to_forge_l1_txs_num"` // toForgeL1TxsNum in which the tx was forged / will be forged
Position int `meddler:"position"`
UserOrigin bool `meddler:"user_origin"` // true if the tx was originated by a user, false if it was aoriginated by a coordinator. Note that this differ from the spec for implementation simplification purpposes
FromIdx Idx `meddler:"from_idx,zeroisnull"` // FromIdx is used by L1Tx/Deposit to indicate the Idx receiver of the L1Tx.DepositAmount (deposit)
FromEthAddr ethCommon.Address `meddler:"from_eth_addr,zeroisnull"`
FromBJJ babyjub.PublicKeyComp `meddler:"from_bjj,zeroisnull"`
ToIdx Idx `meddler:"to_idx"` // ToIdx is ignored in L1Tx/Deposit, but used in the L1Tx/DepositAndTransfer
TokenID TokenID `meddler:"token_id"`
Amount *big.Int `meddler:"amount,bigint"`
// EffectiveAmount only applies to L1UserTx.
EffectiveAmount *big.Int `meddler:"effective_amount,bigintnull"`
DepositAmount *big.Int `meddler:"deposit_amount,bigint"`
@ -261,8 +261,8 @@ func L1TxFromDataAvailability(b []byte, nLevels uint32) (*L1Tx, error) {
func (tx *L1Tx) BytesGeneric() ([]byte, error) {
var b [L1UserTxBytesLen]byte
copy(b[0:20], tx.FromEthAddr.Bytes())
if tx.FromBJJ != nil {
pkCompL := tx.FromBJJ.Compress()
if tx.FromBJJ != EmptyBJJComp {
pkCompL := tx.FromBJJ
pkCompB := SwapEndianness(pkCompL[:])
copy(b[20:52], pkCompB[:])
}
@ -310,7 +310,7 @@ func (tx *L1Tx) BytesCoordinatorTx(compressedSignatureBytes []byte) ([]byte, err
b[0] = v
copy(b[1:33], s)
copy(b[33:65], r)
pkCompL := tx.FromBJJ.Compress()
pkCompL := tx.FromBJJ
pkCompB := SwapEndianness(pkCompL[:])
copy(b[65:97], pkCompB[:])
copy(b[97:101], tx.TokenID.Bytes())
@ -331,12 +331,7 @@ func L1UserTxFromBytes(b []byte) (*L1Tx, error) {
pkCompB := b[20:52]
pkCompL := SwapEndianness(pkCompB)
var pkComp babyjub.PublicKeyComp
copy(pkComp[:], pkCompL)
tx.FromBJJ, err = pkComp.Decompress()
if err != nil {
return nil, tracerr.Wrap(err)
}
copy(tx.FromBJJ[:], pkCompL)
fromIdx, err := IdxFromBytes(b[52:58])
if err != nil {
return nil, tracerr.Wrap(err)
@ -378,12 +373,7 @@ func L1CoordinatorTxFromBytes(b []byte, chainID *big.Int, hermezAddress ethCommo
r := b[33:65]
pkCompB := b[65:97]
pkCompL := SwapEndianness(pkCompB)
var pkComp babyjub.PublicKeyComp
copy(pkComp[:], pkCompL)
tx.FromBJJ, err = pkComp.Decompress()
if err != nil {
return nil, tracerr.Wrap(err)
}
copy(tx.FromBJJ[:], pkCompL)
tx.TokenID, err = TokenIDFromBytes(b[97:101])
if err != nil {
return nil, tracerr.Wrap(err)

+ 35
- 46
common/l1tx_test.go

@ -28,7 +28,7 @@ func TestNewL1UserTx(t *testing.T) {
FromIdx: Idx(300),
}
l1Tx, err := NewL1Tx(l1Tx)
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, "0x00000000000001e240004700", l1Tx.TxID.String())
}
@ -45,7 +45,7 @@ func TestNewL1CoordinatorTx(t *testing.T) {
BatchNum: &batchNum,
}
l1Tx, err := NewL1Tx(l1Tx)
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, "0x01000000000000cafe005800", l1Tx.TxID.String())
}
@ -57,7 +57,7 @@ func TestL1TxCompressedData(t *testing.T) {
TokenID: 5,
}
txCompressedData, err := tx.TxCompressedData()
assert.Nil(t, err)
assert.NoError(t, err)
// test vector value generated from javascript implementation
expectedStr := "7307597389635308713748674793997299267459594577423"
@ -73,7 +73,7 @@ func TestBytesDataAvailability(t *testing.T) {
TokenID: 5,
}
txCompressedData, err := tx.BytesDataAvailability(32)
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, "0000000200000003000000", hex.EncodeToString(txCompressedData))
tx = L1Tx{
@ -83,7 +83,7 @@ func TestBytesDataAvailability(t *testing.T) {
TokenID: 5,
}
txCompressedData, err = tx.BytesDataAvailability(32)
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, "0000000200000003000400", hex.EncodeToString(txCompressedData))
}
@ -94,7 +94,7 @@ func TestL1TxFromDataAvailability(t *testing.T) {
Amount: big.NewInt(4),
}
txCompressedData, err := tx.BytesDataAvailability(32)
assert.Nil(t, err)
assert.NoError(t, err)
l1tx, err := L1TxFromDataAvailability(txCompressedData, 32)
require.NoError(t, err)
assert.Equal(t, tx.FromIdx, l1tx.FromIdx)
@ -106,7 +106,7 @@ func TestL1TxFromDataAvailability(t *testing.T) {
EffectiveAmount: big.NewInt(4),
}
txCompressedData, err = tx.BytesDataAvailability(32)
assert.Nil(t, err)
assert.NoError(t, err)
l1tx, err = L1TxFromDataAvailability(txCompressedData, 32)
require.NoError(t, err)
assert.Equal(t, tx.FromIdx, l1tx.FromIdx)
@ -118,10 +118,7 @@ func TestL1userTxByteParsers(t *testing.T) {
var pkComp babyjub.PublicKeyComp
pkCompL := []byte("0x56ca90f80d7c374ae7485e9bcc47d4ac399460948da6aeeb899311097925a72c")
err := pkComp.UnmarshalText(pkCompL)
require.Nil(t, err)
pk, err := pkComp.Decompress()
require.Nil(t, err)
require.NoError(t, err)
l1Tx := &L1Tx{
UserOrigin: true,
@ -130,17 +127,17 @@ func TestL1userTxByteParsers(t *testing.T) {
Amount: big.NewInt(1),
DepositAmount: big.NewInt(2),
FromIdx: 2,
FromBJJ: pk,
FromBJJ: pkComp,
FromEthAddr: ethCommon.HexToAddress("0xc58d29fA6e86E4FAe04DDcEd660d45BCf3Cb2370"),
}
encodedData, err := l1Tx.BytesUser()
require.Nil(t, err)
require.NoError(t, err)
decodedData, err := L1UserTxFromBytes(encodedData)
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, l1Tx, decodedData)
encodedData2, err := decodedData.BytesUser()
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, encodedData, encodedData2)
// expect error if length!=68
@ -156,13 +153,10 @@ func TestL1TxByteParsersCompatibility(t *testing.T) {
// Data from compatibility test
var pkComp babyjub.PublicKeyComp
pkCompB, err := hex.DecodeString("0dd02deb2c81068e7a0f7e327df80b4ab79ee1f41a7def613e73a20c32eece5a")
require.Nil(t, err)
require.NoError(t, err)
pkCompL := SwapEndianness(pkCompB)
err = pkComp.UnmarshalText([]byte(hex.EncodeToString(pkCompL)))
require.Nil(t, err)
pk, err := pkComp.Decompress()
require.Nil(t, err)
require.NoError(t, err)
depositAmount := new(big.Int)
depositAmount.SetString("100000000000000000000", 10)
@ -172,16 +166,16 @@ func TestL1TxByteParsersCompatibility(t *testing.T) {
Amount: big.NewInt(2400000000000000000),
DepositAmount: depositAmount,
FromIdx: Idx(29767899),
FromBJJ: pk,
FromBJJ: pkComp,
FromEthAddr: ethCommon.HexToAddress("0x85dab5b9e2e361d0c208d77be90efcc0439b0a53"),
UserOrigin: true,
}
expected, err := utils.HexDecode("85dab5b9e2e361d0c208d77be90efcc0439b0a530dd02deb2c81068e7a0f7e327df80b4ab79ee1f41a7def613e73a20c32eece5a000001c638db8be880f00020039c0000053cb88d")
require.Nil(t, err)
require.NoError(t, err)
encodedData, err := l1Tx.BytesUser()
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, expected, encodedData)
}
@ -191,7 +185,7 @@ func TestL1CoordinatorTxByteParsers(t *testing.T) {
chainIDBytes := ethCommon.LeftPadBytes(chainID.Bytes(), 2)
privateKey, err := crypto.HexToECDSA("fad9c8855b740a0b7ed4c221dbad0f33a83a49cad6b3fe8d5817ac83d38b6a19")
require.Nil(t, err)
require.NoError(t, err)
publicKey := privateKey.Public()
publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
@ -200,19 +194,16 @@ func TestL1CoordinatorTxByteParsers(t *testing.T) {
}
publicKeyBytes := crypto.FromECDSAPub(publicKeyECDSA)
pubKey, err := crypto.UnmarshalPubkey(publicKeyBytes)
require.Nil(t, err)
require.NoError(t, err)
fromEthAddr := crypto.PubkeyToAddress(*pubKey)
var pkComp babyjub.PublicKeyComp
pkCompL := []byte("56ca90f80d7c374ae7485e9bcc47d4ac399460948da6aeeb899311097925a72c")
err = pkComp.UnmarshalText(pkCompL)
require.Nil(t, err)
pk, err := pkComp.Decompress()
require.Nil(t, err)
require.NoError(t, err)
bytesMessage1 := []byte("\x19Ethereum Signed Message:\n120")
bytesMessage2 := []byte("I authorize this babyjubjub key for hermez rollup account creation")
babyjub := pk.Compress()
babyjubB := SwapEndianness(babyjub[:])
babyjubB := SwapEndianness(pkComp[:])
var data []byte
data = append(data, bytesMessage1...)
data = append(data, bytesMessage2...)
@ -221,26 +212,26 @@ func TestL1CoordinatorTxByteParsers(t *testing.T) {
data = append(data, hermezAddress.Bytes()...)
hash := crypto.Keccak256Hash(data)
signature, err := crypto.Sign(hash.Bytes(), privateKey)
require.Nil(t, err)
require.NoError(t, err)
// Ethereum adds 27 to v
v := int(signature[64])
signature[64] = byte(v + 27)
l1Tx := &L1Tx{
TokenID: 231,
FromBJJ: pk,
FromBJJ: pkComp,
FromEthAddr: fromEthAddr,
Amount: big.NewInt(0),
DepositAmount: big.NewInt(0),
}
bytesCoordinatorL1, err := l1Tx.BytesCoordinatorTx(signature)
require.Nil(t, err)
require.NoError(t, err)
l1txDecoded, err := L1CoordinatorTxFromBytes(bytesCoordinatorL1, chainID, hermezAddress)
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, l1Tx, l1txDecoded)
bytesCoordinatorL12, err := l1txDecoded.BytesCoordinatorTx(signature)
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, bytesCoordinatorL1, bytesCoordinatorL12)
// expect error if length!=68
@ -256,11 +247,11 @@ func TestL1CoordinatorTxByteParsersCompatibility(t *testing.T) {
// Data from compatibility test
var signature []byte
r, err := hex.DecodeString("da71e5eb097e115405d84d1e7b464009b434b32c014a2df502d1f065ced8bc3b")
require.Nil(t, err)
require.NoError(t, err)
s, err := hex.DecodeString("186d7122ff7f654cfed3156719774898d573900c86599a885a706dbdffe5ea8c")
require.Nil(t, err)
require.NoError(t, err)
v, err := hex.DecodeString("1b")
require.Nil(t, err)
require.NoError(t, err)
signature = append(signature, r[:]...)
signature = append(signature, s[:]...)
@ -268,24 +259,22 @@ func TestL1CoordinatorTxByteParsersCompatibility(t *testing.T) {
var pkComp babyjub.PublicKeyComp
pkCompB, err := hex.DecodeString("a2c2807ee39c3b3378738cff85a46a9465bb8fcf44ea597c33da9719be7c259c")
require.Nil(t, err)
require.NoError(t, err)
pkCompL := SwapEndianness(pkCompB)
err = pkComp.UnmarshalText([]byte(hex.EncodeToString(pkCompL)))
require.Nil(t, err)
require.NoError(t, err)
// Data from the compatibility test
require.Nil(t, err)
pk, err := pkComp.Decompress()
require.Nil(t, err)
require.NoError(t, err)
l1Tx := &L1Tx{
TokenID: 231,
FromBJJ: pk,
FromBJJ: pkComp,
}
encodeData, err := l1Tx.BytesCoordinatorTx(signature)
require.Nil(t, err)
require.NoError(t, err)
expected, err := utils.HexDecode("1b186d7122ff7f654cfed3156719774898d573900c86599a885a706dbdffe5ea8cda71e5eb097e115405d84d1e7b464009b434b32c014a2df502d1f065ced8bc3ba2c2807ee39c3b3378738cff85a46a9465bb8fcf44ea597c33da9719be7c259c000000e7")
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, expected, encodeData)
}

+ 3
- 3
common/l2tx_test.go

@ -17,7 +17,7 @@ func TestNewL2Tx(t *testing.T) {
Nonce: 144,
}
l2Tx, err := NewL2Tx(l2Tx)
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, "0x020000000156660000000090", l2Tx.TxID.String())
}
@ -33,10 +33,10 @@ func TestL2TxByteParsers(t *testing.T) {
// Data from the compatibility test
expected := "00000101000001002b16c9"
encodedData, err := l2Tx.BytesDataAvailability(32)
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, expected, hex.EncodeToString(encodedData))
decodedData, err := L2TxFromBytesDataAvailability(encodedData, 32)
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, l2Tx, decodedData)
}

+ 59
- 38
common/pooll2tx.go

@ -12,19 +12,28 @@ import (
"github.com/iden3/go-iden3-crypto/poseidon"
)
// PoolL2Tx is a struct that represents a L2Tx sent by an account to the coordinator hat is waiting to be forged
// EmptyBJJComp contains the 32 byte array of a empty BabyJubJub PublicKey
// Compressed. It is a valid point in the BabyJubJub curve, so does not give
// errors when being decompressed.
var EmptyBJJComp = babyjub.PublicKeyComp([32]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})
// PoolL2Tx is a struct that represents a L2Tx sent by an account to the
// coordinator that is waiting to be forged
type PoolL2Tx struct {
// Stored in DB: mandatory fileds
// TxID (12 bytes) for L2Tx is:
// bytes: | 1 | 6 | 5 |
// values: | type | FromIdx | Nonce |
TxID TxID `meddler:"tx_id"`
FromIdx Idx `meddler:"from_idx"`
ToIdx Idx `meddler:"to_idx,zeroisnull"`
AuxToIdx Idx `meddler:"-"` // AuxToIdx is only used internally at the StateDB to avoid repeated computation when processing transactions (from Synchronizer, TxSelector, BatchBuilder)
TxID TxID `meddler:"tx_id"`
FromIdx Idx `meddler:"from_idx"`
ToIdx Idx `meddler:"to_idx,zeroisnull"`
// AuxToIdx is only used internally at the StateDB to avoid repeated
// computation when processing transactions (from Synchronizer,
// TxSelector, BatchBuilder)
AuxToIdx Idx `meddler:"-"`
ToEthAddr ethCommon.Address `meddler:"to_eth_addr,zeroisnull"`
ToBJJ *babyjub.PublicKey `meddler:"to_bjj"`
ToBJJ babyjub.PublicKeyComp `meddler:"to_bjj,zeroisnull"`
TokenID TokenID `meddler:"token_id"`
Amount *big.Int `meddler:"amount,bigint"` // TODO: change to float16
Fee FeeSelector `meddler:"fee"`
@ -33,17 +42,17 @@ type PoolL2Tx struct {
Signature babyjub.SignatureComp `meddler:"signature"` // tx signature
Timestamp time.Time `meddler:"timestamp,utctime"` // time when added to the tx pool
// Stored in DB: optional fileds, may be uninitialized
RqFromIdx Idx `meddler:"rq_from_idx,zeroisnull"` // FromIdx is used by L1Tx/Deposit to indicate the Idx receiver of the L1Tx.DepositAmount (deposit)
RqToIdx Idx `meddler:"rq_to_idx,zeroisnull"` // FromIdx is used by L1Tx/Deposit to indicate the Idx receiver of the L1Tx.DepositAmount (deposit)
RqToEthAddr ethCommon.Address `meddler:"rq_to_eth_addr,zeroisnull"`
RqToBJJ *babyjub.PublicKey `meddler:"rq_to_bjj"` // TODO: stop using json, use scanner/valuer
RqTokenID TokenID `meddler:"rq_token_id,zeroisnull"`
RqAmount *big.Int `meddler:"rq_amount,bigintnull"` // TODO: change to float16
RqFee FeeSelector `meddler:"rq_fee,zeroisnull"`
RqNonce Nonce `meddler:"rq_nonce,zeroisnull"` // effective 48 bits used
AbsoluteFee float64 `meddler:"fee_usd,zeroisnull"`
AbsoluteFeeUpdate time.Time `meddler:"usd_update,utctimez"`
Type TxType `meddler:"tx_type"`
RqFromIdx Idx `meddler:"rq_from_idx,zeroisnull"`
RqToIdx Idx `meddler:"rq_to_idx,zeroisnull"`
RqToEthAddr ethCommon.Address `meddler:"rq_to_eth_addr,zeroisnull"`
RqToBJJ babyjub.PublicKeyComp `meddler:"rq_to_bjj,zeroisnull"`
RqTokenID TokenID `meddler:"rq_token_id,zeroisnull"`
RqAmount *big.Int `meddler:"rq_amount,bigintnull"` // TODO: change to float16
RqFee FeeSelector `meddler:"rq_fee,zeroisnull"`
RqNonce Nonce `meddler:"rq_nonce,zeroisnull"` // effective 48 bits used
AbsoluteFee float64 `meddler:"fee_usd,zeroisnull"`
AbsoluteFeeUpdate time.Time `meddler:"usd_update,utctimez"`
Type TxType `meddler:"tx_type"`
// Extra metadata, may be uninitialized
RqTxCompressedData []byte `meddler:"-"` // 253 bits, optional for atomic txs
}
@ -81,7 +90,7 @@ func (tx *PoolL2Tx) SetType() error {
} else if tx.ToIdx == 1 {
tx.Type = TxTypeExit
} else if tx.ToIdx == 0 {
if tx.ToBJJ != nil && tx.ToEthAddr == FFAddr {
if tx.ToBJJ != EmptyBJJComp && tx.ToEthAddr == FFAddr {
tx.Type = TxTypeTransferToBJJ
} else if tx.ToEthAddr != FFAddr && tx.ToEthAddr != EmptyAddr {
tx.Type = TxTypeTransferToEthAddr
@ -125,10 +134,13 @@ func (tx *PoolL2Tx) TxCompressedData() (*big.Int, error) {
return nil, tracerr.Wrap(err)
}
var b [31]byte
toBJJSign := byte(0)
if tx.ToBJJ != nil && babyjub.PointCoordSign(tx.ToBJJ.X) {
pkSign, _ := babyjub.UnpackSignY(tx.ToBJJ)
if pkSign {
toBJJSign = byte(1)
}
b[0] = toBJJSign
b[1] = byte(tx.Fee)
nonceBytes, err := tx.Nonce.Bytes()
@ -174,8 +186,11 @@ func (tx *PoolL2Tx) TxCompressedDataV2() (*big.Int, error) {
}
var b [25]byte
toBJJSign := byte(0)
if tx.ToBJJ != nil && babyjub.PointCoordSign(tx.ToBJJ.X) {
toBJJSign = byte(1)
if tx.ToBJJ != EmptyBJJComp {
sign, _ := babyjub.UnpackSignY(tx.ToBJJ)
if sign {
toBJJSign = byte(1)
}
}
b[0] = toBJJSign
b[1] = byte(tx.Fee)
@ -224,11 +239,14 @@ func (tx *PoolL2Tx) RqTxCompressedDataV2() (*big.Int, error) {
return nil, tracerr.Wrap(err)
}
var b [25]byte
toBJJSign := byte(0)
if tx.RqToBJJ != nil && babyjub.PointCoordSign(tx.RqToBJJ.X) {
toBJJSign = byte(1)
rqToBJJSign := byte(0)
if tx.RqToBJJ != EmptyBJJComp {
sign, _ := babyjub.UnpackSignY(tx.RqToBJJ)
if sign {
rqToBJJSign = byte(1)
}
}
b[0] = toBJJSign
b[0] = rqToBJJSign
b[1] = byte(tx.RqFee)
nonceBytes, err := tx.RqNonce.Bytes()
if err != nil {
@ -260,24 +278,21 @@ func (tx *PoolL2Tx) HashToSign() (*big.Int, error) {
}
toEthAddr := EthAddrToBigInt(tx.ToEthAddr)
rqToEthAddr := EthAddrToBigInt(tx.RqToEthAddr)
toBJJY := big.NewInt(0)
if tx.ToBJJ != nil {
toBJJY = tx.ToBJJ.Y
}
_, toBJJY := babyjub.UnpackSignY(tx.ToBJJ)
rqTxCompressedDataV2, err := tx.RqTxCompressedDataV2()
if err != nil {
return nil, tracerr.Wrap(err)
}
rqToBJJY := big.NewInt(0)
if tx.RqToBJJ != nil {
rqToBJJY = tx.RqToBJJ.Y
}
_, rqToBJJY := babyjub.UnpackSignY(tx.RqToBJJ)
return poseidon.Hash([]*big.Int{toCompressedData, toEthAddr, toBJJY, rqTxCompressedDataV2, rqToEthAddr, rqToBJJY})
}
// VerifySignature returns true if the signature verification is correct for the given PublicKey
func (tx *PoolL2Tx) VerifySignature(pk *babyjub.PublicKey) bool {
// VerifySignature returns true if the signature verification is correct for the given PublicKeyComp
func (tx *PoolL2Tx) VerifySignature(pkComp babyjub.PublicKeyComp) bool {
h, err := tx.HashToSign()
if err != nil {
return false
@ -286,6 +301,10 @@ func (tx *PoolL2Tx) VerifySignature(pk *babyjub.PublicKey) bool {
if err != nil {
return false
}
pk, err := pkComp.Decompress()
if err != nil {
return false
}
return pk.VerifyPoseidon(h, s)
}
@ -325,13 +344,15 @@ func PoolL2TxsToL2Txs(txs []PoolL2Tx) ([]L2Tx, error) {
return l2Txs, nil
}
// PoolL2TxState is a struct that represents the status of a L2 transaction
// PoolL2TxState is a string that represents the status of a L2 transaction
type PoolL2TxState string
const (
// PoolL2TxStatePending represents a valid L2Tx that hasn't started the forging process
// PoolL2TxStatePending represents a valid L2Tx that hasn't started the
// forging process
PoolL2TxStatePending PoolL2TxState = "pend"
// PoolL2TxStateForging represents a valid L2Tx that has started the forging process
// PoolL2TxStateForging represents a valid L2Tx that has started the
// forging process
PoolL2TxStateForging PoolL2TxState = "fing"
// PoolL2TxStateForged represents a L2Tx that has already been forged
PoolL2TxStateForged PoolL2TxState = "fged"

+ 28
- 19
common/pooll2tx_test.go

@ -8,6 +8,7 @@ import (
ethCommon "github.com/ethereum/go-ethereum/common"
"github.com/iden3/go-iden3-crypto/babyjub"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNewPoolL2Tx(t *testing.T) {
@ -19,24 +20,24 @@ func TestNewPoolL2Tx(t *testing.T) {
Nonce: 144,
}
poolL2Tx, err := NewPoolL2Tx(poolL2Tx)
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, "0x020000000156660000000090", poolL2Tx.TxID.String())
}
func TestTxCompressedData(t *testing.T) {
var sk babyjub.PrivateKey
_, err := hex.Decode(sk[:], []byte("0001020304050607080900010203040506070809000102030405060708090001"))
assert.Nil(t, err)
assert.NoError(t, err)
tx := PoolL2Tx{
FromIdx: 2,
ToIdx: 3,
Amount: big.NewInt(4),
TokenID: 5,
Nonce: 6,
ToBJJ: sk.Public(),
ToBJJ: sk.Public().Compress(),
}
txCompressedData, err := tx.TxCompressedData()
assert.Nil(t, err)
assert.NoError(t, err)
// test vector value generated from javascript implementation
expectedStr := "1766847064778421992193717128424891165872736891548909569553540445094274575"
assert.Equal(t, expectedStr, txCompressedData.String())
@ -48,10 +49,10 @@ func TestTxCompressedData(t *testing.T) {
RqTokenID: 10,
RqNonce: 11,
RqFee: 12,
RqToBJJ: sk.Public(),
RqToBJJ: sk.Public().Compress(),
}
txCompressedData, err = tx.RqTxCompressedDataV2()
assert.Nil(t, err)
assert.NoError(t, err)
// test vector value generated from javascript implementation
expectedStr = "6571340879233176732837827812956721483162819083004853354503"
assert.Equal(t, expectedStr, txCompressedData.String())
@ -61,7 +62,7 @@ func TestTxCompressedData(t *testing.T) {
func TestTxCompressedDataV2(t *testing.T) {
var sk babyjub.PrivateKey
_, err := hex.Decode(sk[:], []byte("0001020304050607080900010203040506070809000102030405060708090001"))
assert.Nil(t, err)
assert.NoError(t, err)
tx := PoolL2Tx{
FromIdx: 7,
ToIdx: 8,
@ -69,10 +70,10 @@ func TestTxCompressedDataV2(t *testing.T) {
TokenID: 10,
Nonce: 11,
Fee: 12,
ToBJJ: sk.Public(),
ToBJJ: sk.Public().Compress(),
}
txCompressedData, err := tx.TxCompressedDataV2()
assert.Nil(t, err)
assert.NoError(t, err)
// test vector value generated from javascript implementation
expectedStr := "6571340879233176732837827812956721483162819083004853354503"
assert.Equal(t, expectedStr, txCompressedData.String())
@ -86,7 +87,7 @@ func TestTxCompressedDataV2(t *testing.T) {
func TestRqTxCompressedDataV2(t *testing.T) {
var sk babyjub.PrivateKey
_, err := hex.Decode(sk[:], []byte("0001020304050607080900010203040506070809000102030405060708090001"))
assert.Nil(t, err)
assert.NoError(t, err)
tx := PoolL2Tx{
RqFromIdx: 7,
RqToIdx: 8,
@ -94,10 +95,10 @@ func TestRqTxCompressedDataV2(t *testing.T) {
RqTokenID: 10,
RqNonce: 11,
RqFee: 12,
RqToBJJ: sk.Public(),
RqToBJJ: sk.Public().Compress(),
}
txCompressedData, err := tx.RqTxCompressedDataV2()
assert.Nil(t, err)
assert.NoError(t, err)
// test vector value generated from javascript implementation
expectedStr := "6571340879233176732837827812956721483162819083004853354503"
assert.Equal(t, expectedStr, txCompressedData.String())
@ -110,7 +111,7 @@ func TestRqTxCompressedDataV2(t *testing.T) {
func TestHashToSign(t *testing.T) {
var sk babyjub.PrivateKey
_, err := hex.Decode(sk[:], []byte("0001020304050607080900010203040506070809000102030405060708090001"))
assert.Nil(t, err)
assert.NoError(t, err)
tx := PoolL2Tx{
FromIdx: 2,
ToIdx: 3,
@ -120,29 +121,37 @@ func TestHashToSign(t *testing.T) {
ToEthAddr: ethCommon.HexToAddress("0xc58d29fA6e86E4FAe04DDcEd660d45BCf3Cb2370"),
}
toSign, err := tx.HashToSign()
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, "1469900657138253851938022936440971384682713995864967090251961124784132925291", toSign.String())
}
func TestVerifyTxSignature(t *testing.T) {
var sk babyjub.PrivateKey
_, err := hex.Decode(sk[:], []byte("0001020304050607080900010203040506070809000102030405060708090001"))
assert.Nil(t, err)
assert.NoError(t, err)
tx := PoolL2Tx{
FromIdx: 2,
ToIdx: 3,
Amount: big.NewInt(4),
TokenID: 5,
Nonce: 6,
ToBJJ: sk.Public(),
ToBJJ: sk.Public().Compress(),
RqToEthAddr: ethCommon.HexToAddress("0xc58d29fA6e86E4FAe04DDcEd660d45BCf3Cb2370"),
RqToBJJ: sk.Public(),
RqToBJJ: sk.Public().Compress(),
}
toSign, err := tx.HashToSign()
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, "18645218094210271622244722988708640202588315450486586312909439859037906375295", toSign.String())
sig := sk.SignPoseidon(toSign)
tx.Signature = sig.Compress()
assert.True(t, tx.VerifySignature(sk.Public()))
assert.True(t, tx.VerifySignature(sk.Public().Compress()))
}
func TestDecompressEmptyBJJComp(t *testing.T) {
pkComp := EmptyBJJComp
pk, err := pkComp.Decompress()
require.NoError(t, err)
assert.Equal(t, "2957874849018779266517920829765869116077630550401372566248359756137677864698", pk.X.String())
assert.Equal(t, "0", pk.Y.String())
}

+ 7
- 7
common/tx.go

@ -140,13 +140,13 @@ type Tx struct {
BatchNum *BatchNum `meddler:"batch_num"` // batchNum in which this tx was forged. If the tx is L2, this must be != 0
EthBlockNum int64 `meddler:"eth_block_num"` // Ethereum Block Number in which this L1Tx was added to the queue
// L1
ToForgeL1TxsNum *int64 `meddler:"to_forge_l1_txs_num"` // toForgeL1TxsNum in which the tx was forged / will be forged
UserOrigin *bool `meddler:"user_origin"` // true if the tx was originated by a user, false if it was aoriginated by a coordinator. Note that this differ from the spec for implementation simplification purpposes
FromEthAddr ethCommon.Address `meddler:"from_eth_addr"`
FromBJJ *babyjub.PublicKey `meddler:"from_bjj"`
DepositAmount *big.Int `meddler:"deposit_amount,bigintnull"`
DepositAmountFloat *float64 `meddler:"deposit_amount_f"`
DepositAmountUSD *float64 `meddler:"deposit_amount_usd"`
ToForgeL1TxsNum *int64 `meddler:"to_forge_l1_txs_num"` // toForgeL1TxsNum in which the tx was forged / will be forged
UserOrigin *bool `meddler:"user_origin"` // true if the tx was originated by a user, false if it was aoriginated by a coordinator. Note that this differ from the spec for implementation simplification purpposes
FromEthAddr ethCommon.Address `meddler:"from_eth_addr"`
FromBJJ babyjub.PublicKeyComp `meddler:"from_bjj"`
DepositAmount *big.Int `meddler:"deposit_amount,bigintnull"`
DepositAmountFloat *float64 `meddler:"deposit_amount_f"`
DepositAmountUSD *float64 `meddler:"deposit_amount_usd"`
// L2
Fee *FeeSelector `meddler:"fee"`
FeeUSD *float64 `meddler:"fee_usd"`

+ 3
- 3
common/tx_test.go

@ -40,16 +40,16 @@ func TestTxIDMarshalers(t *testing.T) {
h := []byte("0x00000000000001e240004700")
var txid TxID
err := txid.UnmarshalText(h)
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, h, []byte(txid.String()))
h2, err := txid.MarshalText()
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, h, h2)
var txid2 TxID
err = txid2.UnmarshalText(h2)
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, h2, []byte(txid2.String()))
assert.Equal(t, h, h2)
}

+ 3
- 3
common/utils.go

@ -27,15 +27,15 @@ func EthAddrToBigInt(a ethCommon.Address) *big.Int {
// the Hermez checksum at the last byte, and is encoded in BigEndian) and
// returns the corresponding *babyjub.PublicKey. This method is not part of the
// spec, is used for importing javascript test vectors data.
func BJJFromStringWithChecksum(s string) (*babyjub.PublicKey, error) {
func BJJFromStringWithChecksum(s string) (babyjub.PublicKeyComp, error) {
b, err := hex.DecodeString(s)
if err != nil {
return nil, tracerr.Wrap(err)
return EmptyBJJComp, tracerr.Wrap(err)
}
pkBytes := SwapEndianness(b)
var pkComp babyjub.PublicKeyComp
copy(pkComp[:], pkBytes[:])
return pkComp.Decompress()
return pkComp, nil
}
// CopyBigInt returns a copy of the big int

+ 7
- 4
common/utils_test.go

@ -9,11 +9,14 @@ import (
func TestBJJFromStringWithChecksum(t *testing.T) {
s := "21b0a1688b37f77b1d1d5539ec3b826db5ac78b2513f574a04c50a7d4f8246d7"
pk, err := BJJFromStringWithChecksum(s)
assert.Nil(t, err)
pkComp, err := BJJFromStringWithChecksum(s)
assert.NoError(t, err)
sBytes, err := hex.DecodeString(s)
assert.Nil(t, err)
assert.Equal(t, hex.EncodeToString(SwapEndianness(sBytes)), pk.Compress().String())
assert.NoError(t, err)
assert.Equal(t, hex.EncodeToString(SwapEndianness(sBytes)), pkComp.String())
pk, err := pkComp.Decompress()
assert.NoError(t, err)
// expected values computed with js implementation
assert.Equal(t, "2492816973395423007340226948038371729989170225696553239457870892535792679622", pk.X.String())

+ 1
- 1
common/zk_test.go

@ -11,6 +11,6 @@ import (
func TestZKInputs(t *testing.T) {
zki := NewZKInputs(100, 16, 512, 24, 32, big.NewInt(1))
_, err := json.Marshal(zki)
require.Nil(t, err)
require.NoError(t, err)
// fmt.Println(string(s))
}

+ 4
- 4
db/historydb/historydb.go

@ -822,7 +822,7 @@ func (hdb *HistoryDB) addL1Txs(d meddler.DB, l1txs []common.L1Tx) error {
ToForgeL1TxsNum: l1txs[i].ToForgeL1TxsNum,
UserOrigin: &l1txs[i].UserOrigin,
FromEthAddr: &l1txs[i].FromEthAddr,
FromBJJ: l1txs[i].FromBJJ,
FromBJJ: &l1txs[i].FromBJJ,
DepositAmount: l1txs[i].DepositAmount,
DepositAmountFloat: &depositAmountFloat,
})
@ -929,7 +929,7 @@ func (hdb *HistoryDB) GetHistoryTx(txID common.TxID) (*TxAPI, error) {
// GetHistoryTxs returns a list of txs from the DB using the HistoryTx struct
// and pagination info
func (hdb *HistoryDB) GetHistoryTxs(
ethAddr *ethCommon.Address, bjj *babyjub.PublicKey,
ethAddr *ethCommon.Address, bjj *babyjub.PublicKeyComp,
tokenID *common.TokenID, idx *common.Idx, batchNum *uint, txType *common.TxType,
fromItem, limit *uint, order string,
) ([]TxAPI, uint64, error) {
@ -1082,7 +1082,7 @@ func (hdb *HistoryDB) GetExitAPI(batchNum *uint, idx *common.Idx) (*ExitAPI, err
// GetExitsAPI returns a list of exits from the DB and pagination info
func (hdb *HistoryDB) GetExitsAPI(
ethAddr *ethCommon.Address, bjj *babyjub.PublicKey, tokenID *common.TokenID,
ethAddr *ethCommon.Address, bjj *babyjub.PublicKeyComp, tokenID *common.TokenID,
idx *common.Idx, batchNum *uint, onlyPendingWithdraws *bool,
fromItem, limit *uint, order string,
) ([]ExitAPI, uint64, error) {
@ -1691,7 +1691,7 @@ func (hdb *HistoryDB) GetAccountAPI(idx common.Idx) (*AccountAPI, error) {
// GetAccountsAPI returns a list of accounts from the DB and pagination info
func (hdb *HistoryDB) GetAccountsAPI(
tokenIDs []common.TokenID, ethAddr *ethCommon.Address,
bjj *babyjub.PublicKey, fromItem, limit *uint, order string,
bjj *babyjub.PublicKeyComp, fromItem, limit *uint, order string,
) ([]AccountAPI, uint64, error) {
if ethAddr != nil && bjj != nil {
return nil, 0, tracerr.Wrap(errors.New("ethAddr and bjj are incompatible"))

+ 6
- 6
db/historydb/views.go

@ -135,12 +135,12 @@ type txWrite struct {
BatchNum *common.BatchNum `meddler:"batch_num"` // batchNum in which this tx was forged. If the tx is L2, this must be != 0
EthBlockNum int64 `meddler:"eth_block_num"` // Ethereum Block Number in which this L1Tx was added to the queue
// L1
ToForgeL1TxsNum *int64 `meddler:"to_forge_l1_txs_num"` // toForgeL1TxsNum in which the tx was forged / will be forged
UserOrigin *bool `meddler:"user_origin"` // true if the tx was originated by a user, false if it was aoriginated by a coordinator. Note that this differ from the spec for implementation simplification purpposes
FromEthAddr *ethCommon.Address `meddler:"from_eth_addr"`
FromBJJ *babyjub.PublicKey `meddler:"from_bjj"`
DepositAmount *big.Int `meddler:"deposit_amount,bigintnull"`
DepositAmountFloat *float64 `meddler:"deposit_amount_f"`
ToForgeL1TxsNum *int64 `meddler:"to_forge_l1_txs_num"` // toForgeL1TxsNum in which the tx was forged / will be forged
UserOrigin *bool `meddler:"user_origin"` // true if the tx was originated by a user, false if it was aoriginated by a coordinator. Note that this differ from the spec for implementation simplification purpposes
FromEthAddr *ethCommon.Address `meddler:"from_eth_addr"`
FromBJJ *babyjub.PublicKeyComp `meddler:"from_bjj"`
DepositAmount *big.Int `meddler:"deposit_amount,bigintnull"`
DepositAmountFloat *float64 `meddler:"deposit_amount_f"`
// L2
Fee *common.FeeSelector `meddler:"fee"`
Nonce *common.Nonce `meddler:"nonce"`

+ 6
- 2
db/l2db/l2db.go

@ -88,14 +88,12 @@ func (l2db *L2DB) AddTxTest(tx *common.PoolL2Tx) error {
insertTx := &PoolL2TxWrite{
TxID: tx.TxID,
FromIdx: tx.FromIdx,
ToBJJ: tx.ToBJJ,
TokenID: tx.TokenID,
Amount: tx.Amount,
Fee: tx.Fee,
Nonce: tx.Nonce,
State: common.PoolL2TxStatePending,
Signature: tx.Signature,
RqToBJJ: tx.RqToBJJ,
RqAmount: tx.RqAmount,
Type: tx.Type,
}
@ -118,6 +116,12 @@ func (l2db *L2DB) AddTxTest(tx *common.PoolL2Tx) error {
if tx.RqToEthAddr != nilAddr {
insertTx.RqToEthAddr = &tx.RqToEthAddr
}
if tx.ToBJJ != common.EmptyBJJComp {
insertTx.ToBJJ = &tx.ToBJJ
}
if tx.RqToBJJ != common.EmptyBJJComp {
insertTx.RqToBJJ = &tx.RqToBJJ
}
f := new(big.Float).SetInt(tx.Amount)
amountF, _ := f.Float64()
insertTx.AmountFloat = amountF

+ 21
- 21
db/l2db/views.go

@ -13,27 +13,27 @@ import (
// PoolL2TxWrite holds the necessary data to perform inserts in tx_pool
type PoolL2TxWrite struct {
TxID common.TxID `meddler:"tx_id"`
FromIdx common.Idx `meddler:"from_idx"`
ToIdx *common.Idx `meddler:"to_idx"`
ToEthAddr *ethCommon.Address `meddler:"to_eth_addr"`
ToBJJ *babyjub.PublicKey `meddler:"to_bjj"`
TokenID common.TokenID `meddler:"token_id"`
Amount *big.Int `meddler:"amount,bigint"`
AmountFloat float64 `meddler:"amount_f"`
Fee common.FeeSelector `meddler:"fee"`
Nonce common.Nonce `meddler:"nonce"`
State common.PoolL2TxState `meddler:"state"`
Signature babyjub.SignatureComp `meddler:"signature"`
RqFromIdx *common.Idx `meddler:"rq_from_idx"`
RqToIdx *common.Idx `meddler:"rq_to_idx"`
RqToEthAddr *ethCommon.Address `meddler:"rq_to_eth_addr"`
RqToBJJ *babyjub.PublicKey `meddler:"rq_to_bjj"`
RqTokenID *common.TokenID `meddler:"rq_token_id"`
RqAmount *big.Int `meddler:"rq_amount,bigintnull"`
RqFee *common.FeeSelector `meddler:"rq_fee"`
RqNonce *common.Nonce `meddler:"rq_nonce"`
Type common.TxType `meddler:"tx_type"`
TxID common.TxID `meddler:"tx_id"`
FromIdx common.Idx `meddler:"from_idx"`
ToIdx *common.Idx `meddler:"to_idx"`
ToEthAddr *ethCommon.Address `meddler:"to_eth_addr"`
ToBJJ *babyjub.PublicKeyComp `meddler:"to_bjj"`
TokenID common.TokenID `meddler:"token_id"`
Amount *big.Int `meddler:"amount,bigint"`
AmountFloat float64 `meddler:"amount_f"`
Fee common.FeeSelector `meddler:"fee"`
Nonce common.Nonce `meddler:"nonce"`
State common.PoolL2TxState `meddler:"state"`
Signature babyjub.SignatureComp `meddler:"signature"`
RqFromIdx *common.Idx `meddler:"rq_from_idx"`
RqToIdx *common.Idx `meddler:"rq_to_idx"`
RqToEthAddr *ethCommon.Address `meddler:"rq_to_eth_addr"`
RqToBJJ *babyjub.PublicKeyComp `meddler:"rq_to_bjj"`
RqTokenID *common.TokenID `meddler:"rq_token_id"`
RqAmount *big.Int `meddler:"rq_amount,bigintnull"`
RqFee *common.FeeSelector `meddler:"rq_fee"`
RqNonce *common.Nonce `meddler:"rq_nonce"`
Type common.TxType `meddler:"tx_type"`
}
// PoolTxAPI represents a L2 Tx pool with extra metadata used by the API

+ 96
- 91
db/statedb/statedb_test.go

@ -12,6 +12,7 @@ import (
ethCommon "github.com/ethereum/go-ethereum/common"
ethCrypto "github.com/ethereum/go-ethereum/crypto"
"github.com/hermeznetwork/hermez-node/common"
"github.com/hermeznetwork/hermez-node/log"
"github.com/hermeznetwork/tracerr"
"github.com/iden3/go-iden3-crypto/babyjub"
"github.com/iden3/go-merkletree/db"
@ -22,11 +23,11 @@ import (
func newAccount(t *testing.T, i int) *common.Account {
var sk babyjub.PrivateKey
_, err := hex.Decode(sk[:], []byte("0001020304050607080900010203040506070809000102030405060708090001"))
require.Nil(t, err)
require.NoError(t, err)
pk := sk.Public()
key, err := ethCrypto.GenerateKey()
require.Nil(t, err)
require.NoError(t, err)
address := ethCrypto.PubkeyToAddress(key.PublicKey)
return &common.Account{
@ -34,18 +35,18 @@ func newAccount(t *testing.T, i int) *common.Account {
TokenID: common.TokenID(i),
Nonce: common.Nonce(i),
Balance: big.NewInt(1000),
PublicKey: pk,
PublicKey: pk.Compress(),
EthAddr: address,
}
}
func TestNewStateDBIntermediateState(t *testing.T) {
dir, err := ioutil.TempDir("", "tmpdb")
require.Nil(t, err)
defer assert.Nil(t, os.RemoveAll(dir))
require.NoError(t, err)
defer assert.NoError(t, os.RemoveAll(dir))
sdb, err := NewStateDB(dir, TypeTxSelector, 0)
assert.Nil(t, err)
assert.NoError(t, err)
// test values
k0 := []byte("testkey0")
@ -55,19 +56,19 @@ func TestNewStateDBIntermediateState(t *testing.T) {
// store some data
tx, err := sdb.db.NewTx()
assert.Nil(t, err)
assert.NoError(t, err)
err = tx.Put(k0, v0)
assert.Nil(t, err)
assert.NoError(t, err)
err = tx.Commit()
assert.Nil(t, err)
assert.NoError(t, err)
v, err := sdb.db.Get(k0)
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, v0, v)
// call NewStateDB which should get the db at the last checkpoint state
// executing a Reset (discarding the last 'testkey0'&'testvalue0' data)
sdb, err = NewStateDB(dir, TypeTxSelector, 0)
assert.Nil(t, err)
assert.NoError(t, err)
v, err = sdb.db.Get(k0)
assert.NotNil(t, err)
assert.Equal(t, db.ErrNotFound, tracerr.Unwrap(err))
@ -75,44 +76,44 @@ func TestNewStateDBIntermediateState(t *testing.T) {
// store the same data from the beginning that has ben lost since last NewStateDB
tx, err = sdb.db.NewTx()
assert.Nil(t, err)
assert.NoError(t, err)
err = tx.Put(k0, v0)
assert.Nil(t, err)
assert.NoError(t, err)
err = tx.Commit()
assert.Nil(t, err)
assert.NoError(t, err)
v, err = sdb.db.Get(k0)
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, v0, v)
// make checkpoints with the current state
bn, err := sdb.GetCurrentBatch()
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, common.BatchNum(0), bn)
err = sdb.MakeCheckpoint()
assert.Nil(t, err)
assert.NoError(t, err)
bn, err = sdb.GetCurrentBatch()
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, common.BatchNum(1), bn)
// write more data
tx, err = sdb.db.NewTx()
assert.Nil(t, err)
assert.NoError(t, err)
err = tx.Put(k1, v1)
assert.Nil(t, err)
assert.NoError(t, err)
err = tx.Commit()
assert.Nil(t, err)
assert.NoError(t, err)
v, err = sdb.db.Get(k1)
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, v1, v)
// call NewStateDB which should get the db at the last checkpoint state
// executing a Reset (discarding the last 'testkey1'&'testvalue1' data)
sdb, err = NewStateDB(dir, TypeTxSelector, 0)
assert.Nil(t, err)
assert.NoError(t, err)
v, err = sdb.db.Get(k0)
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, v0, v)
v, err = sdb.db.Get(k1)
@ -123,11 +124,11 @@ func TestNewStateDBIntermediateState(t *testing.T) {
func TestStateDBWithoutMT(t *testing.T) {
dir, err := ioutil.TempDir("", "tmpdb")
require.Nil(t, err)
defer assert.Nil(t, os.RemoveAll(dir))
require.NoError(t, err)
defer assert.NoError(t, os.RemoveAll(dir))
sdb, err := NewStateDB(dir, TypeTxSelector, 0)
assert.Nil(t, err)
assert.NoError(t, err)
// create test accounts
var accounts []*common.Account
@ -144,20 +145,20 @@ func TestStateDBWithoutMT(t *testing.T) {
// add test accounts
for i := 0; i < len(accounts); i++ {
_, err = sdb.CreateAccount(accounts[i].Idx, accounts[i])
assert.Nil(t, err)
assert.NoError(t, err)
}
for i := 0; i < len(accounts); i++ {
existingAccount := accounts[i].Idx
accGetted, err := sdb.GetAccount(existingAccount)
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, accounts[i], accGetted)
}
// try already existing idx and get error
existingAccount := common.Idx(256)
_, err = sdb.GetAccount(existingAccount) // check that exist
assert.Nil(t, err)
assert.NoError(t, err)
_, err = sdb.CreateAccount(common.Idx(256), accounts[1]) // check that can not be created twice
assert.NotNil(t, err)
assert.Equal(t, ErrAccountAlreadyExists, tracerr.Unwrap(err))
@ -167,7 +168,7 @@ func TestStateDBWithoutMT(t *testing.T) {
accounts[i].Nonce = accounts[i].Nonce + 1
existingAccount = common.Idx(i)
_, err = sdb.UpdateAccount(existingAccount, accounts[i])
assert.Nil(t, err)
assert.NoError(t, err)
}
_, err = sdb.MTGetProof(common.Idx(1))
@ -177,11 +178,11 @@ func TestStateDBWithoutMT(t *testing.T) {
func TestStateDBWithMT(t *testing.T) {
dir, err := ioutil.TempDir("", "tmpdb")
require.Nil(t, err)
defer assert.Nil(t, os.RemoveAll(dir))
require.NoError(t, err)
defer assert.NoError(t, os.RemoveAll(dir))
sdb, err := NewStateDB(dir, TypeSynchronizer, 32)
assert.Nil(t, err)
assert.NoError(t, err)
// create test accounts
var accounts []*common.Account
@ -197,43 +198,43 @@ func TestStateDBWithMT(t *testing.T) {
// add test accounts
for i := 0; i < len(accounts); i++ {
_, err = sdb.CreateAccount(accounts[i].Idx, accounts[i])
assert.Nil(t, err)
assert.NoError(t, err)
}
for i := 0; i < len(accounts); i++ {
accGetted, err := sdb.GetAccount(accounts[i].Idx)
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, accounts[i], accGetted)
}
// try already existing idx and get error
_, err = sdb.GetAccount(common.Idx(256)) // check that exist
assert.Nil(t, err)
assert.NoError(t, err)
_, err = sdb.CreateAccount(common.Idx(256), accounts[1]) // check that can not be created twice
assert.NotNil(t, err)
assert.Equal(t, ErrAccountAlreadyExists, tracerr.Unwrap(err))
_, err = sdb.MTGetProof(common.Idx(256))
assert.Nil(t, err)
assert.NoError(t, err)
// update accounts
for i := 0; i < len(accounts); i++ {
accounts[i].Nonce = accounts[i].Nonce + 1
_, err = sdb.UpdateAccount(accounts[i].Idx, accounts[i])
assert.Nil(t, err)
assert.NoError(t, err)
}
a, err := sdb.GetAccount(common.Idx(256)) // check that account value has been updated
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, accounts[0].Nonce, a.Nonce)
}
func TestCheckpoints(t *testing.T) {
dir, err := ioutil.TempDir("", "sdb")
require.Nil(t, err)
defer assert.Nil(t, os.RemoveAll(dir))
require.NoError(t, err)
defer assert.NoError(t, os.RemoveAll(dir))
sdb, err := NewStateDB(dir, TypeSynchronizer, 32)
assert.Nil(t, err)
assert.NoError(t, err)
// create test accounts
var accounts []*common.Account
@ -244,22 +245,22 @@ func TestCheckpoints(t *testing.T) {
// add test accounts
for i := 0; i < len(accounts); i++ {
_, err = sdb.CreateAccount(accounts[i].Idx, accounts[i])
assert.Nil(t, err)
assert.NoError(t, err)
}
// do checkpoints and check that currentBatch is correct
err = sdb.MakeCheckpoint()
assert.Nil(t, err)
assert.NoError(t, err)
cb, err := sdb.GetCurrentBatch()
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, common.BatchNum(1), cb)
for i := 1; i < 10; i++ {
err = sdb.MakeCheckpoint()
assert.Nil(t, err)
assert.NoError(t, err)
cb, err = sdb.GetCurrentBatch()
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, common.BatchNum(i+1), cb)
}
@ -267,29 +268,29 @@ func TestCheckpoints(t *testing.T) {
// reset checkpoint
err = sdb.Reset(3)
assert.Nil(t, err)
assert.NoError(t, err)
// check that reset can be repeated (as there exist the 'current' and
// 'BatchNum3', from where the 'current' is a copy)
err = sdb.Reset(3)
require.Nil(t, err)
require.NoError(t, err)
// check that currentBatch is as expected after Reset
cb, err = sdb.GetCurrentBatch()
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, common.BatchNum(3), cb)
// advance one checkpoint and check that currentBatch is fine
err = sdb.MakeCheckpoint()
assert.Nil(t, err)
assert.NoError(t, err)
cb, err = sdb.GetCurrentBatch()
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, common.BatchNum(4), cb)
err = sdb.DeleteCheckpoint(common.BatchNum(9))
assert.Nil(t, err)
assert.NoError(t, err)
err = sdb.DeleteCheckpoint(common.BatchNum(10))
assert.Nil(t, err)
assert.NoError(t, err)
err = sdb.DeleteCheckpoint(common.BatchNum(9)) // does not exist, should return err
assert.NotNil(t, err)
err = sdb.DeleteCheckpoint(common.BatchNum(11)) // does not exist, should return err
@ -297,44 +298,44 @@ func TestCheckpoints(t *testing.T) {
// Create a LocalStateDB from the initial StateDB
dirLocal, err := ioutil.TempDir("", "ldb")
require.Nil(t, err)
defer assert.Nil(t, os.RemoveAll(dirLocal))
require.NoError(t, err)
defer assert.NoError(t, os.RemoveAll(dirLocal))
ldb, err := NewLocalStateDB(dirLocal, sdb, TypeBatchBuilder, 32)
assert.Nil(t, err)
assert.NoError(t, err)
// get checkpoint 4 from sdb (StateDB) to ldb (LocalStateDB)
err = ldb.Reset(4, true)
assert.Nil(t, err)
assert.NoError(t, err)
// check that currentBatch is 4 after the Reset
cb, err = ldb.GetCurrentBatch()
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, common.BatchNum(4), cb)
// advance one checkpoint in ldb
err = ldb.MakeCheckpoint()
assert.Nil(t, err)
assert.NoError(t, err)
cb, err = ldb.GetCurrentBatch()
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, common.BatchNum(5), cb)
// Create a 2nd LocalStateDB from the initial StateDB
dirLocal2, err := ioutil.TempDir("", "ldb2")
require.Nil(t, err)
defer assert.Nil(t, os.RemoveAll(dirLocal2))
require.NoError(t, err)
defer assert.NoError(t, os.RemoveAll(dirLocal2))
ldb2, err := NewLocalStateDB(dirLocal2, sdb, TypeBatchBuilder, 32)
assert.Nil(t, err)
assert.NoError(t, err)
// get checkpoint 4 from sdb (StateDB) to ldb (LocalStateDB)
err = ldb2.Reset(4, true)
assert.Nil(t, err)
assert.NoError(t, err)
// check that currentBatch is 4 after the Reset
cb, err = ldb2.GetCurrentBatch()
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, common.BatchNum(4), cb)
// advance one checkpoint in ldb2
err = ldb2.MakeCheckpoint()
assert.Nil(t, err)
assert.NoError(t, err)
cb, err = ldb2.GetCurrentBatch()
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, common.BatchNum(5), cb)
debug := false
@ -347,10 +348,10 @@ func TestCheckpoints(t *testing.T) {
func TestStateDBGetAccounts(t *testing.T) {
dir, err := ioutil.TempDir("", "tmpdb")
require.Nil(t, err)
require.NoError(t, err)
sdb, err := NewStateDB(dir, TypeTxSelector, 0)
assert.Nil(t, err)
assert.NoError(t, err)
// create test accounts
var accounts []common.Account
@ -362,17 +363,17 @@ func TestStateDBGetAccounts(t *testing.T) {
// add test accounts
for i := range accounts {
_, err = sdb.CreateAccount(accounts[i].Idx, &accounts[i])
require.Nil(t, err)
require.NoError(t, err)
}
dbAccounts, err := sdb.GetAccounts()
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, accounts, dbAccounts)
}
func printCheckpoints(t *testing.T, path string) {
files, err := ioutil.ReadDir(path)
assert.Nil(t, err)
assert.NoError(t, err)
fmt.Println(path)
for _, f := range files {
@ -393,33 +394,34 @@ func bigFromStr(h string, u int) *big.Int {
func TestCheckAccountsTreeTestVectors(t *testing.T) {
dir, err := ioutil.TempDir("", "tmpdb")
require.Nil(t, err)
defer assert.Nil(t, os.RemoveAll(dir))
require.NoError(t, err)
defer assert.NoError(t, os.RemoveAll(dir))
sdb, err := NewStateDB(dir, TypeSynchronizer, 32)
require.Nil(t, err)
require.NoError(t, err)
ay0 := new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(253), nil), big.NewInt(1))
// test value from js version (compatibility-canary)
assert.Equal(t, "1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", (hex.EncodeToString(ay0.Bytes())))
bjj0, err := babyjub.PointFromSignAndY(true, ay0)
require.Nil(t, err)
bjjPoint0Comp := babyjub.PackSignY(true, ay0)
bjj0 := babyjub.PublicKeyComp(bjjPoint0Comp)
ay1 := bigFromStr("00", 16)
bjj1, err := babyjub.PointFromSignAndY(false, ay1)
require.Nil(t, err)
bjjPoint1Comp := babyjub.PackSignY(false, ay1)
bjj1 := babyjub.PublicKeyComp(bjjPoint1Comp)
ay2 := bigFromStr("21b0a1688b37f77b1d1d5539ec3b826db5ac78b2513f574a04c50a7d4f8246d7", 16)
bjj2, err := babyjub.PointFromSignAndY(false, ay2)
require.Nil(t, err)
bjjPoint2Comp := babyjub.PackSignY(false, ay2)
bjj2 := babyjub.PublicKeyComp(bjjPoint2Comp)
ay3 := bigFromStr("0x10", 16) // 0x10=16
bjj3, err := babyjub.PointFromSignAndY(false, ay3)
require.Nil(t, err)
bjjPoint3Comp := babyjub.PackSignY(false, ay3)
require.NoError(t, err)
bjj3 := babyjub.PublicKeyComp(bjjPoint3Comp)
accounts := []*common.Account{
{
Idx: 1,
TokenID: 0xFFFFFFFF,
PublicKey: (*babyjub.PublicKey)(bjj0),
PublicKey: bjj0,
EthAddr: ethCommon.HexToAddress("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"),
Nonce: common.Nonce(0xFFFFFFFFFF),
Balance: bigFromStr("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16),
@ -427,7 +429,7 @@ func TestCheckAccountsTreeTestVectors(t *testing.T) {
{
Idx: 100,
TokenID: 0,
PublicKey: (*babyjub.PublicKey)(bjj1),
PublicKey: bjj1,
EthAddr: ethCommon.HexToAddress("0x00"),
Nonce: common.Nonce(0),
Balance: bigFromStr("0", 10),
@ -435,7 +437,7 @@ func TestCheckAccountsTreeTestVectors(t *testing.T) {
{
Idx: 0xFFFFFFFFFFFF,
TokenID: 3,
PublicKey: (*babyjub.PublicKey)(bjj2),
PublicKey: bjj2,
EthAddr: ethCommon.HexToAddress("0xA3C88ac39A76789437AED31B9608da72e1bbfBF9"),
Nonce: common.Nonce(129),
Balance: bigFromStr("42000000000000000000", 10),
@ -443,7 +445,7 @@ func TestCheckAccountsTreeTestVectors(t *testing.T) {
{
Idx: 10000,
TokenID: 1000,
PublicKey: (*babyjub.PublicKey)(bjj3),
PublicKey: bjj3,
EthAddr: ethCommon.HexToAddress("0x64"),
Nonce: common.Nonce(1900),
Balance: bigFromStr("14000000000000000000", 10),
@ -451,9 +453,12 @@ func TestCheckAccountsTreeTestVectors(t *testing.T) {
}
for i := 0; i < len(accounts); i++ {
_, err = accounts[i].HashValue()
require.Nil(t, err)
require.NoError(t, err)
_, err = sdb.CreateAccount(accounts[i].Idx, accounts[i])
require.Nil(t, err)
if err != nil {
log.Error(err)
}
require.NoError(t, err)
}
// root value generated by js version:
assert.Equal(t, "17298264051379321456969039521810887093935433569451713402227686942080129181291", sdb.mt.Root().BigInt().String())

+ 37
- 26
db/statedb/txprocessors.go

@ -304,10 +304,11 @@ func (s *StateDB) ProcessTxs(ptc ProcessTxsConfig, coordIdxs []common.Idx, l1use
if s.zki != nil {
s.zki.TokenID3[iFee] = accCoord.TokenID.BigInt()
s.zki.Nonce3[iFee] = accCoord.Nonce.BigInt()
if babyjub.PointCoordSign(accCoord.PublicKey.X) {
coordBJJSign, coordBJJY := babyjub.UnpackSignY(accCoord.PublicKey)
if coordBJJSign {
s.zki.Sign3[iFee] = big.NewInt(1)
}
s.zki.Ay3[iFee] = accCoord.PublicKey.Y
s.zki.Ay3[iFee] = coordBJJY
s.zki.Balance3[iFee] = accCoord.Balance
s.zki.EthAddr3[iFee] = common.EthAddrToBigInt(accCoord.EthAddr)
}
@ -432,8 +433,8 @@ func (s *StateDB) processL1Tx(exitTree *merkletree.MerkleTree, tx *common.L1Tx)
}
s.zki.DepositAmountF[s.i] = big.NewInt(int64(depositAmountF16))
s.zki.FromEthAddr[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
if tx.FromBJJ != nil {
s.zki.FromBJJCompressed[s.i] = BJJCompressedTo256BigInts(tx.FromBJJ.Compress())
if tx.FromBJJ != common.EmptyBJJComp {
s.zki.FromBJJCompressed[s.i] = BJJCompressedTo256BigInts(tx.FromBJJ)
}
// Intermediate States, for all the transactions except for the last one
@ -567,8 +568,8 @@ func (s *StateDB) processL2Tx(coordIdxsMap map[common.TokenID]common.Idx, collec
s.zki.AuxToIdx[s.i] = tx.AuxToIdx.BigInt()
}
if tx.ToBJJ != nil {
s.zki.ToBJJAy[s.i] = tx.ToBJJ.Y
if tx.ToBJJ != common.EmptyBJJComp {
_, s.zki.ToBJJAy[s.i] = babyjub.UnpackSignY(tx.ToBJJ)
}
s.zki.ToEthAddr[s.i] = common.EthAddrToBigInt(tx.ToEthAddr)
@ -643,10 +644,11 @@ func (s *StateDB) applyCreateAccount(tx *common.L1Tx) error {
if s.zki != nil {
s.zki.TokenID1[s.i] = tx.TokenID.BigInt()
s.zki.Nonce1[s.i] = big.NewInt(0)
if babyjub.PointCoordSign(tx.FromBJJ.X) {
fromBJJSign, fromBJJY := babyjub.UnpackSignY(tx.FromBJJ)
if fromBJJSign {
s.zki.Sign1[s.i] = big.NewInt(1)
}
s.zki.Ay1[s.i] = tx.FromBJJ.Y
s.zki.Ay1[s.i] = fromBJJY
s.zki.Balance1[s.i] = tx.EffectiveDepositAmount
s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
@ -683,10 +685,11 @@ func (s *StateDB) applyDeposit(tx *common.L1Tx, transfer bool) error {
if s.zki != nil {
s.zki.TokenID1[s.i] = accSender.TokenID.BigInt()
s.zki.Nonce1[s.i] = accSender.Nonce.BigInt()
if babyjub.PointCoordSign(accSender.PublicKey.X) {
senderBJJSign, senderBJJY := babyjub.UnpackSignY(accSender.PublicKey)
if senderBJJSign {
s.zki.Sign1[s.i] = big.NewInt(1)
}
s.zki.Ay1[s.i] = accSender.PublicKey.Y
s.zki.Ay1[s.i] = senderBJJY
s.zki.Balance1[s.i] = accSender.Balance
s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(accSender.EthAddr)
}
@ -721,10 +724,11 @@ func (s *StateDB) applyDeposit(tx *common.L1Tx, transfer bool) error {
if s.zki != nil {
s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
receiverBJJSign, receiverBJJY := babyjub.UnpackSignY(accReceiver.PublicKey)
if receiverBJJSign {
s.zki.Sign2[s.i] = big.NewInt(1)
}
s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
s.zki.Ay2[s.i] = receiverBJJY
s.zki.Balance2[s.i] = accReceiver.Balance
s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
}
@ -769,10 +773,11 @@ func (s *StateDB) applyTransfer(coordIdxsMap map[common.TokenID]common.Idx,
// Set the State1 before updating the Sender leaf
s.zki.TokenID1[s.i] = accSender.TokenID.BigInt()
s.zki.Nonce1[s.i] = accSender.Nonce.BigInt()
if babyjub.PointCoordSign(accSender.PublicKey.X) {
senderBJJSign, senderBJJY := babyjub.UnpackSignY(accSender.PublicKey)
if senderBJJSign {
s.zki.Sign1[s.i] = big.NewInt(1)
}
s.zki.Ay1[s.i] = accSender.PublicKey.Y
s.zki.Ay1[s.i] = senderBJJY
s.zki.Balance1[s.i] = accSender.Balance
s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(accSender.EthAddr)
}
@ -835,10 +840,11 @@ func (s *StateDB) applyTransfer(coordIdxsMap map[common.TokenID]common.Idx,
// Set the State2 before updating the Receiver leaf
s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
receiverBJJSign, receiverBJJY := babyjub.UnpackSignY(accReceiver.PublicKey)
if receiverBJJSign {
s.zki.Sign2[s.i] = big.NewInt(1)
}
s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
s.zki.Ay2[s.i] = receiverBJJY
s.zki.Balance2[s.i] = accReceiver.Balance
s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
}
@ -874,10 +880,11 @@ func (s *StateDB) applyCreateAccountDepositTransfer(tx *common.L1Tx) error {
// Set the State1 before updating the Sender leaf
s.zki.TokenID1[s.i] = tx.TokenID.BigInt()
s.zki.Nonce1[s.i] = big.NewInt(0)
if babyjub.PointCoordSign(tx.FromBJJ.X) {
fromBJJSign, fromBJJY := babyjub.UnpackSignY(tx.FromBJJ)
if fromBJJSign {
s.zki.Sign1[s.i] = big.NewInt(1)
}
s.zki.Ay1[s.i] = tx.FromBJJ.Y
s.zki.Ay1[s.i] = fromBJJY
s.zki.Balance1[s.i] = tx.EffectiveDepositAmount
s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
}
@ -921,10 +928,11 @@ func (s *StateDB) applyCreateAccountDepositTransfer(tx *common.L1Tx) error {
// Set the State2 before updating the Receiver leaf
s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
receiverBJJSign, receiverBJJY := babyjub.UnpackSignY(accReceiver.PublicKey)
if receiverBJJSign {
s.zki.Sign2[s.i] = big.NewInt(1)
}
s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
s.zki.Ay2[s.i] = receiverBJJY
s.zki.Balance2[s.i] = accReceiver.Balance
s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
}
@ -959,10 +967,11 @@ func (s *StateDB) applyExit(coordIdxsMap map[common.TokenID]common.Idx,
if s.zki != nil {
s.zki.TokenID1[s.i] = acc.TokenID.BigInt()
s.zki.Nonce1[s.i] = acc.Nonce.BigInt()
if babyjub.PointCoordSign(acc.PublicKey.X) {
accBJJSign, accBJJY := babyjub.UnpackSignY(acc.PublicKey)
if accBJJSign {
s.zki.Sign1[s.i] = big.NewInt(1)
}
s.zki.Ay1[s.i] = acc.PublicKey.Y
s.zki.Ay1[s.i] = accBJJY
s.zki.Balance1[s.i] = acc.Balance
s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(acc.EthAddr)
@ -1027,10 +1036,11 @@ func (s *StateDB) applyExit(coordIdxsMap map[common.TokenID]common.Idx,
// Set the State2 before creating the Exit leaf
s.zki.TokenID2[s.i] = acc.TokenID.BigInt()
s.zki.Nonce2[s.i] = big.NewInt(0)
if babyjub.PointCoordSign(acc.PublicKey.X) {
accBJJSign, accBJJY := babyjub.UnpackSignY(acc.PublicKey)
if accBJJSign {
s.zki.Sign2[s.i] = big.NewInt(1)
}
s.zki.Ay2[s.i] = acc.PublicKey.Y
s.zki.Ay2[s.i] = accBJJY
s.zki.Balance2[s.i] = tx.Amount
s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(acc.EthAddr)
}
@ -1057,10 +1067,11 @@ func (s *StateDB) applyExit(coordIdxsMap map[common.TokenID]common.Idx,
// Set the State2 before updating the Exit leaf
s.zki.TokenID2[s.i] = acc.TokenID.BigInt()
s.zki.Nonce2[s.i] = big.NewInt(0)
if babyjub.PointCoordSign(acc.PublicKey.X) {
accBJJSign, accBJJY := babyjub.UnpackSignY(acc.PublicKey)
if accBJJSign {
s.zki.Sign2[s.i] = big.NewInt(1)
}
s.zki.Ay2[s.i] = acc.PublicKey.Y
s.zki.Ay2[s.i] = accBJJY
s.zki.Balance2[s.i] = tx.Amount
s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(acc.EthAddr)
}

+ 68
- 68
db/statedb/txprocessors_test.go

@ -19,17 +19,17 @@ import (
func checkBalance(t *testing.T, tc *til.Context, sdb *StateDB, username string, tokenid int, expected string) {
idx := tc.Users[username].Accounts[common.TokenID(tokenid)].Idx
acc, err := sdb.GetAccount(idx)
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, expected, acc.Balance.String())
}
func TestComputeEffectiveAmounts(t *testing.T) {
dir, err := ioutil.TempDir("", "tmpdb")
require.Nil(t, err)
defer assert.Nil(t, os.RemoveAll(dir))
require.NoError(t, err)
defer assert.NoError(t, os.RemoveAll(dir))
sdb, err := NewStateDB(dir, TypeSynchronizer, 32)
assert.Nil(t, err)
assert.NoError(t, err)
set := `
Type: Blockchain
@ -44,7 +44,7 @@ func TestComputeEffectiveAmounts(t *testing.T) {
`
tc := til.NewContext(common.RollupConstMaxL1UserTx)
blocks, err := tc.GenerateBlocks(set)
require.Nil(t, err)
require.NoError(t, err)
ptc := ProcessTxsConfig{
NLevels: 32,
@ -53,7 +53,7 @@ func TestComputeEffectiveAmounts(t *testing.T) {
MaxL1Tx: 16,
}
_, err = sdb.ProcessTxs(ptc, nil, blocks[0].Rollup.L1UserTxs, nil, nil)
require.Nil(t, err)
require.NoError(t, err)
tx := common.L1Tx{
FromIdx: 256,
@ -198,16 +198,16 @@ func TestComputeEffectiveAmounts(t *testing.T) {
func TestProcessTxsBalances(t *testing.T) {
dir, err := ioutil.TempDir("", "tmpdb")
require.Nil(t, err)
defer assert.Nil(t, os.RemoveAll(dir))
require.NoError(t, err)
defer assert.NoError(t, os.RemoveAll(dir))
sdb, err := NewStateDB(dir, TypeSynchronizer, 32)
assert.Nil(t, err)
assert.NoError(t, err)
// generate test transactions from test.SetBlockchain0 code
tc := til.NewContext(common.RollupConstMaxL1UserTx)
blocks, err := tc.GenerateBlocks(til.SetBlockchainMinimumFlow0)
require.Nil(t, err)
require.NoError(t, err)
// Coordinator Idx where to send the fees
coordIdxs := []common.Idx{256, 257}
@ -220,26 +220,26 @@ func TestProcessTxsBalances(t *testing.T) {
log.Debug("block:0 batch:0, only L1CoordinatorTxs")
_, err = sdb.ProcessTxs(ptc, nil, nil, blocks[0].Rollup.Batches[0].L1CoordinatorTxs, nil)
require.Nil(t, err)
require.NoError(t, err)
log.Debug("block:0 batch:1")
l1UserTxs := []common.L1Tx{}
l2Txs := common.L2TxsToPoolL2Txs(blocks[0].Rollup.Batches[1].L2Txs)
_, err = sdb.ProcessTxs(ptc, coordIdxs, l1UserTxs, blocks[0].Rollup.Batches[1].L1CoordinatorTxs, l2Txs)
require.Nil(t, err)
require.NoError(t, err)
log.Debug("block:0 batch:2")
l1UserTxs = til.L1TxsToCommonL1Txs(tc.Queues[*blocks[0].Rollup.Batches[2].Batch.ForgeL1TxsNum])
l2Txs = common.L2TxsToPoolL2Txs(blocks[0].Rollup.Batches[2].L2Txs)
_, err = sdb.ProcessTxs(ptc, coordIdxs, l1UserTxs, blocks[0].Rollup.Batches[2].L1CoordinatorTxs, l2Txs)
require.Nil(t, err)
require.NoError(t, err)
checkBalance(t, tc, sdb, "A", 0, "500")
log.Debug("block:0 batch:3")
l1UserTxs = til.L1TxsToCommonL1Txs(tc.Queues[*blocks[0].Rollup.Batches[3].Batch.ForgeL1TxsNum])
l2Txs = common.L2TxsToPoolL2Txs(blocks[0].Rollup.Batches[3].L2Txs)
_, err = sdb.ProcessTxs(ptc, coordIdxs, l1UserTxs, blocks[0].Rollup.Batches[3].L1CoordinatorTxs, l2Txs)
require.Nil(t, err)
require.NoError(t, err)
checkBalance(t, tc, sdb, "A", 0, "500")
checkBalance(t, tc, sdb, "A", 1, "500")
@ -247,7 +247,7 @@ func TestProcessTxsBalances(t *testing.T) {
l1UserTxs = til.L1TxsToCommonL1Txs(tc.Queues[*blocks[0].Rollup.Batches[4].Batch.ForgeL1TxsNum])
l2Txs = common.L2TxsToPoolL2Txs(blocks[0].Rollup.Batches[4].L2Txs)
_, err = sdb.ProcessTxs(ptc, coordIdxs, l1UserTxs, blocks[0].Rollup.Batches[4].L1CoordinatorTxs, l2Txs)
require.Nil(t, err)
require.NoError(t, err)
checkBalance(t, tc, sdb, "A", 0, "500")
checkBalance(t, tc, sdb, "A", 1, "500")
@ -255,7 +255,7 @@ func TestProcessTxsBalances(t *testing.T) {
l1UserTxs = til.L1TxsToCommonL1Txs(tc.Queues[*blocks[0].Rollup.Batches[5].Batch.ForgeL1TxsNum])
l2Txs = common.L2TxsToPoolL2Txs(blocks[0].Rollup.Batches[5].L2Txs)
_, err = sdb.ProcessTxs(ptc, coordIdxs, l1UserTxs, blocks[0].Rollup.Batches[5].L1CoordinatorTxs, l2Txs)
require.Nil(t, err)
require.NoError(t, err)
checkBalance(t, tc, sdb, "A", 0, "600")
checkBalance(t, tc, sdb, "A", 1, "500")
checkBalance(t, tc, sdb, "B", 0, "400")
@ -264,7 +264,7 @@ func TestProcessTxsBalances(t *testing.T) {
l1UserTxs = til.L1TxsToCommonL1Txs(tc.Queues[*blocks[0].Rollup.Batches[6].Batch.ForgeL1TxsNum])
l2Txs = common.L2TxsToPoolL2Txs(blocks[0].Rollup.Batches[6].L2Txs)
_, err = sdb.ProcessTxs(ptc, coordIdxs, l1UserTxs, blocks[0].Rollup.Batches[6].L1CoordinatorTxs, l2Txs)
require.Nil(t, err)
require.NoError(t, err)
checkBalance(t, tc, sdb, "Coord", 0, "10")
checkBalance(t, tc, sdb, "Coord", 1, "20")
checkBalance(t, tc, sdb, "A", 0, "600")
@ -278,7 +278,7 @@ func TestProcessTxsBalances(t *testing.T) {
l1UserTxs = til.L1TxsToCommonL1Txs(tc.Queues[*blocks[0].Rollup.Batches[7].Batch.ForgeL1TxsNum])
l2Txs = common.L2TxsToPoolL2Txs(blocks[0].Rollup.Batches[7].L2Txs)
_, err = sdb.ProcessTxs(ptc, coordIdxs, l1UserTxs, blocks[0].Rollup.Batches[7].L1CoordinatorTxs, l2Txs)
require.Nil(t, err)
require.NoError(t, err)
checkBalance(t, tc, sdb, "Coord", 0, "35")
checkBalance(t, tc, sdb, "Coord", 1, "30")
checkBalance(t, tc, sdb, "A", 0, "430")
@ -293,7 +293,7 @@ func TestProcessTxsBalances(t *testing.T) {
l1UserTxs = til.L1TxsToCommonL1Txs(tc.Queues[*blocks[1].Rollup.Batches[0].Batch.ForgeL1TxsNum])
l2Txs = common.L2TxsToPoolL2Txs(blocks[1].Rollup.Batches[0].L2Txs)
_, err = sdb.ProcessTxs(ptc, coordIdxs, l1UserTxs, blocks[1].Rollup.Batches[0].L1CoordinatorTxs, l2Txs)
require.Nil(t, err)
require.NoError(t, err)
checkBalance(t, tc, sdb, "Coord", 0, "75")
checkBalance(t, tc, sdb, "Coord", 1, "30")
checkBalance(t, tc, sdb, "A", 0, "730")
@ -308,14 +308,14 @@ func TestProcessTxsBalances(t *testing.T) {
l1UserTxs = til.L1TxsToCommonL1Txs(tc.Queues[*blocks[1].Rollup.Batches[1].Batch.ForgeL1TxsNum])
l2Txs = common.L2TxsToPoolL2Txs(blocks[1].Rollup.Batches[1].L2Txs)
_, err = sdb.ProcessTxs(ptc, coordIdxs, l1UserTxs, blocks[1].Rollup.Batches[1].L1CoordinatorTxs, l2Txs)
require.Nil(t, err)
require.NoError(t, err)
// use Set of PoolL2 txs
poolL2Txs, err := tc.GeneratePoolL2Txs(til.SetPoolL2MinimumFlow1)
assert.Nil(t, err)
assert.NoError(t, err)
_, err = sdb.ProcessTxs(ptc, coordIdxs, []common.L1Tx{}, []common.L1Tx{}, poolL2Txs)
require.Nil(t, err)
require.NoError(t, err)
checkBalance(t, tc, sdb, "Coord", 0, "105")
checkBalance(t, tc, sdb, "Coord", 1, "40")
checkBalance(t, tc, sdb, "A", 0, "510")
@ -330,16 +330,16 @@ func TestProcessTxsBalances(t *testing.T) {
func TestProcessTxsSynchronizer(t *testing.T) {
dir, err := ioutil.TempDir("", "tmpdb")
require.Nil(t, err)
defer assert.Nil(t, os.RemoveAll(dir))
require.NoError(t, err)
defer assert.NoError(t, os.RemoveAll(dir))
sdb, err := NewStateDB(dir, TypeSynchronizer, 32)
assert.Nil(t, err)
assert.NoError(t, err)
// generate test transactions from test.SetBlockchain0 code
tc := til.NewContext(common.RollupConstMaxL1UserTx)
blocks, err := tc.GenerateBlocks(til.SetBlockchain0)
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, 31, len(blocks[0].Rollup.L1UserTxs))
assert.Equal(t, 4, len(blocks[0].Rollup.Batches[0].L1CoordinatorTxs))
@ -367,7 +367,7 @@ func TestProcessTxsSynchronizer(t *testing.T) {
// to create the Coordinator accounts to receive the fees
log.Debug("block:0 batch:0, only L1CoordinatorTxs")
ptOut, err := sdb.ProcessTxs(ptc, nil, nil, blocks[0].Rollup.Batches[0].L1CoordinatorTxs, nil)
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, 4, len(ptOut.CreatedAccounts))
assert.Equal(t, 0, len(ptOut.CollectedFees))
@ -375,7 +375,7 @@ func TestProcessTxsSynchronizer(t *testing.T) {
l2Txs := common.L2TxsToPoolL2Txs(blocks[0].Rollup.Batches[1].L2Txs)
ptOut, err = sdb.ProcessTxs(ptc, coordIdxs, blocks[0].Rollup.L1UserTxs,
blocks[0].Rollup.Batches[1].L1CoordinatorTxs, l2Txs)
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, 0, len(ptOut.ExitInfos))
assert.Equal(t, 31, len(ptOut.CreatedAccounts))
assert.Equal(t, 4, len(ptOut.CollectedFees))
@ -384,13 +384,13 @@ func TestProcessTxsSynchronizer(t *testing.T) {
assert.Equal(t, "0", ptOut.CollectedFees[common.TokenID(2)].String())
assert.Equal(t, "0", ptOut.CollectedFees[common.TokenID(3)].String())
acc, err := sdb.GetAccount(idxA1)
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, "50", acc.Balance.String())
log.Debug("block:0 batch:2")
l2Txs = common.L2TxsToPoolL2Txs(blocks[0].Rollup.Batches[2].L2Txs)
ptOut, err = sdb.ProcessTxs(ptc, coordIdxs, nil, blocks[0].Rollup.Batches[2].L1CoordinatorTxs, l2Txs)
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, 0, len(ptOut.ExitInfos))
assert.Equal(t, 0, len(ptOut.CreatedAccounts))
assert.Equal(t, 4, len(ptOut.CollectedFees))
@ -399,7 +399,7 @@ func TestProcessTxsSynchronizer(t *testing.T) {
assert.Equal(t, "0", ptOut.CollectedFees[common.TokenID(2)].String())
assert.Equal(t, "0", ptOut.CollectedFees[common.TokenID(3)].String())
acc, err = sdb.GetAccount(idxA1)
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, "35", acc.Balance.String())
log.Debug("block:1 batch:0")
@ -410,7 +410,7 @@ func TestProcessTxsSynchronizer(t *testing.T) {
assert.Equal(t, common.Nonce(0), l2Txs[2].Nonce)
ptOut, err = sdb.ProcessTxs(ptc, coordIdxs, nil, blocks[1].Rollup.Batches[0].L1CoordinatorTxs, l2Txs)
require.Nil(t, err)
require.NoError(t, err)
// after processing expect l2Txs[0:2].Nonce!=0 and has expected value
assert.Equal(t, common.Nonce(6), l2Txs[0].Nonce)
@ -425,14 +425,14 @@ func TestProcessTxsSynchronizer(t *testing.T) {
assert.Equal(t, "0", ptOut.CollectedFees[common.TokenID(2)].String())
assert.Equal(t, "0", ptOut.CollectedFees[common.TokenID(3)].String())
acc, err = sdb.GetAccount(idxA1)
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, "57", acc.Balance.String())
log.Debug("block:1 batch:1")
l2Txs = common.L2TxsToPoolL2Txs(blocks[1].Rollup.Batches[1].L2Txs)
ptOut, err = sdb.ProcessTxs(ptc, coordIdxs, blocks[1].Rollup.L1UserTxs,
blocks[1].Rollup.Batches[1].L1CoordinatorTxs, l2Txs)
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, 2, len(ptOut.ExitInfos)) // 2, as previous batch was without L1UserTxs, and has pending the 'ForceExit(1) A: 5'
assert.Equal(t, 1, len(ptOut.CreatedAccounts))
@ -442,32 +442,32 @@ func TestProcessTxsSynchronizer(t *testing.T) {
assert.Equal(t, "0", ptOut.CollectedFees[common.TokenID(2)].String())
assert.Equal(t, "0", ptOut.CollectedFees[common.TokenID(3)].String())
acc, err = sdb.GetAccount(idxA1)
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, "77", acc.Balance.String())
idxB0 := tc.Users["C"].Accounts[common.TokenID(0)].Idx
acc, err = sdb.GetAccount(idxB0)
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, "51", acc.Balance.String())
// get balance of Coordinator account for TokenID==0
acc, err = sdb.GetAccount(common.Idx(256))
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, "2", acc.Balance.String())
}
func TestProcessTxsBatchBuilder(t *testing.T) {
dir, err := ioutil.TempDir("", "tmpdb")
require.Nil(t, err)
defer assert.Nil(t, os.RemoveAll(dir))
require.NoError(t, err)
defer assert.NoError(t, os.RemoveAll(dir))
sdb, err := NewStateDB(dir, TypeBatchBuilder, 32)
assert.Nil(t, err)
assert.NoError(t, err)
// generate test transactions from test.SetBlockchain0 code
tc := til.NewContext(common.RollupConstMaxL1UserTx)
blocks, err := tc.GenerateBlocks(til.SetBlockchain0)
require.Nil(t, err)
require.NoError(t, err)
// Coordinator Idx where to send the fees
coordIdxs := []common.Idx{256, 257, 258, 259}
@ -486,58 +486,58 @@ func TestProcessTxsBatchBuilder(t *testing.T) {
// to create the Coordinator accounts to receive the fees
log.Debug("block:0 batch:0, only L1CoordinatorTxs")
ptOut, err := sdb.ProcessTxs(ptc, nil, nil, blocks[0].Rollup.Batches[0].L1CoordinatorTxs, nil)
require.Nil(t, err)
require.NoError(t, err)
// expect 0 at CreatedAccount, as is only computed when StateDB.Type==TypeSynchronizer
assert.Equal(t, 0, len(ptOut.CreatedAccounts))
log.Debug("block:0 batch:1")
l2Txs := common.L2TxsToPoolL2Txs(blocks[0].Rollup.Batches[1].L2Txs)
ptOut, err = sdb.ProcessTxs(ptc, coordIdxs, blocks[0].Rollup.L1UserTxs, blocks[0].Rollup.Batches[1].L1CoordinatorTxs, l2Txs)
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, 0, len(ptOut.ExitInfos))
assert.Equal(t, 0, len(ptOut.CreatedAccounts))
acc, err := sdb.GetAccount(idxA1)
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, "50", acc.Balance.String())
log.Debug("block:0 batch:2")
l2Txs = common.L2TxsToPoolL2Txs(blocks[0].Rollup.Batches[2].L2Txs)
ptOut, err = sdb.ProcessTxs(ptc, coordIdxs, nil, blocks[0].Rollup.Batches[2].L1CoordinatorTxs, l2Txs)
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, 0, len(ptOut.ExitInfos))
assert.Equal(t, 0, len(ptOut.CreatedAccounts))
acc, err = sdb.GetAccount(idxA1)
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, "35", acc.Balance.String())
log.Debug("block:1 batch:0")
l2Txs = common.L2TxsToPoolL2Txs(blocks[1].Rollup.Batches[0].L2Txs)
_, err = sdb.ProcessTxs(ptc, coordIdxs, nil, blocks[1].Rollup.Batches[0].L1CoordinatorTxs, l2Txs)
require.Nil(t, err)
require.NoError(t, err)
acc, err = sdb.GetAccount(idxA1)
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, "57", acc.Balance.String())
log.Debug("block:1 batch:1")
l2Txs = common.L2TxsToPoolL2Txs(blocks[1].Rollup.Batches[1].L2Txs)
_, err = sdb.ProcessTxs(ptc, coordIdxs, blocks[1].Rollup.L1UserTxs, blocks[1].Rollup.Batches[1].L1CoordinatorTxs, l2Txs)
require.Nil(t, err)
require.NoError(t, err)
acc, err = sdb.GetAccount(idxA1)
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, "77", acc.Balance.String())
idxB0 := tc.Users["C"].Accounts[common.TokenID(0)].Idx
acc, err = sdb.GetAccount(idxB0)
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, "51", acc.Balance.String())
// get balance of Coordinator account for TokenID==0
acc, err = sdb.GetAccount(common.Idx(256))
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, common.TokenID(0), acc.TokenID)
assert.Equal(t, "2", acc.Balance.String())
acc, err = sdb.GetAccount(common.Idx(257))
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, common.TokenID(1), acc.TokenID)
assert.Equal(t, "2", acc.Balance.String())
@ -546,15 +546,15 @@ func TestProcessTxsBatchBuilder(t *testing.T) {
func TestProcessTxsRootTestVectors(t *testing.T) {
dir, err := ioutil.TempDir("", "tmpdb")
require.Nil(t, err)
defer assert.Nil(t, os.RemoveAll(dir))
require.NoError(t, err)
defer assert.NoError(t, os.RemoveAll(dir))
sdb, err := NewStateDB(dir, TypeBatchBuilder, 32)
assert.Nil(t, err)
assert.NoError(t, err)
// same values than in the js test
bjj0, err := common.BJJFromStringWithChecksum("21b0a1688b37f77b1d1d5539ec3b826db5ac78b2513f574a04c50a7d4f8246d7")
assert.Nil(t, err)
assert.NoError(t, err)
l1Txs := []common.L1Tx{
{
FromIdx: 0,
@ -587,30 +587,30 @@ func TestProcessTxsRootTestVectors(t *testing.T) {
MaxL1Tx: 16,
}
_, err = sdb.ProcessTxs(ptc, nil, l1Txs, nil, l2Txs)
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, "9827704113668630072730115158977131501210702363656902211840117643154933433410", sdb.mt.Root().BigInt().String())
}
func TestCreateAccountDepositMaxValue(t *testing.T) {
dir, err := ioutil.TempDir("", "tmpdb")
require.Nil(t, err)
defer assert.Nil(t, os.RemoveAll(dir))
require.NoError(t, err)
defer assert.NoError(t, os.RemoveAll(dir))
nLevels := 16
sdb, err := NewStateDB(dir, TypeBatchBuilder, nLevels)
assert.Nil(t, err)
assert.NoError(t, err)
users := generateJsUsers(t)
daMaxHex, err := hex.DecodeString("FFFF")
require.Nil(t, err)
require.NoError(t, err)
daMaxF16 := common.Float16(binary.BigEndian.Uint16(daMaxHex))
daMaxBI := daMaxF16.BigInt()
assert.Equal(t, "10235000000000000000000000000000000", daMaxBI.String())
daMax1Hex, err := hex.DecodeString("FFFE")
require.Nil(t, err)
require.NoError(t, err)
daMax1F16 := common.Float16(binary.BigEndian.Uint16(daMax1Hex))
daMax1BI := daMax1F16.BigInt()
assert.Equal(t, "10225000000000000000000000000000000", daMax1BI.String())
@ -621,7 +621,7 @@ func TestCreateAccountDepositMaxValue(t *testing.T) {
DepositAmount: daMaxBI,
Amount: big.NewInt(0),
TokenID: 1,
FromBJJ: users[0].BJJ.Public(),
FromBJJ: users[0].BJJ.Public().Compress(),
FromEthAddr: users[0].Addr,
ToIdx: 0,
Type: common.TxTypeCreateAccountDeposit,
@ -632,7 +632,7 @@ func TestCreateAccountDepositMaxValue(t *testing.T) {
DepositAmount: daMax1BI,
Amount: big.NewInt(0),
TokenID: 1,
FromBJJ: users[1].BJJ.Public(),
FromBJJ: users[1].BJJ.Public().Compress(),
FromEthAddr: users[1].Addr,
ToIdx: 0,
Type: common.TxTypeCreateAccountDeposit,
@ -648,13 +648,13 @@ func TestCreateAccountDepositMaxValue(t *testing.T) {
}
_, err = sdb.ProcessTxs(ptc, nil, l1Txs, nil, nil)
require.Nil(t, err)
require.NoError(t, err)
// check balances
acc, err := sdb.GetAccount(common.Idx(256))
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, daMaxBI, acc.Balance)
acc, err = sdb.GetAccount(common.Idx(257))
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, daMax1BI, acc.Balance)
}

+ 10
- 12
db/statedb/utils.go

@ -19,8 +19,8 @@ func concatEthAddrTokenID(addr ethCommon.Address, tokenID common.TokenID) []byte
b = append(b[:], tokenID.Bytes()[:]...)
return b
}
func concatEthAddrBJJTokenID(addr ethCommon.Address, pk *babyjub.PublicKey, tokenID common.TokenID) []byte {
pkComp := pk.Compress()
func concatEthAddrBJJTokenID(addr ethCommon.Address, pk babyjub.PublicKeyComp, tokenID common.TokenID) []byte {
pkComp := pk
var b []byte
b = append(b, addr.Bytes()...)
b = append(b[:], pkComp[:]...)
@ -33,7 +33,7 @@ func concatEthAddrBJJTokenID(addr ethCommon.Address, pk *babyjub.PublicKey, toke
// - key: EthAddr & BabyJubJub PublicKey Compressed, value: idx
// If Idx already exist for the given EthAddr & BJJ, the remaining Idx will be
// always the smallest one.
func (s *StateDB) setIdxByEthAddrBJJ(idx common.Idx, addr ethCommon.Address, pk *babyjub.PublicKey, tokenID common.TokenID) error {
func (s *StateDB) setIdxByEthAddrBJJ(idx common.Idx, addr ethCommon.Address, pk babyjub.PublicKeyComp, tokenID common.TokenID) error {
oldIdx, err := s.GetIdxByEthAddrBJJ(addr, pk, tokenID)
if err == nil {
// EthAddr & BJJ already have an Idx
@ -46,10 +46,6 @@ func (s *StateDB) setIdxByEthAddrBJJ(idx common.Idx, addr ethCommon.Address, pk
}
}
if pk == nil {
return tracerr.Wrap(fmt.Errorf("BabyJubJub pk not defined"))
}
// store idx for EthAddr & BJJ assuming that EthAddr & BJJ still don't
// have an Idx stored in the DB, and if so, the already stored Idx is
// bigger than the given one, so should be updated to the new one
@ -89,11 +85,13 @@ func (s *StateDB) GetIdxByEthAddr(addr ethCommon.Address, tokenID common.TokenID
k := concatEthAddrTokenID(addr, tokenID)
b, err := s.db.Get(append(PrefixKeyAddr, k...))
if err != nil {
return common.Idx(0), tracerr.Wrap(fmt.Errorf("GetIdxByEthAddr: %s: ToEthAddr: %s, TokenID: %d", ErrToIdxNotFound, addr.Hex(), tokenID))
return common.Idx(0), tracerr.Wrap(fmt.Errorf("GetIdxByEthAddr: %s: ToEthAddr: %s, TokenID: %d",
ErrToIdxNotFound, addr.Hex(), tokenID))
}
idx, err := common.IdxFromBytes(b)
if err != nil {
return common.Idx(0), tracerr.Wrap(fmt.Errorf("GetIdxByEthAddr: %s: ToEthAddr: %s, TokenID: %d", err, addr.Hex(), tokenID))
return common.Idx(0), tracerr.Wrap(fmt.Errorf("GetIdxByEthAddr: %s: ToEthAddr: %s, TokenID: %d",
err, addr.Hex(), tokenID))
}
return idx, nil
}
@ -103,12 +101,12 @@ func (s *StateDB) GetIdxByEthAddr(addr ethCommon.Address, tokenID common.TokenID
// address, it's ignored in the query. If `pk` is nil, it's ignored in the
// query. Will return common.Idx(0) and error in case that Idx is not found in
// the StateDB.
func (s *StateDB) GetIdxByEthAddrBJJ(addr ethCommon.Address, pk *babyjub.PublicKey, tokenID common.TokenID) (common.Idx, error) {
if !bytes.Equal(addr.Bytes(), common.EmptyAddr.Bytes()) && pk == nil {
func (s *StateDB) GetIdxByEthAddrBJJ(addr ethCommon.Address, pk babyjub.PublicKeyComp, tokenID common.TokenID) (common.Idx, error) {
if !bytes.Equal(addr.Bytes(), common.EmptyAddr.Bytes()) && pk == common.EmptyBJJComp {
// ToEthAddr
// case ToEthAddr!=0 && ToBJJ=0
return s.GetIdxByEthAddr(addr, tokenID)
} else if !bytes.Equal(addr.Bytes(), common.EmptyAddr.Bytes()) && pk != nil {
} else if !bytes.Equal(addr.Bytes(), common.EmptyAddr.Bytes()) && pk != common.EmptyBJJComp {
// case ToEthAddr!=0 && ToBJJ!=0
k := concatEthAddrBJJTokenID(addr, pk, tokenID)
b, err := s.db.Get(append(PrefixKeyAddrBJJ, k...))

+ 19
- 19
db/statedb/utils_test.go

@ -17,11 +17,11 @@ import (
func TestGetIdx(t *testing.T) {
dir, err := ioutil.TempDir("", "tmpdb")
require.Nil(t, err)
defer assert.Nil(t, os.RemoveAll(dir))
require.NoError(t, err)
defer assert.NoError(t, os.RemoveAll(dir))
sdb, err := NewStateDB(dir, TypeTxSelector, 0)
assert.Nil(t, err)
assert.NoError(t, err)
var sk babyjub.PrivateKey
copy(sk[:], []byte("1234")) // only for testing
@ -39,50 +39,50 @@ func TestGetIdx(t *testing.T) {
tokenID1 := common.TokenID(1)
// store the keys for idx by Addr & BJJ
err = sdb.setIdxByEthAddrBJJ(idx, addr, pk, tokenID0)
require.Nil(t, err)
err = sdb.setIdxByEthAddrBJJ(idx, addr, pk.Compress(), tokenID0)
require.NoError(t, err)
idxR, err := sdb.GetIdxByEthAddrBJJ(addr, pk, tokenID0)
assert.Nil(t, err)
idxR, err := sdb.GetIdxByEthAddrBJJ(addr, pk.Compress(), tokenID0)
assert.NoError(t, err)
assert.Equal(t, idx, idxR)
// expect error when getting only by EthAddr, as value does not exist
// in the db for only EthAddr
_, err = sdb.GetIdxByEthAddr(addr, tokenID0)
assert.Nil(t, err)
assert.NoError(t, err)
_, err = sdb.GetIdxByEthAddr(addr2, tokenID0)
assert.NotNil(t, err)
// expect error when getting by EthAddr and BJJ, but for another TokenID
_, err = sdb.GetIdxByEthAddrBJJ(addr, pk, tokenID1)
_, err = sdb.GetIdxByEthAddrBJJ(addr, pk.Compress(), tokenID1)
assert.NotNil(t, err)
// expect to fail
idxR, err = sdb.GetIdxByEthAddrBJJ(addr2, pk, tokenID0)
idxR, err = sdb.GetIdxByEthAddrBJJ(addr2, pk.Compress(), tokenID0)
assert.NotNil(t, err)
assert.Equal(t, common.Idx(0), idxR)
idxR, err = sdb.GetIdxByEthAddrBJJ(addr, pk2, tokenID0)
idxR, err = sdb.GetIdxByEthAddrBJJ(addr, pk2.Compress(), tokenID0)
assert.NotNil(t, err)
assert.Equal(t, common.Idx(0), idxR)
// try to store bigger idx, will not affect as already exist a smaller
// Idx for that Addr & BJJ
err = sdb.setIdxByEthAddrBJJ(idx2, addr, pk, tokenID0)
assert.Nil(t, err)
err = sdb.setIdxByEthAddrBJJ(idx2, addr, pk.Compress(), tokenID0)
assert.NoError(t, err)
// store smaller idx
err = sdb.setIdxByEthAddrBJJ(idx3, addr, pk, tokenID0)
assert.Nil(t, err)
err = sdb.setIdxByEthAddrBJJ(idx3, addr, pk.Compress(), tokenID0)
assert.NoError(t, err)
idxR, err = sdb.GetIdxByEthAddrBJJ(addr, pk, tokenID0)
assert.Nil(t, err)
idxR, err = sdb.GetIdxByEthAddrBJJ(addr, pk.Compress(), tokenID0)
assert.NoError(t, err)
assert.Equal(t, idx3, idxR)
// by EthAddr should work
idxR, err = sdb.GetIdxByEthAddr(addr, tokenID0)
assert.Nil(t, err)
assert.NoError(t, err)
assert.Equal(t, idx3, idxR)
// expect error when trying to get Idx by addr2 & pk2
idxR, err = sdb.GetIdxByEthAddrBJJ(addr2, pk2, tokenID0)
idxR, err = sdb.GetIdxByEthAddrBJJ(addr2, pk2.Compress(), tokenID0)
assert.NotNil(t, err)
expectedErr := fmt.Errorf("GetIdxByEthAddrBJJ: %s: ToEthAddr: %s, ToBJJ: %s, TokenID: %d", ErrToIdxNotFound, addr2.Hex(), pk2, tokenID0)
assert.Equal(t, expectedErr, tracerr.Unwrap(err))

+ 119
- 120
db/statedb/zkinputsgen_test.go
File diff suppressed because it is too large
View File


+ 11
- 14
eth/rollup.go

@ -245,11 +245,11 @@ type RollupInterface interface {
RollupForgeBatch(*RollupForgeBatchArgs) (*types.Transaction, error)
RollupAddToken(tokenAddress ethCommon.Address, feeAddToken, deadline *big.Int) (*types.Transaction, error)
RollupWithdrawMerkleProof(babyPubKey *babyjub.PublicKey, tokenID uint32, numExitRoot, idx int64, amount *big.Int, siblings []*big.Int, instantWithdraw bool) (*types.Transaction, error)
RollupWithdrawMerkleProof(babyPubKey babyjub.PublicKeyComp, tokenID uint32, numExitRoot, idx int64, amount *big.Int, siblings []*big.Int, instantWithdraw bool) (*types.Transaction, error)
RollupWithdrawCircuit(proofA, proofC [2]*big.Int, proofB [2][2]*big.Int, tokenID uint32, numExitRoot, idx int64, amount *big.Int, instantWithdraw bool) (*types.Transaction, error)
RollupL1UserTxERC20ETH(fromBJJ *babyjub.PublicKey, fromIdx int64, depositAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64) (*types.Transaction, error)
RollupL1UserTxERC20Permit(fromBJJ *babyjub.PublicKey, fromIdx int64, depositAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64, deadline *big.Int) (tx *types.Transaction, err error)
RollupL1UserTxERC20ETH(fromBJJ babyjub.PublicKeyComp, fromIdx int64, depositAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64) (*types.Transaction, error)
RollupL1UserTxERC20Permit(fromBJJ babyjub.PublicKeyComp, fromIdx int64, depositAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64, deadline *big.Int) (tx *types.Transaction, err error)
// Governance Public Functions
RollupUpdateForgeL1L2BatchTimeout(newForgeL1L2BatchTimeout int64) (*types.Transaction, error)
@ -416,12 +416,11 @@ func (c *RollupClient) RollupAddToken(tokenAddress ethCommon.Address, feeAddToke
}
// RollupWithdrawMerkleProof is the interface to call the smart contract function
func (c *RollupClient) RollupWithdrawMerkleProof(fromBJJ *babyjub.PublicKey, tokenID uint32, numExitRoot, idx int64, amount *big.Int, siblings []*big.Int, instantWithdraw bool) (tx *types.Transaction, err error) {
func (c *RollupClient) RollupWithdrawMerkleProof(fromBJJ babyjub.PublicKeyComp, tokenID uint32, numExitRoot, idx int64, amount *big.Int, siblings []*big.Int, instantWithdraw bool) (tx *types.Transaction, err error) {
if tx, err = c.client.CallAuth(
0,
func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
pkCompL := fromBJJ.Compress()
pkCompB := common.SwapEndianness(pkCompL[:])
pkCompB := common.SwapEndianness(fromBJJ[:])
babyPubKey := new(big.Int).SetBytes(pkCompB)
numExitRootB := uint32(numExitRoot)
idxBig := big.NewInt(idx)
@ -440,14 +439,13 @@ func (c *RollupClient) RollupWithdrawCircuit(proofA, proofC [2]*big.Int, proofB
}
// RollupL1UserTxERC20ETH is the interface to call the smart contract function
func (c *RollupClient) RollupL1UserTxERC20ETH(fromBJJ *babyjub.PublicKey, fromIdx int64, depositAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64) (tx *types.Transaction, err error) {
func (c *RollupClient) RollupL1UserTxERC20ETH(fromBJJ babyjub.PublicKeyComp, fromIdx int64, depositAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64) (tx *types.Transaction, err error) {
if tx, err = c.client.CallAuth(
0,
func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
var babyPubKey *big.Int
if fromBJJ != nil {
pkCompL := fromBJJ.Compress()
pkCompB := common.SwapEndianness(pkCompL[:])
if fromBJJ != common.EmptyBJJComp {
pkCompB := common.SwapEndianness(fromBJJ[:])
babyPubKey = new(big.Int).SetBytes(pkCompB)
} else {
babyPubKey = big.NewInt(0)
@ -476,14 +474,13 @@ func (c *RollupClient) RollupL1UserTxERC20ETH(fromBJJ *babyjub.PublicKey, fromId
}
// RollupL1UserTxERC20Permit is the interface to call the smart contract function
func (c *RollupClient) RollupL1UserTxERC20Permit(fromBJJ *babyjub.PublicKey, fromIdx int64, depositAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64, deadline *big.Int) (tx *types.Transaction, err error) {
func (c *RollupClient) RollupL1UserTxERC20Permit(fromBJJ babyjub.PublicKeyComp, fromIdx int64, depositAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64, deadline *big.Int) (tx *types.Transaction, err error) {
if tx, err = c.client.CallAuth(
0,
func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
var babyPubKey *big.Int
if fromBJJ != nil {
pkCompL := fromBJJ.Compress()
pkCompB := common.SwapEndianness(pkCompL[:])
if fromBJJ != common.EmptyBJJComp {
pkCompB := common.SwapEndianness(fromBJJ[:])
babyPubKey = new(big.Int).SetBytes(pkCompB)
} else {
babyPubKey = big.NewInt(0)

+ 6
- 9
eth/rollup_test.go

@ -278,7 +278,7 @@ func TestRollupL1UserTxETHCreateAccountDeposit(t *testing.T) {
tokenIDUint32 := uint32(0)
depositAmount, _ := new(big.Int).SetString("1000000000000000000000", 10)
l1Tx := common.L1Tx{
FromBJJ: key.BJJPublicKey,
FromBJJ: key.BJJPublicKey.Compress(),
FromIdx: common.Idx(fromIdxInt64),
ToIdx: common.Idx(toIdxInt64),
DepositAmount: depositAmount,
@ -310,7 +310,7 @@ func TestRollupL1UserTxERC20CreateAccountDeposit(t *testing.T) {
toIdxInt64 := int64(0)
depositAmount, _ := new(big.Int).SetString("1000000000000000000000", 10)
l1Tx := common.L1Tx{
FromBJJ: key.BJJPublicKey,
FromBJJ: key.BJJPublicKey.Compress(),
FromIdx: common.Idx(fromIdxInt64),
ToIdx: common.Idx(toIdxInt64),
DepositAmount: depositAmount,
@ -342,7 +342,7 @@ func TestRollupL1UserTxERC20PermitCreateAccountDeposit(t *testing.T) {
toIdxInt64 := int64(0)
depositAmount, _ := new(big.Int).SetString("1000000000000000000000", 10)
l1Tx := common.L1Tx{
FromBJJ: key.BJJPublicKey,
FromBJJ: key.BJJPublicKey.Compress(),
FromIdx: common.Idx(fromIdxInt64),
ToIdx: common.Idx(toIdxInt64),
DepositAmount: depositAmount,
@ -374,7 +374,7 @@ func TestRollupL1UserTxETHDeposit(t *testing.T) {
tokenIDUint32 := uint32(0)
depositAmount, _ := new(big.Int).SetString("1000000000000000000000", 10)
l1Tx := common.L1Tx{
FromBJJ: nil,
FromBJJ: common.EmptyBJJComp,
FromIdx: common.Idx(fromIdxInt64),
ToIdx: common.Idx(toIdxInt64),
DepositAmount: depositAmount,
@ -404,7 +404,7 @@ func TestRollupL1UserTxERC20Deposit(t *testing.T) {
toIdxInt64 := int64(0)
depositAmount, _ := new(big.Int).SetString("1000000000000000000000", 10)
l1Tx := common.L1Tx{
FromBJJ: nil,
FromBJJ: common.EmptyBJJComp,
FromIdx: common.Idx(fromIdxInt64),
ToIdx: common.Idx(toIdxInt64),
DepositAmount: depositAmount,
@ -909,9 +909,6 @@ func TestRollupWithdrawMerkleProof(t *testing.T) {
pkCompLE := common.SwapEndianness(pkCompBE)
copy(pkComp[:], pkCompLE)
pk, err := pkComp.Decompress()
require.NoError(t, err)
require.NoError(t, err)
tokenID := uint32(tokenHEZID)
numExitRoot := int64(3)
@ -926,7 +923,7 @@ func TestRollupWithdrawMerkleProof(t *testing.T) {
// siblings = append(siblings, siblingBytes1)
instantWithdraw := true
_, err = rollupClientAux.RollupWithdrawMerkleProof(pk, tokenID, numExitRoot, fromIdx, amount, siblings, instantWithdraw)
_, err = rollupClientAux.RollupWithdrawMerkleProof(pkComp, tokenID, numExitRoot, fromIdx, amount, siblings, instantWithdraw)
require.NoError(t, err)
currentBlockNum, err := rollupClient.client.EthLastBlock()

+ 1
- 1
go.mod

@ -14,7 +14,7 @@ require (
github.com/go-sql-driver/mysql v1.5.0 // indirect
github.com/gobuffalo/packr/v2 v2.8.0
github.com/hermeznetwork/tracerr v0.3.1-0.20201126162137-de9930d0cf29
github.com/iden3/go-iden3-crypto v0.0.6-0.20201203095229-821a601d2002
github.com/iden3/go-iden3-crypto v0.0.6-0.20201221160344-58e589b6eb4c
github.com/iden3/go-merkletree v0.0.0-20201215142017-730707e5659a
github.com/jinzhu/copier v0.0.0-20190924061706-b57f9002281a
github.com/jmoiron/sqlx v1.2.1-0.20200615141059-0794cb1f47ee

+ 2
- 6
go.sum

@ -342,14 +342,10 @@ github.com/iden3/go-circom-prover-verifier v0.0.1/go.mod h1:1FkpX4nUXxYcY2fpzqd2
github.com/iden3/go-circom-witnesscalc v0.0.1/go.mod h1:xjT1BlFZDBioHOlbD75SmZZLC1d1AfOycqbSa/1QRJU=
github.com/iden3/go-iden3-core v0.0.8 h1:PLw7iCiX7Pw1dqBkR+JaLQWqB5RKd+vgu25UBdvFXGQ=
github.com/iden3/go-iden3-core v0.0.8/go.mod h1:URNjIhMql6sEbWubIGrjJdw5wHCE1Pk1XghxjBOtA3s=
github.com/iden3/go-iden3-crypto v0.0.5 h1:inCSm5a+ry+nbpVTL/9+m6UcIwSv6nhUm0tnIxEbcps=
github.com/iden3/go-iden3-crypto v0.0.5/go.mod h1:XKw1oDwYn2CIxKOtr7m/mL5jMn4mLOxAxtZBRxQBev8=
github.com/iden3/go-iden3-crypto v0.0.6-0.20200819064831-09d161e9f670 h1:gNBFu/WnRfNn+xywE04fgCWSHlb6wr0nIIll9i4R2fc=
github.com/iden3/go-iden3-crypto v0.0.6-0.20200819064831-09d161e9f670/go.mod h1:oBgthFLboAWi9feaBUFy7OxEcyn9vA1khHSL/WwWFyg=
github.com/iden3/go-iden3-crypto v0.0.6-0.20201016142444-94e92e88fb4e h1:DvzTgAkzfcW8l4mHgEaMv2hgDTlisym/gGNNTNKqnpQ=
github.com/iden3/go-iden3-crypto v0.0.6-0.20201016142444-94e92e88fb4e/go.mod h1:oBgthFLboAWi9feaBUFy7OxEcyn9vA1khHSL/WwWFyg=
github.com/iden3/go-iden3-crypto v0.0.6-0.20201203095229-821a601d2002 h1:f2twuL20aAqq1TlSdfQgL5r68hKjB/ioQdSctREQLuY=
github.com/iden3/go-iden3-crypto v0.0.6-0.20201203095229-821a601d2002/go.mod h1:oBgthFLboAWi9feaBUFy7OxEcyn9vA1khHSL/WwWFyg=
github.com/iden3/go-iden3-crypto v0.0.6-0.20201221160344-58e589b6eb4c h1:D2u8FFYey6iFXLsqqJZ8R7ch8gZum+/b98whvoSDbyg=
github.com/iden3/go-iden3-crypto v0.0.6-0.20201221160344-58e589b6eb4c/go.mod h1:oBgthFLboAWi9feaBUFy7OxEcyn9vA1khHSL/WwWFyg=
github.com/iden3/go-merkletree v0.0.0-20200902123354-eeb949f8c334 h1:FQngDJKiwM6i4kHlVFvSpJa9sO+QvZ7C+GqoPWe+5BI=
github.com/iden3/go-merkletree v0.0.0-20200902123354-eeb949f8c334/go.mod h1:MRe6i0mi2oDVUzgBIHsNRE6XAg8EBuqIQZMsd+do+dU=
github.com/iden3/go-merkletree v0.0.0-20201103115630-ad30c8309b44 h1:d6AbzJWWUosTpjb6Ab+I0bMO4UPY+u/HgkOdhksxDgY=

+ 2
- 2
synchronizer/synchronizer_test.go

@ -457,9 +457,9 @@ func TestSync(t *testing.T) {
// Block 4
// Generate 2 withdraws manually
_, err = client.RollupWithdrawMerkleProof(tc.Users["A"].BJJ.Public(), 1, 4, 256, big.NewInt(100), []*big.Int{}, true)
_, err = client.RollupWithdrawMerkleProof(tc.Users["A"].BJJ.Public().Compress(), 1, 4, 256, big.NewInt(100), []*big.Int{}, true)
require.NoError(t, err)
_, err = client.RollupWithdrawMerkleProof(tc.Users["C"].BJJ.Public(), 1, 3, 258, big.NewInt(50), []*big.Int{}, false)
_, err = client.RollupWithdrawMerkleProof(tc.Users["C"].BJJ.Public().Compress(), 1, 3, 258, big.NewInt(50), []*big.Int{}, false)
require.NoError(t, err)
client.CtlMineBlock()

+ 1
- 1
test/debugapi/debugapi_test.go

@ -35,7 +35,7 @@ func newAccount(t *testing.T, i int) *common.Account {
TokenID: common.TokenID(i),
Nonce: common.Nonce(i),
Balance: big.NewInt(1000),
PublicKey: pk,
PublicKey: pk.Compress(),
EthAddr: address,
}
}

+ 9
- 4
test/ethclient.go

@ -731,14 +731,14 @@ var errTODO = fmt.Errorf("TODO: Not implemented yet")
// }
// RollupL1UserTxERC20Permit is the interface to call the smart contract function
func (c *Client) RollupL1UserTxERC20Permit(fromBJJ *babyjub.PublicKey, fromIdx int64, depositAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64, deadline *big.Int) (tx *types.Transaction, err error) {
func (c *Client) RollupL1UserTxERC20Permit(fromBJJ babyjub.PublicKeyComp, fromIdx int64, depositAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64, deadline *big.Int) (tx *types.Transaction, err error) {
log.Error("TODO")
return nil, tracerr.Wrap(errTODO)
}
// RollupL1UserTxERC20ETH sends an L1UserTx to the Rollup.
func (c *Client) RollupL1UserTxERC20ETH(
fromBJJ *babyjub.PublicKey,
fromBJJ babyjub.PublicKeyComp,
fromIdx int64,
depositAmount *big.Int,
amount *big.Int,
@ -826,7 +826,7 @@ func (c *Client) RollupWithdrawCircuit(proofA, proofC [2]*big.Int, proofB [2][2]
}
// RollupWithdrawMerkleProof is the interface to call the smart contract function
func (c *Client) RollupWithdrawMerkleProof(babyPubKey *babyjub.PublicKey, tokenID uint32, numExitRoot, idx int64, amount *big.Int, siblings []*big.Int, instantWithdraw bool) (tx *types.Transaction, err error) {
func (c *Client) RollupWithdrawMerkleProof(babyPubKey babyjub.PublicKeyComp, tokenID uint32, numExitRoot, idx int64, amount *big.Int, siblings []*big.Int, instantWithdraw bool) (tx *types.Transaction, err error) {
c.rw.Lock()
defer c.rw.Unlock()
cpy := c.nextBlock().copy()
@ -843,6 +843,11 @@ func (c *Client) RollupWithdrawMerkleProof(babyPubKey *babyjub.PublicKey, tokenI
}
r.State.ExitNullifierMap[numExitRoot][idx] = true
babyPubKeyDecomp, err := babyPubKey.Decompress()
if err != nil {
return nil, tracerr.Wrap(err)
}
type data struct {
BabyPubKey *babyjub.PublicKey
TokenID uint32
@ -853,7 +858,7 @@ func (c *Client) RollupWithdrawMerkleProof(babyPubKey *babyjub.PublicKey, tokenI
InstantWithdraw bool
}
tx = r.addTransaction(c.newTransaction("withdrawMerkleProof", data{
BabyPubKey: babyPubKey,
BabyPubKey: babyPubKeyDecomp,
TokenID: tokenID,
NumExitRoot: numExitRoot,
Idx: idx,

+ 1
- 1
test/ethclient_test.go

@ -158,7 +158,7 @@ func TestClientRollup(t *testing.T) {
tx := common.L1Tx{
FromIdx: 0,
FromEthAddr: keys[i].Addr,
FromBJJ: keys[i].BJJPublicKey,
FromBJJ: keys[i].BJJPublicKey.Compress(),
TokenID: common.TokenID(0),
Amount: big.NewInt(0),
DepositAmount: big.NewInt(10 + int64(i)),

+ 1
- 1
test/historydb.go

@ -130,7 +130,7 @@ func GenAccounts(totalAccounts, userAccounts int, tokens []common.Token, userAdd
TokenID: tokens[i%len(tokens)].TokenID,
EthAddr: addr,
BatchNum: batches[i%len(batches)].BatchNum,
PublicKey: pubK,
PublicKey: pubK.Compress(),
Balance: big.NewInt(int64(i * 10000000)), //nolint:gomnd
})
}

+ 1
- 1
test/l2db.go

@ -78,7 +78,7 @@ func GenAuths(nAuths int) []*common.AccountCreationAuth {
// Generate auth
auth := &common.AccountCreationAuth{
EthAddr: ethCrypto.PubkeyToAddress(ethPrivK.PublicKey),
BJJ: bjjPrivK.Public(),
BJJ: bjjPrivK.Public().Compress(),
}
// Sign
h, err := auth.HashToSign()

+ 3
- 3
test/til/lang_test.go

@ -58,7 +58,7 @@ func TestParseBlockchainTxs(t *testing.T) {
parser := newParser(strings.NewReader(s))
instructions, err := parser.parse()
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, 25, len(instructions.instructions))
assert.Equal(t, 7, len(instructions.users))
@ -92,7 +92,7 @@ func TestParsePoolTxs(t *testing.T) {
parser := newParser(strings.NewReader(s))
instructions, err := parser.parse()
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, 5, len(instructions.instructions))
assert.Equal(t, 4, len(instructions.users))
@ -151,7 +151,7 @@ func TestParseErrors(t *testing.T) {
`
parser = newParser(strings.NewReader(s))
_, err = parser.parse()
assert.Nil(t, err)
assert.NoError(t, err)
s = `
Type: Blockchain
Transfer(1) A-B: 10 (256)

+ 6
- 6
test/til/sets_test.go

@ -11,23 +11,23 @@ import (
func TestCompileSetsBase(t *testing.T) {
parser := newParser(strings.NewReader(SetBlockchain0))
_, err := parser.parse()
assert.Nil(t, err)
assert.NoError(t, err)
parser = newParser(strings.NewReader(SetPool0))
_, err = parser.parse()
assert.Nil(t, err)
assert.NoError(t, err)
tc := NewContext(common.RollupConstMaxL1UserTx)
_, err = tc.GenerateBlocks(SetBlockchain0)
assert.Nil(t, err)
assert.NoError(t, err)
_, err = tc.GeneratePoolL2Txs(SetPool0)
assert.Nil(t, err)
assert.NoError(t, err)
}
func TestCompileSetsMinimumFlow(t *testing.T) {
// minimum flow
tc := NewContext(common.RollupConstMaxL1UserTx)
_, err := tc.GenerateBlocks(SetBlockchainMinimumFlow0)
assert.Nil(t, err)
assert.NoError(t, err)
_, err = tc.GeneratePoolL2Txs(SetPoolL2MinimumFlow0)
assert.Nil(t, err)
assert.NoError(t, err)
}

+ 7
- 7
test/til/txs.go

@ -200,7 +200,7 @@ func (tc *Context) generateBlocks() ([]common.BlockData, error) {
}
tx := common.L1Tx{
FromEthAddr: tc.Users[inst.From].Addr,
FromBJJ: tc.Users[inst.From].BJJ.Public(),
FromBJJ: tc.Users[inst.From].BJJ.Public().Compress(),
TokenID: inst.TokenID,
Amount: big.NewInt(0),
DepositAmount: big.NewInt(0),
@ -220,7 +220,7 @@ func (tc *Context) generateBlocks() ([]common.BlockData, error) {
}
tx := common.L1Tx{
FromEthAddr: tc.Users[inst.From].Addr,
FromBJJ: tc.Users[inst.From].BJJ.Public(),
FromBJJ: tc.Users[inst.From].BJJ.Public().Compress(),
TokenID: inst.TokenID,
Amount: big.NewInt(0),
DepositAmount: inst.DepositAmount,
@ -498,7 +498,7 @@ func (tc *Context) addToL1UserQueue(tx L1Tx) error {
tx.L1Tx.FromIdx = tc.Users[tx.fromIdxName].Accounts[tx.L1Tx.TokenID].Idx
}
tx.L1Tx.FromEthAddr = tc.Users[tx.fromIdxName].Addr
tx.L1Tx.FromBJJ = tc.Users[tx.fromIdxName].BJJ.Public()
tx.L1Tx.FromBJJ = tc.Users[tx.fromIdxName].BJJ.Public().Compress()
if tx.toIdxName == "" {
tx.L1Tx.ToIdx = common.Idx(0)
} else {
@ -609,20 +609,20 @@ func (tc *Context) generatePoolL2Txs() ([]common.PoolL2Tx, error) {
State: common.PoolL2TxStatePending,
Timestamp: time.Now(),
RqToEthAddr: common.EmptyAddr,
RqToBJJ: nil,
RqToBJJ: common.EmptyBJJComp,
Type: inst.Typ,
}
if tx.Type == common.TxTypeTransfer {
tx.ToIdx = tc.Users[inst.To].Accounts[inst.TokenID].Idx
tx.ToEthAddr = tc.Users[inst.To].Addr
tx.ToBJJ = tc.Users[inst.To].BJJ.Public()
tx.ToBJJ = tc.Users[inst.To].BJJ.Public().Compress()
} else if tx.Type == common.TxTypeTransferToEthAddr {
tx.ToIdx = common.Idx(0)
tx.ToEthAddr = tc.Users[inst.To].Addr
} else if tx.Type == common.TxTypeTransferToBJJ {
tx.ToIdx = common.Idx(0)
tx.ToEthAddr = common.FFAddr
tx.ToBJJ = tc.Users[inst.To].BJJ.Public()
tx.ToBJJ = tc.Users[inst.To].BJJ.Public().Compress()
}
nTx, err := common.NewPoolL2Tx(&tx)
if err != nil {
@ -844,7 +844,7 @@ func (tc *Context) FillBlocksExtra(blocks []common.BlockData, cfg *ConfigExtra)
Idx: common.Idx(tc.extra.idx),
TokenID: tx.TokenID,
BatchNum: batch.Batch.BatchNum,
PublicKey: user.BJJ.Public(),
PublicKey: user.BJJ.Public().Compress(),
EthAddr: user.Addr,
Nonce: 0,
Balance: big.NewInt(0),

+ 17
- 18
test/til/txs_test.go

@ -22,7 +22,7 @@ func TestGenerateBlocksNoBatches(t *testing.T) {
`
tc := NewContext(common.RollupConstMaxL1UserTx)
blocks, err := tc.GenerateBlocks(set)
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, 1, len(blocks))
assert.Equal(t, 0, len(blocks[0].Rollup.Batches))
assert.Equal(t, 2, len(blocks[0].Rollup.AddedTokens))
@ -89,7 +89,7 @@ func TestGenerateBlocks(t *testing.T) {
`
tc := NewContext(common.RollupConstMaxL1UserTx)
blocks, err := tc.GenerateBlocks(set)
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, 2, len(blocks))
assert.Equal(t, 5, len(blocks[0].Rollup.Batches))
assert.Equal(t, 1, len(blocks[1].Rollup.Batches))
@ -147,7 +147,7 @@ func (tc *Context) checkL1TxParams(t *testing.T, tx common.L1Tx, typ common.TxTy
assert.Equal(t, tc.Users[from].Accounts[tokenID].Idx, tx.FromIdx)
}
assert.Equal(t, tc.Users[from].Addr.Hex(), tx.FromEthAddr.Hex())
assert.Equal(t, tc.Users[from].BJJ.Public(), tx.FromBJJ)
assert.Equal(t, tc.Users[from].BJJ.Public().Compress(), tx.FromBJJ)
if tx.ToIdx != common.Idx(0) {
assert.Equal(t, tc.Users[to].Accounts[tokenID].Idx, tx.ToIdx)
}
@ -193,7 +193,7 @@ func TestGeneratePoolL2Txs(t *testing.T) {
`
tc := NewContext(common.RollupConstMaxL1UserTx)
_, err := tc.GenerateBlocks(set)
require.Nil(t, err)
require.NoError(t, err)
set = `
Type: PoolL2
PoolTransfer(1) A-B: 6 (1)
@ -209,7 +209,7 @@ func TestGeneratePoolL2Txs(t *testing.T) {
PoolTransferToBJJ(1) A-B: 1 (1)
`
poolL2Txs, err := tc.GeneratePoolL2Txs(set)
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, 11, len(poolL2Txs))
assert.Equal(t, common.TxTypeTransfer, poolL2Txs[0].Type)
assert.Equal(t, common.TxTypeExit, poolL2Txs[8].Type)
@ -223,7 +223,7 @@ func TestGeneratePoolL2Txs(t *testing.T) {
assert.Equal(t, common.Nonce(3), poolL2Txs[8].Nonce)
assert.Equal(t, tc.Users["B"].Addr.Hex(), poolL2Txs[9].ToEthAddr.Hex())
assert.Nil(t, poolL2Txs[9].ToBJJ)
assert.Equal(t, common.EmptyBJJComp, poolL2Txs[9].ToBJJ)
assert.Equal(t, common.TxTypeTransferToEthAddr, poolL2Txs[9].Type)
assert.Equal(t, common.FFAddr, poolL2Txs[10].ToEthAddr)
assert.Equal(t, tc.Users["B"].BJJ.Public().String(), poolL2Txs[10].ToBJJ.String())
@ -237,7 +237,7 @@ func TestGeneratePoolL2Txs(t *testing.T) {
PoolTransfer(1) A-C: 3 (1)
`
poolL2Txs, err = tc.GeneratePoolL2Txs(set)
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, common.Nonce(6), poolL2Txs[0].Nonce)
assert.Equal(t, common.Nonce(2), poolL2Txs[1].Nonce)
assert.Equal(t, common.Nonce(7), poolL2Txs[2].Nonce)
@ -253,14 +253,14 @@ func TestGeneratePoolL2Txs(t *testing.T) {
`
tc = NewContext(common.RollupConstMaxL1UserTx)
_, err = tc.GenerateBlocks(set)
require.Nil(t, err)
require.NoError(t, err)
set = `
Type: PoolL2
PoolTransferToEthAddr(1) A-B: 3 (1)
PoolTransferToBJJ(1) A-C: 3 (1)
`
_, err = tc.GeneratePoolL2Txs(set)
require.Nil(t, err)
require.NoError(t, err)
// expect error, as FromIdx=B is still not created for TokenID=1
set = `
Type: PoolL2
@ -284,7 +284,7 @@ func TestGeneratePoolL2TxsFromInstructions(t *testing.T) {
`
tc := NewContext(common.RollupConstMaxL1UserTx)
_, err := tc.GenerateBlocks(set)
require.Nil(t, err)
require.NoError(t, err)
// Generate Pool txs using instructions
instructionSet := []Instruction{}
@ -312,18 +312,18 @@ func TestGeneratePoolL2TxsFromInstructions(t *testing.T) {
Fee: 1,
})
txsFromInstructions, err := tc.GeneratePoolL2TxsFromInstructions(instructionSet)
require.Nil(t, err)
require.NoError(t, err)
// Generate Pool txs using string
tc = NewContext(common.RollupConstMaxL1UserTx)
_, err = tc.GenerateBlocks(set)
require.Nil(t, err)
require.NoError(t, err)
stringSet := `
Type: PoolL2
PoolTransferToEthAddr(1) B-A: 3 (1)
PoolTransferToBJJ(1) B-A: 3 (1)
`
txsFromString, err := tc.GeneratePoolL2Txs(stringSet)
require.Nil(t, err)
require.NoError(t, err)
// Compare generated txs from instructions and string
// timestamps will be different
for i := 0; i < len(txsFromString); i++ {
@ -396,7 +396,7 @@ func TestGenerateErrors(t *testing.T) {
`
tc = NewContext(common.RollupConstMaxL1UserTx)
_, err = tc.GenerateBlocks(set)
require.Nil(t, err)
require.NoError(t, err)
// check nonces
set = `
@ -414,7 +414,7 @@ func TestGenerateErrors(t *testing.T) {
`
tc = NewContext(common.RollupConstMaxL1UserTx)
_, err = tc.GenerateBlocks(set)
require.Nil(t, err)
require.NoError(t, err)
assert.Equal(t, common.Nonce(3), tc.Users["A"].Accounts[common.TokenID(1)].Nonce)
assert.Equal(t, common.Idx(256), tc.Users["A"].Accounts[common.TokenID(1)].Idx)
assert.Equal(t, common.Nonce(1), tc.Users["B"].Accounts[common.TokenID(1)].Nonce)
@ -520,8 +520,7 @@ func TestGenerateFromInstructions(t *testing.T) {
tc := NewContext(common.RollupConstMaxL1UserTx)
blockFromInstructions, err := tc.GenerateBlocksFromInstructions(setInst)
assert.NoError(t, err)
require.Nil(t, err)
require.NoError(t, err)
// Generate block from string
setString := `
@ -540,7 +539,7 @@ func TestGenerateFromInstructions(t *testing.T) {
`
tc = NewContext(common.RollupConstMaxL1UserTx)
blockFromString, err := tc.GenerateBlocks(setString)
require.Nil(t, err)
require.NoError(t, err)
// Generated data should be equivalent, except for Eth Addrs and BJJs
for i, strBatch := range blockFromString[0].Rollup.Batches {

+ 4
- 4
txselector/txselector.go

@ -267,7 +267,7 @@ func (txsel *TxSelector) processTxToEthAddrBJJ(validTxs txs, l1CoordinatorTxs []
!bytes.Equal(l2Tx.ToEthAddr.Bytes(), common.FFAddr.Bytes()) {
// case: ToEthAddr != 0x00 neither 0xff
var accAuth *common.AccountCreationAuth
if l2Tx.ToBJJ != nil {
if l2Tx.ToBJJ != common.EmptyBJJComp {
// case: ToBJJ!=0:
// if idx exist for EthAddr&BJJ use it
_, err := txsel.localAccountsDB.GetIdxByEthAddrBJJ(l2Tx.ToEthAddr,
@ -326,7 +326,7 @@ func (txsel *TxSelector) processTxToEthAddrBJJ(validTxs txs, l1CoordinatorTxs []
}
positionL1++
l1CoordinatorTxs = append(l1CoordinatorTxs, l1CoordinatorTx)
} else if bytes.Equal(l2Tx.ToEthAddr.Bytes(), common.FFAddr.Bytes()) && l2Tx.ToBJJ != nil {
} else if bytes.Equal(l2Tx.ToEthAddr.Bytes(), common.FFAddr.Bytes()) && l2Tx.ToBJJ != common.EmptyBJJComp {
// if idx exist for EthAddr&BJJ use it
_, err := txsel.localAccountsDB.GetIdxByEthAddrBJJ(l2Tx.ToEthAddr, l2Tx.ToBJJ,
l2Tx.TokenID)
@ -358,10 +358,10 @@ func (txsel *TxSelector) processTxToEthAddrBJJ(validTxs txs, l1CoordinatorTxs []
}
func checkAlreadyPendingToCreate(l1CoordinatorTxs []common.L1Tx,
addr ethCommon.Address, bjj *babyjub.PublicKey) bool {
addr ethCommon.Address, bjj babyjub.PublicKeyComp) bool {
for i := 0; i < len(l1CoordinatorTxs); i++ {
if bytes.Equal(l1CoordinatorTxs[i].FromEthAddr.Bytes(), addr.Bytes()) {
if bjj == nil {
if bjj == common.EmptyBJJComp {
return true
}
if l1CoordinatorTxs[i].FromBJJ == bjj {

+ 4
- 4
txselector/txselector_test.go

@ -28,13 +28,13 @@ func initTest(t *testing.T, testSet string) *TxSelector {
dir, err := ioutil.TempDir("", "tmpdb")
require.NoError(t, err)
defer assert.Nil(t, os.RemoveAll(dir))
defer assert.NoError(t, os.RemoveAll(dir))
sdb, err := statedb.NewStateDB(dir, statedb.TypeTxSelector, 0)
require.NoError(t, err)
txselDir, err := ioutil.TempDir("", "tmpTxSelDB")
require.NoError(t, err)
defer assert.Nil(t, os.RemoveAll(dir))
defer assert.NoError(t, os.RemoveAll(dir))
coordAccount := &CoordAccount{ // TODO TMP
Addr: ethCommon.HexToAddress("0xc58d29fA6e86E4FAe04DDcEd660d45BCf3Cb2370"),
@ -89,7 +89,7 @@ func TestGetL2TxSelection(t *testing.T) {
blocks, err := tc.GenerateBlocks(til.SetBlockchain0)
assert.NoError(t, err)
// poolL2Txs, err := tc.GeneratePoolL2Txs(til.SetPool0)
// assert.Nil(t, err)
// assert.NoError(t, err)
coordIdxs := make(map[common.TokenID]common.Idx)
coordIdxs[common.TokenID(0)] = common.Idx(256)
@ -155,7 +155,7 @@ func TestGetL2TxSelection(t *testing.T) {
addL2Txs(t, txsel, common.L2TxsToPoolL2Txs(blocks[0].Batches[2].L2Txs))
_, l2Txs, err = txsel.GetL2TxSelection(coordIdxs, 0)
assert.Nil(t, err)
assert.NoError(t, err)
for _, tx := range l2Txs {
fmt.Println(tx.FromIdx, tx.ToIdx, tx.AbsoluteFee)
}

Loading…
Cancel
Save