OSDN Git Service

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