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.

230 lines
6.2 KiB

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. cmn "github.com/tendermint/go-common"
  10. dbm "github.com/tendermint/go-db"
  11. "github.com/tendermint/go-merkle"
  12. "github.com/tendermint/go-wire"
  13. )
  14. const (
  15. ValidatorSetChangePrefix string = "val:"
  16. )
  17. //-----------------------------------------
  18. type PersistentDummyApplication struct {
  19. app *DummyApplication
  20. db dbm.DB
  21. // latest received
  22. // TODO: move to merkle tree?
  23. blockHeader *types.Header
  24. // validator set
  25. changes []*types.Validator
  26. }
  27. func NewPersistentDummyApplication(dbDir string) *PersistentDummyApplication {
  28. db := dbm.NewDB("dummy", "leveldb", dbDir)
  29. lastBlock := LoadLastBlock(db)
  30. stateTree := merkle.NewIAVLTree(0, db)
  31. stateTree.Load(lastBlock.AppHash)
  32. log.Notice("Loaded state", "block", lastBlock.Height, "root", stateTree.Hash())
  33. return &PersistentDummyApplication{
  34. app: &DummyApplication{state: stateTree},
  35. db: db,
  36. }
  37. }
  38. func (app *PersistentDummyApplication) Info() (resInfo types.ResponseInfo) {
  39. resInfo = app.app.Info()
  40. lastBlock := LoadLastBlock(app.db)
  41. resInfo.LastBlockHeight = lastBlock.Height
  42. resInfo.LastBlockAppHash = lastBlock.AppHash
  43. return resInfo
  44. }
  45. func (app *PersistentDummyApplication) SetOption(key string, value string) (log string) {
  46. return app.app.SetOption(key, value)
  47. }
  48. // tx is either "key=value" or just arbitrary bytes
  49. func (app *PersistentDummyApplication) DeliverTx(tx []byte) types.Result {
  50. // if it starts with "val:", update the validator set
  51. // format is "val:pubkey/power"
  52. if isValidatorTx(tx) {
  53. // update validators in the merkle tree
  54. // and in app.changes
  55. return app.execValidatorTx(tx)
  56. }
  57. // otherwise, update the key-value store
  58. return app.app.DeliverTx(tx)
  59. }
  60. func (app *PersistentDummyApplication) CheckTx(tx []byte) types.Result {
  61. return app.app.CheckTx(tx)
  62. }
  63. func (app *PersistentDummyApplication) Commit() types.Result {
  64. // Save
  65. appHash := app.app.state.Save()
  66. log.Info("Saved state", "root", appHash)
  67. lastBlock := LastBlockInfo{
  68. Height: app.blockHeader.Height,
  69. AppHash: appHash, // this hash will be in the next block header
  70. }
  71. SaveLastBlock(app.db, lastBlock)
  72. return types.NewResultOK(appHash, "")
  73. }
  74. func (app *PersistentDummyApplication) Query(reqQuery types.RequestQuery) types.ResponseQuery {
  75. return app.app.Query(reqQuery)
  76. }
  77. // Save the validators in the merkle tree
  78. func (app *PersistentDummyApplication) InitChain(validators []*types.Validator) {
  79. for _, v := range validators {
  80. r := app.updateValidator(v)
  81. if r.IsErr() {
  82. log.Error("Error updating validators", "r", r)
  83. }
  84. }
  85. }
  86. // Track the block hash and header information
  87. func (app *PersistentDummyApplication) BeginBlock(hash []byte, header *types.Header) {
  88. // update latest block info
  89. app.blockHeader = header
  90. // reset valset changes
  91. app.changes = make([]*types.Validator, 0)
  92. }
  93. // Update the validator set
  94. func (app *PersistentDummyApplication) EndBlock(height uint64) (resEndBlock types.ResponseEndBlock) {
  95. return types.ResponseEndBlock{Diffs: app.changes}
  96. }
  97. //-----------------------------------------
  98. // persist the last block info
  99. var lastBlockKey = []byte("lastblock")
  100. type LastBlockInfo struct {
  101. Height uint64
  102. AppHash []byte
  103. }
  104. // Get the last block from the db
  105. func LoadLastBlock(db dbm.DB) (lastBlock LastBlockInfo) {
  106. buf := db.Get(lastBlockKey)
  107. if len(buf) != 0 {
  108. r, n, err := bytes.NewReader(buf), new(int), new(error)
  109. wire.ReadBinaryPtr(&lastBlock, r, 0, n, err)
  110. if *err != nil {
  111. // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED
  112. log.Crit(fmt.Sprintf("Data has been corrupted or its spec has changed: %v\n", *err))
  113. }
  114. // TODO: ensure that buf is completely read.
  115. }
  116. return lastBlock
  117. }
  118. func SaveLastBlock(db dbm.DB, lastBlock LastBlockInfo) {
  119. log.Notice("Saving block", "height", lastBlock.Height, "root", lastBlock.AppHash)
  120. buf, n, err := new(bytes.Buffer), new(int), new(error)
  121. wire.WriteBinary(lastBlock, buf, n, err)
  122. if *err != nil {
  123. // TODO
  124. cmn.PanicCrisis(*err)
  125. }
  126. db.Set(lastBlockKey, buf.Bytes())
  127. }
  128. //---------------------------------------------
  129. // update validators
  130. func (app *PersistentDummyApplication) Validators() (validators []*types.Validator) {
  131. app.app.state.Iterate(func(key, value []byte) bool {
  132. if isValidatorTx(key) {
  133. validator := new(types.Validator)
  134. err := types.ReadMessage(bytes.NewBuffer(value), validator)
  135. if err != nil {
  136. panic(err)
  137. }
  138. validators = append(validators, validator)
  139. }
  140. return false
  141. })
  142. return
  143. }
  144. func MakeValSetChangeTx(pubkey []byte, power uint64) []byte {
  145. return []byte(fmt.Sprintf("val:%X/%d", pubkey, power))
  146. }
  147. func isValidatorTx(tx []byte) bool {
  148. if strings.HasPrefix(string(tx), ValidatorSetChangePrefix) {
  149. return true
  150. }
  151. return false
  152. }
  153. // format is "val:pubkey1/power1,addr2/power2,addr3/power3"tx
  154. func (app *PersistentDummyApplication) execValidatorTx(tx []byte) types.Result {
  155. tx = tx[len(ValidatorSetChangePrefix):]
  156. pubKeyAndPower := strings.Split(string(tx), "/")
  157. if len(pubKeyAndPower) != 2 {
  158. return types.ErrEncodingError.SetLog(fmt.Sprintf("Expected 'pubkey/power'. Got %v", pubKeyAndPower))
  159. }
  160. pubkeyS, powerS := pubKeyAndPower[0], pubKeyAndPower[1]
  161. pubkey, err := hex.DecodeString(pubkeyS)
  162. if err != nil {
  163. return types.ErrEncodingError.SetLog(fmt.Sprintf("Pubkey (%s) is invalid hex", pubkeyS))
  164. }
  165. power, err := strconv.Atoi(powerS)
  166. if err != nil {
  167. return types.ErrEncodingError.SetLog(fmt.Sprintf("Power (%s) is not an int", powerS))
  168. }
  169. // update
  170. return app.updateValidator(&types.Validator{pubkey, uint64(power)})
  171. }
  172. // add, update, or remove a validator
  173. func (app *PersistentDummyApplication) updateValidator(v *types.Validator) types.Result {
  174. key := []byte("val:" + string(v.PubKey))
  175. if v.Power == 0 {
  176. // remove validator
  177. if !app.app.state.Has(key) {
  178. return types.ErrUnauthorized.SetLog(fmt.Sprintf("Cannot remove non-existent validator %X", key))
  179. }
  180. app.app.state.Remove(key)
  181. } else {
  182. // add or update validator
  183. value := bytes.NewBuffer(make([]byte, 0))
  184. if err := types.WriteMessage(v, value); err != nil {
  185. return types.ErrInternalError.SetLog(fmt.Sprintf("Error encoding validator: %v", err))
  186. }
  187. app.app.state.Set(key, value.Bytes())
  188. }
  189. // we only update the changes array if we succesfully updated the tree
  190. app.changes = append(app.changes, v)
  191. return types.OK
  192. }