/
persistency.go
68 lines (56 loc) · 1.34 KB
/
persistency.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
package bridge
import (
"encoding/json"
"os"
)
type Blockheight struct {
LastHeight uint64 `json:"lastHeight"`
StellarCursor string `json:"stellarCursor"`
}
type ChainPersistency struct {
location string
}
// newChainPersistency creates new ChainPersistency object and returns a reference to it.
func newChainPersistency(location string) *ChainPersistency {
return &ChainPersistency{
location: location,
}
}
func (b *ChainPersistency) saveHeight(height uint64) error {
blockheight, err := b.GetHeight()
if err != nil {
return err
}
blockheight.LastHeight = height
return b.Save(blockheight)
}
func (b *ChainPersistency) saveStellarCursor(cursor string) error {
blockheight, err := b.GetHeight()
if err != nil {
return err
}
blockheight.StellarCursor = cursor
return b.Save(blockheight)
}
func (b *ChainPersistency) GetHeight() (*Blockheight, error) {
var blockheight Blockheight
file, err := os.ReadFile(b.location)
if os.IsNotExist(err) {
return &blockheight, nil
}
if err != nil {
return nil, err
}
err = json.Unmarshal(file, &blockheight)
if err != nil {
return nil, err
}
return &blockheight, nil
}
func (b *ChainPersistency) Save(blockheight *Blockheight) error {
updatedPersistency, err := json.Marshal(blockheight)
if err != nil {
return err
}
return os.WriteFile(b.location, updatedPersistency, 0644)
}