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