github.com/franono/tendermint@v0.32.2-0.20200527150959-749313264ce9/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/franono/tendermint/abci/example/code"
    13  	"github.com/franono/tendermint/abci/types"
    14  	"github.com/franono/tendermint/crypto/ed25519"
    15  	"github.com/franono/tendermint/libs/log"
    16  	tmtypes "github.com/franono/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  func (app *PersistentKVStoreApplication) ListSnapshots(
   148  	req types.RequestListSnapshots) types.ResponseListSnapshots {
   149  	return types.ResponseListSnapshots{}
   150  }
   151  
   152  func (app *PersistentKVStoreApplication) LoadSnapshotChunk(
   153  	req types.RequestLoadSnapshotChunk) types.ResponseLoadSnapshotChunk {
   154  	return types.ResponseLoadSnapshotChunk{}
   155  }
   156  
   157  func (app *PersistentKVStoreApplication) OfferSnapshot(
   158  	req types.RequestOfferSnapshot) types.ResponseOfferSnapshot {
   159  	return types.ResponseOfferSnapshot{Result: types.ResponseOfferSnapshot_ABORT}
   160  }
   161  
   162  func (app *PersistentKVStoreApplication) ApplySnapshotChunk(
   163  	req types.RequestApplySnapshotChunk) types.ResponseApplySnapshotChunk {
   164  	return types.ResponseApplySnapshotChunk{Result: types.ResponseApplySnapshotChunk_ABORT}
   165  }
   166  
   167  //---------------------------------------------
   168  // update validators
   169  
   170  func (app *PersistentKVStoreApplication) Validators() (validators []types.ValidatorUpdate) {
   171  	itr, err := app.app.state.db.Iterator(nil, nil)
   172  	if err != nil {
   173  		panic(err)
   174  	}
   175  	for ; itr.Valid(); itr.Next() {
   176  		if isValidatorTx(itr.Key()) {
   177  			validator := new(types.ValidatorUpdate)
   178  			err := types.ReadMessage(bytes.NewBuffer(itr.Value()), validator)
   179  			if err != nil {
   180  				panic(err)
   181  			}
   182  			validators = append(validators, *validator)
   183  		}
   184  	}
   185  	return
   186  }
   187  
   188  func MakeValSetChangeTx(pubkey types.PubKey, power int64) []byte {
   189  	pubStr := base64.StdEncoding.EncodeToString(pubkey.Data)
   190  	return []byte(fmt.Sprintf("val:%s!%d", pubStr, power))
   191  }
   192  
   193  func isValidatorTx(tx []byte) bool {
   194  	return strings.HasPrefix(string(tx), ValidatorSetChangePrefix)
   195  }
   196  
   197  // format is "val:pubkey!power"
   198  // pubkey is a base64-encoded 32-byte ed25519 key
   199  func (app *PersistentKVStoreApplication) execValidatorTx(tx []byte) types.ResponseDeliverTx {
   200  	tx = tx[len(ValidatorSetChangePrefix):]
   201  
   202  	//get the pubkey and power
   203  	pubKeyAndPower := strings.Split(string(tx), "!")
   204  	if len(pubKeyAndPower) != 2 {
   205  		return types.ResponseDeliverTx{
   206  			Code: code.CodeTypeEncodingError,
   207  			Log:  fmt.Sprintf("Expected 'pubkey!power'. Got %v", pubKeyAndPower)}
   208  	}
   209  	pubkeyS, powerS := pubKeyAndPower[0], pubKeyAndPower[1]
   210  
   211  	// decode the pubkey
   212  	pubkey, err := base64.StdEncoding.DecodeString(pubkeyS)
   213  	if err != nil {
   214  		return types.ResponseDeliverTx{
   215  			Code: code.CodeTypeEncodingError,
   216  			Log:  fmt.Sprintf("Pubkey (%s) is invalid base64", pubkeyS)}
   217  	}
   218  
   219  	// decode the power
   220  	power, err := strconv.ParseInt(powerS, 10, 64)
   221  	if err != nil {
   222  		return types.ResponseDeliverTx{
   223  			Code: code.CodeTypeEncodingError,
   224  			Log:  fmt.Sprintf("Power (%s) is not an int", powerS)}
   225  	}
   226  
   227  	// update
   228  	return app.updateValidator(types.Ed25519ValidatorUpdate(pubkey, power))
   229  }
   230  
   231  // add, update, or remove a validator
   232  func (app *PersistentKVStoreApplication) updateValidator(v types.ValidatorUpdate) types.ResponseDeliverTx {
   233  	key := []byte("val:" + string(v.PubKey.Data))
   234  
   235  	pubkey := ed25519.PubKeyEd25519{}
   236  	copy(pubkey[:], v.PubKey.Data)
   237  
   238  	if v.Power == 0 {
   239  		// remove validator
   240  		hasKey, err := app.app.state.db.Has(key)
   241  		if err != nil {
   242  			panic(err)
   243  		}
   244  		if !hasKey {
   245  			pubStr := base64.StdEncoding.EncodeToString(v.PubKey.Data)
   246  			return types.ResponseDeliverTx{
   247  				Code: code.CodeTypeUnauthorized,
   248  				Log:  fmt.Sprintf("Cannot remove non-existent validator %s", pubStr)}
   249  		}
   250  		app.app.state.db.Delete(key)
   251  		delete(app.valAddrToPubKeyMap, string(pubkey.Address()))
   252  	} else {
   253  		// add or update validator
   254  		value := bytes.NewBuffer(make([]byte, 0))
   255  		if err := types.WriteMessage(&v, value); err != nil {
   256  			return types.ResponseDeliverTx{
   257  				Code: code.CodeTypeEncodingError,
   258  				Log:  fmt.Sprintf("Error encoding validator: %v", err)}
   259  		}
   260  		app.app.state.db.Set(key, value.Bytes())
   261  		app.valAddrToPubKeyMap[string(pubkey.Address())] = v.PubKey
   262  	}
   263  
   264  	// we only update the changes array if we successfully updated the tree
   265  	app.ValUpdates = append(app.ValUpdates, v)
   266  
   267  	return types.ResponseDeliverTx{Code: code.CodeTypeOK}
   268  }