github.com/okex/exchain@v1.8.0/libs/tendermint/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/okex/exchain/libs/tm-db"
    11  
    12  	"github.com/okex/exchain/libs/tendermint/abci/example/code"
    13  	"github.com/okex/exchain/libs/tendermint/abci/types"
    14  	"github.com/okex/exchain/libs/tendermint/crypto/ed25519"
    15  	"github.com/okex/exchain/libs/tendermint/libs/log"
    16  	tmtypes "github.com/okex/exchain/libs/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) PreDeliverRealTx([]byte) types.TxEssentials {
    84  	return nil
    85  }
    86  
    87  func (app *PersistentKVStoreApplication) DeliverRealTx(tx types.TxEssentials) types.ResponseDeliverTx {
    88  	panic("do not support deliver real tx")
    89  }
    90  
    91  func (app *PersistentKVStoreApplication) CheckTx(req types.RequestCheckTx) types.ResponseCheckTx {
    92  	return app.app.CheckTx(req)
    93  }
    94  
    95  // Commit will panic if InitChain was not called
    96  func (app *PersistentKVStoreApplication) Commit(req types.RequestCommit) types.ResponseCommit {
    97  	return app.app.Commit(req)
    98  }
    99  
   100  // When path=/val and data={validator address}, returns the validator update (types.ValidatorUpdate) varint encoded.
   101  // For any other path, returns an associated value or nil if missing.
   102  func (app *PersistentKVStoreApplication) Query(reqQuery types.RequestQuery) (resQuery types.ResponseQuery) {
   103  	switch reqQuery.Path {
   104  	case "/val":
   105  		key := []byte("val:" + string(reqQuery.Data))
   106  		value, err := app.app.state.db.Get(key)
   107  		if err != nil {
   108  			panic(err)
   109  		}
   110  
   111  		resQuery.Key = reqQuery.Data
   112  		resQuery.Value = value
   113  		return
   114  	default:
   115  		return app.app.Query(reqQuery)
   116  	}
   117  }
   118  
   119  // Save the validators in the merkle tree
   120  func (app *PersistentKVStoreApplication) InitChain(req types.RequestInitChain) types.ResponseInitChain {
   121  	for _, v := range req.Validators {
   122  		r := app.updateValidator(v)
   123  		if r.IsErr() {
   124  			app.logger.Error("Error updating validators", "r", r)
   125  		}
   126  	}
   127  	return types.ResponseInitChain{}
   128  }
   129  
   130  // Track the block hash and header information
   131  func (app *PersistentKVStoreApplication) BeginBlock(req types.RequestBeginBlock) types.ResponseBeginBlock {
   132  	// reset valset changes
   133  	app.ValUpdates = make([]types.ValidatorUpdate, 0)
   134  
   135  	for _, ev := range req.ByzantineValidators {
   136  		if ev.Type == tmtypes.ABCIEvidenceTypeDuplicateVote {
   137  			// decrease voting power by 1
   138  			if ev.TotalVotingPower == 0 {
   139  				continue
   140  			}
   141  			app.updateValidator(types.ValidatorUpdate{
   142  				PubKey: app.valAddrToPubKeyMap[string(ev.Validator.Address)],
   143  				Power:  ev.TotalVotingPower - 1,
   144  			})
   145  		}
   146  	}
   147  	return types.ResponseBeginBlock{}
   148  }
   149  
   150  // Update the validator set
   151  func (app *PersistentKVStoreApplication) EndBlock(req types.RequestEndBlock) types.ResponseEndBlock {
   152  	return types.ResponseEndBlock{ValidatorUpdates: app.ValUpdates}
   153  }
   154  
   155  func (app *PersistentKVStoreApplication) ParallelTxs(_ [][]byte, _ bool) []*types.ResponseDeliverTx {
   156  	return nil
   157  }
   158  
   159  //---------------------------------------------
   160  // update validators
   161  
   162  func (app *PersistentKVStoreApplication) Validators() (validators []types.ValidatorUpdate) {
   163  	itr, err := app.app.state.db.Iterator(nil, nil)
   164  	if err != nil {
   165  		panic(err)
   166  	}
   167  	for ; itr.Valid(); itr.Next() {
   168  		if isValidatorTx(itr.Key()) {
   169  			validator := new(types.ValidatorUpdate)
   170  			err := types.ReadMessage(bytes.NewBuffer(itr.Value()), validator)
   171  			if err != nil {
   172  				panic(err)
   173  			}
   174  			validators = append(validators, *validator)
   175  		}
   176  	}
   177  	return
   178  }
   179  
   180  func MakeValSetChangeTx(pubkey types.PubKey, power int64) []byte {
   181  	pubStr := base64.StdEncoding.EncodeToString(pubkey.Data)
   182  	return []byte(fmt.Sprintf("val:%s!%d", pubStr, power))
   183  }
   184  
   185  func isValidatorTx(tx []byte) bool {
   186  	return strings.HasPrefix(string(tx), ValidatorSetChangePrefix)
   187  }
   188  
   189  // format is "val:pubkey!power"
   190  // pubkey is a base64-encoded 32-byte ed25519 key
   191  func (app *PersistentKVStoreApplication) execValidatorTx(tx []byte) types.ResponseDeliverTx {
   192  	tx = tx[len(ValidatorSetChangePrefix):]
   193  
   194  	//get the pubkey and power
   195  	pubKeyAndPower := strings.Split(string(tx), "!")
   196  	if len(pubKeyAndPower) != 2 {
   197  		return types.ResponseDeliverTx{
   198  			Code: code.CodeTypeEncodingError,
   199  			Log:  fmt.Sprintf("Expected 'pubkey!power'. Got %v", pubKeyAndPower)}
   200  	}
   201  	pubkeyS, powerS := pubKeyAndPower[0], pubKeyAndPower[1]
   202  
   203  	// decode the pubkey
   204  	pubkey, err := base64.StdEncoding.DecodeString(pubkeyS)
   205  	if err != nil {
   206  		return types.ResponseDeliverTx{
   207  			Code: code.CodeTypeEncodingError,
   208  			Log:  fmt.Sprintf("Pubkey (%s) is invalid base64", pubkeyS)}
   209  	}
   210  
   211  	// decode the power
   212  	power, err := strconv.ParseInt(powerS, 10, 64)
   213  	if err != nil {
   214  		return types.ResponseDeliverTx{
   215  			Code: code.CodeTypeEncodingError,
   216  			Log:  fmt.Sprintf("Power (%s) is not an int", powerS)}
   217  	}
   218  
   219  	// update
   220  	return app.updateValidator(types.Ed25519ValidatorUpdate(pubkey, power))
   221  }
   222  
   223  // add, update, or remove a validator
   224  func (app *PersistentKVStoreApplication) updateValidator(v types.ValidatorUpdate) types.ResponseDeliverTx {
   225  	key := []byte("val:" + string(v.PubKey.Data))
   226  
   227  	pubkey := ed25519.PubKeyEd25519{}
   228  	copy(pubkey[:], v.PubKey.Data)
   229  
   230  	if v.Power == 0 {
   231  		// remove validator
   232  		hasKey, err := app.app.state.db.Has(key)
   233  		if err != nil {
   234  			panic(err)
   235  		}
   236  		if !hasKey {
   237  			pubStr := base64.StdEncoding.EncodeToString(v.PubKey.Data)
   238  			return types.ResponseDeliverTx{
   239  				Code: code.CodeTypeUnauthorized,
   240  				Log:  fmt.Sprintf("Cannot remove non-existent validator %s", pubStr)}
   241  		}
   242  		app.app.state.db.Delete(key)
   243  		delete(app.valAddrToPubKeyMap, string(pubkey.Address()))
   244  	} else {
   245  		// add or update validator
   246  		value := bytes.NewBuffer(make([]byte, 0))
   247  		if err := types.WriteMessage(&v, value); err != nil {
   248  			return types.ResponseDeliverTx{
   249  				Code: code.CodeTypeEncodingError,
   250  				Log:  fmt.Sprintf("Error encoding validator: %v", err)}
   251  		}
   252  		app.app.state.db.Set(key, value.Bytes())
   253  		app.valAddrToPubKeyMap[string(pubkey.Address())] = v.PubKey
   254  	}
   255  
   256  	// we only update the changes array if we successfully updated the tree
   257  	app.ValUpdates = append(app.ValUpdates, v)
   258  
   259  	return types.ResponseDeliverTx{Code: code.CodeTypeOK}
   260  }