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.

112 lines
2.0 KiB

  1. package batch
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/vocdoni/go-dvote/db"
  6. "github.com/vocdoni/go-dvote/types"
  7. )
  8. var rdb *db.LevelDbStorage
  9. var bdb *db.LevelDbStorage
  10. var BatchSignal chan bool
  11. var BatchSize int
  12. var err error
  13. func Setup(l *db.LevelDbStorage) {
  14. rdb = l.WithPrefix([]byte("relay_"))
  15. bdb = l.WithPrefix([]byte("batch_"))
  16. }
  17. func Recieve(messages <-chan types.Message) {
  18. var message types.Message
  19. var payload []byte
  20. var e types.Envelope
  21. var b types.Ballot
  22. for {
  23. message = <-messages
  24. payload = message.Data
  25. err = json.Unmarshal(payload, &e)
  26. if err != nil {
  27. //log error
  28. }
  29. err = json.Unmarshal(e.Ballot, &b)
  30. if err != nil {
  31. //log error
  32. }
  33. err = Add(b)
  34. if err != nil {
  35. //log error
  36. }
  37. fmt.Println("Got > " + string(payload))
  38. }
  39. }
  40. //add (queue for counting)
  41. func Add(ballot types.Ballot) error {
  42. //this is probably adding []
  43. //err := bdb.Put(fmt.Sprintf("%v", p.Nullifier)),[]byte(fmt.Sprintf("%v", p)))
  44. var b []byte
  45. var n []byte
  46. var err error
  47. b, err = json.Marshal(ballot)
  48. n, err = json.Marshal(ballot.Nullifier)
  49. err = bdb.Put(n, b)
  50. if err != nil {
  51. return err
  52. }
  53. //this actually needs to see if it was added
  54. if bdb.Count() >= BatchSize {
  55. BatchSignal <- true
  56. }
  57. return nil
  58. }
  59. //create (return batch)
  60. //k is []byte 'batch_' + nullifier
  61. //v is []byte package
  62. //returns slice of nullifiers, batch json
  63. func Fetch() ([]string, []string) {
  64. var n []string
  65. var b []string
  66. iter := bdb.Iter()
  67. for iter.Next() {
  68. k := iter.Key()
  69. v := iter.Value()
  70. err := iter.Error()
  71. if err != nil {
  72. panic(err)
  73. }
  74. n = append(n, string(k[6:]))
  75. b = append(b, string(v))
  76. }
  77. iter.Release()
  78. // jn, err := json.Marshal(n)
  79. // if err != nil {
  80. // panic(err)
  81. // }
  82. // jb, err := json.Marshal(b)
  83. // if err != nil {
  84. // panic(err)
  85. // }
  86. return n, b
  87. }
  88. //move from bdb to rdb once pinned
  89. func Compact(n []string) {
  90. for _, k := range n {
  91. //fmt.Println(k)
  92. v, err := bdb.Get([]byte(k))
  93. if err != nil {
  94. fmt.Println(err.Error())
  95. }
  96. rdb.Put([]byte(k), v)
  97. bdb.Delete([]byte(k))
  98. }
  99. }