-
Notifications
You must be signed in to change notification settings - Fork 127
/
badger_asset.go
50 lines (42 loc) · 1.03 KB
/
badger_asset.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package storage
import (
"fmt"
"github.com/MixinNetwork/mixin/common"
"github.com/MixinNetwork/mixin/crypto"
"github.com/dgraph-io/badger"
)
func (s *BadgerStore) WriteAsset(a *common.Asset) error {
if !a.AssetId().HasValue() {
return fmt.Errorf("invalid asset %s %s", a.ChainId.String(), a.AssetKey)
}
txn := s.snapshotsDB.NewTransaction(true)
defer txn.Discard()
key := graphAssetKey(a.AssetId())
val := common.MsgpackMarshalPanic(a)
err := txn.Set(key, val)
if err != nil {
return err
}
return txn.Commit()
}
func (s *BadgerStore) ReadAsset(id crypto.Hash) (*common.Asset, error) {
txn := s.snapshotsDB.NewTransaction(false)
defer txn.Discard()
ival, err := txn.Get(graphAssetKey(id))
if err == badger.ErrKeyNotFound {
return nil, nil
}
if err != nil {
return nil, err
}
v, err := ival.ValueCopy(nil)
if err != nil {
return nil, err
}
var a common.Asset
err = common.MsgpackUnmarshal(v, &a)
return &a, err
}
func graphAssetKey(id crypto.Hash) []byte {
return append([]byte(graphPrefixAsset), id[:]...)
}