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.

79 lines
1.9 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, *types.TMSPInfo, *types.LastBlockInfo, *types.ConfigInfo) {
  17. return Fmt("hashes:%v, txs:%v", app.hashCount, app.txCount), nil, nil, nil
  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) types.Result {
  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.Result{
  32. Code: types.CodeType_BadNonce,
  33. Data: nil,
  34. Log: fmt.Sprintf("Invalid nonce. Expected %v, got %v", app.txCount, txValue),
  35. }
  36. }
  37. }
  38. app.txCount += 1
  39. return types.OK
  40. }
  41. func (app *CounterApplication) CheckTx(tx []byte) types.Result {
  42. if app.serial {
  43. tx8 := make([]byte, 8)
  44. copy(tx8[len(tx8)-len(tx):], tx)
  45. txValue := binary.BigEndian.Uint64(tx8)
  46. if txValue < uint64(app.txCount) {
  47. return types.Result{
  48. Code: types.CodeType_BadNonce,
  49. Data: nil,
  50. Log: fmt.Sprintf("Invalid nonce. Expected >= %v, got %v", app.txCount, txValue),
  51. }
  52. }
  53. }
  54. return types.OK
  55. }
  56. func (app *CounterApplication) Commit() types.Result {
  57. app.hashCount += 1
  58. if app.txCount == 0 {
  59. return types.OK
  60. } else {
  61. hash := make([]byte, 8)
  62. binary.BigEndian.PutUint64(hash, uint64(app.txCount))
  63. return types.NewResultOK(hash, "")
  64. }
  65. }
  66. func (app *CounterApplication) Query(query []byte) types.Result {
  67. return types.NewResultOK(nil, fmt.Sprintf("Query is not supported"))
  68. }