forked from celestiaorg/celestia-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pidstore.go
77 lines (63 loc) · 1.93 KB
/
pidstore.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
70
71
72
73
74
75
76
77
package pidstore
import (
"context"
"encoding/json"
"fmt"
"github.com/ipfs/go-datastore"
"github.com/ipfs/go-datastore/namespace"
logging "github.com/ipfs/go-log/v2"
"github.com/libp2p/go-libp2p/core/peer"
)
var (
storePrefix = datastore.NewKey("pidstore")
peersKey = datastore.NewKey("peers")
log = logging.Logger("pidstore")
)
// PeerIDStore is used to store/load peers to/from disk.
type PeerIDStore struct {
ds datastore.Datastore
}
// NewPeerIDStore creates a new peer ID store backed by the given datastore.
func NewPeerIDStore(ctx context.Context, ds datastore.Datastore) (*PeerIDStore, error) {
pidstore := &PeerIDStore{
ds: namespace.Wrap(ds, storePrefix),
}
// check if pidstore is already initialized, and if not,
// initialize the pidstore
exists, err := pidstore.ds.Has(ctx, peersKey)
if err != nil {
return nil, err
}
if !exists {
return pidstore, pidstore.Put(ctx, []peer.ID{})
}
return pidstore, nil
}
// Load loads the peers from datastore and returns them.
func (p *PeerIDStore) Load(ctx context.Context) ([]peer.ID, error) {
log.Debug("Loading peers")
bin, err := p.ds.Get(ctx, peersKey)
if err != nil {
return nil, fmt.Errorf("pidstore: loading peers from datastore: %w", err)
}
var peers []peer.ID
err = json.Unmarshal(bin, &peers)
if err != nil {
return nil, fmt.Errorf("pidstore: unmarshalling peer IDs: %w", err)
}
log.Infow("Loaded peers from disk", "amount", len(peers))
return peers, nil
}
// Put persists the given peer IDs to the datastore.
func (p *PeerIDStore) Put(ctx context.Context, peers []peer.ID) error {
log.Debugw("Persisting peers to disk", "amount", len(peers))
bin, err := json.Marshal(peers)
if err != nil {
return fmt.Errorf("pidstore: marshal peerlist: %w", err)
}
if err = p.ds.Put(ctx, peersKey, bin); err != nil {
return fmt.Errorf("pidstore: error writing to datastore: %w", err)
}
log.Infow("Persisted peers successfully", "amount", len(peers))
return nil
}