github.com/pokt-network/tendermint@v0.32.11-0.20230426215212-59310158d3e9/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/tendermint/tendermint/abci/example/code"
    13  	"github.com/tendermint/tendermint/abci/types"
    14  	"github.com/tendermint/tendermint/crypto/ed25519"
    15  	"github.com/tendermint/tendermint/libs/log"
    16  	tmtypes "github.com/tendermint/tendermint/types"
    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]types.PubKey
    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]types.PubKey),
    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  	for _, ev := range req.ByzantineValidators {
   128  		if ev.Type == tmtypes.ABCIEvidenceTypeDuplicateVote {
   129  			// decrease voting power by 1
   130  			if ev.TotalVotingPower == 0 {
   131  				continue
   132  			}
   133  			app.updateValidator(types.ValidatorUpdate{
   134  				PubKey: app.valAddrToPubKeyMap[string(ev.Validator.Address)],
   135  				Power:  ev.TotalVotingPower - 1,
   136  			})
   137  		}
   138  	}
   139  	return types.ResponseBeginBlock{}
   140  }
   141  
   142  // Update the validator set
   143  func (app *PersistentKVStoreApplication) EndBlock(req types.RequestEndBlock) types.ResponseEndBlock {
   144  	return types.ResponseEndBlock{ValidatorUpdates: app.ValUpdates}
   145  }
   146  
   147  //---------------------------------------------
   148  // update validators
   149  
   150  func (app *PersistentKVStoreApplication) Validators() (validators []types.ValidatorUpdate) {
   151  	itr, err := app.app.state.db.Iterator(nil, nil)
   152  	if err != nil {
   153  		panic(err)
   154  	}
   155  	for ; itr.Valid(); itr.Next() {
   156  		if isValidatorTx(itr.Key()) {
   157  			validator := new(types.ValidatorUpdate)
   158  			err := types.ReadMessage(bytes.NewBuffer(itr.Value()), validator)
   159  			if err != nil {
   160  				panic(err)
   161  			}
   162  			validators = append(validators, *validator)
   163  		}
   164  	}
   165  	return
   166  }
   167  
   168  func MakeValSetChangeTx(pubkey types.PubKey, power int64) []byte {
   169  	pubStr := base64.StdEncoding.EncodeToString(pubkey.Data)
   170  	return []byte(fmt.Sprintf("val:%s!%d", pubStr, power))
   171  }
   172  
   173  func isValidatorTx(tx []byte) bool {
   174  	return strings.HasPrefix(string(tx), ValidatorSetChangePrefix)
   175  }
   176  
   177  // format is "val:pubkey!power"
   178  // pubkey is a base64-encoded 32-byte ed25519 key
   179  func (app *PersistentKVStoreApplication) execValidatorTx(tx []byte) types.ResponseDeliverTx {
   180  	tx = tx[len(ValidatorSetChangePrefix):]
   181  
   182  	//get the pubkey and power
   183  	pubKeyAndPower := strings.Split(string(tx), "!")
   184  	if len(pubKeyAndPower) != 2 {
   185  		return types.ResponseDeliverTx{
   186  			Code: code.CodeTypeEncodingError,
   187  			Log:  fmt.Sprintf("Expected 'pubkey!power'. Got %v", pubKeyAndPower)}
   188  	}
   189  	pubkeyS, powerS := pubKeyAndPower[0], pubKeyAndPower[1]
   190  
   191  	// decode the pubkey
   192  	pubkey, err := base64.StdEncoding.DecodeString(pubkeyS)
   193  	if err != nil {
   194  		return types.ResponseDeliverTx{
   195  			Code: code.CodeTypeEncodingError,
   196  			Log:  fmt.Sprintf("Pubkey (%s) is invalid base64", pubkeyS)}
   197  	}
   198  
   199  	// decode the power
   200  	power, err := strconv.ParseInt(powerS, 10, 64)
   201  	if err != nil {
   202  		return types.ResponseDeliverTx{
   203  			Code: code.CodeTypeEncodingError,
   204  			Log:  fmt.Sprintf("Power (%s) is not an int", powerS)}
   205  	}
   206  
   207  	// update
   208  	return app.updateValidator(types.Ed25519ValidatorUpdate(pubkey, power))
   209  }
   210  
   211  // add, update, or remove a validator
   212  func (app *PersistentKVStoreApplication) updateValidator(v types.ValidatorUpdate) types.ResponseDeliverTx {
   213  	key := []byte("val:" + string(v.PubKey.Data))
   214  
   215  	pubkey := ed25519.PubKeyEd25519{}
   216  	copy(pubkey[:], v.PubKey.Data)
   217  
   218  	if v.Power == 0 {
   219  		// remove validator
   220  		hasKey, err := app.app.state.db.Has(key)
   221  		if err != nil {
   222  			panic(err)
   223  		}
   224  		if !hasKey {
   225  			pubStr := base64.StdEncoding.EncodeToString(v.PubKey.Data)
   226  			return types.ResponseDeliverTx{
   227  				Code: code.CodeTypeUnauthorized,
   228  				Log:  fmt.Sprintf("Cannot remove non-existent validator %s", pubStr)}
   229  		}
   230  		app.app.state.db.Delete(key)
   231  		delete(app.valAddrToPubKeyMap, string(pubkey.Address()))
   232  	} else {
   233  		// add or update validator
   234  		value := bytes.NewBuffer(make([]byte, 0))
   235  		if err := types.WriteMessage(&v, value); err != nil {
   236  			return types.ResponseDeliverTx{
   237  				Code: code.CodeTypeEncodingError,
   238  				Log:  fmt.Sprintf("Error encoding validator: %v", err)}
   239  		}
   240  		app.app.state.db.Set(key, value.Bytes())
   241  		app.valAddrToPubKeyMap[string(pubkey.Address())] = v.PubKey
   242  	}
   243  
   244  	// we only update the changes array if we successfully updated the tree
   245  	app.ValUpdates = append(app.ValUpdates, v)
   246  
   247  	return types.ResponseDeliverTx{Code: code.CodeTypeOK}
   248  }