arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
hermez-node/db/statedb/statedb.go
db/statedb/statedb.goRaw
  1package statedb
  2
  3import (
  4	"errors"
  5	"fmt"
  6	"math/big"
  7	"os"
  8	"strconv"
  9
 10	"github.com/hermeznetwork/hermez-node/common"
 11	"github.com/hermeznetwork/hermez-node/log"
 12	"github.com/iden3/go-merkletree"
 13	"github.com/iden3/go-merkletree/db"
 14	"github.com/iden3/go-merkletree/db/pebble"
 15)
 16
 17// TODO(Edu): Document here how StateDB is kept consistent
 18
 19var (
 20	// ErrStateDBWithoutMT is used when a method that requires a MerkleTree
 21	// is called in a StateDB that does not have a MerkleTree defined
 22	ErrStateDBWithoutMT = errors.New("Can not call method to use MerkleTree in a StateDB without MerkleTree")
 23
 24	// ErrAccountAlreadyExists is used when CreateAccount is called and the
 25	// Account already exists
 26	ErrAccountAlreadyExists = errors.New("Can not CreateAccount because Account already exists")
 27
 28	// ErrToIdxNotFound is used when trying to get the ToIdx from ToEthAddr
 29	// or ToEthAddr&ToBJJ
 30	ErrToIdxNotFound = errors.New("ToIdx can not be found")
 31	// ErrGetIdxNoCase is used when trying to get the Idx from EthAddr &
 32	// BJJ with not compatible combination
 33	ErrGetIdxNoCase = errors.New("Can not get Idx due unexpected combination of ethereum Address & BabyJubJub PublicKey")
 34
 35	// KeyCurrentBatch is used as key in the db to store the current BatchNum
 36	KeyCurrentBatch = []byte("k:currentbatch")
 37
 38	// PrefixKeyIdx is the key prefix for idx in the db
 39	PrefixKeyIdx = []byte("i:")
 40	// PrefixKeyAccHash is the key prefix for account hash in the db
 41	PrefixKeyAccHash = []byte("h:")
 42	// PrefixKeyMT is the key prefix for merkle tree in the db
 43	PrefixKeyMT = []byte("m:")
 44	// PrefixKeyAddr is the key prefix for address in the db
 45	PrefixKeyAddr = []byte("a:")
 46	// PrefixKeyAddrBJJ is the key prefix for address-babyjubjub in the db
 47	PrefixKeyAddrBJJ = []byte("ab:")
 48)
 49
 50const (
 51	// PathBatchNum defines the subpath of the Batch Checkpoint in the
 52	// subpath of the StateDB
 53	PathBatchNum = "/BatchNum"
 54	// PathCurrent defines the subpath of the current Batch in the subpath
 55	// of the StateDB
 56	PathCurrent = "/current"
 57	// TypeSynchronizer defines a StateDB used by the Synchronizer, that
 58	// generates the ExitTree when processing the txs
 59	TypeSynchronizer = "synchronizer"
 60	// TypeTxSelector defines a StateDB used by the TxSelector, without
 61	// computing ExitTree neither the ZKInputs
 62	TypeTxSelector = "txselector"
 63	// TypeBatchBuilder defines a StateDB used by the BatchBuilder, that
 64	// generates the ExitTree and the ZKInput when processing the txs
 65	TypeBatchBuilder = "batchbuilder"
 66)
 67
 68// TypeStateDB determines the type of StateDB
 69type TypeStateDB string
 70
 71// StateDB represents the StateDB object
 72type StateDB struct {
 73	path         string
 74	currentBatch common.BatchNum
 75	db           *pebble.PebbleStorage
 76	mt           *merkletree.MerkleTree
 77	typ          TypeStateDB
 78	// idx holds the current Idx that the BatchBuilder is using
 79	idx common.Idx
 80	zki *common.ZKInputs
 81	// i is the current transaction index in the ZKInputs generation (zki)
 82	i int
 83	// accumulatedFees contains the accumulated fees for each token (Coord
 84	// Idx) in the processed batch
 85	accumulatedFees map[common.Idx]*big.Int
 86}
 87
 88// NewStateDB creates a new StateDB, allowing to use an in-memory or in-disk
 89// storage
 90func NewStateDB(path string, typ TypeStateDB, nLevels int) (*StateDB, error) {
 91	var sto *pebble.PebbleStorage
 92	var err error
 93	sto, err = pebble.NewPebbleStorage(path+PathCurrent, false)
 94	if err != nil {
 95		return nil, err
 96	}
 97
 98	var mt *merkletree.MerkleTree = nil
 99	if typ == TypeSynchronizer || typ == TypeBatchBuilder {
100		mt, err = merkletree.NewMerkleTree(sto.WithPrefix(PrefixKeyMT), nLevels)
101		if err != nil {
102			return nil, err
103		}
104	}
105	if typ == TypeTxSelector && nLevels != 0 {
106		return nil, fmt.Errorf("invalid StateDB parameters: StateDB type==TypeStateDB can not have nLevels!=0")
107	}
108
109	sdb := &StateDB{
110		path: path,
111		db:   sto,
112		mt:   mt,
113		typ:  typ,
114	}
115
116	// load currentBatch
117	sdb.currentBatch, err = sdb.GetCurrentBatch()
118	if err != nil {
119		return nil, err
120	}
121
122	// make reset (get checkpoint) at currentBatch
123	err = sdb.reset(sdb.currentBatch, false)
124	if err != nil {
125		return nil, err
126	}
127
128	return sdb, nil
129}
130
131// DB returns the *pebble.PebbleStorage from the StateDB
132func (s *StateDB) DB() *pebble.PebbleStorage {
133	return s.db
134}
135
136// GetCurrentBatch returns the current BatchNum stored in the StateDB
137func (s *StateDB) GetCurrentBatch() (common.BatchNum, error) {
138	cbBytes, err := s.db.Get(KeyCurrentBatch)
139	if err == db.ErrNotFound {
140		return 0, nil
141	}
142	if err != nil {
143		return 0, err
144	}
145	return common.BatchNumFromBytes(cbBytes)
146}
147
148// setCurrentBatch stores the current BatchNum in the StateDB
149func (s *StateDB) setCurrentBatch() error {
150	tx, err := s.db.NewTx()
151	if err != nil {
152		return err
153	}
154	err = tx.Put(KeyCurrentBatch, s.currentBatch.Bytes())
155	if err != nil {
156		return err
157	}
158	if err := tx.Commit(); err != nil {
159		return err
160	}
161	return nil
162}
163
164// MakeCheckpoint does a checkpoint at the given batchNum in the defined path. Internally this advances & stores the current BatchNum, and then stores a Checkpoint of the current state of the StateDB.
165func (s *StateDB) MakeCheckpoint() error {
166	// advance currentBatch
167	s.currentBatch++
168	log.Debugw("Making StateDB checkpoint", "batch", s.currentBatch, "type", s.typ)
169
170	checkpointPath := s.path + PathBatchNum + strconv.Itoa(int(s.currentBatch))
171
172	err := s.setCurrentBatch()
173	if err != nil {
174		return err
175	}
176
177	// if checkpoint BatchNum already exist in disk, delete it
178	if _, err := os.Stat(checkpointPath); !os.IsNotExist(err) {
179		err := os.RemoveAll(checkpointPath)
180		if err != nil {
181			return err
182		}
183	} else if err != nil && !os.IsNotExist(err) {
184		return err
185	}
186
187	// execute Checkpoint
188	err = s.db.Pebble().Checkpoint(checkpointPath)
189	if err != nil {
190		return err
191	}
192
193	return nil
194}
195
196// DeleteCheckpoint removes if exist the checkpoint of the given batchNum
197func (s *StateDB) DeleteCheckpoint(batchNum common.BatchNum) error {
198	checkpointPath := s.path + PathBatchNum + strconv.Itoa(int(batchNum))
199
200	if _, err := os.Stat(checkpointPath); os.IsNotExist(err) {
201		return fmt.Errorf("Checkpoint with batchNum %d does not exist in DB", batchNum)
202	}
203
204	return os.RemoveAll(checkpointPath)
205}
206
207func pebbleMakeCheckpoint(source, dest string) error {
208	// Remove dest folder (if it exists) before doing the checkpoint
209	if _, err := os.Stat(dest); !os.IsNotExist(err) {
210		err := os.RemoveAll(dest)
211		if err != nil {
212			return err
213		}
214	} else if err != nil && !os.IsNotExist(err) {
215		return err
216	}
217
218	sto, err := pebble.NewPebbleStorage(source, false)
219	if err != nil {
220		return err
221	}
222	defer func() {
223		errClose := sto.Pebble().Close()
224		if errClose != nil {
225			log.Errorw("Pebble.Close", "err", errClose)
226		}
227	}()
228
229	// execute Checkpoint
230	err = sto.Pebble().Checkpoint(dest)
231	if err != nil {
232		return err
233	}
234
235	return nil
236}
237
238// Reset resets the StateDB to the checkpoint at the given batchNum. Reset
239// does not delete the checkpoints between old current and the new current,
240// those checkpoints will remain in the storage, and eventually will be
241// deleted when MakeCheckpoint overwrites them.
242func (s *StateDB) Reset(batchNum common.BatchNum) error {
243	return s.reset(batchNum, true)
244}
245
246// reset resets the StateDB to the checkpoint at the given batchNum. Reset
247// does not delete the checkpoints between old current and the new current,
248// those checkpoints will remain in the storage, and eventually will be
249// deleted when MakeCheckpoint overwrites them.  `closeCurrent` will close the
250// currently opened db before doing the reset.
251func (s *StateDB) reset(batchNum common.BatchNum, closeCurrent bool) error {
252	checkpointPath := s.path + PathBatchNum + strconv.Itoa(int(batchNum))
253	currentPath := s.path + PathCurrent
254
255	if closeCurrent {
256		if err := s.db.Pebble().Close(); err != nil {
257			return err
258		}
259	}
260	// remove 'current'
261	err := os.RemoveAll(currentPath)
262	if err != nil {
263		return err
264	}
265	if batchNum == 0 {
266		// if batchNum == 0, open the new fresh 'current'
267		sto, err := pebble.NewPebbleStorage(currentPath, false)
268		if err != nil {
269			return err
270		}
271		s.db = sto
272		s.idx = 255
273		s.currentBatch = batchNum
274		return nil
275	}
276
277	// copy 'BatchNumX' to 'current'
278	err = pebbleMakeCheckpoint(checkpointPath, currentPath)
279	if err != nil {
280		return err
281	}
282
283	// open the new 'current'
284	sto, err := pebble.NewPebbleStorage(currentPath, false)
285	if err != nil {
286		return err
287	}
288	s.db = sto
289
290	// get currentBatch num
291	s.currentBatch, err = s.GetCurrentBatch()
292	if err != nil {
293		return err
294	}
295	// idx is obtained from the statedb reset
296	s.idx, err = s.getIdx()
297	if err != nil {
298		return err
299	}
300
301	if s.mt != nil {
302		// open the MT for the current s.db
303		mt, err := merkletree.NewMerkleTree(s.db.WithPrefix(PrefixKeyMT), s.mt.MaxLevels())
304		if err != nil {
305			return err
306		}
307		s.mt = mt
308	}
309
310	return nil
311}
312
313// GetAccount returns the account for the given Idx
314func (s *StateDB) GetAccount(idx common.Idx) (*common.Account, error) {
315	return getAccountInTreeDB(s.db, idx)
316}
317
318// GetAccounts returns all the accounts in the db.  Use for debugging pruposes
319// only.
320func (s *StateDB) GetAccounts() ([]common.Account, error) {
321	idxDB := s.db.WithPrefix(PrefixKeyIdx)
322	idxs := []common.Idx{}
323	// NOTE: Current implementation of Iterate in the pebble interface is
324	// not efficient, as it iterates over all keys.  Improve it following
325	// this example: https://github.com/cockroachdb/pebble/pull/923/files
326	if err := idxDB.Iterate(func(k []byte, v []byte) (bool, error) {
327		idx, err := common.IdxFromBytes(k)
328		if err != nil {
329			return false, err
330		}
331		idxs = append(idxs, idx)
332		return true, nil
333	}); err != nil {
334		return nil, err
335	}
336	accs := []common.Account{}
337	for i := range idxs {
338		acc, err := s.GetAccount(idxs[i])
339		if err != nil {
340			return nil, err
341		}
342		accs = append(accs, *acc)
343	}
344	return accs, nil
345}
346
347// getAccountInTreeDB is abstracted from StateDB to be used from StateDB and
348// from ExitTree.  GetAccount returns the account for the given Idx
349func getAccountInTreeDB(sto db.Storage, idx common.Idx) (*common.Account, error) {
350	idxBytes, err := idx.Bytes()
351	if err != nil {
352		return nil, err
353	}
354	vBytes, err := sto.Get(append(PrefixKeyIdx, idxBytes[:]...))
355	if err != nil {
356		return nil, err
357	}
358	accBytes, err := sto.Get(append(PrefixKeyAccHash, vBytes...))
359	if err != nil {
360		return nil, err
361	}
362	var b [32 * common.NLeafElems]byte
363	copy(b[:], accBytes)
364	account, err := common.AccountFromBytes(b)
365	if err != nil {
366		return nil, err
367	}
368	account.Idx = idx
369	return account, nil
370}
371
372// CreateAccount creates a new Account in the StateDB for the given Idx.  If
373// StateDB.mt==nil, MerkleTree is not affected, otherwise updates the
374// MerkleTree, returning a CircomProcessorProof.
375func (s *StateDB) CreateAccount(idx common.Idx, account *common.Account) (*merkletree.CircomProcessorProof, error) {
376	cpp, err := createAccountInTreeDB(s.db, s.mt, idx, account)
377	if err != nil {
378		return cpp, err
379	}
380	// store idx by EthAddr & BJJ
381	err = s.setIdxByEthAddrBJJ(idx, account.EthAddr, account.PublicKey, account.TokenID)
382	return cpp, err
383}
384
385// createAccountInTreeDB is abstracted from StateDB to be used from StateDB and
386// from ExitTree.  Creates a new Account in the StateDB for the given Idx.  If
387// StateDB.mt==nil, MerkleTree is not affected, otherwise updates the
388// MerkleTree, returning a CircomProcessorProof.
389func createAccountInTreeDB(sto db.Storage, mt *merkletree.MerkleTree, idx common.Idx, account *common.Account) (*merkletree.CircomProcessorProof, error) {
390	// store at the DB the key: v, and value: leaf.Bytes()
391	v, err := account.HashValue()
392	if err != nil {
393		return nil, err
394	}
395	accountBytes, err := account.Bytes()
396	if err != nil {
397		return nil, err
398	}
399
400	// store the Leaf value
401	tx, err := sto.NewTx()
402	if err != nil {
403		return nil, err
404	}
405
406	idxBytes, err := idx.Bytes()
407	if err != nil {
408		return nil, err
409	}
410	_, err = tx.Get(append(PrefixKeyIdx, idxBytes[:]...))
411	if err != db.ErrNotFound {
412		return nil, ErrAccountAlreadyExists
413	}
414
415	err = tx.Put(append(PrefixKeyAccHash, v.Bytes()...), accountBytes[:])
416	if err != nil {
417		return nil, err
418	}
419	err = tx.Put(append(PrefixKeyIdx, idxBytes[:]...), v.Bytes())
420	if err != nil {
421		return nil, err
422	}
423
424	if err := tx.Commit(); err != nil {
425		return nil, err
426	}
427
428	if mt != nil {
429		return mt.AddAndGetCircomProof(idx.BigInt(), v)
430	}
431
432	return nil, nil
433}
434
435// UpdateAccount updates the Account in the StateDB for the given Idx.  If
436// StateDB.mt==nil, MerkleTree is not affected, otherwise updates the
437// MerkleTree, returning a CircomProcessorProof.
438func (s *StateDB) UpdateAccount(idx common.Idx, account *common.Account) (*merkletree.CircomProcessorProof, error) {
439	return updateAccountInTreeDB(s.db, s.mt, idx, account)
440}
441
442// updateAccountInTreeDB is abstracted from StateDB to be used from StateDB and
443// from ExitTree.  Updates the Account in the StateDB for the given Idx.  If
444// StateDB.mt==nil, MerkleTree is not affected, otherwise updates the
445// MerkleTree, returning a CircomProcessorProof.
446func updateAccountInTreeDB(sto db.Storage, mt *merkletree.MerkleTree, idx common.Idx, account *common.Account) (*merkletree.CircomProcessorProof, error) {
447	// store at the DB the key: v, and value: account.Bytes()
448	v, err := account.HashValue()
449	if err != nil {
450		return nil, err
451	}
452	accountBytes, err := account.Bytes()
453	if err != nil {
454		return nil, err
455	}
456
457	tx, err := sto.NewTx()
458	if err != nil {
459		return nil, err
460	}
461	err = tx.Put(append(PrefixKeyAccHash, v.Bytes()...), accountBytes[:])
462	if err != nil {
463		return nil, err
464	}
465	idxBytes, err := idx.Bytes()
466	if err != nil {
467		return nil, err
468	}
469	err = tx.Put(append(PrefixKeyIdx, idxBytes[:]...), v.Bytes())
470	if err != nil {
471		return nil, err
472	}
473
474	if err := tx.Commit(); err != nil {
475		return nil, err
476	}
477
478	if mt != nil {
479		return mt.Update(idx.BigInt(), v)
480	}
481	return nil, nil
482}
483
484// MTGetProof returns the CircomVerifierProof for a given Idx
485func (s *StateDB) MTGetProof(idx common.Idx) (*merkletree.CircomVerifierProof, error) {
486	if s.mt == nil {
487		return nil, ErrStateDBWithoutMT
488	}
489	return s.mt.GenerateCircomVerifierProof(idx.BigInt(), s.mt.Root())
490}
491
492// MTGetRoot returns the current root of the underlying Merkle Tree
493func (s *StateDB) MTGetRoot() *big.Int {
494	return s.mt.Root().BigInt()
495}
496
497// LocalStateDB represents the local StateDB which allows to make copies from
498// the synchronizer StateDB, and is used by the tx-selector and the
499// batch-builder. LocalStateDB is an in-memory storage.
500type LocalStateDB struct {
501	*StateDB
502	synchronizerStateDB *StateDB
503}
504
505// NewLocalStateDB returns a new LocalStateDB connected to the given
506// synchronizerDB
507func NewLocalStateDB(path string, synchronizerDB *StateDB, typ TypeStateDB, nLevels int) (*LocalStateDB, error) {
508	s, err := NewStateDB(path, typ, nLevels)
509	if err != nil {
510		return nil, err
511	}
512	return &LocalStateDB{
513		s,
514		synchronizerDB,
515	}, nil
516}
517
518// Reset performs a reset in the LocaStateDB. If fromSynchronizer is true, it
519// gets the state from LocalStateDB.synchronizerStateDB for the given batchNum. If fromSynchronizer is false, get the state from LocalStateDB checkpoints.
520func (l *LocalStateDB) Reset(batchNum common.BatchNum, fromSynchronizer bool) error {
521	if batchNum == 0 {
522		l.idx = 0
523		return nil
524	}
525
526	synchronizerCheckpointPath := l.synchronizerStateDB.path + PathBatchNum + strconv.Itoa(int(batchNum))
527	checkpointPath := l.path + PathBatchNum + strconv.Itoa(int(batchNum))
528	currentPath := l.path + PathCurrent
529
530	if fromSynchronizer {
531		// use checkpoint from SynchronizerStateDB
532		if _, err := os.Stat(synchronizerCheckpointPath); os.IsNotExist(err) {
533			// if synchronizerStateDB does not have checkpoint at batchNum, return err
534			return fmt.Errorf("Checkpoint not exist in Synchronizer")
535		}
536
537		if err := l.db.Pebble().Close(); err != nil {
538			return err
539		}
540		// remove 'current'
541		err := os.RemoveAll(currentPath)
542		if err != nil {
543			return err
544		}
545		// copy synchronizer'BatchNumX' to 'current'
546		err = pebbleMakeCheckpoint(synchronizerCheckpointPath, currentPath)
547		if err != nil {
548			return err
549		}
550		// copy synchronizer'BatchNumX' to 'BatchNumX'
551		err = pebbleMakeCheckpoint(synchronizerCheckpointPath, checkpointPath)
552		if err != nil {
553			return err
554		}
555
556		// open the new 'current'
557		sto, err := pebble.NewPebbleStorage(currentPath, false)
558		if err != nil {
559			return err
560		}
561		l.db = sto
562
563		// get currentBatch num
564		l.currentBatch, err = l.GetCurrentBatch()
565		if err != nil {
566			return err
567		}
568		// open the MT for the current s.db
569		mt, err := merkletree.NewMerkleTree(l.db.WithPrefix(PrefixKeyMT), l.mt.MaxLevels())
570		if err != nil {
571			return err
572		}
573		l.mt = mt
574
575		return nil
576	}
577	// use checkpoint from LocalStateDB
578	return l.StateDB.reset(batchNum, true)
579}