-
Notifications
You must be signed in to change notification settings - Fork 175
/
utils.go
174 lines (150 loc) · 5.77 KB
/
utils.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
package cmd
import (
"encoding/hex"
"encoding/json"
"fmt"
"path/filepath"
"strings"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/rs/zerolog"
"github.com/onflow/flow-go/crypto"
"github.com/onflow/flow-go/model/bootstrap"
"github.com/onflow/flow-go/model/flow"
"github.com/onflow/flow-go/module"
"github.com/onflow/flow-go/module/id"
"github.com/onflow/flow-go/network/p2p"
"github.com/onflow/flow-go/network/p2p/cache"
p2plogging "github.com/onflow/flow-go/network/p2p/logging"
"github.com/onflow/flow-go/network/p2p/translator"
"github.com/onflow/flow-go/network/p2p/unicast/protocols"
"github.com/onflow/flow-go/state/protocol/inmem"
"github.com/onflow/flow-go/utils/io"
)
// loadRootProtocolSnapshot loads the root protocol snapshot from disk
func loadRootProtocolSnapshot(dir string) (*inmem.Snapshot, error) {
path := filepath.Join(dir, bootstrap.PathRootProtocolStateSnapshot)
data, err := io.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("could not read root snapshot (path=%s): %w", path, err)
}
var snapshot inmem.EncodableSnapshot
err = json.Unmarshal(data, &snapshot)
if err != nil {
return nil, err
}
return inmem.SnapshotFromEncodable(snapshot), nil
}
// LoadPrivateNodeInfo the private info for this node from disk (e.g., private staking/network keys).
func LoadPrivateNodeInfo(dir string, myID flow.Identifier) (*bootstrap.NodeInfoPriv, error) {
path := filepath.Join(dir, fmt.Sprintf(bootstrap.PathNodeInfoPriv, myID))
data, err := io.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("could not read private node info (path=%s): %w", path, err)
}
var info bootstrap.NodeInfoPriv
err = json.Unmarshal(data, &info)
return &info, err
}
func LoadNetworkPrivateKey(dir string, myID flow.Identifier) (crypto.PrivateKey, error) {
path := filepath.Join(dir, fmt.Sprintf(filepath.Join(bootstrap.DirPrivateRoot,
"private-node-info_%v/network_private_key"), myID))
data, err := io.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("could not read private node info (path=%s): %w", path, err)
}
keyBytes, err := hex.DecodeString(strings.Trim(string(data), "\n "))
if err != nil {
return nil, fmt.Errorf("could not hex decode networking key (path=%s): %w", path, err)
}
networkingKey, err := crypto.DecodePrivateKey(crypto.ECDSASecp256k1, keyBytes)
if err != nil {
return nil, fmt.Errorf("could not decode networking key (path=%s): %w", path, err)
}
return networkingKey, nil
}
// loadSecretsEncryptionKey loads the encryption key for the secrets database.
// If the file does not exist, returns os.ErrNotExist.
func loadSecretsEncryptionKey(dir string, myID flow.Identifier) ([]byte, error) {
path := filepath.Join(dir, fmt.Sprintf(bootstrap.PathSecretsEncryptionKey, myID))
data, err := io.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("could not read secrets db encryption key (path=%s): %w", path, err)
}
return data, nil
}
func rateLimiterPeerFilter(rateLimiter p2p.RateLimiter) p2p.PeerFilter {
return func(p peer.ID) error {
if rateLimiter.IsRateLimited(p) {
return fmt.Errorf("peer is rate limited")
}
return nil
}
}
// BootstrapIdentities converts the bootstrap node addresses and keys to a Flow Identity list where
// each Flow Identity is initialized with the passed address, the networking key
// and the Node ID set to ZeroID, role set to Access, 0 stake and no staking key.
func BootstrapIdentities(addresses []string, keys []string) (flow.IdentityList, error) {
if len(addresses) != len(keys) {
return nil, fmt.Errorf("number of addresses and keys provided for the boostrap nodes don't match")
}
ids := make(flow.IdentityList, len(addresses))
for i, address := range addresses {
bytes, err := hex.DecodeString(keys[i])
if err != nil {
return nil, fmt.Errorf("failed to decode secured GRPC server public key hex %w", err)
}
publicFlowNetworkingKey, err := crypto.DecodePublicKey(crypto.ECDSAP256, bytes)
if err != nil {
return nil, fmt.Errorf("failed to get public flow networking key could not decode public key bytes %w", err)
}
// create the identity of the peer by setting only the relevant fields
ids[i] = &flow.Identity{
NodeID: flow.ZeroID, // the NodeID is the hash of the staking key and for the public network it does not apply
Address: address,
Role: flow.RoleAccess, // the upstream node has to be an access node
NetworkPubKey: publicFlowNetworkingKey,
}
}
return ids, nil
}
func CreatePublicIDTranslatorAndIdentifierProvider(
logger zerolog.Logger,
networkKey crypto.PrivateKey,
sporkID flow.Identifier,
getLibp2pNode func() p2p.LibP2PNode,
idCache *cache.ProtocolStateIDCache,
) (
p2p.IDTranslator,
func() module.IdentifierProvider,
error,
) {
idTranslator := translator.NewHierarchicalIDTranslator(idCache, translator.NewPublicNetworkIDTranslator())
peerID, err := peerIDFromNetworkKey(networkKey)
if err != nil {
return nil, nil, fmt.Errorf("could not get peer ID from network key: %w", err)
}
// use the default identifier provider
factory := func() module.IdentifierProvider {
return id.NewCustomIdentifierProvider(func() flow.IdentifierList {
pids := getLibp2pNode().GetPeersForProtocol(protocols.FlowProtocolID(sporkID))
result := make(flow.IdentifierList, 0, len(pids))
for _, pid := range pids {
// exclude own Identifier
if pid == peerID {
continue
}
if flowID, err := idTranslator.GetFlowID(pid); err != nil {
// TODO: this is an instance of "log error and continue with best effort" anti-pattern
logger.Fatal().Err(err).Str("peer", p2plogging.PeerId(pid)).Msg("failed to translate to Flow ID")
} else {
result = append(result, flowID)
}
}
if len(result) == 0 {
logger.Error().Msgf("empty identifier list, pids: %v", pids)
}
return result
})
}
return idTranslator, factory, nil
}