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