accounts: replaced raw KV store with AVL tree
@@ -2,23 +2,24 @@ package wavelet
import (
"encoding/binary"
+ "github.com/perlin-network/wavelet/avl"
"github.com/perlin-network/wavelet/store"
"github.com/pkg/errors"
)
-// TODO(kenta): use a merklized AVL tree w/ versioning instead of raw key/value pairs
type accounts struct {
- kv store.KV
+ tree *avl.Tree
}
func newAccounts(kv store.KV) accounts {
- return accounts{kv: kv}
+ return accounts{tree: avl.New(kv)}
}
func (a accounts) ReadAccountBalance(id []byte) (uint64, error) {
- buf, err := a.kv.Get(append(keyAccounts[:], append(keyAccountBalance[:], id...)...))
- if err != nil {
- return 0, errors.Wrap(err, "failed to load account balance")
+ buf, exists := a.tree.Lookup(append(keyAccounts[:], append(keyAccountBalance[:], id...)...))
+
+ if !exists {
+ return 0, errors.New("accounts: could not find account balance")
}
return binary.LittleEndian.Uint64(buf), nil
@@ -28,7 +29,9 @@ func (a accounts) WriteAccountBalance(id []byte, balance uint64) error {
var buf [8]byte
binary.LittleEndian.PutUint64(buf[:], balance)
- err := a.kv.Put(append(keyAccounts[:], append(keyAccountBalance[:], id...)...), buf[:])
+ a.tree.Insert(append(keyAccounts[:], append(keyAccountBalance[:], id...)...), buf[:])
+
+ err := a.tree.Commit()
if err != nil {
return errors.Wrap(err, "failed to store account balance")
}
