tendermint/example/counter/counter.go

86 lines
2.1 KiB
Go
Raw Normal View History

2016-02-14 14:59:53 -08:00
package counter
2015-11-29 00:43:49 -08:00
import (
"encoding/binary"
. "github.com/tendermint/go-common"
"github.com/tendermint/tmsp/types"
)
type CounterApplication struct {
hashCount int
txCount int
serial bool
2015-11-29 00:43:49 -08:00
}
func NewCounterApplication(serial bool) *CounterApplication {
return &CounterApplication{serial: serial}
2015-11-29 00:43:49 -08:00
}
2016-12-26 17:44:36 -08:00
func (app *CounterApplication) Info() types.ResponseInfo {
return types.ResponseInfo{Data: Fmt("{\"hashes\":%v,\"txs\":%v}", app.hashCount, app.txCount)}
2015-11-29 00:43:49 -08:00
}
func (app *CounterApplication) SetOption(key string, value string) (log string) {
if key == "serial" && value == "on" {
app.serial = true
}
return ""
2015-11-29 00:43:49 -08:00
}
2017-01-12 12:27:08 -08:00
func (app *CounterApplication) DeliverTx(tx []byte) types.Result {
if app.serial {
2016-11-23 15:22:22 -08:00
if len(tx) > 8 {
return types.ErrEncodingError.SetLog(Fmt("Max tx size is 8 bytes, got %d", len(tx)))
}
tx8 := make([]byte, 8)
copy(tx8[len(tx8)-len(tx):], tx)
txValue := binary.BigEndian.Uint64(tx8)
if txValue != uint64(app.txCount) {
2016-11-21 20:42:42 -08:00
return types.ErrBadNonce.SetLog(Fmt("Invalid nonce. Expected %v, got %v", app.txCount, txValue))
}
}
app.txCount += 1
2016-03-23 02:50:29 -07:00
return types.OK
2015-11-29 00:43:49 -08:00
}
func (app *CounterApplication) CheckTx(tx []byte) types.Result {
if app.serial {
2016-11-23 15:22:22 -08:00
if len(tx) > 8 {
return types.ErrEncodingError.SetLog(Fmt("Max tx size is 8 bytes, got %d", len(tx)))
}
tx8 := make([]byte, 8)
copy(tx8[len(tx8)-len(tx):], tx)
txValue := binary.BigEndian.Uint64(tx8)
if txValue < uint64(app.txCount) {
2016-11-21 20:42:42 -08:00
return types.ErrBadNonce.SetLog(Fmt("Invalid nonce. Expected >= %v, got %v", app.txCount, txValue))
}
}
2016-03-23 02:50:29 -07:00
return types.OK
}
2016-03-23 02:50:29 -07:00
func (app *CounterApplication) Commit() types.Result {
app.hashCount += 1
if app.txCount == 0 {
2016-03-23 02:50:29 -07:00
return types.OK
} else {
hash := make([]byte, 8)
binary.BigEndian.PutUint64(hash, uint64(app.txCount))
2016-03-23 02:50:29 -07:00
return types.NewResultOK(hash, "")
}
2015-11-29 00:43:49 -08:00
}
func (app *CounterApplication) Query(query []byte) types.Result {
2016-12-22 15:24:45 -08:00
queryStr := string(query)
switch queryStr {
case "hash":
return types.NewResultOK(nil, Fmt("%v", app.hashCount))
case "tx":
return types.NewResultOK(nil, Fmt("%v", app.txCount))
}
return types.ErrUnknownRequest.SetLog(Fmt("Invalid nonce. Expected hash or tx, got %v", queryStr))
2015-11-29 00:43:49 -08:00
}