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.

78 lines
2.0 KiB

  1. package merkletree
  2. import (
  3. "bytes"
  4. "crypto/sha256"
  5. "errors"
  6. )
  7. // ErrNotFound is used by the implementations of the interface db.Storage for
  8. // when a key is not found in the storage
  9. var ErrNotFound = errors.New("key not found")
  10. // Storage is the interface that defines the methods for the storage used in
  11. // the merkletree. Examples of the interface implementation can be found at
  12. // db/memory and db/leveldb directories.
  13. type Storage interface {
  14. NewTx() (Tx, error)
  15. WithPrefix(prefix []byte) Storage
  16. Get([]byte) (*Node, error)
  17. GetRoot() (*Hash, error)
  18. List(int) ([]KV, error)
  19. Close()
  20. Iterate(func([]byte, *Node) (bool, error)) error
  21. }
  22. // Tx is the interface that defines the methods for the db transaction used in
  23. // the merkletree storage. Examples of the interface implementation can be
  24. // found at db/memory and db/leveldb directories.
  25. type Tx interface {
  26. // Get retrieves the value for the given key
  27. // looking first in the content of the Tx, and
  28. // then into the content of the Storage
  29. Get([]byte) (*Node, error)
  30. GetRoot() (*Hash, error)
  31. SetRoot(*Hash) error
  32. // Put sets the key & value into the Tx
  33. Put(k []byte, v *Node) error
  34. // Add adds the given Tx into the Tx
  35. Add(Tx) error
  36. Commit() error
  37. Close()
  38. }
  39. // KV contains a key (K) and a value (V)
  40. type KV struct {
  41. K []byte
  42. V Node
  43. }
  44. // KvMap is a key-value map between a sha256 byte array hash, and a KV struct
  45. type KvMap map[[sha256.Size]byte]KV
  46. // Get retrieves the value respective to a key from the KvMap
  47. func (m KvMap) Get(k []byte) (Node, bool) {
  48. v, ok := m[sha256.Sum256(k)]
  49. return v.V, ok
  50. }
  51. // Put stores a key and a value in the KvMap
  52. func (m KvMap) Put(k []byte, v Node) {
  53. m[sha256.Sum256(k)] = KV{k, v}
  54. }
  55. // Concat concatenates arrays of bytes
  56. func Concat(vs ...[]byte) []byte {
  57. var b bytes.Buffer
  58. for _, v := range vs {
  59. b.Write(v)
  60. }
  61. return b.Bytes()
  62. }
  63. // Clone clones a byte array into a new byte array
  64. func Clone(b0 []byte) []byte {
  65. b1 := make([]byte, len(b0))
  66. copy(b1, b0)
  67. return b1
  68. }