ledger.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. package blockchain
  2. import (
  3. "bytes"
  4. "compress/gzip"
  5. "context"
  6. "encoding/json"
  7. "io"
  8. "io/ioutil"
  9. "log"
  10. "sync"
  11. "time"
  12. "github.com/mudler/edgevpn/pkg/hub"
  13. "github.com/pkg/errors"
  14. )
  15. type Ledger struct {
  16. sync.Mutex
  17. blockchain Store
  18. channel io.Writer
  19. onDisk bool
  20. }
  21. type Store interface {
  22. Add(Block)
  23. Len() int
  24. Last() Block
  25. }
  26. // New returns a new ledger which writes to the writer
  27. func New(w io.Writer, s Store) *Ledger {
  28. c := &Ledger{channel: w, blockchain: s}
  29. c.newGenesis()
  30. return c
  31. }
  32. func (l *Ledger) newGenesis() {
  33. t := time.Now()
  34. genesisBlock := Block{}
  35. genesisBlock = Block{0, t.String(), map[string]map[string]Data{}, genesisBlock.Checksum(), ""}
  36. l.blockchain.Add(genesisBlock)
  37. }
  38. // Syncronizer starts a goroutine which
  39. // writes the blockchain to the periodically
  40. func (l *Ledger) Syncronizer(ctx context.Context, t time.Duration) {
  41. go func() {
  42. t := time.NewTicker(t)
  43. defer t.Stop()
  44. for {
  45. select {
  46. case <-t.C:
  47. l.Lock()
  48. bytes, err := json.Marshal(l.blockchain.Last())
  49. if err != nil {
  50. log.Println(err)
  51. }
  52. l.channel.Write(compress(bytes).Bytes())
  53. l.Unlock()
  54. case <-ctx.Done():
  55. return
  56. }
  57. }
  58. }()
  59. }
  60. func compress(b []byte) *bytes.Buffer {
  61. var buf bytes.Buffer
  62. gz := gzip.NewWriter(&buf)
  63. gz.Write(b)
  64. gz.Close()
  65. return &buf
  66. }
  67. func deCompress(b []byte) (*bytes.Buffer, error) {
  68. r, err := gzip.NewReader(bytes.NewReader(b))
  69. if err != nil {
  70. return nil, err
  71. }
  72. result, err := ioutil.ReadAll(r)
  73. if err != nil {
  74. return nil, err
  75. }
  76. return bytes.NewBuffer(result), nil
  77. }
  78. // Update the blockchain from a message
  79. func (l *Ledger) Update(h *hub.Message) (err error) {
  80. //chain := make(Blockchain, 0)
  81. block := &Block{}
  82. b, err := deCompress([]byte(h.Message))
  83. if err != nil {
  84. err = errors.Wrap(err, "failed decompressing")
  85. return
  86. }
  87. err = json.Unmarshal(b.Bytes(), block)
  88. if err != nil {
  89. err = errors.Wrap(err, "failed unmarshalling blockchain data")
  90. return
  91. }
  92. l.Lock()
  93. if block.Index > l.blockchain.Len() || (block.Index == l.blockchain.Len() &&
  94. block.Hash != l.blockchain.Last().Hash) {
  95. l.blockchain.Add(*block)
  96. }
  97. l.Unlock()
  98. return
  99. }
  100. // Announce keeps updating async data to the blockchain.
  101. // Sends a broadcast at the specified interval
  102. // by making sure the async retrieved value is written to the
  103. // blockchain
  104. func (l *Ledger) Announce(ctx context.Context, t time.Duration, async func()) {
  105. go func() {
  106. t := time.NewTicker(t)
  107. defer t.Stop()
  108. for {
  109. select {
  110. case <-t.C:
  111. async()
  112. case <-ctx.Done():
  113. return
  114. }
  115. }
  116. }()
  117. }
  118. // AnnounceDeleteBucket Announce a deletion of a bucket. It stops when the bucket is deleted
  119. // It takes an interval time and a max timeout.
  120. // It is best effort, and the timeout is necessary, or we might flood network with requests
  121. // if more writers are attempting to write to the same resource
  122. func (l *Ledger) AnnounceDeleteBucket(ctx context.Context, interval, timeout time.Duration, bucket string) {
  123. del, cancel := context.WithTimeout(ctx, timeout)
  124. l.Announce(del, interval, func() {
  125. _, exists := l.CurrentData()[bucket]
  126. if exists {
  127. l.DeleteBucket(bucket)
  128. } else {
  129. cancel()
  130. }
  131. })
  132. }
  133. // AnnounceDeleteBucketKey Announce a deletion of a key from a bucket. It stops when the key is deleted
  134. func (l *Ledger) AnnounceDeleteBucketKey(ctx context.Context, interval, timeout time.Duration, bucket, key string) {
  135. del, cancel := context.WithTimeout(ctx, timeout)
  136. l.Announce(del, interval, func() {
  137. _, exists := l.CurrentData()[bucket][key]
  138. if exists {
  139. l.Delete(bucket, key)
  140. } else {
  141. cancel()
  142. }
  143. })
  144. }
  145. // Persist Keeps announcing something into the blockchain until it is reconciled
  146. func (l *Ledger) Persist(ctx context.Context, interval, timeout time.Duration, bucket, key string, value interface{}) {
  147. put, cancel := context.WithTimeout(ctx, timeout)
  148. l.Announce(put, interval, func() {
  149. v, exists := l.CurrentData()[bucket][key]
  150. realv, _ := json.Marshal(value)
  151. switch {
  152. case !exists || string(v) != string(realv):
  153. l.Add(bucket, map[string]interface{}{key: value})
  154. case exists && string(v) == string(realv):
  155. cancel()
  156. }
  157. })
  158. }
  159. // GetKey retrieve the current key from the blockchain
  160. func (l *Ledger) GetKey(b, s string) (value Data, exists bool) {
  161. l.Lock()
  162. defer l.Unlock()
  163. if l.blockchain.Len() > 0 {
  164. last := l.blockchain.Last()
  165. if _, exists = last.Storage[b]; !exists {
  166. return
  167. }
  168. value, exists = last.Storage[b][s]
  169. if exists {
  170. return
  171. }
  172. }
  173. return
  174. }
  175. // Exists returns true if there is one element with a matching value
  176. func (l *Ledger) Exists(b string, f func(Data) bool) (exists bool) {
  177. l.Lock()
  178. defer l.Unlock()
  179. if l.blockchain.Len() > 0 {
  180. for _, bv := range l.blockchain.Last().Storage[b] {
  181. if f(bv) {
  182. exists = true
  183. return
  184. }
  185. }
  186. }
  187. return
  188. }
  189. // CurrentData returns the current ledger data (locking)
  190. func (l *Ledger) CurrentData() map[string]map[string]Data {
  191. l.Lock()
  192. defer l.Unlock()
  193. return l.blockchain.Last().Storage
  194. }
  195. // LastBlock returns the last block in the blockchain
  196. func (l *Ledger) LastBlock() Block {
  197. l.Lock()
  198. defer l.Unlock()
  199. return l.blockchain.Last()
  200. }
  201. // Add data to the blockchain
  202. func (l *Ledger) Add(b string, s map[string]interface{}) {
  203. l.Lock()
  204. current := l.blockchain.Last().Storage
  205. for s, k := range s {
  206. if _, exists := current[b]; !exists {
  207. current[b] = make(map[string]Data)
  208. }
  209. dat, _ := json.Marshal(k)
  210. current[b][s] = Data(string(dat))
  211. }
  212. l.Unlock()
  213. l.writeData(current)
  214. }
  215. // Delete data from the ledger (locking)
  216. func (l *Ledger) Delete(b string, k string) {
  217. l.Lock()
  218. new := make(map[string]map[string]Data)
  219. for bb, kk := range l.blockchain.Last().Storage {
  220. if _, exists := new[bb]; !exists {
  221. new[bb] = make(map[string]Data)
  222. }
  223. // Copy all keys/v except b/k
  224. for kkk, v := range kk {
  225. if !(bb == b && kkk == k) {
  226. new[bb][kkk] = v
  227. }
  228. }
  229. }
  230. l.Unlock()
  231. l.writeData(new)
  232. }
  233. // DeleteBucket deletes a bucket from the ledger (locking)
  234. func (l *Ledger) DeleteBucket(b string) {
  235. l.Lock()
  236. new := make(map[string]map[string]Data)
  237. for bb, kk := range l.blockchain.Last().Storage {
  238. // Copy all except the specified bucket
  239. if bb == b {
  240. continue
  241. }
  242. if _, exists := new[bb]; !exists {
  243. new[bb] = make(map[string]Data)
  244. }
  245. for kkk, v := range kk {
  246. new[bb][kkk] = v
  247. }
  248. }
  249. l.Unlock()
  250. l.writeData(new)
  251. }
  252. // String returns the blockchain as string
  253. func (l *Ledger) String() string {
  254. bytes, _ := json.MarshalIndent(l.blockchain, "", " ")
  255. return string(bytes)
  256. }
  257. // Index returns last known blockchain index
  258. func (l *Ledger) Index() int {
  259. return l.blockchain.Len()
  260. }
  261. func (l *Ledger) writeData(s map[string]map[string]Data) {
  262. newBlock := l.blockchain.Last().NewBlock(s)
  263. if newBlock.IsValid(l.blockchain.Last()) {
  264. l.Lock()
  265. l.blockchain.Add(newBlock)
  266. l.Unlock()
  267. }
  268. bytes, err := json.Marshal(l.blockchain.Last())
  269. if err != nil {
  270. log.Println(err)
  271. }
  272. l.channel.Write(compress(bytes).Bytes())
  273. }