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