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.

221 lines
6.1 KiB

7 years ago
8 years ago
8 years ago
8 years ago
8 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 dummy
  2. import (
  3. "bytes"
  4. "encoding/hex"
  5. "fmt"
  6. "strconv"
  7. "strings"
  8. "github.com/tendermint/abci/example/code"
  9. "github.com/tendermint/abci/types"
  10. crypto "github.com/tendermint/go-crypto"
  11. "github.com/tendermint/iavl"
  12. cmn "github.com/tendermint/tmlibs/common"
  13. dbm "github.com/tendermint/tmlibs/db"
  14. "github.com/tendermint/tmlibs/log"
  15. )
  16. const (
  17. ValidatorSetChangePrefix string = "val:"
  18. )
  19. //-----------------------------------------
  20. var _ types.Application = (*PersistentDummyApplication)(nil)
  21. type PersistentDummyApplication struct {
  22. app *DummyApplication
  23. // validator set
  24. changes []*types.Validator
  25. logger log.Logger
  26. }
  27. func NewPersistentDummyApplication(dbDir string) *PersistentDummyApplication {
  28. name := "dummy"
  29. db, err := dbm.NewGoLevelDB(name, dbDir)
  30. if err != nil {
  31. panic(err)
  32. }
  33. stateTree := iavl.NewVersionedTree(500, db)
  34. stateTree.Load()
  35. return &PersistentDummyApplication{
  36. app: &DummyApplication{state: stateTree},
  37. logger: log.NewNopLogger(),
  38. }
  39. }
  40. func (app *PersistentDummyApplication) SetLogger(l log.Logger) {
  41. app.logger = l
  42. }
  43. func (app *PersistentDummyApplication) Info(req types.RequestInfo) types.ResponseInfo {
  44. res := app.app.Info(req)
  45. res.LastBlockHeight = app.app.state.LatestVersion()
  46. res.LastBlockAppHash = app.app.state.Hash()
  47. return res
  48. }
  49. func (app *PersistentDummyApplication) 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 *PersistentDummyApplication) DeliverTx(tx []byte) types.ResponseDeliverTx {
  54. // if it starts with "val:", update the validator set
  55. // format is "val:pubkey/power"
  56. if isValidatorTx(tx) {
  57. // update validators in the merkle tree
  58. // and in app.changes
  59. return app.execValidatorTx(tx)
  60. }
  61. // otherwise, update the key-value store
  62. return app.app.DeliverTx(tx)
  63. }
  64. func (app *PersistentDummyApplication) CheckTx(tx []byte) types.ResponseCheckTx {
  65. return app.app.CheckTx(tx)
  66. }
  67. // Commit will panic if InitChain was not called
  68. func (app *PersistentDummyApplication) Commit() types.ResponseCommit {
  69. // Save a new version for next height
  70. height := app.app.state.LatestVersion() + 1
  71. var appHash []byte
  72. var err error
  73. appHash, err = app.app.state.SaveVersion(height)
  74. if err != nil {
  75. // if this wasn't a dummy app, we'd do something smarter
  76. panic(err)
  77. }
  78. app.logger.Info("Commit block", "height", height, "root", appHash)
  79. return types.ResponseCommit{Code: code.CodeTypeOK, Data: appHash}
  80. }
  81. func (app *PersistentDummyApplication) Query(reqQuery types.RequestQuery) types.ResponseQuery {
  82. return app.app.Query(reqQuery)
  83. }
  84. // Save the validators in the merkle tree
  85. func (app *PersistentDummyApplication) InitChain(req types.RequestInitChain) types.ResponseInitChain {
  86. for _, v := range req.Validators {
  87. r := app.updateValidator(v)
  88. if r.IsErr() {
  89. app.logger.Error("Error updating validators", "r", r)
  90. }
  91. }
  92. return types.ResponseInitChain{}
  93. }
  94. // Track the block hash and header information
  95. func (app *PersistentDummyApplication) BeginBlock(req types.RequestBeginBlock) types.ResponseBeginBlock {
  96. // reset valset changes
  97. app.changes = make([]*types.Validator, 0)
  98. return types.ResponseBeginBlock{}
  99. }
  100. // Update the validator set
  101. func (app *PersistentDummyApplication) EndBlock(req types.RequestEndBlock) types.ResponseEndBlock {
  102. return types.ResponseEndBlock{Diffs: app.changes}
  103. }
  104. //---------------------------------------------
  105. // update validators
  106. func (app *PersistentDummyApplication) Validators() (validators []*types.Validator) {
  107. app.app.state.Iterate(func(key, value []byte) bool {
  108. if isValidatorTx(key) {
  109. validator := new(types.Validator)
  110. err := types.ReadMessage(bytes.NewBuffer(value), validator)
  111. if err != nil {
  112. panic(err)
  113. }
  114. validators = append(validators, validator)
  115. }
  116. return false
  117. })
  118. return
  119. }
  120. func MakeValSetChangeTx(pubkey []byte, power uint64) []byte {
  121. return []byte(cmn.Fmt("val:%X/%d", pubkey, power))
  122. }
  123. func isValidatorTx(tx []byte) bool {
  124. return strings.HasPrefix(string(tx), ValidatorSetChangePrefix)
  125. }
  126. // format is "val:pubkey1/power1,addr2/power2,addr3/power3"tx
  127. func (app *PersistentDummyApplication) execValidatorTx(tx []byte) types.ResponseDeliverTx {
  128. tx = tx[len(ValidatorSetChangePrefix):]
  129. //get the pubkey and power
  130. pubKeyAndPower := strings.Split(string(tx), "/")
  131. if len(pubKeyAndPower) != 2 {
  132. return types.ResponseDeliverTx{
  133. Code: code.CodeTypeEncodingError,
  134. Log: fmt.Sprintf("Expected 'pubkey/power'. Got %v", pubKeyAndPower)}
  135. }
  136. pubkeyS, powerS := pubKeyAndPower[0], pubKeyAndPower[1]
  137. // decode the pubkey, ensuring its go-crypto encoded
  138. pubkey, err := hex.DecodeString(pubkeyS)
  139. if err != nil {
  140. return types.ResponseDeliverTx{
  141. Code: code.CodeTypeEncodingError,
  142. Log: fmt.Sprintf("Pubkey (%s) is invalid hex", pubkeyS)}
  143. }
  144. _, err = crypto.PubKeyFromBytes(pubkey)
  145. if err != nil {
  146. return types.ResponseDeliverTx{
  147. Code: code.CodeTypeEncodingError,
  148. Log: fmt.Sprintf("Pubkey (%X) is invalid go-crypto encoded", pubkey)}
  149. }
  150. // decode the power
  151. power, err := strconv.Atoi(powerS)
  152. if err != nil {
  153. return types.ResponseDeliverTx{
  154. Code: code.CodeTypeEncodingError,
  155. Log: fmt.Sprintf("Power (%s) is not an int", powerS)}
  156. }
  157. // update
  158. return app.updateValidator(&types.Validator{pubkey, uint64(power)})
  159. }
  160. // add, update, or remove a validator
  161. func (app *PersistentDummyApplication) updateValidator(v *types.Validator) types.ResponseDeliverTx {
  162. key := []byte("val:" + string(v.PubKey))
  163. if v.Power == 0 {
  164. // remove validator
  165. if !app.app.state.Has(key) {
  166. return types.ResponseDeliverTx{
  167. Code: code.CodeTypeUnauthorized,
  168. Log: fmt.Sprintf("Cannot remove non-existent validator %X", key)}
  169. }
  170. app.app.state.Remove(key)
  171. } else {
  172. // add or update validator
  173. value := bytes.NewBuffer(make([]byte, 0))
  174. if err := types.WriteMessage(v, value); err != nil {
  175. return types.ResponseDeliverTx{
  176. Code: code.CodeTypeEncodingError,
  177. Log: fmt.Sprintf("Error encoding validator: %v", err)}
  178. }
  179. app.app.state.Set(key, value.Bytes())
  180. }
  181. // we only update the changes array if we successfully updated the tree
  182. app.changes = append(app.changes, v)
  183. return types.ResponseDeliverTx{Code: code.CodeTypeOK}
  184. }