tendermint/abci/example/kvstore/persistent_kvstore.go

238 lines
6.9 KiB
Go
Raw Permalink Normal View History

2018-02-19 20:34:51 +00:00
package kvstore
2016-08-24 01:42:57 -04:00
import (
"bytes"
"encoding/base64"
"fmt"
2016-11-21 23:42:42 -05:00
"strconv"
"strings"
2016-08-24 01:42:57 -04:00
2018-06-22 06:59:02 +02:00
"github.com/tendermint/tendermint/abci/example/code"
"github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/crypto/ed25519"
2018-07-01 22:36:49 -04:00
"github.com/tendermint/tendermint/libs/log"
tmtypes "github.com/tendermint/tendermint/types"
dbm "github.com/tendermint/tm-db"
2016-08-24 01:42:57 -04:00
)
2016-11-21 23:42:42 -05:00
const (
ValidatorSetChangePrefix string = "val:"
)
2016-08-24 01:42:57 -04:00
//-----------------------------------------
2018-02-19 20:34:51 +00:00
var _ types.Application = (*PersistentKVStoreApplication)(nil)
2018-02-19 20:34:51 +00:00
type PersistentKVStoreApplication struct {
app *KVStoreApplication
2016-09-09 23:01:53 -04:00
2016-11-21 23:42:42 -05:00
// validator set
ValUpdates []types.ValidatorUpdate
2017-04-28 00:37:18 +04:00
valAddrToPubKeyMap map[string]types.PubKey
2017-04-28 00:37:18 +04:00
logger log.Logger
2016-08-24 01:42:57 -04:00
}
2018-02-19 20:34:51 +00:00
func NewPersistentKVStoreApplication(dbDir string) *PersistentKVStoreApplication {
name := "kvstore"
2017-10-18 12:46:51 +02:00
db, err := dbm.NewGoLevelDB(name, dbDir)
if err != nil {
panic(err)
}
2016-08-24 01:42:57 -04:00
state := loadState(db)
2016-08-24 01:42:57 -04:00
2018-02-19 20:34:51 +00:00
return &PersistentKVStoreApplication{
app: &KVStoreApplication{state: state},
valAddrToPubKeyMap: make(map[string]types.PubKey),
logger: log.NewNopLogger(),
2016-08-24 01:42:57 -04:00
}
}
2018-02-19 20:34:51 +00:00
func (app *PersistentKVStoreApplication) SetLogger(l log.Logger) {
2017-04-28 00:37:18 +04:00
app.logger = l
}
func (app *PersistentKVStoreApplication) Info(req types.RequestInfo) types.ResponseInfo {
res := app.app.Info(req)
res.LastBlockHeight = app.app.state.Height
res.LastBlockAppHash = app.app.state.AppHash
return res
2016-08-24 01:42:57 -04:00
}
func (app *PersistentKVStoreApplication) SetOption(req types.RequestSetOption) types.ResponseSetOption {
return app.app.SetOption(req)
2016-08-24 01:42:57 -04:00
}
// tx is either "val:pubkey!power" or "key=value" or just arbitrary bytes
func (app *PersistentKVStoreApplication) DeliverTx(req types.RequestDeliverTx) types.ResponseDeliverTx {
2016-11-21 23:42:42 -05:00
// if it starts with "val:", update the validator set
// format is "val:pubkey!power"
if isValidatorTx(req.Tx) {
2016-11-21 23:42:42 -05:00
// update validators in the merkle tree
// and in app.ValUpdates
return app.execValidatorTx(req.Tx)
2016-11-21 23:42:42 -05:00
}
// otherwise, update the key-value store
return app.app.DeliverTx(req)
2016-08-24 01:42:57 -04:00
}
func (app *PersistentKVStoreApplication) CheckTx(req types.RequestCheckTx) types.ResponseCheckTx {
return app.app.CheckTx(req)
2016-08-24 01:42:57 -04:00
}
// Commit will panic if InitChain was not called
func (app *PersistentKVStoreApplication) Commit() types.ResponseCommit {
return app.app.Commit()
2016-08-24 01:42:57 -04:00
}
// When path=/val and data={validator address}, returns the validator update (types.ValidatorUpdate) varint encoded.
// For any other path, returns an associated value or nil if missing.
func (app *PersistentKVStoreApplication) Query(reqQuery types.RequestQuery) (resQuery types.ResponseQuery) {
switch reqQuery.Path {
case "/val":
key := []byte("val:" + string(reqQuery.Data))
value := app.app.state.db.Get(key)
resQuery.Key = reqQuery.Data
resQuery.Value = value
return
default:
return app.app.Query(reqQuery)
}
2016-08-24 01:42:57 -04:00
}
2016-11-21 23:42:42 -05:00
// Save the validators in the merkle tree
func (app *PersistentKVStoreApplication) InitChain(req types.RequestInitChain) types.ResponseInitChain {
for _, v := range req.Validators {
2016-11-21 23:42:42 -05:00
r := app.updateValidator(v)
if r.IsErr() {
2017-04-28 00:37:18 +04:00
app.logger.Error("Error updating validators", "r", r)
2016-11-21 23:42:42 -05:00
}
}
return types.ResponseInitChain{}
2016-08-24 01:42:57 -04:00
}
2016-11-21 23:42:42 -05:00
// Track the block hash and header information
func (app *PersistentKVStoreApplication) BeginBlock(req types.RequestBeginBlock) types.ResponseBeginBlock {
2016-11-21 23:42:42 -05:00
// reset valset changes
app.ValUpdates = make([]types.ValidatorUpdate, 0)
for _, ev := range req.ByzantineValidators {
if ev.Type == tmtypes.ABCIEvidenceTypeDuplicateVote {
// decrease voting power by 1
if ev.TotalVotingPower == 0 {
continue
}
app.updateValidator(types.ValidatorUpdate{
PubKey: app.valAddrToPubKeyMap[string(ev.Validator.Address)],
Power: ev.TotalVotingPower - 1,
})
}
}
return types.ResponseBeginBlock{}
2016-08-24 01:42:57 -04:00
}
2016-11-21 23:42:42 -05:00
// Update the validator set
func (app *PersistentKVStoreApplication) EndBlock(req types.RequestEndBlock) types.ResponseEndBlock {
return types.ResponseEndBlock{ValidatorUpdates: app.ValUpdates}
2016-08-24 01:42:57 -04:00
}
2016-11-06 02:02:08 +00:00
2016-11-21 23:42:42 -05:00
//---------------------------------------------
// update validators
func (app *PersistentKVStoreApplication) Validators() (validators []types.ValidatorUpdate) {
itr := app.app.state.db.Iterator(nil, nil)
for ; itr.Valid(); itr.Next() {
if isValidatorTx(itr.Key()) {
validator := new(types.ValidatorUpdate)
err := types.ReadMessage(bytes.NewBuffer(itr.Value()), validator)
2016-11-21 23:42:42 -05:00
if err != nil {
panic(err)
}
validators = append(validators, *validator)
2016-11-21 23:42:42 -05:00
}
}
2016-11-21 23:42:42 -05:00
return
}
func MakeValSetChangeTx(pubkey types.PubKey, power int64) []byte {
pubStr := base64.StdEncoding.EncodeToString(pubkey.Data)
return []byte(fmt.Sprintf("val:%s!%d", pubStr, power))
2016-11-21 23:42:42 -05:00
}
func isValidatorTx(tx []byte) bool {
2017-09-21 15:26:43 -04:00
return strings.HasPrefix(string(tx), ValidatorSetChangePrefix)
2016-11-21 23:42:42 -05:00
}
// format is "val:pubkey!power"
// pubkey is a base64-encoded 32-byte ed25519 key
func (app *PersistentKVStoreApplication) execValidatorTx(tx []byte) types.ResponseDeliverTx {
2016-11-21 23:42:42 -05:00
tx = tx[len(ValidatorSetChangePrefix):]
//get the pubkey and power
pubKeyAndPower := strings.Split(string(tx), "!")
2016-11-21 23:42:42 -05:00
if len(pubKeyAndPower) != 2 {
return types.ResponseDeliverTx{
2017-11-30 14:29:12 -05:00
Code: code.CodeTypeEncodingError,
Log: fmt.Sprintf("Expected 'pubkey!power'. Got %v", pubKeyAndPower)}
2016-11-21 23:42:42 -05:00
}
pubkeyS, powerS := pubKeyAndPower[0], pubKeyAndPower[1]
2018-05-23 22:20:35 -04:00
// decode the pubkey
pubkey, err := base64.StdEncoding.DecodeString(pubkeyS)
2016-11-21 23:42:42 -05:00
if err != nil {
return types.ResponseDeliverTx{
2017-11-30 14:29:12 -05:00
Code: code.CodeTypeEncodingError,
Log: fmt.Sprintf("Pubkey (%s) is invalid base64", pubkeyS)}
2016-11-21 23:42:42 -05:00
}
// decode the power
2017-12-01 00:41:07 -05:00
power, err := strconv.ParseInt(powerS, 10, 64)
2016-11-21 23:42:42 -05:00
if err != nil {
return types.ResponseDeliverTx{
2017-11-30 14:29:12 -05:00
Code: code.CodeTypeEncodingError,
Log: fmt.Sprintf("Power (%s) is not an int", powerS)}
2016-11-21 23:42:42 -05:00
}
// update
return app.updateValidator(types.Ed25519ValidatorUpdate(pubkey, power))
2016-11-21 23:42:42 -05:00
}
// add, update, or remove a validator
func (app *PersistentKVStoreApplication) updateValidator(v types.ValidatorUpdate) types.ResponseDeliverTx {
2018-05-23 22:20:35 -04:00
key := []byte("val:" + string(v.PubKey.Data))
pubkey := ed25519.PubKeyEd25519{}
copy(pubkey[:], v.PubKey.Data)
2016-11-21 23:42:42 -05:00
if v.Power == 0 {
// remove validator
if !app.app.state.db.Has(key) {
pubStr := base64.StdEncoding.EncodeToString(v.PubKey.Data)
return types.ResponseDeliverTx{
2017-11-30 14:29:12 -05:00
Code: code.CodeTypeUnauthorized,
Log: fmt.Sprintf("Cannot remove non-existent validator %s", pubStr)}
2016-11-21 23:42:42 -05:00
}
app.app.state.db.Delete(key)
delete(app.valAddrToPubKeyMap, string(pubkey.Address()))
2016-11-21 23:42:42 -05:00
} else {
// add or update validator
value := bytes.NewBuffer(make([]byte, 0))
if err := types.WriteMessage(&v, value); err != nil {
return types.ResponseDeliverTx{
2017-11-30 14:29:12 -05:00
Code: code.CodeTypeEncodingError,
Log: fmt.Sprintf("Error encoding validator: %v", err)}
2016-11-21 23:42:42 -05:00
}
app.app.state.db.Set(key, value.Bytes())
app.valAddrToPubKeyMap[string(pubkey.Address())] = v.PubKey
2016-11-21 23:42:42 -05:00
}
2017-09-21 15:26:43 -04:00
// we only update the changes array if we successfully updated the tree
app.ValUpdates = append(app.ValUpdates, v)
2016-11-21 23:42:42 -05:00
return types.ResponseDeliverTx{Code: code.CodeTypeOK}
2016-11-21 23:42:42 -05:00
}