You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

268 lines
7.8 KiB

lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
8 years ago
8 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
8 years ago
8 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. package kvstore
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "fmt"
  6. "strconv"
  7. "strings"
  8. dbm "github.com/tendermint/tm-db"
  9. "github.com/tendermint/tendermint/abci/example/code"
  10. "github.com/tendermint/tendermint/abci/types"
  11. "github.com/tendermint/tendermint/crypto/ed25519"
  12. "github.com/tendermint/tendermint/libs/log"
  13. tmtypes "github.com/tendermint/tendermint/types"
  14. )
  15. const (
  16. ValidatorSetChangePrefix string = "val:"
  17. )
  18. //-----------------------------------------
  19. var _ types.Application = (*PersistentKVStoreApplication)(nil)
  20. type PersistentKVStoreApplication struct {
  21. app *Application
  22. // validator set
  23. ValUpdates []types.ValidatorUpdate
  24. valAddrToPubKeyMap map[string]types.PubKey
  25. logger log.Logger
  26. }
  27. func NewPersistentKVStoreApplication(dbDir string) *PersistentKVStoreApplication {
  28. name := "kvstore"
  29. db, err := dbm.NewGoLevelDB(name, dbDir)
  30. if err != nil {
  31. panic(err)
  32. }
  33. state := loadState(db)
  34. return &PersistentKVStoreApplication{
  35. app: &Application{state: state},
  36. valAddrToPubKeyMap: make(map[string]types.PubKey),
  37. logger: log.NewNopLogger(),
  38. }
  39. }
  40. func (app *PersistentKVStoreApplication) SetLogger(l log.Logger) {
  41. app.logger = l
  42. }
  43. func (app *PersistentKVStoreApplication) Info(req types.RequestInfo) types.ResponseInfo {
  44. res := app.app.Info(req)
  45. res.LastBlockHeight = app.app.state.Height
  46. res.LastBlockAppHash = app.app.state.AppHash
  47. return res
  48. }
  49. func (app *PersistentKVStoreApplication) SetOption(req types.RequestSetOption) types.ResponseSetOption {
  50. return app.app.SetOption(req)
  51. }
  52. // tx is either "val:pubkey!power" or "key=value" or just arbitrary bytes
  53. func (app *PersistentKVStoreApplication) DeliverTx(req types.RequestDeliverTx) types.ResponseDeliverTx {
  54. // if it starts with "val:", update the validator set
  55. // format is "val:pubkey!power"
  56. if isValidatorTx(req.Tx) {
  57. // update validators in the merkle tree
  58. // and in app.ValUpdates
  59. return app.execValidatorTx(req.Tx)
  60. }
  61. // otherwise, update the key-value store
  62. return app.app.DeliverTx(req)
  63. }
  64. func (app *PersistentKVStoreApplication) CheckTx(req types.RequestCheckTx) types.ResponseCheckTx {
  65. return app.app.CheckTx(req)
  66. }
  67. // Commit will panic if InitChain was not called
  68. func (app *PersistentKVStoreApplication) Commit() types.ResponseCommit {
  69. return app.app.Commit()
  70. }
  71. // When path=/val and data={validator address}, returns the validator update (types.ValidatorUpdate) varint encoded.
  72. // For any other path, returns an associated value or nil if missing.
  73. func (app *PersistentKVStoreApplication) Query(reqQuery types.RequestQuery) (resQuery types.ResponseQuery) {
  74. switch reqQuery.Path {
  75. case "/val":
  76. key := []byte("val:" + string(reqQuery.Data))
  77. value, err := app.app.state.db.Get(key)
  78. if err != nil {
  79. panic(err)
  80. }
  81. resQuery.Key = reqQuery.Data
  82. resQuery.Value = value
  83. return
  84. default:
  85. return app.app.Query(reqQuery)
  86. }
  87. }
  88. // Save the validators in the merkle tree
  89. func (app *PersistentKVStoreApplication) InitChain(req types.RequestInitChain) types.ResponseInitChain {
  90. for _, v := range req.Validators {
  91. r := app.updateValidator(v)
  92. if r.IsErr() {
  93. app.logger.Error("Error updating validators", "r", r)
  94. }
  95. }
  96. return types.ResponseInitChain{}
  97. }
  98. // Track the block hash and header information
  99. func (app *PersistentKVStoreApplication) BeginBlock(req types.RequestBeginBlock) types.ResponseBeginBlock {
  100. // reset valset changes
  101. app.ValUpdates = make([]types.ValidatorUpdate, 0)
  102. for _, ev := range req.ByzantineValidators {
  103. if ev.Type == tmtypes.ABCIEvidenceTypeDuplicateVote {
  104. // decrease voting power by 1
  105. if ev.TotalVotingPower == 0 {
  106. continue
  107. }
  108. app.updateValidator(types.ValidatorUpdate{
  109. PubKey: app.valAddrToPubKeyMap[string(ev.Validator.Address)],
  110. Power: ev.TotalVotingPower - 1,
  111. })
  112. }
  113. }
  114. return types.ResponseBeginBlock{}
  115. }
  116. // Update the validator set
  117. func (app *PersistentKVStoreApplication) EndBlock(req types.RequestEndBlock) types.ResponseEndBlock {
  118. return types.ResponseEndBlock{ValidatorUpdates: app.ValUpdates}
  119. }
  120. func (app *PersistentKVStoreApplication) ListSnapshots(
  121. req types.RequestListSnapshots) types.ResponseListSnapshots {
  122. return types.ResponseListSnapshots{}
  123. }
  124. func (app *PersistentKVStoreApplication) LoadSnapshotChunk(
  125. req types.RequestLoadSnapshotChunk) types.ResponseLoadSnapshotChunk {
  126. return types.ResponseLoadSnapshotChunk{}
  127. }
  128. func (app *PersistentKVStoreApplication) OfferSnapshot(
  129. req types.RequestOfferSnapshot) types.ResponseOfferSnapshot {
  130. return types.ResponseOfferSnapshot{Result: types.ResponseOfferSnapshot_ABORT}
  131. }
  132. func (app *PersistentKVStoreApplication) ApplySnapshotChunk(
  133. req types.RequestApplySnapshotChunk) types.ResponseApplySnapshotChunk {
  134. return types.ResponseApplySnapshotChunk{Result: types.ResponseApplySnapshotChunk_ABORT}
  135. }
  136. //---------------------------------------------
  137. // update validators
  138. func (app *PersistentKVStoreApplication) Validators() (validators []types.ValidatorUpdate) {
  139. itr, err := app.app.state.db.Iterator(nil, nil)
  140. if err != nil {
  141. panic(err)
  142. }
  143. for ; itr.Valid(); itr.Next() {
  144. if isValidatorTx(itr.Key()) {
  145. validator := new(types.ValidatorUpdate)
  146. err := types.ReadMessage(bytes.NewBuffer(itr.Value()), validator)
  147. if err != nil {
  148. panic(err)
  149. }
  150. validators = append(validators, *validator)
  151. }
  152. }
  153. return
  154. }
  155. func MakeValSetChangeTx(pubkey types.PubKey, power int64) []byte {
  156. pubStr := base64.StdEncoding.EncodeToString(pubkey.Data)
  157. return []byte(fmt.Sprintf("val:%s!%d", pubStr, power))
  158. }
  159. func isValidatorTx(tx []byte) bool {
  160. return strings.HasPrefix(string(tx), ValidatorSetChangePrefix)
  161. }
  162. // format is "val:pubkey!power"
  163. // pubkey is a base64-encoded 32-byte ed25519 key
  164. func (app *PersistentKVStoreApplication) execValidatorTx(tx []byte) types.ResponseDeliverTx {
  165. tx = tx[len(ValidatorSetChangePrefix):]
  166. //get the pubkey and power
  167. pubKeyAndPower := strings.Split(string(tx), "!")
  168. if len(pubKeyAndPower) != 2 {
  169. return types.ResponseDeliverTx{
  170. Code: code.CodeTypeEncodingError,
  171. Log: fmt.Sprintf("Expected 'pubkey!power'. Got %v", pubKeyAndPower)}
  172. }
  173. pubkeyS, powerS := pubKeyAndPower[0], pubKeyAndPower[1]
  174. // decode the pubkey
  175. pubkey, err := base64.StdEncoding.DecodeString(pubkeyS)
  176. if err != nil {
  177. return types.ResponseDeliverTx{
  178. Code: code.CodeTypeEncodingError,
  179. Log: fmt.Sprintf("Pubkey (%s) is invalid base64", pubkeyS)}
  180. }
  181. // decode the power
  182. power, err := strconv.ParseInt(powerS, 10, 64)
  183. if err != nil {
  184. return types.ResponseDeliverTx{
  185. Code: code.CodeTypeEncodingError,
  186. Log: fmt.Sprintf("Power (%s) is not an int", powerS)}
  187. }
  188. // update
  189. return app.updateValidator(types.Ed25519ValidatorUpdate(pubkey, power))
  190. }
  191. // add, update, or remove a validator
  192. func (app *PersistentKVStoreApplication) updateValidator(v types.ValidatorUpdate) types.ResponseDeliverTx {
  193. key := []byte("val:" + string(v.PubKey.Data))
  194. pubkey := ed25519.PubKeyEd25519{}
  195. copy(pubkey[:], v.PubKey.Data)
  196. if v.Power == 0 {
  197. // remove validator
  198. hasKey, err := app.app.state.db.Has(key)
  199. if err != nil {
  200. panic(err)
  201. }
  202. if !hasKey {
  203. pubStr := base64.StdEncoding.EncodeToString(v.PubKey.Data)
  204. return types.ResponseDeliverTx{
  205. Code: code.CodeTypeUnauthorized,
  206. Log: fmt.Sprintf("Cannot remove non-existent validator %s", pubStr)}
  207. }
  208. app.app.state.db.Delete(key)
  209. delete(app.valAddrToPubKeyMap, string(pubkey.Address()))
  210. } else {
  211. // add or update validator
  212. value := bytes.NewBuffer(make([]byte, 0))
  213. if err := types.WriteMessage(&v, value); err != nil {
  214. return types.ResponseDeliverTx{
  215. Code: code.CodeTypeEncodingError,
  216. Log: fmt.Sprintf("Error encoding validator: %v", err)}
  217. }
  218. app.app.state.db.Set(key, value.Bytes())
  219. app.valAddrToPubKeyMap[string(pubkey.Address())] = v.PubKey
  220. }
  221. // we only update the changes array if we successfully updated the tree
  222. app.ValUpdates = append(app.ValUpdates, v)
  223. return types.ResponseDeliverTx{Code: code.CodeTypeOK}
  224. }