clientdb.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. // Copyright 2020 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package server
  17. import (
  18. "bytes"
  19. "encoding/binary"
  20. "time"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/common/mclock"
  23. "github.com/ethereum/go-ethereum/ethdb"
  24. "github.com/ethereum/go-ethereum/les/utils"
  25. "github.com/ethereum/go-ethereum/log"
  26. "github.com/ethereum/go-ethereum/p2p/enode"
  27. "github.com/ethereum/go-ethereum/rlp"
  28. lru "github.com/hashicorp/golang-lru"
  29. )
  30. const (
  31. balanceCacheLimit = 8192 // the maximum number of cached items in service token balance queue
  32. // nodeDBVersion is the version identifier of the node data in db
  33. //
  34. // Changelog:
  35. // Version 0 => 1
  36. // * Replace `lastTotal` with `meta` in positive balance: version 0=>1
  37. //
  38. // Version 1 => 2
  39. // * Positive Balance and negative balance is changed:
  40. // * Cumulative time is replaced with expiration
  41. nodeDBVersion = 2
  42. // dbCleanupCycle is the cycle of db for useless data cleanup
  43. dbCleanupCycle = time.Hour
  44. )
  45. var (
  46. positiveBalancePrefix = []byte("pb:") // dbVersion(uint16 big endian) + positiveBalancePrefix + id -> balance
  47. negativeBalancePrefix = []byte("nb:") // dbVersion(uint16 big endian) + negativeBalancePrefix + ip -> balance
  48. expirationKey = []byte("expiration:") // dbVersion(uint16 big endian) + expirationKey -> posExp, negExp
  49. )
  50. type nodeDB struct {
  51. db ethdb.KeyValueStore
  52. cache *lru.Cache
  53. auxbuf []byte // 37-byte auxiliary buffer for key encoding
  54. verbuf [2]byte // 2-byte auxiliary buffer for db version
  55. evictCallBack func(mclock.AbsTime, bool, utils.ExpiredValue) bool // Callback to determine whether the balance can be evicted.
  56. clock mclock.Clock
  57. closeCh chan struct{}
  58. cleanupHook func() // Test hook used for testing
  59. }
  60. func newNodeDB(db ethdb.KeyValueStore, clock mclock.Clock) *nodeDB {
  61. cache, _ := lru.New(balanceCacheLimit)
  62. ndb := &nodeDB{
  63. db: db,
  64. cache: cache,
  65. auxbuf: make([]byte, 37),
  66. clock: clock,
  67. closeCh: make(chan struct{}),
  68. }
  69. binary.BigEndian.PutUint16(ndb.verbuf[:], uint16(nodeDBVersion))
  70. go ndb.expirer()
  71. return ndb
  72. }
  73. func (db *nodeDB) close() {
  74. close(db.closeCh)
  75. }
  76. func (db *nodeDB) getPrefix(neg bool) []byte {
  77. prefix := positiveBalancePrefix
  78. if neg {
  79. prefix = negativeBalancePrefix
  80. }
  81. return append(db.verbuf[:], prefix...)
  82. }
  83. func (db *nodeDB) key(id []byte, neg bool) []byte {
  84. prefix := positiveBalancePrefix
  85. if neg {
  86. prefix = negativeBalancePrefix
  87. }
  88. if len(prefix)+len(db.verbuf)+len(id) > len(db.auxbuf) {
  89. db.auxbuf = append(db.auxbuf, make([]byte, len(prefix)+len(db.verbuf)+len(id)-len(db.auxbuf))...)
  90. }
  91. copy(db.auxbuf[:len(db.verbuf)], db.verbuf[:])
  92. copy(db.auxbuf[len(db.verbuf):len(db.verbuf)+len(prefix)], prefix)
  93. copy(db.auxbuf[len(prefix)+len(db.verbuf):len(prefix)+len(db.verbuf)+len(id)], id)
  94. return db.auxbuf[:len(prefix)+len(db.verbuf)+len(id)]
  95. }
  96. func (db *nodeDB) getExpiration() (utils.Fixed64, utils.Fixed64) {
  97. blob, err := db.db.Get(append(db.verbuf[:], expirationKey...))
  98. if err != nil || len(blob) != 16 {
  99. return 0, 0
  100. }
  101. return utils.Fixed64(binary.BigEndian.Uint64(blob[:8])), utils.Fixed64(binary.BigEndian.Uint64(blob[8:16]))
  102. }
  103. func (db *nodeDB) setExpiration(pos, neg utils.Fixed64) {
  104. var buff [16]byte
  105. binary.BigEndian.PutUint64(buff[:8], uint64(pos))
  106. binary.BigEndian.PutUint64(buff[8:16], uint64(neg))
  107. db.db.Put(append(db.verbuf[:], expirationKey...), buff[:16])
  108. }
  109. func (db *nodeDB) getOrNewBalance(id []byte, neg bool) utils.ExpiredValue {
  110. key := db.key(id, neg)
  111. item, exist := db.cache.Get(string(key))
  112. if exist {
  113. return item.(utils.ExpiredValue)
  114. }
  115. var b utils.ExpiredValue
  116. enc, err := db.db.Get(key)
  117. if err != nil || len(enc) == 0 {
  118. return b
  119. }
  120. if err := rlp.DecodeBytes(enc, &b); err != nil {
  121. log.Crit("Failed to decode positive balance", "err", err)
  122. }
  123. db.cache.Add(string(key), b)
  124. return b
  125. }
  126. func (db *nodeDB) setBalance(id []byte, neg bool, b utils.ExpiredValue) {
  127. key := db.key(id, neg)
  128. enc, err := rlp.EncodeToBytes(&(b))
  129. if err != nil {
  130. log.Crit("Failed to encode positive balance", "err", err)
  131. }
  132. db.db.Put(key, enc)
  133. db.cache.Add(string(key), b)
  134. }
  135. func (db *nodeDB) delBalance(id []byte, neg bool) {
  136. key := db.key(id, neg)
  137. db.db.Delete(key)
  138. db.cache.Remove(string(key))
  139. }
  140. // getPosBalanceIDs returns a lexicographically ordered list of IDs of accounts
  141. // with a positive balance
  142. func (db *nodeDB) getPosBalanceIDs(start, stop enode.ID, maxCount int) (result []enode.ID) {
  143. if maxCount <= 0 {
  144. return
  145. }
  146. prefix := db.getPrefix(false)
  147. keylen := len(prefix) + len(enode.ID{})
  148. it := db.db.NewIterator(prefix, start.Bytes())
  149. defer it.Release()
  150. for it.Next() {
  151. var id enode.ID
  152. if len(it.Key()) != keylen {
  153. return
  154. }
  155. copy(id[:], it.Key()[keylen-len(id):])
  156. if bytes.Compare(id.Bytes(), stop.Bytes()) >= 0 {
  157. return
  158. }
  159. result = append(result, id)
  160. if len(result) == maxCount {
  161. return
  162. }
  163. }
  164. return
  165. }
  166. // forEachBalance iterates all balances and passes values to callback.
  167. func (db *nodeDB) forEachBalance(neg bool, callback func(id enode.ID, balance utils.ExpiredValue) bool) {
  168. prefix := db.getPrefix(neg)
  169. keylen := len(prefix) + len(enode.ID{})
  170. it := db.db.NewIterator(prefix, nil)
  171. defer it.Release()
  172. for it.Next() {
  173. var id enode.ID
  174. if len(it.Key()) != keylen {
  175. return
  176. }
  177. copy(id[:], it.Key()[keylen-len(id):])
  178. var b utils.ExpiredValue
  179. if err := rlp.DecodeBytes(it.Value(), &b); err != nil {
  180. continue
  181. }
  182. if !callback(id, b) {
  183. return
  184. }
  185. }
  186. }
  187. func (db *nodeDB) expirer() {
  188. for {
  189. select {
  190. case <-db.clock.After(dbCleanupCycle):
  191. db.expireNodes()
  192. case <-db.closeCh:
  193. return
  194. }
  195. }
  196. }
  197. // expireNodes iterates the whole node db and checks whether the
  198. // token balances can be deleted.
  199. func (db *nodeDB) expireNodes() {
  200. var (
  201. visited int
  202. deleted int
  203. start = time.Now()
  204. )
  205. for _, neg := range []bool{false, true} {
  206. iter := db.db.NewIterator(db.getPrefix(neg), nil)
  207. for iter.Next() {
  208. visited++
  209. var balance utils.ExpiredValue
  210. if err := rlp.DecodeBytes(iter.Value(), &balance); err != nil {
  211. log.Crit("Failed to decode negative balance", "err", err)
  212. }
  213. if db.evictCallBack != nil && db.evictCallBack(db.clock.Now(), neg, balance) {
  214. deleted++
  215. db.db.Delete(iter.Key())
  216. }
  217. }
  218. }
  219. // Invoke testing hook if it's not nil.
  220. if db.cleanupHook != nil {
  221. db.cleanupHook()
  222. }
  223. log.Debug("Expire nodes", "visited", visited, "deleted", deleted, "elapsed", common.PrettyDuration(time.Since(start)))
  224. }