tendermint/state/state.go

485 lines
14 KiB
Go
Raw Normal View History

package state
import (
"bytes"
2015-05-22 13:53:10 -07:00
"io"
"io/ioutil"
"time"
2015-07-19 09:40:55 -07:00
acm "github.com/tendermint/tendermint/account"
. "github.com/tendermint/go-common"
dbm "github.com/tendermint/go-db"
2015-04-13 18:26:41 -07:00
"github.com/tendermint/tendermint/events"
"github.com/tendermint/go-merkle"
ptypes "github.com/tendermint/tendermint/permission/types"
. "github.com/tendermint/tendermint/state/types"
2015-04-01 17:30:16 -07:00
"github.com/tendermint/tendermint/types"
"github.com/tendermint/go-wire"
)
var (
stateKey = []byte("stateKey")
minBondAmount = int64(1) // TODO adjust
defaultAccountsCacheCapacity = 1000 // TODO adjust
unbondingPeriodBlocks = int(60 * 24 * 365) // TODO probably better to make it time based.
validatorTimeoutBlocks = int(10) // TODO adjust
)
2014-10-06 21:28:49 -07:00
//-----------------------------------------------------------------------------
2014-10-07 01:05:54 -07:00
// NOTE: not goroutine-safe.
type State struct {
DB dbm.DB
ChainID string
LastBlockHeight int
LastBlockHash []byte
LastBlockParts types.PartSetHeader
LastBlockTime time.Time
BondedValidators *types.ValidatorSet
LastBondedValidators *types.ValidatorSet
UnbondingValidators *types.ValidatorSet
accounts merkle.Tree // Shouldn't be accessed directly.
validatorInfos merkle.Tree // Shouldn't be accessed directly.
2015-05-22 13:53:10 -07:00
nameReg merkle.Tree // Shouldn't be accessed directly.
2015-04-13 18:26:41 -07:00
2015-04-15 23:40:27 -07:00
evc events.Fireable // typically an events.EventCache
}
func LoadState(db dbm.DB) *State {
2014-10-07 01:05:54 -07:00
s := &State{DB: db}
buf := db.Get(stateKey)
if len(buf) == 0 {
2014-10-03 17:59:54 -07:00
return nil
} else {
r, n, err := bytes.NewReader(buf), new(int64), new(error)
2015-07-25 15:45:45 -07:00
s.ChainID = wire.ReadString(r, n, err)
s.LastBlockHeight = wire.ReadVarint(r, n, err)
s.LastBlockHash = wire.ReadByteSlice(r, n, err)
s.LastBlockParts = wire.ReadBinary(types.PartSetHeader{}, r, n, err).(types.PartSetHeader)
s.LastBlockTime = wire.ReadTime(r, n, err)
s.BondedValidators = wire.ReadBinary(&types.ValidatorSet{}, r, n, err).(*types.ValidatorSet)
s.LastBondedValidators = wire.ReadBinary(&types.ValidatorSet{}, r, n, err).(*types.ValidatorSet)
s.UnbondingValidators = wire.ReadBinary(&types.ValidatorSet{}, r, n, err).(*types.ValidatorSet)
2015-07-25 15:45:45 -07:00
accountsHash := wire.ReadByteSlice(r, n, err)
s.accounts = merkle.NewIAVLTree(wire.BasicCodec, acm.AccountCodec, defaultAccountsCacheCapacity, db)
s.accounts.Load(accountsHash)
2015-07-25 15:45:45 -07:00
validatorInfosHash := wire.ReadByteSlice(r, n, err)
s.validatorInfos = merkle.NewIAVLTree(wire.BasicCodec, types.ValidatorInfoCodec, 0, db)
s.validatorInfos.Load(validatorInfosHash)
2015-07-25 15:45:45 -07:00
nameRegHash := wire.ReadByteSlice(r, n, err)
s.nameReg = merkle.NewIAVLTree(wire.BasicCodec, NameRegCodec, 0, db)
2015-05-22 13:53:10 -07:00
s.nameReg.Load(nameRegHash)
if *err != nil {
2015-06-16 21:16:58 -07:00
// DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED
Exit(Fmt("Data has been corrupted or its spec has changed: %v\n", *err))
}
2014-10-11 21:27:58 -07:00
// TODO: ensure that buf is completely read.
}
return s
}
func (s *State) Save() {
s.accounts.Save()
2014-12-17 01:37:13 -08:00
s.validatorInfos.Save()
2015-05-22 13:53:10 -07:00
s.nameReg.Save()
buf, n, err := new(bytes.Buffer), new(int64), new(error)
2015-07-25 15:45:45 -07:00
wire.WriteString(s.ChainID, buf, n, err)
wire.WriteVarint(s.LastBlockHeight, buf, n, err)
wire.WriteByteSlice(s.LastBlockHash, buf, n, err)
wire.WriteBinary(s.LastBlockParts, buf, n, err)
wire.WriteTime(s.LastBlockTime, buf, n, err)
wire.WriteBinary(s.BondedValidators, buf, n, err)
wire.WriteBinary(s.LastBondedValidators, buf, n, err)
wire.WriteBinary(s.UnbondingValidators, buf, n, err)
wire.WriteByteSlice(s.accounts.Hash(), buf, n, err)
wire.WriteByteSlice(s.validatorInfos.Hash(), buf, n, err)
wire.WriteByteSlice(s.nameReg.Hash(), buf, n, err)
if *err != nil {
2015-07-19 16:42:52 -07:00
PanicCrisis(*err)
}
2014-10-07 01:05:54 -07:00
s.DB.Set(stateKey, buf.Bytes())
}
// CONTRACT:
// Copy() is a cheap way to take a snapshot,
// as if State were copied by value.
func (s *State) Copy() *State {
return &State{
DB: s.DB,
ChainID: s.ChainID,
LastBlockHeight: s.LastBlockHeight,
LastBlockHash: s.LastBlockHash,
LastBlockParts: s.LastBlockParts,
LastBlockTime: s.LastBlockTime,
2015-03-20 05:47:52 -07:00
BondedValidators: s.BondedValidators.Copy(), // TODO remove need for Copy() here.
LastBondedValidators: s.LastBondedValidators.Copy(), // That is, make updates to the validator set
UnbondingValidators: s.UnbondingValidators.Copy(), // copy the valSet lazily.
accounts: s.accounts.Copy(),
validatorInfos: s.validatorInfos.Copy(),
2015-05-22 13:53:10 -07:00
nameReg: s.nameReg.Copy(),
2015-04-17 13:18:50 -07:00
evc: nil,
}
}
// Returns a hash that represents the state data, excluding Last*
func (s *State) Hash() []byte {
2015-08-07 10:43:24 -07:00
return merkle.SimpleHashFromMap(map[string]interface{}{
"BondedValidators": s.BondedValidators,
"UnbondingValidators": s.UnbondingValidators,
"Accounts": s.accounts,
"ValidatorInfos": s.validatorInfos,
"NameRegistry": s.nameReg,
})
}
// Mutates the block in place and updates it with new state hash.
2015-06-05 14:15:40 -07:00
func (s *State) ComputeBlockStateHash(block *types.Block) error {
sCopy := s.Copy()
2015-04-15 23:40:27 -07:00
// sCopy has no event cache in it, so this won't fire events
err := execBlock(sCopy, block, types.PartSetHeader{})
if err != nil {
return err
2015-03-18 01:27:16 -07:00
}
// Set block.StateHash
block.StateHash = sCopy.Hash()
2015-03-18 01:27:16 -07:00
return nil
}
2015-06-19 08:36:20 -07:00
func (s *State) SetDB(db dbm.DB) {
s.DB = db
}
//-------------------------------------
// State.params
func (s *State) GetGasLimit() int64 {
return 1000000 // TODO
}
// State.params
//-------------------------------------
// State.accounts
2015-06-16 21:16:58 -07:00
// Returns nil if account does not exist with given address.
// The returned Account is a copy, so mutating it
// has no side effects.
// Implements Statelike
2015-07-19 09:40:55 -07:00
func (s *State) GetAccount(address []byte) *acm.Account {
_, acc := s.accounts.Get(address)
if acc == nil {
return nil
}
2015-07-19 09:40:55 -07:00
return acc.(*acm.Account).Copy()
}
// The account is copied before setting, so mutating it
// afterwards has no side effects.
// Implements Statelike
2015-07-19 09:40:55 -07:00
func (s *State) UpdateAccount(account *acm.Account) bool {
return s.accounts.Set(account.Address, account.Copy())
}
// Implements Statelike
func (s *State) RemoveAccount(address []byte) bool {
_, removed := s.accounts.Remove(address)
return removed
}
// The returned Account is a copy, so mutating it
// has no side effects.
func (s *State) GetAccounts() merkle.Tree {
return s.accounts.Copy()
}
2015-06-19 08:36:20 -07:00
// Set the accounts tree
func (s *State) SetAccounts(accounts merkle.Tree) {
s.accounts = accounts
}
// State.accounts
//-------------------------------------
// State.validators
// The returned ValidatorInfo is a copy, so mutating it
// has no side effects.
func (s *State) GetValidatorInfo(address []byte) *types.ValidatorInfo {
_, valInfo := s.validatorInfos.Get(address)
if valInfo == nil {
2014-10-12 21:14:10 -07:00
return nil
}
return valInfo.(*types.ValidatorInfo).Copy()
}
// Returns false if new, true if updated.
// The valInfo is copied before setting, so mutating it
// afterwards has no side effects.
func (s *State) SetValidatorInfo(valInfo *types.ValidatorInfo) (updated bool) {
return s.validatorInfos.Set(valInfo.Address, valInfo.Copy())
2014-10-12 21:14:10 -07:00
}
2015-06-19 08:36:20 -07:00
func (s *State) GetValidatorInfos() merkle.Tree {
return s.validatorInfos.Copy()
}
func (s *State) unbondValidator(val *types.Validator) {
// Move validator to UnbondingValidators
val, removed := s.BondedValidators.Remove(val.Address)
2014-10-12 21:14:10 -07:00
if !removed {
2015-07-19 16:42:52 -07:00
PanicCrisis("Couldn't remove validator for unbonding")
2014-10-12 21:14:10 -07:00
}
val.UnbondHeight = s.LastBlockHeight + 1
2014-10-12 21:14:10 -07:00
added := s.UnbondingValidators.Add(val)
if !added {
2015-07-19 16:42:52 -07:00
PanicCrisis("Couldn't add validator for unbonding")
2014-10-12 21:14:10 -07:00
}
}
func (s *State) rebondValidator(val *types.Validator) {
// Move validator to BondingValidators
val, removed := s.UnbondingValidators.Remove(val.Address)
if !removed {
2015-07-19 16:42:52 -07:00
PanicCrisis("Couldn't remove validator for rebonding")
}
val.BondHeight = s.LastBlockHeight + 1
added := s.BondedValidators.Add(val)
if !added {
2015-07-19 16:42:52 -07:00
PanicCrisis("Couldn't add validator for rebonding")
}
}
func (s *State) releaseValidator(val *types.Validator) {
// Update validatorInfo
valInfo := s.GetValidatorInfo(val.Address)
if valInfo == nil {
2015-07-19 16:42:52 -07:00
PanicSanity("Couldn't find validatorInfo for release")
2014-10-12 21:14:10 -07:00
}
valInfo.ReleasedHeight = s.LastBlockHeight + 1
s.SetValidatorInfo(valInfo)
// Send coins back to UnbondTo outputs
2015-05-12 17:40:19 -07:00
accounts, err := getOrMakeOutputs(s, nil, valInfo.UnbondTo)
if err != nil {
2015-07-19 16:42:52 -07:00
PanicSanity("Couldn't get or make unbondTo accounts")
}
adjustByOutputs(accounts, valInfo.UnbondTo)
for _, acc := range accounts {
s.UpdateAccount(acc)
}
// Remove validator from UnbondingValidators
_, removed := s.UnbondingValidators.Remove(val.Address)
2014-10-12 21:14:10 -07:00
if !removed {
2015-07-19 16:42:52 -07:00
PanicCrisis("Couldn't remove validator for release")
}
}
func (s *State) destroyValidator(val *types.Validator) {
// Update validatorInfo
valInfo := s.GetValidatorInfo(val.Address)
if valInfo == nil {
2015-07-19 16:42:52 -07:00
PanicSanity("Couldn't find validatorInfo for release")
}
valInfo.DestroyedHeight = s.LastBlockHeight + 1
valInfo.DestroyedAmount = val.VotingPower
s.SetValidatorInfo(valInfo)
// Remove validator
_, removed := s.BondedValidators.Remove(val.Address)
if !removed {
_, removed := s.UnbondingValidators.Remove(val.Address)
if !removed {
2015-07-19 16:42:52 -07:00
PanicCrisis("Couldn't remove validator for destruction")
}
2014-10-07 23:11:04 -07:00
}
}
2015-06-19 08:36:20 -07:00
// Set the validator infos tree
func (s *State) SetValidatorInfos(validatorInfos merkle.Tree) {
s.validatorInfos = validatorInfos
}
// State.validators
//-------------------------------------
// State.storage
2015-01-11 14:27:46 -08:00
func (s *State) LoadStorage(hash []byte) (storage merkle.Tree) {
2015-07-25 15:45:45 -07:00
storage = merkle.NewIAVLTree(wire.BasicCodec, wire.BasicCodec, 1024, s.DB)
storage.Load(hash)
return storage
2014-12-17 01:37:13 -08:00
}
// State.storage
//-------------------------------------
2015-05-22 13:53:10 -07:00
// State.nameReg
func (s *State) GetNameRegEntry(name string) *types.NameRegEntry {
2015-05-22 13:53:10 -07:00
_, value := s.nameReg.Get(name)
if value == nil {
return nil
}
entry := value.(*types.NameRegEntry)
return entry.Copy()
2015-05-22 13:53:10 -07:00
}
func (s *State) UpdateNameRegEntry(entry *types.NameRegEntry) bool {
return s.nameReg.Set(entry.Name, entry)
}
func (s *State) RemoveNameRegEntry(name string) bool {
2015-05-22 13:53:10 -07:00
_, removed := s.nameReg.Remove(name)
return removed
}
func (s *State) GetNames() merkle.Tree {
return s.nameReg.Copy()
}
2015-06-19 08:36:20 -07:00
// Set the name reg tree
func (s *State) SetNameReg(nameReg merkle.Tree) {
s.nameReg = nameReg
}
2015-05-22 13:53:10 -07:00
func NameRegEncoder(o interface{}, w io.Writer, n *int64, err *error) {
2015-07-25 15:45:45 -07:00
wire.WriteBinary(o.(*types.NameRegEntry), w, n, err)
2015-05-22 13:53:10 -07:00
}
func NameRegDecoder(r io.Reader, n *int64, err *error) interface{} {
2015-07-25 15:45:45 -07:00
return wire.ReadBinary(&types.NameRegEntry{}, r, n, err)
2015-05-22 13:53:10 -07:00
}
2015-07-25 15:45:45 -07:00
var NameRegCodec = wire.Codec{
2015-05-22 13:53:10 -07:00
Encode: NameRegEncoder,
Decode: NameRegDecoder,
}
// State.nameReg
//-------------------------------------
2015-04-15 23:40:27 -07:00
// Implements events.Eventable. Typically uses events.EventCache
func (s *State) SetFireable(evc events.Fireable) {
s.evc = evc
2015-04-13 18:26:41 -07:00
}
//-----------------------------------------------------------------------------
// Genesis
2014-10-07 23:11:04 -07:00
func MakeGenesisStateFromFile(db dbm.DB, genDocFile string) (*GenesisDoc, *State) {
jsonBlob, err := ioutil.ReadFile(genDocFile)
if err != nil {
Exit(Fmt("Couldn't read GenesisDoc file: %v", err))
}
genDoc := GenesisDocFromJSON(jsonBlob)
return genDoc, MakeGenesisState(db, genDoc)
}
func MakeGenesisState(db dbm.DB, genDoc *GenesisDoc) *State {
if len(genDoc.Validators) == 0 {
Exit(Fmt("The genesis file has no validators"))
}
if genDoc.GenesisTime.IsZero() {
genDoc.GenesisTime = time.Now()
}
// Make accounts state tree
accounts := merkle.NewIAVLTree(wire.BasicCodec, acm.AccountCodec, defaultAccountsCacheCapacity, db)
for _, genAcc := range genDoc.Accounts {
perm := ptypes.ZeroAccountPermissions
if genAcc.Permissions != nil {
perm = *genAcc.Permissions
}
acc := &acm.Account{
Address: genAcc.Address,
PubKey: nil,
Sequence: 0,
Balance: genAcc.Amount,
Permissions: perm,
}
accounts.Set(acc.Address, acc)
}
// global permissions are saved as the 0 address
// so they are included in the accounts tree
globalPerms := ptypes.DefaultAccountPermissions
if genDoc.Params != nil && genDoc.Params.GlobalPermissions != nil {
globalPerms = *genDoc.Params.GlobalPermissions
// XXX: make sure the set bits are all true
// Without it the HasPermission() functions will fail
globalPerms.Base.SetBit = ptypes.AllPermFlags
}
permsAcc := &acm.Account{
Address: ptypes.GlobalPermissionsAddress,
PubKey: nil,
Sequence: 0,
Balance: 1337,
Permissions: globalPerms,
}
accounts.Set(permsAcc.Address, permsAcc)
// Make validatorInfos state tree && validators slice
validatorInfos := merkle.NewIAVLTree(wire.BasicCodec, types.ValidatorInfoCodec, 0, db)
validators := make([]*types.Validator, len(genDoc.Validators))
for i, val := range genDoc.Validators {
pubKey := val.PubKey
address := pubKey.Address()
// Make ValidatorInfo
valInfo := &types.ValidatorInfo{
Address: address,
PubKey: pubKey,
UnbondTo: make([]*types.TxOutput, len(val.UnbondTo)),
FirstBondHeight: 0,
FirstBondAmount: val.Amount,
}
for i, unbondTo := range val.UnbondTo {
valInfo.UnbondTo[i] = &types.TxOutput{
Address: unbondTo.Address,
Amount: unbondTo.Amount,
}
}
validatorInfos.Set(address, valInfo)
// Make validator
validators[i] = &types.Validator{
Address: address,
PubKey: pubKey,
VotingPower: val.Amount,
}
}
// Make namereg tree
nameReg := merkle.NewIAVLTree(wire.BasicCodec, NameRegCodec, 0, db)
// TODO: add names, contracts to genesis.json
// IAVLTrees must be persisted before copy operations.
accounts.Save()
validatorInfos.Save()
nameReg.Save()
return &State{
DB: db,
ChainID: genDoc.ChainID,
LastBlockHeight: 0,
LastBlockHash: nil,
LastBlockParts: types.PartSetHeader{},
LastBlockTime: genDoc.GenesisTime,
BondedValidators: types.NewValidatorSet(validators),
LastBondedValidators: types.NewValidatorSet(nil),
UnbondingValidators: types.NewValidatorSet(nil),
accounts: accounts,
validatorInfos: validatorInfos,
nameReg: nameReg,
}
}
func RandGenesisState(numAccounts int, randBalance bool, minBalance int64, numValidators int, randBonded bool, minBonded int64) (*State, []*acm.PrivAccount, []*types.PrivValidator) {
db := dbm.NewMemDB()
genDoc, privAccounts, privValidators := RandGenesisDoc(numAccounts, randBalance, minBalance, numValidators, randBonded, minBonded)
s0 := MakeGenesisState(db, genDoc)
s0.Save()
return s0, privAccounts, privValidators
}