memorydb.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. // Copyright 2018 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 memorydb implements the key-value database layer based on memory maps.
  17. package memorydb
  18. import (
  19. "errors"
  20. "sort"
  21. "strings"
  22. "sync"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/ethdb"
  25. )
  26. var (
  27. // errMemorydbClosed is returned if a memory database was already closed at the
  28. // invocation of a data access operation.
  29. errMemorydbClosed = errors.New("database closed")
  30. // errMemorydbNotFound is returned if a key is requested that is not found in
  31. // the provided memory database.
  32. errMemorydbNotFound = errors.New("not found")
  33. // errSnapshotReleased is returned if callers want to retrieve data from a
  34. // released snapshot.
  35. errSnapshotReleased = errors.New("snapshot released")
  36. )
  37. // Database is an ephemeral key-value store. Apart from basic data storage
  38. // functionality it also supports batch writes and iterating over the keyspace in
  39. // binary-alphabetical order.
  40. type Database struct {
  41. db map[string][]byte
  42. lock sync.RWMutex
  43. }
  44. // New returns a wrapped map with all the required database interface methods
  45. // implemented.
  46. func New() *Database {
  47. return &Database{
  48. db: make(map[string][]byte),
  49. }
  50. }
  51. // NewWithCap returns a wrapped map pre-allocated to the provided capacity with
  52. // all the required database interface methods implemented.
  53. func NewWithCap(size int) *Database {
  54. return &Database{
  55. db: make(map[string][]byte, size),
  56. }
  57. }
  58. // Close deallocates the internal map and ensures any consecutive data access op
  59. // fails with an error.
  60. func (db *Database) Close() error {
  61. db.lock.Lock()
  62. defer db.lock.Unlock()
  63. db.db = nil
  64. return nil
  65. }
  66. // Has retrieves if a key is present in the key-value store.
  67. func (db *Database) Has(key []byte) (bool, error) {
  68. db.lock.RLock()
  69. defer db.lock.RUnlock()
  70. if db.db == nil {
  71. return false, errMemorydbClosed
  72. }
  73. _, ok := db.db[string(key)]
  74. return ok, nil
  75. }
  76. // Get retrieves the given key if it's present in the key-value store.
  77. func (db *Database) Get(key []byte) ([]byte, error) {
  78. db.lock.RLock()
  79. defer db.lock.RUnlock()
  80. if db.db == nil {
  81. return nil, errMemorydbClosed
  82. }
  83. if entry, ok := db.db[string(key)]; ok {
  84. return common.CopyBytes(entry), nil
  85. }
  86. return nil, errMemorydbNotFound
  87. }
  88. // Put inserts the given value into the key-value store.
  89. func (db *Database) Put(key []byte, value []byte) error {
  90. db.lock.Lock()
  91. defer db.lock.Unlock()
  92. if db.db == nil {
  93. return errMemorydbClosed
  94. }
  95. db.db[string(key)] = common.CopyBytes(value)
  96. return nil
  97. }
  98. // Delete removes the key from the key-value store.
  99. func (db *Database) Delete(key []byte) error {
  100. db.lock.Lock()
  101. defer db.lock.Unlock()
  102. if db.db == nil {
  103. return errMemorydbClosed
  104. }
  105. delete(db.db, string(key))
  106. return nil
  107. }
  108. // NewBatch creates a write-only key-value store that buffers changes to its host
  109. // database until a final write is called.
  110. func (db *Database) NewBatch() ethdb.Batch {
  111. return &batch{
  112. db: db,
  113. }
  114. }
  115. // NewBatchWithSize creates a write-only database batch with pre-allocated buffer.
  116. func (db *Database) NewBatchWithSize(size int) ethdb.Batch {
  117. return &batch{
  118. db: db,
  119. }
  120. }
  121. // NewIterator creates a binary-alphabetical iterator over a subset
  122. // of database content with a particular key prefix, starting at a particular
  123. // initial key (or after, if it does not exist).
  124. func (db *Database) NewIterator(prefix []byte, start []byte) ethdb.Iterator {
  125. db.lock.RLock()
  126. defer db.lock.RUnlock()
  127. var (
  128. pr = string(prefix)
  129. st = string(append(prefix, start...))
  130. keys = make([]string, 0, len(db.db))
  131. values = make([][]byte, 0, len(db.db))
  132. )
  133. // Collect the keys from the memory database corresponding to the given prefix
  134. // and start
  135. for key := range db.db {
  136. if !strings.HasPrefix(key, pr) {
  137. continue
  138. }
  139. if key >= st {
  140. keys = append(keys, key)
  141. }
  142. }
  143. // Sort the items and retrieve the associated values
  144. sort.Strings(keys)
  145. for _, key := range keys {
  146. values = append(values, db.db[key])
  147. }
  148. return &iterator{
  149. index: -1,
  150. keys: keys,
  151. values: values,
  152. }
  153. }
  154. // NewSnapshot creates a database snapshot based on the current state.
  155. // The created snapshot will not be affected by all following mutations
  156. // happened on the database.
  157. func (db *Database) NewSnapshot() (ethdb.Snapshot, error) {
  158. return newSnapshot(db), nil
  159. }
  160. // Stat returns a particular internal stat of the database.
  161. func (db *Database) Stat(property string) (string, error) {
  162. return "", errors.New("unknown property")
  163. }
  164. // Compact is not supported on a memory database, but there's no need either as
  165. // a memory database doesn't waste space anyway.
  166. func (db *Database) Compact(start []byte, limit []byte) error {
  167. return nil
  168. }
  169. // Len returns the number of entries currently present in the memory database.
  170. //
  171. // Note, this method is only used for testing (i.e. not public in general) and
  172. // does not have explicit checks for closed-ness to allow simpler testing code.
  173. func (db *Database) Len() int {
  174. db.lock.RLock()
  175. defer db.lock.RUnlock()
  176. return len(db.db)
  177. }
  178. // keyvalue is a key-value tuple tagged with a deletion field to allow creating
  179. // memory-database write batches.
  180. type keyvalue struct {
  181. key []byte
  182. value []byte
  183. delete bool
  184. }
  185. // batch is a write-only memory batch that commits changes to its host
  186. // database when Write is called. A batch cannot be used concurrently.
  187. type batch struct {
  188. db *Database
  189. writes []keyvalue
  190. size int
  191. }
  192. // Put inserts the given value into the batch for later committing.
  193. func (b *batch) Put(key, value []byte) error {
  194. b.writes = append(b.writes, keyvalue{common.CopyBytes(key), common.CopyBytes(value), false})
  195. b.size += len(key) + len(value)
  196. return nil
  197. }
  198. // Delete inserts the a key removal into the batch for later committing.
  199. func (b *batch) Delete(key []byte) error {
  200. b.writes = append(b.writes, keyvalue{common.CopyBytes(key), nil, true})
  201. b.size += len(key)
  202. return nil
  203. }
  204. // ValueSize retrieves the amount of data queued up for writing.
  205. func (b *batch) ValueSize() int {
  206. return b.size
  207. }
  208. // Write flushes any accumulated data to the memory database.
  209. func (b *batch) Write() error {
  210. b.db.lock.Lock()
  211. defer b.db.lock.Unlock()
  212. for _, keyvalue := range b.writes {
  213. if keyvalue.delete {
  214. delete(b.db.db, string(keyvalue.key))
  215. continue
  216. }
  217. b.db.db[string(keyvalue.key)] = keyvalue.value
  218. }
  219. return nil
  220. }
  221. // Reset resets the batch for reuse.
  222. func (b *batch) Reset() {
  223. b.writes = b.writes[:0]
  224. b.size = 0
  225. }
  226. // Replay replays the batch contents.
  227. func (b *batch) Replay(w ethdb.KeyValueWriter) error {
  228. for _, keyvalue := range b.writes {
  229. if keyvalue.delete {
  230. if err := w.Delete(keyvalue.key); err != nil {
  231. return err
  232. }
  233. continue
  234. }
  235. if err := w.Put(keyvalue.key, keyvalue.value); err != nil {
  236. return err
  237. }
  238. }
  239. return nil
  240. }
  241. // iterator can walk over the (potentially partial) keyspace of a memory key
  242. // value store. Internally it is a deep copy of the entire iterated state,
  243. // sorted by keys.
  244. type iterator struct {
  245. index int
  246. keys []string
  247. values [][]byte
  248. }
  249. // Next moves the iterator to the next key/value pair. It returns whether the
  250. // iterator is exhausted.
  251. func (it *iterator) Next() bool {
  252. // Short circuit if iterator is already exhausted in the forward direction.
  253. if it.index >= len(it.keys) {
  254. return false
  255. }
  256. it.index += 1
  257. return it.index < len(it.keys)
  258. }
  259. // Error returns any accumulated error. Exhausting all the key/value pairs
  260. // is not considered to be an error. A memory iterator cannot encounter errors.
  261. func (it *iterator) Error() error {
  262. return nil
  263. }
  264. // Key returns the key of the current key/value pair, or nil if done. The caller
  265. // should not modify the contents of the returned slice, and its contents may
  266. // change on the next call to Next.
  267. func (it *iterator) Key() []byte {
  268. // Short circuit if iterator is not in a valid position
  269. if it.index < 0 || it.index >= len(it.keys) {
  270. return nil
  271. }
  272. return []byte(it.keys[it.index])
  273. }
  274. // Value returns the value of the current key/value pair, or nil if done. The
  275. // caller should not modify the contents of the returned slice, and its contents
  276. // may change on the next call to Next.
  277. func (it *iterator) Value() []byte {
  278. // Short circuit if iterator is not in a valid position
  279. if it.index < 0 || it.index >= len(it.keys) {
  280. return nil
  281. }
  282. return it.values[it.index]
  283. }
  284. // Release releases associated resources. Release should always succeed and can
  285. // be called multiple times without causing error.
  286. func (it *iterator) Release() {
  287. it.index, it.keys, it.values = -1, nil, nil
  288. }
  289. // snapshot wraps a batch of key-value entries deep copied from the in-memory
  290. // database for implementing the Snapshot interface.
  291. type snapshot struct {
  292. db map[string][]byte
  293. lock sync.RWMutex
  294. }
  295. // newSnapshot initializes the snapshot with the given database instance.
  296. func newSnapshot(db *Database) *snapshot {
  297. db.lock.RLock()
  298. defer db.lock.RUnlock()
  299. copied := make(map[string][]byte)
  300. for key, val := range db.db {
  301. copied[key] = common.CopyBytes(val)
  302. }
  303. return &snapshot{db: copied}
  304. }
  305. // Has retrieves if a key is present in the snapshot backing by a key-value
  306. // data store.
  307. func (snap *snapshot) Has(key []byte) (bool, error) {
  308. snap.lock.RLock()
  309. defer snap.lock.RUnlock()
  310. if snap.db == nil {
  311. return false, errSnapshotReleased
  312. }
  313. _, ok := snap.db[string(key)]
  314. return ok, nil
  315. }
  316. // Get retrieves the given key if it's present in the snapshot backing by
  317. // key-value data store.
  318. func (snap *snapshot) Get(key []byte) ([]byte, error) {
  319. snap.lock.RLock()
  320. defer snap.lock.RUnlock()
  321. if snap.db == nil {
  322. return nil, errSnapshotReleased
  323. }
  324. if entry, ok := snap.db[string(key)]; ok {
  325. return common.CopyBytes(entry), nil
  326. }
  327. return nil, errMemorydbNotFound
  328. }
  329. // Release releases associated resources. Release should always succeed and can
  330. // be called multiple times without causing error.
  331. func (snap *snapshot) Release() {
  332. snap.lock.Lock()
  333. defer snap.lock.Unlock()
  334. snap.db = nil
  335. }