-
Notifications
You must be signed in to change notification settings - Fork 662
/
chain_state.go
63 lines (52 loc) · 1.28 KB
/
chain_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
// Copyright (C) 2019-2021, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package state
import (
"github.com/ava-labs/avalanchego/database"
"github.com/ava-labs/avalanchego/ids"
)
const (
lastAcceptedByte byte = iota
)
var (
lastAcceptedKey = []byte{lastAcceptedByte}
_ ChainState = &chainState{}
)
type ChainState interface {
SetLastAccepted(blkID ids.ID) error
DeleteLastAccepted() error
GetLastAccepted() (ids.ID, error)
}
type chainState struct {
lastAccepted ids.ID
db database.Database
}
func NewChainState(db database.Database) ChainState {
return &chainState{db: db}
}
func (s *chainState) SetLastAccepted(blkID ids.ID) error {
if s.lastAccepted == blkID {
return nil
}
s.lastAccepted = blkID
return s.db.Put(lastAcceptedKey, blkID[:])
}
func (s *chainState) DeleteLastAccepted() error {
s.lastAccepted = ids.Empty
return s.db.Delete(lastAcceptedKey)
}
func (s *chainState) GetLastAccepted() (ids.ID, error) {
if s.lastAccepted != ids.Empty {
return s.lastAccepted, nil
}
lastAcceptedBytes, err := s.db.Get(lastAcceptedKey)
if err != nil {
return ids.ID{}, err
}
lastAccepted, err := ids.ToID(lastAcceptedBytes)
if err != nil {
return ids.ID{}, err
}
s.lastAccepted = lastAccepted
return lastAccepted, nil
}