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.

71 lines
1.8 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. package counter
  2. import (
  3. "encoding/binary"
  4. "fmt"
  5. . "github.com/tendermint/go-common"
  6. "github.com/tendermint/tmsp/types"
  7. )
  8. type CounterApplication struct {
  9. hashCount int
  10. txCount int
  11. serial bool
  12. }
  13. func NewCounterApplication(serial bool) *CounterApplication {
  14. return &CounterApplication{serial: serial}
  15. }
  16. func (app *CounterApplication) Info() string {
  17. return Fmt("hashes:%v, txs:%v", app.hashCount, app.txCount)
  18. }
  19. func (app *CounterApplication) SetOption(key string, value string) (log string) {
  20. if key == "serial" && value == "on" {
  21. app.serial = true
  22. }
  23. return ""
  24. }
  25. func (app *CounterApplication) AppendTx(tx []byte) (code types.CodeType, result []byte, log string) {
  26. if app.serial {
  27. tx8 := make([]byte, 8)
  28. copy(tx8[len(tx8)-len(tx):], tx)
  29. txValue := binary.BigEndian.Uint64(tx8)
  30. if txValue != uint64(app.txCount) {
  31. return types.CodeType_BadNonce, nil, fmt.Sprintf("Invalid nonce. Expected %v, got %v", app.txCount, txValue)
  32. }
  33. }
  34. app.txCount += 1
  35. return types.CodeType_OK, nil, ""
  36. }
  37. func (app *CounterApplication) CheckTx(tx []byte) (code types.CodeType, result []byte, log string) {
  38. if app.serial {
  39. tx8 := make([]byte, 8)
  40. copy(tx8[len(tx8)-len(tx):], tx)
  41. txValue := binary.BigEndian.Uint64(tx8)
  42. if txValue < uint64(app.txCount) {
  43. return types.CodeType_BadNonce, nil, fmt.Sprintf("Invalid nonce. Expected >= %v, got %v", app.txCount, txValue)
  44. }
  45. }
  46. return types.CodeType_OK, nil, ""
  47. }
  48. func (app *CounterApplication) Commit() (hash []byte, log string) {
  49. app.hashCount += 1
  50. if app.txCount == 0 {
  51. return nil, ""
  52. } else {
  53. hash := make([]byte, 8)
  54. binary.BigEndian.PutUint64(hash, uint64(app.txCount))
  55. return hash, ""
  56. }
  57. }
  58. func (app *CounterApplication) Query(query []byte) (code types.CodeType, result []byte, log string) {
  59. return types.CodeType_OK, nil, fmt.Sprintf("Query is not supported")
  60. }