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.

216 lines
6.0 KiB

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