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.

367 lines
11 KiB

cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 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
7 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
7 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
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
7 years ago
7 years ago
7 years ago
7 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 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/encoding"
  12. "github.com/tendermint/tendermint/libs/log"
  13. cryptoproto "github.com/tendermint/tendermint/proto/tendermint/crypto"
  14. ptypes "github.com/tendermint/tendermint/proto/tendermint/types"
  15. )
  16. const (
  17. ValidatorSetChangePrefix string = "val:"
  18. )
  19. //-----------------------------------------
  20. var _ types.Application = (*PersistentKVStoreApplication)(nil)
  21. type PersistentKVStoreApplication struct {
  22. app *Application
  23. // validator set
  24. ValUpdates []types.ValidatorUpdate
  25. valAddrToPubKeyMap map[string]cryptoproto.PublicKey
  26. logger log.Logger
  27. }
  28. func NewPersistentKVStoreApplication(logger log.Logger, dbDir string) *PersistentKVStoreApplication {
  29. name := "kvstore"
  30. db, err := dbm.NewGoLevelDB(name, dbDir)
  31. if err != nil {
  32. panic(err)
  33. }
  34. state := loadState(db)
  35. return &PersistentKVStoreApplication{
  36. app: &Application{state: state},
  37. valAddrToPubKeyMap: make(map[string]cryptoproto.PublicKey),
  38. logger: logger,
  39. }
  40. }
  41. func (app *PersistentKVStoreApplication) Close() error {
  42. return app.app.state.db.Close()
  43. }
  44. func (app *PersistentKVStoreApplication) Info(req types.RequestInfo) types.ResponseInfo {
  45. res := app.app.Info(req)
  46. res.LastBlockHeight = app.app.state.Height
  47. res.LastBlockAppHash = app.app.state.AppHash
  48. return res
  49. }
  50. // tx is either "val:pubkey!power" or "key=value" or just arbitrary bytes
  51. func (app *PersistentKVStoreApplication) HandleTx(tx []byte) *types.ResponseDeliverTx {
  52. // if it starts with "val:", update the validator set
  53. // format is "val:pubkey!power"
  54. if isValidatorTx(tx) {
  55. // update validators in the merkle tree
  56. // and in app.ValUpdates
  57. return app.execValidatorTx(tx)
  58. }
  59. if isPrepareTx(tx) {
  60. return app.execPrepareTx(tx)
  61. }
  62. // otherwise, update the key-value store
  63. return app.app.HandleTx(tx)
  64. }
  65. func (app *PersistentKVStoreApplication) CheckTx(req types.RequestCheckTx) types.ResponseCheckTx {
  66. return app.app.CheckTx(req)
  67. }
  68. // Commit will panic if InitChain was not called
  69. func (app *PersistentKVStoreApplication) Commit() types.ResponseCommit {
  70. return app.app.Commit()
  71. }
  72. // When path=/val and data={validator address}, returns the validator update (types.ValidatorUpdate) varint encoded.
  73. // For any other path, returns an associated value or nil if missing.
  74. func (app *PersistentKVStoreApplication) Query(reqQuery types.RequestQuery) (resQuery types.ResponseQuery) {
  75. switch reqQuery.Path {
  76. case "/val":
  77. key := []byte("val:" + string(reqQuery.Data))
  78. value, err := app.app.state.db.Get(key)
  79. if err != nil {
  80. panic(err)
  81. }
  82. resQuery.Key = reqQuery.Data
  83. resQuery.Value = value
  84. return
  85. default:
  86. return app.app.Query(reqQuery)
  87. }
  88. }
  89. // Save the validators in the merkle tree
  90. func (app *PersistentKVStoreApplication) InitChain(req types.RequestInitChain) types.ResponseInitChain {
  91. for _, v := range req.Validators {
  92. r := app.updateValidator(v)
  93. if r.IsErr() {
  94. app.logger.Error("error updating validators", "r", r)
  95. }
  96. }
  97. return types.ResponseInitChain{}
  98. }
  99. // Track the block hash and header information
  100. // Execute transactions
  101. // Update the validator set
  102. func (app *PersistentKVStoreApplication) FinalizeBlock(req types.RequestFinalizeBlock) types.ResponseFinalizeBlock {
  103. // reset valset changes
  104. app.ValUpdates = make([]types.ValidatorUpdate, 0)
  105. // Punish validators who committed equivocation.
  106. for _, ev := range req.ByzantineValidators {
  107. if ev.Type == types.EvidenceType_DUPLICATE_VOTE {
  108. addr := string(ev.Validator.Address)
  109. if pubKey, ok := app.valAddrToPubKeyMap[addr]; ok {
  110. app.updateValidator(types.ValidatorUpdate{
  111. PubKey: pubKey,
  112. Power: ev.Validator.Power - 1,
  113. })
  114. app.logger.Info("Decreased val power by 1 because of the equivocation",
  115. "val", addr)
  116. } else {
  117. app.logger.Error("Wanted to punish val, but can't find it",
  118. "val", addr)
  119. }
  120. }
  121. }
  122. respTxs := make([]*types.ResponseDeliverTx, len(req.Txs))
  123. for i, tx := range req.Txs {
  124. respTxs[i] = app.HandleTx(tx)
  125. }
  126. return types.ResponseFinalizeBlock{Txs: respTxs, ValidatorUpdates: app.ValUpdates}
  127. }
  128. func (app *PersistentKVStoreApplication) ListSnapshots(
  129. req types.RequestListSnapshots) types.ResponseListSnapshots {
  130. return types.ResponseListSnapshots{}
  131. }
  132. func (app *PersistentKVStoreApplication) LoadSnapshotChunk(
  133. req types.RequestLoadSnapshotChunk) types.ResponseLoadSnapshotChunk {
  134. return types.ResponseLoadSnapshotChunk{}
  135. }
  136. func (app *PersistentKVStoreApplication) OfferSnapshot(
  137. req types.RequestOfferSnapshot) types.ResponseOfferSnapshot {
  138. return types.ResponseOfferSnapshot{Result: types.ResponseOfferSnapshot_ABORT}
  139. }
  140. func (app *PersistentKVStoreApplication) ApplySnapshotChunk(
  141. req types.RequestApplySnapshotChunk) types.ResponseApplySnapshotChunk {
  142. return types.ResponseApplySnapshotChunk{Result: types.ResponseApplySnapshotChunk_ABORT}
  143. }
  144. func (app *PersistentKVStoreApplication) ExtendVote(
  145. req types.RequestExtendVote) types.ResponseExtendVote {
  146. return types.ResponseExtendVote{
  147. VoteExtension: ConstructVoteExtension(req.Vote.ValidatorAddress),
  148. }
  149. }
  150. func (app *PersistentKVStoreApplication) VerifyVoteExtension(
  151. req types.RequestVerifyVoteExtension) types.ResponseVerifyVoteExtension {
  152. return types.RespondVerifyVoteExtension(
  153. app.verifyExtension(req.Vote.ValidatorAddress, req.Vote.VoteExtension))
  154. }
  155. func (app *PersistentKVStoreApplication) PrepareProposal(
  156. req types.RequestPrepareProposal) types.ResponsePrepareProposal {
  157. return types.ResponsePrepareProposal{BlockData: app.substPrepareTx(req.BlockData)}
  158. }
  159. func (app *PersistentKVStoreApplication) ProcessProposal(
  160. req types.RequestProcessProposal) types.ResponseProcessProposal {
  161. for _, tx := range req.Txs {
  162. if len(tx) == 0 {
  163. return types.ResponseProcessProposal{Result: types.ResponseProcessProposal_REJECT}
  164. }
  165. }
  166. return types.ResponseProcessProposal{Result: types.ResponseProcessProposal_ACCEPT}
  167. }
  168. //---------------------------------------------
  169. // update validators
  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. if err = itr.Error(); err != nil {
  186. panic(err)
  187. }
  188. return
  189. }
  190. func MakeValSetChangeTx(pubkey cryptoproto.PublicKey, power int64) []byte {
  191. pk, err := encoding.PubKeyFromProto(pubkey)
  192. if err != nil {
  193. panic(err)
  194. }
  195. pubStr := base64.StdEncoding.EncodeToString(pk.Bytes())
  196. return []byte(fmt.Sprintf("val:%s!%d", pubStr, power))
  197. }
  198. func isValidatorTx(tx []byte) bool {
  199. return strings.HasPrefix(string(tx), ValidatorSetChangePrefix)
  200. }
  201. // format is "val:pubkey!power"
  202. // pubkey is a base64-encoded 32-byte ed25519 key
  203. func (app *PersistentKVStoreApplication) execValidatorTx(tx []byte) *types.ResponseDeliverTx {
  204. tx = tx[len(ValidatorSetChangePrefix):]
  205. // get the pubkey and power
  206. pubKeyAndPower := strings.Split(string(tx), "!")
  207. if len(pubKeyAndPower) != 2 {
  208. return &types.ResponseDeliverTx{
  209. Code: code.CodeTypeEncodingError,
  210. Log: fmt.Sprintf("Expected 'pubkey!power'. Got %v", pubKeyAndPower)}
  211. }
  212. pubkeyS, powerS := pubKeyAndPower[0], pubKeyAndPower[1]
  213. // decode the pubkey
  214. pubkey, err := base64.StdEncoding.DecodeString(pubkeyS)
  215. if err != nil {
  216. return &types.ResponseDeliverTx{
  217. Code: code.CodeTypeEncodingError,
  218. Log: fmt.Sprintf("Pubkey (%s) is invalid base64", pubkeyS)}
  219. }
  220. // decode the power
  221. power, err := strconv.ParseInt(powerS, 10, 64)
  222. if err != nil {
  223. return &types.ResponseDeliverTx{
  224. Code: code.CodeTypeEncodingError,
  225. Log: fmt.Sprintf("Power (%s) is not an int", powerS)}
  226. }
  227. // update
  228. return app.updateValidator(types.UpdateValidator(pubkey, power, ""))
  229. }
  230. // add, update, or remove a validator
  231. func (app *PersistentKVStoreApplication) updateValidator(v types.ValidatorUpdate) *types.ResponseDeliverTx {
  232. pubkey, err := encoding.PubKeyFromProto(v.PubKey)
  233. if err != nil {
  234. panic(fmt.Errorf("can't decode public key: %w", err))
  235. }
  236. key := []byte("val:" + string(pubkey.Bytes()))
  237. if v.Power == 0 {
  238. // remove validator
  239. hasKey, err := app.app.state.db.Has(key)
  240. if err != nil {
  241. panic(err)
  242. }
  243. if !hasKey {
  244. pubStr := base64.StdEncoding.EncodeToString(pubkey.Bytes())
  245. return &types.ResponseDeliverTx{
  246. Code: code.CodeTypeUnauthorized,
  247. Log: fmt.Sprintf("Cannot remove non-existent validator %s", pubStr)}
  248. }
  249. if err = app.app.state.db.Delete(key); err != nil {
  250. panic(err)
  251. }
  252. delete(app.valAddrToPubKeyMap, string(pubkey.Address()))
  253. } else {
  254. // add or update validator
  255. value := bytes.NewBuffer(make([]byte, 0))
  256. if err := types.WriteMessage(&v, value); err != nil {
  257. return &types.ResponseDeliverTx{
  258. Code: code.CodeTypeEncodingError,
  259. Log: fmt.Sprintf("error encoding validator: %v", err)}
  260. }
  261. if err = app.app.state.db.Set(key, value.Bytes()); err != nil {
  262. panic(err)
  263. }
  264. app.valAddrToPubKeyMap[string(pubkey.Address())] = v.PubKey
  265. }
  266. // we only update the changes array if we successfully updated the tree
  267. app.ValUpdates = append(app.ValUpdates, v)
  268. return &types.ResponseDeliverTx{Code: code.CodeTypeOK}
  269. }
  270. // -----------------------------
  271. const PreparePrefix = "prepare"
  272. func isPrepareTx(tx []byte) bool {
  273. return strings.HasPrefix(string(tx), PreparePrefix)
  274. }
  275. // execPrepareTx is noop. tx data is considered as placeholder
  276. // and is substitute at the PrepareProposal.
  277. func (app *PersistentKVStoreApplication) execPrepareTx(tx []byte) *types.ResponseDeliverTx {
  278. // noop
  279. return &types.ResponseDeliverTx{}
  280. }
  281. // substPrepareTx subst all the preparetx in the blockdata
  282. // to null string(could be any arbitrary string).
  283. func (app *PersistentKVStoreApplication) substPrepareTx(blockData [][]byte) [][]byte {
  284. // TODO: this mechanism will change with the current spec of PrepareProposal
  285. // We now have a special type for marking a tx as changed
  286. for i, tx := range blockData {
  287. if isPrepareTx(tx) {
  288. blockData[i] = make([]byte, len(tx))
  289. }
  290. }
  291. return blockData
  292. }
  293. func ConstructVoteExtension(valAddr []byte) *ptypes.VoteExtension {
  294. return &ptypes.VoteExtension{
  295. AppDataToSign: valAddr,
  296. AppDataSelfAuthenticating: valAddr,
  297. }
  298. }
  299. func (app *PersistentKVStoreApplication) verifyExtension(valAddr []byte, ext *ptypes.VoteExtension) bool {
  300. if ext == nil {
  301. return false
  302. }
  303. canonical := ConstructVoteExtension(valAddr)
  304. if !bytes.Equal(canonical.AppDataToSign, ext.AppDataToSign) {
  305. return false
  306. }
  307. if !bytes.Equal(canonical.AppDataSelfAuthenticating, ext.AppDataSelfAuthenticating) {
  308. return false
  309. }
  310. return true
  311. }