arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
hermez-node/db/statedb/utils.go
db/statedb/utils.goRaw
  1package statedb
  2
  3import (
  4	"bytes"
  5	"fmt"
  6	"math/big"
  7
  8	ethCommon "github.com/ethereum/go-ethereum/common"
  9	"github.com/hermeznetwork/hermez-node/common"
 10	"github.com/hermeznetwork/hermez-node/log"
 11	"github.com/hermeznetwork/tracerr"
 12	"github.com/iden3/go-iden3-crypto/babyjub"
 13	"github.com/iden3/go-merkletree"
 14)
 15
 16func concatEthAddrTokenID(addr ethCommon.Address, tokenID common.TokenID) []byte {
 17	var b []byte
 18	b = append(b, addr.Bytes()...)
 19	b = append(b[:], tokenID.Bytes()[:]...)
 20	return b
 21}
 22func concatEthAddrBJJTokenID(addr ethCommon.Address, pk *babyjub.PublicKey, tokenID common.TokenID) []byte {
 23	pkComp := pk.Compress()
 24	var b []byte
 25	b = append(b, addr.Bytes()...)
 26	b = append(b[:], pkComp[:]...)
 27	b = append(b[:], tokenID.Bytes()[:]...)
 28	return b
 29}
 30
 31// setIdxByEthAddrBJJ stores the given Idx in the StateDB as follows:
 32// - key: Eth Address, value: idx
 33// - key: EthAddr & BabyJubJub PublicKey Compressed, value: idx
 34// If Idx already exist for the given EthAddr & BJJ, the remaining Idx will be
 35// always the smallest one.
 36func (s *StateDB) setIdxByEthAddrBJJ(idx common.Idx, addr ethCommon.Address, pk *babyjub.PublicKey, tokenID common.TokenID) error {
 37	oldIdx, err := s.GetIdxByEthAddrBJJ(addr, pk, tokenID)
 38	if err == nil {
 39		// EthAddr & BJJ already have an Idx
 40		// check which Idx is smaller
 41		// if new idx is smaller, store the new one
 42		// if new idx is bigger, don't store and return, as the used one will be the old
 43		if idx >= oldIdx {
 44			log.Debug("StateDB.setIdxByEthAddrBJJ: Idx not stored because there already exist a smaller Idx for the given EthAddr & BJJ")
 45			return nil
 46		}
 47	}
 48
 49	if pk == nil {
 50		return tracerr.Wrap(fmt.Errorf("BabyJubJub pk not defined"))
 51	}
 52
 53	// store idx for EthAddr & BJJ assuming that EthAddr & BJJ still don't
 54	// have an Idx stored in the DB, and if so, the already stored Idx is
 55	// bigger than the given one, so should be updated to the new one
 56	// (smaller)
 57	tx, err := s.db.NewTx()
 58	if err != nil {
 59		return tracerr.Wrap(err)
 60	}
 61	idxBytes, err := idx.Bytes()
 62	if err != nil {
 63		return tracerr.Wrap(err)
 64	}
 65	// store Addr&BJJ-idx
 66	k := concatEthAddrBJJTokenID(addr, pk, tokenID)
 67	err = tx.Put(append(PrefixKeyAddrBJJ, k...), idxBytes[:])
 68	if err != nil {
 69		return tracerr.Wrap(err)
 70	}
 71
 72	// store Addr-idx
 73	k = concatEthAddrTokenID(addr, tokenID)
 74	err = tx.Put(append(PrefixKeyAddr, k...), idxBytes[:])
 75	if err != nil {
 76		return tracerr.Wrap(err)
 77	}
 78	err = tx.Commit()
 79	if err != nil {
 80		return tracerr.Wrap(err)
 81	}
 82	return nil
 83}
 84
 85// GetIdxByEthAddr returns the smallest Idx in the StateDB for the given
 86// Ethereum Address. Will return common.Idx(0) and error in case that Idx is
 87// not found in the StateDB.
 88func (s *StateDB) GetIdxByEthAddr(addr ethCommon.Address, tokenID common.TokenID) (common.Idx, error) {
 89	k := concatEthAddrTokenID(addr, tokenID)
 90	b, err := s.db.Get(append(PrefixKeyAddr, k...))
 91	if err != nil {
 92		return common.Idx(0), tracerr.Wrap(fmt.Errorf("GetIdxByEthAddr: %s: ToEthAddr: %s, TokenID: %d", ErrToIdxNotFound, addr.Hex(), tokenID))
 93	}
 94	idx, err := common.IdxFromBytes(b)
 95	if err != nil {
 96		return common.Idx(0), tracerr.Wrap(fmt.Errorf("GetIdxByEthAddr: %s: ToEthAddr: %s, TokenID: %d", err, addr.Hex(), tokenID))
 97	}
 98	return idx, nil
 99}
100
101// GetIdxByEthAddrBJJ returns the smallest Idx in the StateDB for the given
102// Ethereum Address AND the given BabyJubJub PublicKey. If `addr` is the zero
103// address, it's ignored in the query.  If `pk` is nil, it's ignored in the
104// query.  Will return common.Idx(0) and error in case that Idx is not found in
105// the StateDB.
106func (s *StateDB) GetIdxByEthAddrBJJ(addr ethCommon.Address, pk *babyjub.PublicKey, tokenID common.TokenID) (common.Idx, error) {
107	if !bytes.Equal(addr.Bytes(), common.EmptyAddr.Bytes()) && pk == nil {
108		// ToEthAddr
109		// case ToEthAddr!=0 && ToBJJ=0
110		return s.GetIdxByEthAddr(addr, tokenID)
111	} else if !bytes.Equal(addr.Bytes(), common.EmptyAddr.Bytes()) && pk != nil {
112		// case ToEthAddr!=0 && ToBJJ!=0
113		k := concatEthAddrBJJTokenID(addr, pk, tokenID)
114		b, err := s.db.Get(append(PrefixKeyAddrBJJ, k...))
115		if err != nil {
116			return common.Idx(0), tracerr.Wrap(fmt.Errorf("GetIdxByEthAddrBJJ: %s: ToEthAddr: %s, ToBJJ: %s, TokenID: %d", ErrToIdxNotFound, addr.Hex(), pk, tokenID))
117		}
118		idx, err := common.IdxFromBytes(b)
119		if err != nil {
120			return common.Idx(0), tracerr.Wrap(fmt.Errorf("GetIdxByEthAddrBJJ: %s: ToEthAddr: %s, ToBJJ: %s, TokenID: %d", err, addr.Hex(), pk, tokenID))
121		}
122		return idx, nil
123	}
124	// rest of cases (included case ToEthAddr==0) are not possible
125	return common.Idx(0), tracerr.Wrap(fmt.Errorf("GetIdxByEthAddrBJJ: Not found, %s: ToEthAddr: %s, ToBJJ: %s, TokenID: %d", ErrGetIdxNoCase, addr.Hex(), pk, tokenID))
126}
127
128func (s *StateDB) getTokenIDsFromIdxs(idxs []common.Idx) (map[common.TokenID]common.Idx, error) {
129	m := make(map[common.TokenID]common.Idx)
130	for i := 0; i < len(idxs); i++ {
131		a, err := s.GetAccount(idxs[i])
132		if err != nil {
133			return nil, tracerr.Wrap(fmt.Errorf("getTokenIDsFromIdxs error on GetAccount with Idx==%d: %s", idxs[i], err.Error()))
134		}
135		m[a.TokenID] = idxs[i]
136	}
137	return m, nil
138}
139
140func siblingsToZKInputFormat(s []*merkletree.Hash) []*big.Int {
141	b := make([]*big.Int, len(s))
142	for i := 0; i < len(s); i++ {
143		b[i] = s[i].BigInt()
144	}
145	return b
146}
147
148// BJJCompressedTo256BigInts returns a [256]*big.Int array with the bit
149// representation of the babyjub.PublicKeyComp
150func BJJCompressedTo256BigInts(pkComp babyjub.PublicKeyComp) [256]*big.Int {
151	var r [256]*big.Int
152	b := pkComp[:]
153
154	for i := 0; i < 256; i++ {
155		if b[i/8]&(1<<(i%8)) == 0 {
156			r[i] = big.NewInt(0)
157		} else {
158			r[i] = big.NewInt(1)
159		}
160	}
161
162	return r
163}
164
165// formatAccumulatedFees returns an array of [nFeeAccounts]*big.Int containing
166// the balance of each FeeAccount, taken from the 'collectedFees' map, in the
167// order of the 'orderTokenIDs'
168func formatAccumulatedFees(collectedFees map[common.TokenID]*big.Int, orderTokenIDs []*big.Int) []*big.Int {
169	accFeeOut := make([]*big.Int, len(orderTokenIDs))
170	for i := 0; i < len(orderTokenIDs); i++ {
171		tokenID := common.TokenIDFromBigInt(orderTokenIDs[i])
172		if _, ok := collectedFees[tokenID]; ok {
173			accFeeOut[i] = collectedFees[tokenID]
174		} else {
175			accFeeOut[i] = big.NewInt(0)
176		}
177	}
178	return accFeeOut
179}