-
Notifications
You must be signed in to change notification settings - Fork 651
/
state.go
69 lines (57 loc) · 1.55 KB
/
state.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// (c) 2019-2020, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package avm
import (
"errors"
"github.com/ava-labs/avalanchego/cache"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/vms/components/avax"
)
var (
errCacheTypeMismatch = errors.New("type returned from cache doesn't match the expected type")
)
func uniqueID(id ids.ID, prefix uint64, cacher cache.Cacher) ids.ID {
if cachedIDIntf, found := cacher.Get(id); found {
return cachedIDIntf.(ids.ID)
}
uID := id.Prefix(prefix)
cacher.Put(id, uID)
return uID
}
// state is a thin wrapper around a database to provide, caching, serialization,
// and de-serialization.
type state struct{ avax.State }
// Tx attempts to load a transaction from storage.
func (s *state) Tx(id ids.ID) (*Tx, error) {
if txIntf, found := s.Cache.Get(id); found {
if tx, ok := txIntf.(*Tx); ok {
return tx, nil
}
return nil, errCacheTypeMismatch
}
bytes, err := s.DB.Get(id.Bytes())
if err != nil {
return nil, err
}
// The key was in the database
tx := &Tx{}
if err := s.GenesisCodec.Unmarshal(bytes, tx); err != nil {
return nil, err
}
unsignedBytes, err := s.GenesisCodec.Marshal(&tx.UnsignedTx)
if err != nil {
return nil, err
}
tx.Initialize(unsignedBytes, bytes)
s.Cache.Put(id, tx)
return tx, nil
}
// SetTx saves the provided transaction to storage.
func (s *state) SetTx(id ids.ID, tx *Tx) error {
if tx == nil {
s.Cache.Evict(id)
return s.DB.Delete(id.Bytes())
}
s.Cache.Put(id, tx)
return s.DB.Put(id.Bytes(), tx.Bytes())
}