-
Notifications
You must be signed in to change notification settings - Fork 16
/
utils.go
218 lines (200 loc) · 6.03 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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
package p2p
import (
"bytes"
"crypto/ecdsa"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"fmt"
qprotocol "github.com/Qitmeer/qng/core/protocol"
"github.com/Qitmeer/qng/p2p/common"
"github.com/Qitmeer/qng/p2p/iputils"
pb "github.com/Qitmeer/qng/p2p/proto/v1"
"github.com/Qitmeer/qng/p2p/qnr"
"github.com/Qitmeer/qng/params"
"github.com/Qitmeer/qng/version"
ecrypto "github.com/ethereum/go-ethereum/crypto"
"github.com/libp2p/go-libp2p/core/crypto"
"github.com/libp2p/go-libp2p/core/protocol"
"github.com/prysmaticlabs/go-bitfield"
"io/ioutil"
"net"
"os"
"path"
"strings"
"time"
)
const keyPath = "network.key"
const metaDataPath = "metaData"
const PeerStore = "peerstore"
const dialTimeout = 1 * time.Second
// Retrieves an external ipv4 address and converts into a libp2p formatted value.
func IpAddr() net.IP {
ip, err := iputils.ExternalIPv4()
if err != nil {
log.Error(fmt.Sprintf("Could not get IPv4 address: %v", err))
return nil
}
return net.ParseIP(ip)
}
// Determines a private key for p2p networking from the p2p service's
// configuration struct. If no key is found, it generates a new one.
func privKey(cfg *common.Config) (crypto.PrivKey, error) {
return PrivateKey(cfg.DataDir, cfg.PrivateKey, cfg.ReadWritePermissions)
}
// Determines a private key for p2p networking from the p2p service's
// configuration struct. If no key is found, it generates a new one.
func PrivateKey(dataDir string, privateKeyPath string, readWritePermissions os.FileMode) (crypto.PrivKey, error) {
defaultKeyPath := path.Join(dataDir, keyPath)
_, err := os.Stat(defaultKeyPath)
defaultKeysExist := !os.IsNotExist(err)
if err != nil && defaultKeysExist {
return nil, err
}
if privateKeyPath == "" && !defaultKeysExist {
priv, _, err := crypto.GenerateSecp256k1Key(rand.Reader)
if err != nil {
return nil, err
}
rawbytes, err := priv.Raw()
if err != nil {
return nil, err
}
dst := make([]byte, hex.EncodedLen(len(rawbytes)))
hex.Encode(dst, rawbytes)
if err = ioutil.WriteFile(defaultKeyPath, dst, readWritePermissions); err != nil {
return nil, err
}
return priv, nil
}
if defaultKeysExist && privateKeyPath == "" {
privateKeyPath = defaultKeyPath
}
return retrievePrivKeyFromFile(privateKeyPath)
}
func ConvertToInterfacePubkey(pubkey *ecdsa.PublicKey) crypto.PubKey {
cpubKey, err := crypto.ECDSAPublicKeyFromPubKey(*pubkey)
if err != nil {
log.Error(err.Error())
}
return cpubKey
}
// SerializeQNR takes the qnr record in its key-value form and serializes it.
func SerializeQNR(record *qnr.Record) (string, error) {
buf := bytes.NewBuffer([]byte{})
if err := record.EncodeRLP(buf); err != nil {
return "", fmt.Errorf("could not encode ENR record to bytes:%w", err)
}
enrString := base64.URLEncoding.EncodeToString(buf.Bytes())
return enrString, nil
}
// Retrieves a p2p networking private key from a file path.
func retrievePrivKeyFromFile(path string) (crypto.PrivKey, error) {
src, err := ioutil.ReadFile(path)
if err != nil {
log.Error(fmt.Sprintf("Error reading private key from file:%v", err))
return nil, err
}
dst := make([]byte, hex.DecodedLen(len(src)))
_, err = hex.Decode(dst, src)
if err != nil {
return nil, fmt.Errorf("failed to decode hex string:%w", err)
}
unmarshalledKey, err := crypto.UnmarshalSecp256k1PrivateKey(dst)
if err != nil {
return nil, err
}
return unmarshalledKey, nil
}
// Retrieves node p2p metadata from a set of configuration values
// from the p2p service.
func metaDataFromConfig(cfg *common.Config) (*pb.MetaData, error) {
defaultKeyPath := path.Join(cfg.DataDir, metaDataPath)
metaDataPath := cfg.MetaDataDir
_, err := os.Stat(defaultKeyPath)
defaultMetadataExist := !os.IsNotExist(err)
if err != nil && defaultMetadataExist {
return nil, err
}
if metaDataPath == "" && !defaultMetadataExist {
metaData := &pb.MetaData{
SeqNumber: 0,
Subnets: bitfield.NewBitvector64(),
}
dst, err := metaData.Marshal()
if err != nil {
return nil, err
}
if err = ioutil.WriteFile(defaultKeyPath, dst, cfg.ReadWritePermissions); err != nil {
return nil, err
}
return metaData, nil
}
if defaultMetadataExist && metaDataPath == "" {
metaDataPath = defaultKeyPath
}
src, err := ioutil.ReadFile(metaDataPath)
if err != nil {
log.Error(fmt.Sprintf("Error reading metadata from file:%s", err.Error()))
return nil, err
}
metaData := &pb.MetaData{}
if err := metaData.Unmarshal(src); err != nil {
return nil, err
}
return metaData, nil
}
// Attempt to dial an address to verify its connectivity
func verifyConnectivity(addr string, port uint, protocol string) (interface{}, error) {
if addr != "" && len(protocol) > 0 {
a := fmt.Sprintf("%s:%d", addr, port)
conn, err := net.DialTimeout(protocol, a, dialTimeout)
if err != nil {
log.Warn(fmt.Sprintf("IP address is not accessible:protocol=%s address=%s error=%s", protocol, a, err))
return nil, err
}
info := fmt.Sprintf("%s %s OK", conn.RemoteAddr().String(), conn.RemoteAddr().Network())
err = conn.Close()
if err != nil {
log.Warn(fmt.Sprintf("Could not close connection:protocol=%s address=%s error=%s", protocol, a, err))
}
return info, nil
}
return nil, fmt.Errorf("input address is error")
}
func filterBootStrapAddrs(hostID string, addrs []string) []string {
result := []string{}
for _, addr := range addrs {
if strings.HasSuffix(addr, hostID) {
continue
}
result = append(result, addr)
}
return result
}
func BuildUserAgent(name string) string {
return fmt.Sprintf("%s|%s|%s", name, version.String(), params.ActiveNetParams.Name)
}
func ToECDSAPrivKey(privKey crypto.PrivKey) (*ecdsa.PrivateKey, error) {
pkb, err := privKey.Raw()
if err != nil {
return nil, err
}
pk, err := ecrypto.HexToECDSA(hex.EncodeToString(pkb))
if err != nil {
return nil, err
}
return pk, nil
}
func ProtocolDHT() protocol.ID {
switch params.ActiveNetParams.Net {
case qprotocol.MainNet:
return "/qitmeer/kad/1.0.0"
case qprotocol.TestNet:
return "/qitmeer/kad/1.0.0/testnet"
case qprotocol.MixNet:
return "/qitmeer/kad/1.0.0/mixnet"
default:
return "/qitmeer/kad/1.0.0/privnet"
}
}