cosmos-sdk/state/merkle.go

73 lines
1.5 KiB
Go
Raw Normal View History

package state
import (
"github.com/tendermint/merkleeyes/iavl"
"github.com/tendermint/tmlibs/merkle"
)
// State represents the app states, separating the commited state (for queries)
// from the working state (for CheckTx and AppendTx)
type State struct {
2017-07-27 07:40:17 -07:00
committed *Bonsai
deliverTx *Bonsai
checkTx *Bonsai
persistent bool
}
func NewState(tree merkle.Tree, persistent bool) State {
2017-07-27 07:40:17 -07:00
base := NewBonsai(tree)
return State{
2017-07-27 07:40:17 -07:00
committed: base,
deliverTx: base.Checkpoint().(*Bonsai),
checkTx: base.Checkpoint().(*Bonsai),
persistent: persistent,
}
}
2017-07-25 21:06:12 -07:00
func (s State) Committed() *Bonsai {
2017-07-27 07:40:17 -07:00
return s.committed
}
2017-07-25 21:06:12 -07:00
func (s State) Append() *Bonsai {
2017-07-27 07:40:17 -07:00
return s.deliverTx
}
2017-07-25 21:06:12 -07:00
func (s State) Check() *Bonsai {
2017-07-27 07:40:17 -07:00
return s.checkTx
}
// Hash updates the tree
func (s *State) Hash() []byte {
return s.deliverTx.Hash()
}
// BatchSet is used for some weird magic in storing the new height
func (s *State) BatchSet(key, value []byte) {
if s.persistent {
// This is in the batch with the Save, but not in the tree
2017-07-27 07:40:17 -07:00
tree, ok := s.deliverTx.Tree.(*iavl.IAVLTree)
if ok {
tree.BatchSet(key, value)
}
}
}
// Commit save persistent nodes to the database and re-copies the trees
2017-07-27 08:17:22 -07:00
func (s *State) Commit() ([]byte, error) {
2017-07-27 07:40:17 -07:00
err := s.committed.Commit(s.deliverTx)
if err != nil {
2017-07-27 08:17:22 -07:00
return nil, err
2017-07-27 07:40:17 -07:00
}
var hash []byte
if s.persistent {
2017-07-27 07:40:17 -07:00
hash = s.committed.Tree.Save()
} else {
2017-07-27 07:40:17 -07:00
hash = s.committed.Tree.Hash()
}
2017-07-27 07:40:17 -07:00
s.deliverTx = s.committed.Checkpoint().(*Bonsai)
s.checkTx = s.committed.Checkpoint().(*Bonsai)
2017-07-27 08:17:22 -07:00
return hash, nil
}