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.

229 lines
6.1 KiB

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