tendermint/state/state.go

423 lines
12 KiB
Go
Raw Normal View History

package state
import (
"bytes"
"errors"
2014-10-12 21:14:10 -07:00
"fmt"
"time"
. "github.com/tendermint/tendermint/binary"
. "github.com/tendermint/tendermint/blocks"
2014-10-12 21:14:10 -07:00
. "github.com/tendermint/tendermint/common"
2014-10-04 19:16:49 -07:00
. "github.com/tendermint/tendermint/db"
"github.com/tendermint/tendermint/merkle"
)
var (
2014-10-12 21:14:10 -07:00
ErrStateInvalidAccountId = errors.New("Error State invalid account id")
ErrStateInvalidSignature = errors.New("Error State invalid signature")
ErrStateInvalidSequenceNumber = errors.New("Error State invalid sequence number")
ErrStateInvalidAccountState = errors.New("Error State invalid account state")
ErrStateInsufficientFunds = errors.New("Error State insufficient funds")
2014-10-11 21:27:58 -07:00
stateKey = []byte("stateKey")
2014-10-12 21:14:10 -07:00
minBondAmount = uint64(1) // TODO adjust
defaultAccountDetailsCacheCapacity = 1000 // TODO adjust
unbondingPeriodBlocks = uint32(60 * 24 * 365) // TODO probably better to make it time based.
validatorTimeoutBlocks = uint32(10) // TODO adjust
)
2014-10-06 21:28:49 -07:00
//-----------------------------------------------------------------------------
2014-10-12 21:14:10 -07:00
type InvalidTxError struct {
Tx Tx
Reason error
}
func (txErr InvalidTxError) Error() string {
return fmt.Sprintf("Invalid tx: [%v] reason: [%v]", txErr.Tx, txErr.Reason)
}
//-----------------------------------------------------------------------------
2014-10-07 01:05:54 -07:00
// NOTE: not goroutine-safe.
type State struct {
2014-10-12 21:14:10 -07:00
DB DB
Height uint32 // Last known block height
BlockHash []byte // Last known block hash
CommitTime time.Time
AccountDetails merkle.Tree
BondedValidators *ValidatorSet
UnbondingValidators *ValidatorSet
}
2014-10-07 23:11:04 -07:00
func GenesisState(db DB, genesisTime time.Time, accDets []*AccountDetail) *State {
2014-10-04 19:16:49 -07:00
2014-10-06 21:28:49 -07:00
// TODO: Use "uint64Codec" instead of BasicCodec
2014-10-11 21:27:58 -07:00
accountDetails := merkle.NewIAVLTree(BasicCodec, AccountDetailCodec, defaultAccountDetailsCacheCapacity, db)
validators := []*Validator{}
2014-10-04 19:16:49 -07:00
2014-10-07 23:11:04 -07:00
for _, accDet := range accDets {
accountDetails.Set(accDet.Id, accDet)
2014-10-12 21:14:10 -07:00
if accDet.Status == AccountStatusBonded {
2014-10-11 21:27:58 -07:00
validators = append(validators, &Validator{
Account: accDet.Account,
BondHeight: 0,
VotingPower: accDet.Balance,
Accum: 0,
})
2014-10-04 19:16:49 -07:00
}
}
2014-10-11 21:27:58 -07:00
if len(validators) == 0 {
panic("Must have some validators")
}
2014-10-04 19:16:49 -07:00
return &State{
2014-10-12 21:14:10 -07:00
DB: db,
Height: 0,
BlockHash: nil,
CommitTime: genesisTime,
AccountDetails: accountDetails,
BondedValidators: NewValidatorSet(validators),
UnbondingValidators: NewValidatorSet(nil),
2014-10-04 19:16:49 -07:00
}
2014-10-03 17:59:54 -07:00
}
2014-10-04 19:16:49 -07:00
func LoadState(db 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 {
reader := bytes.NewReader(buf)
var n int64
var err error
2014-10-07 01:05:54 -07:00
s.Height = ReadUInt32(reader, &n, &err)
s.CommitTime = ReadTime(reader, &n, &err)
s.BlockHash = ReadByteSlice(reader, &n, &err)
2014-10-07 23:11:04 -07:00
accountDetailsHash := ReadByteSlice(reader, &n, &err)
2014-10-11 21:27:58 -07:00
s.AccountDetails = merkle.NewIAVLTree(BasicCodec, AccountDetailCodec, defaultAccountDetailsCacheCapacity, db)
s.AccountDetails.Load(accountDetailsHash)
2014-10-12 17:57:23 -07:00
s.BondedValidators = ReadValidatorSet(reader, &n, &err)
2014-10-12 21:14:10 -07:00
s.UnbondingValidators = ReadValidatorSet(reader, &n, &err)
if err != nil {
panic(err)
}
2014-10-11 21:27:58 -07:00
// TODO: ensure that buf is completely read.
}
return s
}
// Save this state into the db.
2014-09-11 10:55:32 -07:00
// For convenience, the commitTime (required by ConsensusAgent)
// is saved here.
func (s *State) Save(commitTime time.Time) {
2014-10-07 01:05:54 -07:00
s.CommitTime = commitTime
2014-10-11 21:27:58 -07:00
s.AccountDetails.Save()
var buf bytes.Buffer
var n int64
var err error
2014-10-07 01:05:54 -07:00
WriteUInt32(&buf, s.Height, &n, &err)
WriteTime(&buf, commitTime, &n, &err)
2014-10-07 01:05:54 -07:00
WriteByteSlice(&buf, s.BlockHash, &n, &err)
2014-10-11 21:27:58 -07:00
WriteByteSlice(&buf, s.AccountDetails.Hash(), &n, &err)
2014-10-12 17:57:23 -07:00
WriteBinary(&buf, s.BondedValidators, &n, &err)
2014-10-12 21:14:10 -07:00
WriteBinary(&buf, s.UnbondingValidators, &n, &err)
if err != nil {
panic(err)
}
2014-10-07 01:05:54 -07:00
s.DB.Set(stateKey, buf.Bytes())
}
func (s *State) Copy() *State {
return &State{
2014-10-12 21:14:10 -07:00
DB: s.DB,
Height: s.Height,
CommitTime: s.CommitTime,
BlockHash: s.BlockHash,
AccountDetails: s.AccountDetails.Copy(),
BondedValidators: s.BondedValidators.Copy(),
UnbondingValidators: s.UnbondingValidators.Copy(),
}
}
2014-09-11 22:44:59 -07:00
// If the tx is invalid, an error will be returned.
2014-10-06 21:28:49 -07:00
// Unlike AppendBlock(), state will not be altered.
func (s *State) ExecTx(tx Tx) error {
2014-10-07 23:11:04 -07:00
accDet := s.GetAccountDetail(tx.GetSignature().SignerId)
if accDet == nil {
return ErrStateInvalidAccountId
}
// Check signature
if !accDet.Verify(tx) {
return ErrStateInvalidSignature
}
// Check sequence
if tx.GetSequence() <= accDet.Sequence {
return ErrStateInvalidSequenceNumber
}
2014-10-12 21:14:10 -07:00
// Subtract fee from balance.
if accDet.Balance < tx.GetFee() {
return ErrStateInsufficientFunds
} else {
accDet.Balance -= tx.GetFee()
}
2014-10-07 23:11:04 -07:00
// Exec tx
switch tx.(type) {
case *SendTx:
stx := tx.(*SendTx)
toAccDet := s.GetAccountDetail(stx.To)
// Accounts must be nominal
2014-10-12 21:14:10 -07:00
if accDet.Status != AccountStatusNominal {
2014-10-07 23:11:04 -07:00
return ErrStateInvalidAccountState
}
2014-10-12 21:14:10 -07:00
if toAccDet.Status != AccountStatusNominal {
2014-10-07 23:11:04 -07:00
return ErrStateInvalidAccountState
}
// Check account balance
2014-10-12 21:14:10 -07:00
if accDet.Balance < stx.Amount {
2014-10-07 23:11:04 -07:00
return ErrStateInsufficientFunds
}
// Check existence of destination account
if toAccDet == nil {
return ErrStateInvalidAccountId
}
2014-10-07 23:11:04 -07:00
// Good!
2014-10-12 21:14:10 -07:00
accDet.Balance -= stx.Amount
toAccDet.Balance += stx.Amount
2014-10-07 23:11:04 -07:00
s.SetAccountDetail(accDet)
s.SetAccountDetail(toAccDet)
2014-10-12 21:14:10 -07:00
return nil
2014-10-07 23:11:04 -07:00
//case *NameTx
case *BondTx:
2014-10-12 21:14:10 -07:00
//btx := tx.(*BondTx)
2014-10-07 23:11:04 -07:00
// Account must be nominal
2014-10-12 21:14:10 -07:00
if accDet.Status != AccountStatusNominal {
2014-10-07 23:11:04 -07:00
return ErrStateInvalidAccountState
}
// Check account balance
if accDet.Balance < minBondAmount {
return ErrStateInsufficientFunds
}
// Good!
2014-10-12 21:14:10 -07:00
accDet.Status = AccountStatusBonded
2014-10-07 23:11:04 -07:00
s.SetAccountDetail(accDet)
2014-10-12 21:14:10 -07:00
added := s.BondedValidators.Add(&Validator{
2014-10-12 17:57:23 -07:00
Account: accDet.Account,
BondHeight: s.Height,
VotingPower: accDet.Balance,
Accum: 0,
})
if !added {
panic("Failed to add validator")
}
2014-10-12 21:14:10 -07:00
return nil
2014-10-07 23:11:04 -07:00
case *UnbondTx:
2014-10-12 21:14:10 -07:00
//utx := tx.(*UnbondTx)
2014-10-12 17:57:23 -07:00
// Account must be bonded.
2014-10-12 21:14:10 -07:00
if accDet.Status != AccountStatusBonded {
2014-10-12 17:57:23 -07:00
return ErrStateInvalidAccountState
}
// Good!
2014-10-12 21:14:10 -07:00
s.unbondValidator(accDet.Id, accDet)
2014-10-12 17:57:23 -07:00
s.SetAccountDetail(accDet)
2014-10-12 21:14:10 -07:00
return nil
case *DupeoutTx:
{
// NOTE: accDet is the one who created this transaction.
// Subtract any fees, save, and forget.
s.SetAccountDetail(accDet)
accDet = nil
2014-10-12 17:57:23 -07:00
}
2014-10-12 21:14:10 -07:00
dtx := tx.(*DupeoutTx)
// Verify the signatures
if dtx.VoteA.SignerId != dtx.VoteB.SignerId {
return ErrStateInvalidSignature
2014-10-12 17:57:23 -07:00
}
2014-10-12 21:14:10 -07:00
accused := s.GetAccountDetail(dtx.VoteA.SignerId)
if !accused.Verify(&dtx.VoteA) || !accused.Verify(&dtx.VoteB) {
return ErrStateInvalidSignature
}
// Verify equivocation
if dtx.VoteA.Height != dtx.VoteB.Height {
return errors.New("DupeoutTx height must be the same.")
}
if dtx.VoteA.Type == VoteTypeCommit && dtx.VoteA.Round < dtx.VoteB.Round {
// Check special case.
// Validators should not sign another vote after committing.
} else {
if dtx.VoteA.Round != dtx.VoteB.Round {
return errors.New("DupeoutTx rounds don't match")
}
if dtx.VoteA.Type != dtx.VoteB.Type {
return errors.New("DupeoutTx types don't match")
}
if bytes.Equal(dtx.VoteA.BlockHash, dtx.VoteB.BlockHash) {
return errors.New("DupeoutTx blockhash shouldn't match")
}
}
// Good! (Bad validator!)
if accused.Status == AccountStatusBonded {
_, removed := s.BondedValidators.Remove(accused.Id)
if !removed {
panic("Failed to remove accused validator")
}
} else if accused.Status == AccountStatusUnbonding {
_, removed := s.UnbondingValidators.Remove(accused.Id)
if !removed {
panic("Failed to remove accused validator")
}
} else {
panic("Couldn't find accused validator")
}
accused.Status = AccountStatusDupedOut
updated := s.SetAccountDetail(accused)
if !updated {
panic("Failed to update accused validator account")
}
return nil
default:
panic("Unknown Tx type")
}
}
// accDet optional
func (s *State) unbondValidator(accountId uint64, accDet *AccountDetail) {
if accDet == nil {
accDet = s.GetAccountDetail(accountId)
}
accDet.Status = AccountStatusUnbonding
s.SetAccountDetail(accDet)
val, removed := s.BondedValidators.Remove(accDet.Id)
if !removed {
panic("Failed to remove validator")
}
val.UnbondHeight = s.Height
added := s.UnbondingValidators.Add(val)
if !added {
panic("Failed to add validator")
}
}
func (s *State) releaseValidator(accountId uint64) {
accDet := s.GetAccountDetail(accountId)
if accDet.Status != AccountStatusUnbonding {
panic("Cannot release validator")
}
accDet.Status = AccountStatusNominal
// TODO: move balance to designated address, UnbondTo.
s.SetAccountDetail(accDet)
_, removed := s.UnbondingValidators.Remove(accountId)
if !removed {
panic("Couldn't release validator")
2014-10-07 23:11:04 -07:00
}
}
// "checkStateHash": If false, instead of checking the resulting
// state.Hash() against block.StateHash, it *sets* the block.StateHash.
// (used for constructing a new proposal)
2014-09-11 22:44:59 -07:00
// NOTE: If an error occurs during block execution, state will be left
2014-10-07 19:37:20 -07:00
// at an invalid state. Copy the state before calling AppendBlock!
func (s *State) AppendBlock(b *Block, checkStateHash bool) error {
2014-09-11 22:44:59 -07:00
// Basic block validation.
2014-10-07 01:05:54 -07:00
err := b.ValidateBasic(s.Height, s.BlockHash)
2014-09-11 22:44:59 -07:00
if err != nil {
return err
}
// Commit each tx
for _, tx := range b.Data.Txs {
2014-10-07 01:05:54 -07:00
err := s.ExecTx(tx)
2014-09-11 22:44:59 -07:00
if err != nil {
2014-10-12 21:14:10 -07:00
return InvalidTxError{tx, err}
}
}
// Update LastCommitHeight as necessary.
for _, sig := range b.Validation.Signatures {
_, val := s.BondedValidators.GetById(sig.SignerId)
if val == nil {
return ErrStateInvalidSignature
}
val.LastCommitHeight = b.Height
updated := s.BondedValidators.Update(val)
if !updated {
panic("Failed to update validator LastCommitHeight")
2014-09-11 22:44:59 -07:00
}
}
2014-10-12 17:57:23 -07:00
// If any unbonding periods are over,
// reward account with bonded coins.
2014-10-12 21:14:10 -07:00
toRelease := []*Validator{}
s.UnbondingValidators.Iterate(func(val *Validator) bool {
if val.UnbondHeight+unbondingPeriodBlocks < b.Height {
toRelease = append(toRelease, val)
}
return false
})
for _, val := range toRelease {
s.releaseValidator(val.Id)
}
2014-10-12 17:57:23 -07:00
// If any validators haven't signed in a while,
// unbond them, they have timed out.
2014-10-12 21:14:10 -07:00
toTimeout := []*Validator{}
s.BondedValidators.Iterate(func(val *Validator) bool {
if val.LastCommitHeight+validatorTimeoutBlocks < b.Height {
toTimeout = append(toTimeout, val)
}
return false
})
for _, val := range toTimeout {
s.unbondValidator(val.Id, nil)
}
2014-10-12 17:57:23 -07:00
2014-10-07 00:43:34 -07:00
// Increment validator AccumPowers
2014-10-12 17:57:23 -07:00
s.BondedValidators.IncrementAccum()
2014-10-07 00:43:34 -07:00
// Check or set block.StateHash
stateHash := s.Hash()
if checkStateHash {
// State hash should match
if !bytes.Equal(stateHash, b.StateHash) {
return Errorf("Invalid state hash. Got %X, block says %X",
stateHash, b.StateHash)
}
} else {
// Set the state hash.
if b.StateHash != nil {
panic("Cannot overwrite block.StateHash")
}
b.StateHash = stateHash
2014-10-07 00:43:34 -07:00
}
2014-10-07 01:05:54 -07:00
s.Height = b.Height
s.BlockHash = b.Hash()
return nil
}
2014-10-07 23:11:04 -07:00
func (s *State) GetAccountDetail(accountId uint64) *AccountDetail {
2014-10-11 21:27:58 -07:00
_, accDet := s.AccountDetails.Get(accountId)
2014-10-07 23:11:04 -07:00
if accDet == nil {
2014-10-06 21:28:49 -07:00
return nil
}
2014-10-07 23:11:04 -07:00
return accDet.(*AccountDetail)
}
// Returns false if new, true if updated.
func (s *State) SetAccountDetail(accDet *AccountDetail) (updated bool) {
return s.AccountDetails.Set(accDet.Id, accDet)
}
// Returns a hash that represents the state data,
// excluding Height, BlockHash, and CommitTime.
func (s *State) Hash() []byte {
hashables := []merkle.Hashable{
s.AccountDetails,
s.BondedValidators,
s.UnbondingValidators,
}
return merkle.HashFromHashables(hashables)
}