github.com/vipernet-xyz/tm@v0.34.24/abci/example/kvstore/persistent_kvstore.go (about)

     1  package kvstore
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/base64"
     6  	"fmt"
     7  	"strconv"
     8  	"strings"
     9  
    10  	dbm "github.com/tendermint/tm-db"
    11  
    12  	"github.com/vipernet-xyz/tm/abci/example/code"
    13  	"github.com/vipernet-xyz/tm/abci/types"
    14  	cryptoenc "github.com/vipernet-xyz/tm/crypto/encoding"
    15  	"github.com/vipernet-xyz/tm/libs/log"
    16  	pc "github.com/vipernet-xyz/tm/proto/tendermint/crypto"
    17  )
    18  
    19  const (
    20  	ValidatorSetChangePrefix string = "val:"
    21  )
    22  
    23  //-----------------------------------------
    24  
    25  var _ types.Application = (*PersistentKVStoreApplication)(nil)
    26  
    27  type PersistentKVStoreApplication struct {
    28  	app *Application
    29  
    30  	// validator set
    31  	ValUpdates []types.ValidatorUpdate
    32  
    33  	valAddrToPubKeyMap map[string]pc.PublicKey
    34  
    35  	logger log.Logger
    36  }
    37  
    38  func NewPersistentKVStoreApplication(dbDir string) *PersistentKVStoreApplication {
    39  	name := "kvstore"
    40  	db, err := dbm.NewGoLevelDB(name, dbDir)
    41  	if err != nil {
    42  		panic(err)
    43  	}
    44  
    45  	state := loadState(db)
    46  
    47  	return &PersistentKVStoreApplication{
    48  		app:                &Application{state: state},
    49  		valAddrToPubKeyMap: make(map[string]pc.PublicKey),
    50  		logger:             log.NewNopLogger(),
    51  	}
    52  }
    53  
    54  func (app *PersistentKVStoreApplication) SetLogger(l log.Logger) {
    55  	app.logger = l
    56  }
    57  
    58  func (app *PersistentKVStoreApplication) Info(req types.RequestInfo) types.ResponseInfo {
    59  	res := app.app.Info(req)
    60  	res.LastBlockHeight = app.app.state.Height
    61  	res.LastBlockAppHash = app.app.state.AppHash
    62  	return res
    63  }
    64  
    65  func (app *PersistentKVStoreApplication) SetOption(req types.RequestSetOption) types.ResponseSetOption {
    66  	return app.app.SetOption(req)
    67  }
    68  
    69  // tx is either "val:pubkey!power" or "key=value" or just arbitrary bytes
    70  func (app *PersistentKVStoreApplication) DeliverTx(req types.RequestDeliverTx) types.ResponseDeliverTx {
    71  	// if it starts with "val:", update the validator set
    72  	// format is "val:pubkey!power"
    73  	if isValidatorTx(req.Tx) {
    74  		// update validators in the merkle tree
    75  		// and in app.ValUpdates
    76  		return app.execValidatorTx(req.Tx)
    77  	}
    78  
    79  	// otherwise, update the key-value store
    80  	return app.app.DeliverTx(req)
    81  }
    82  
    83  func (app *PersistentKVStoreApplication) CheckTx(req types.RequestCheckTx) types.ResponseCheckTx {
    84  	return app.app.CheckTx(req)
    85  }
    86  
    87  // Commit will panic if InitChain was not called
    88  func (app *PersistentKVStoreApplication) Commit() types.ResponseCommit {
    89  	return app.app.Commit()
    90  }
    91  
    92  // When path=/val and data={validator address}, returns the validator update (types.ValidatorUpdate) varint encoded.
    93  // For any other path, returns an associated value or nil if missing.
    94  func (app *PersistentKVStoreApplication) Query(reqQuery types.RequestQuery) (resQuery types.ResponseQuery) {
    95  	switch reqQuery.Path {
    96  	case "/val":
    97  		key := []byte("val:" + string(reqQuery.Data))
    98  		value, err := app.app.state.db.Get(key)
    99  		if err != nil {
   100  			panic(err)
   101  		}
   102  
   103  		resQuery.Key = reqQuery.Data
   104  		resQuery.Value = value
   105  		return
   106  	default:
   107  		return app.app.Query(reqQuery)
   108  	}
   109  }
   110  
   111  // Save the validators in the merkle tree
   112  func (app *PersistentKVStoreApplication) InitChain(req types.RequestInitChain) types.ResponseInitChain {
   113  	for _, v := range req.Validators {
   114  		r := app.updateValidator(v)
   115  		if r.IsErr() {
   116  			app.logger.Error("Error updating validators", "r", r)
   117  		}
   118  	}
   119  	return types.ResponseInitChain{}
   120  }
   121  
   122  // Track the block hash and header information
   123  func (app *PersistentKVStoreApplication) BeginBlock(req types.RequestBeginBlock) types.ResponseBeginBlock {
   124  	// reset valset changes
   125  	app.ValUpdates = make([]types.ValidatorUpdate, 0)
   126  
   127  	// Punish validators who committed equivocation.
   128  	for _, ev := range req.ByzantineValidators {
   129  		if ev.Type == types.EvidenceType_DUPLICATE_VOTE {
   130  			addr := string(ev.Validator.Address)
   131  			if pubKey, ok := app.valAddrToPubKeyMap[addr]; ok {
   132  				app.updateValidator(types.ValidatorUpdate{
   133  					PubKey: pubKey,
   134  					Power:  ev.Validator.Power - 1,
   135  				})
   136  				app.logger.Info("Decreased val power by 1 because of the equivocation",
   137  					"val", addr)
   138  			} else {
   139  				app.logger.Error("Wanted to punish val, but can't find it",
   140  					"val", addr)
   141  			}
   142  		}
   143  	}
   144  
   145  	return types.ResponseBeginBlock{}
   146  }
   147  
   148  // Update the validator set
   149  func (app *PersistentKVStoreApplication) EndBlock(req types.RequestEndBlock) types.ResponseEndBlock {
   150  	return types.ResponseEndBlock{ValidatorUpdates: app.ValUpdates}
   151  }
   152  
   153  func (app *PersistentKVStoreApplication) ListSnapshots(
   154  	req types.RequestListSnapshots) types.ResponseListSnapshots {
   155  	return types.ResponseListSnapshots{}
   156  }
   157  
   158  func (app *PersistentKVStoreApplication) LoadSnapshotChunk(
   159  	req types.RequestLoadSnapshotChunk) types.ResponseLoadSnapshotChunk {
   160  	return types.ResponseLoadSnapshotChunk{}
   161  }
   162  
   163  func (app *PersistentKVStoreApplication) OfferSnapshot(
   164  	req types.RequestOfferSnapshot) types.ResponseOfferSnapshot {
   165  	return types.ResponseOfferSnapshot{Result: types.ResponseOfferSnapshot_ABORT}
   166  }
   167  
   168  func (app *PersistentKVStoreApplication) ApplySnapshotChunk(
   169  	req types.RequestApplySnapshotChunk) types.ResponseApplySnapshotChunk {
   170  	return types.ResponseApplySnapshotChunk{Result: types.ResponseApplySnapshotChunk_ABORT}
   171  }
   172  
   173  //---------------------------------------------
   174  // update validators
   175  
   176  func (app *PersistentKVStoreApplication) Validators() (validators []types.ValidatorUpdate) {
   177  	itr, err := app.app.state.db.Iterator(nil, nil)
   178  	if err != nil {
   179  		panic(err)
   180  	}
   181  	for ; itr.Valid(); itr.Next() {
   182  		if isValidatorTx(itr.Key()) {
   183  			validator := new(types.ValidatorUpdate)
   184  			err := types.ReadMessage(bytes.NewBuffer(itr.Value()), validator)
   185  			if err != nil {
   186  				panic(err)
   187  			}
   188  			validators = append(validators, *validator)
   189  		}
   190  	}
   191  	if err = itr.Error(); err != nil {
   192  		panic(err)
   193  	}
   194  	return
   195  }
   196  
   197  func MakeValSetChangeTx(pubkey pc.PublicKey, power int64) []byte {
   198  	pk, err := cryptoenc.PubKeyFromProto(pubkey)
   199  	if err != nil {
   200  		panic(err)
   201  	}
   202  	pubStr := base64.StdEncoding.EncodeToString(pk.Bytes())
   203  	return []byte(fmt.Sprintf("val:%s!%d", pubStr, power))
   204  }
   205  
   206  func isValidatorTx(tx []byte) bool {
   207  	return strings.HasPrefix(string(tx), ValidatorSetChangePrefix)
   208  }
   209  
   210  // format is "val:pubkey!power"
   211  // pubkey is a base64-encoded 32-byte ed25519 key
   212  func (app *PersistentKVStoreApplication) execValidatorTx(tx []byte) types.ResponseDeliverTx {
   213  	tx = tx[len(ValidatorSetChangePrefix):]
   214  
   215  	//  get the pubkey and power
   216  	pubKeyAndPower := strings.Split(string(tx), "!")
   217  	if len(pubKeyAndPower) != 2 {
   218  		return types.ResponseDeliverTx{
   219  			Code: code.CodeTypeEncodingError,
   220  			Log:  fmt.Sprintf("Expected 'pubkey!power'. Got %v", pubKeyAndPower)}
   221  	}
   222  	pubkeyS, powerS := pubKeyAndPower[0], pubKeyAndPower[1]
   223  
   224  	// decode the pubkey
   225  	pubkey, err := base64.StdEncoding.DecodeString(pubkeyS)
   226  	if err != nil {
   227  		return types.ResponseDeliverTx{
   228  			Code: code.CodeTypeEncodingError,
   229  			Log:  fmt.Sprintf("Pubkey (%s) is invalid base64", pubkeyS)}
   230  	}
   231  
   232  	// decode the power
   233  	power, err := strconv.ParseInt(powerS, 10, 64)
   234  	if err != nil {
   235  		return types.ResponseDeliverTx{
   236  			Code: code.CodeTypeEncodingError,
   237  			Log:  fmt.Sprintf("Power (%s) is not an int", powerS)}
   238  	}
   239  
   240  	// update
   241  	return app.updateValidator(types.UpdateValidator(pubkey, power, ""))
   242  }
   243  
   244  // add, update, or remove a validator
   245  func (app *PersistentKVStoreApplication) updateValidator(v types.ValidatorUpdate) types.ResponseDeliverTx {
   246  	pubkey, err := cryptoenc.PubKeyFromProto(v.PubKey)
   247  	if err != nil {
   248  		panic(fmt.Errorf("can't decode public key: %w", err))
   249  	}
   250  	key := []byte("val:" + string(pubkey.Bytes()))
   251  
   252  	if v.Power == 0 {
   253  		// remove validator
   254  		hasKey, err := app.app.state.db.Has(key)
   255  		if err != nil {
   256  			panic(err)
   257  		}
   258  		if !hasKey {
   259  			pubStr := base64.StdEncoding.EncodeToString(pubkey.Bytes())
   260  			return types.ResponseDeliverTx{
   261  				Code: code.CodeTypeUnauthorized,
   262  				Log:  fmt.Sprintf("Cannot remove non-existent validator %s", pubStr)}
   263  		}
   264  		if err = app.app.state.db.Delete(key); err != nil {
   265  			panic(err)
   266  		}
   267  		delete(app.valAddrToPubKeyMap, string(pubkey.Address()))
   268  	} else {
   269  		// add or update validator
   270  		value := bytes.NewBuffer(make([]byte, 0))
   271  		if err := types.WriteMessage(&v, value); err != nil {
   272  			return types.ResponseDeliverTx{
   273  				Code: code.CodeTypeEncodingError,
   274  				Log:  fmt.Sprintf("Error encoding validator: %v", err)}
   275  		}
   276  		if err = app.app.state.db.Set(key, value.Bytes()); err != nil {
   277  			panic(err)
   278  		}
   279  		app.valAddrToPubKeyMap[string(pubkey.Address())] = v.PubKey
   280  	}
   281  
   282  	// we only update the changes array if we successfully updated the tree
   283  	app.ValUpdates = append(app.ValUpdates, v)
   284  
   285  	return types.ResponseDeliverTx{Code: code.CodeTypeOK}
   286  }