forked from textileio/go-threads
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
205 lines (185 loc) · 4.73 KB
/
util.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
package util
import (
"crypto/rand"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/alecthomas/jsonschema"
ipfslite "github.com/hsanjuan/ipfs-lite"
logging "github.com/ipfs/go-log/v2"
"github.com/libp2p/go-libp2p-core/crypto"
"github.com/libp2p/go-libp2p-core/peer"
swarm "github.com/libp2p/go-libp2p-swarm"
ma "github.com/multiformats/go-multiaddr"
"github.com/phayes/freeport"
core "github.com/singyiu/go-threads/core/db"
"github.com/tidwall/sjson"
"go.uber.org/zap/zapcore"
)
var (
bootstrapPeers = []string{
"/ip4/104.210.43.77/tcp/4001/p2p/QmR69wtWUMm1TWnmuD4JqC1TWLZcc8iR2KrTenfZZbiztd", // us-west-1 hub ipfs host
"/ip4/104.210.43.77/tcp/4006/p2p/12D3KooWQEtCBXMKjVas6Ph1pUHG2T4Lc9j1KvnAipojP2xcKU7n", // us-west-1 hub threads host
}
)
// CanDial returns whether or not the address is dialable.
func CanDial(addr ma.Multiaddr, s *swarm.Swarm) bool {
parts := strings.Split(addr.String(), "/"+ma.ProtocolWithCode(ma.P_P2P).Name)
addr, _ = ma.NewMultiaddr(parts[0])
tr := s.TransportForDialing(addr)
return tr != nil && tr.CanDial(addr)
}
// SetupDefaultLoggingConfig sets up a standard logging configuration.
func SetupDefaultLoggingConfig(repoPath string) error {
folder := filepath.Join(repoPath, "log")
if err := os.MkdirAll(folder, os.ModePerm); err != nil {
return err
}
c := logging.Config{
Format: logging.ColorizedOutput,
Stderr: true,
File: filepath.Join(folder, "threads.log"),
Level: logging.LevelError,
}
logging.SetupLogging(c)
return nil
}
// SetLogLevels sets levels for the given systems.
func SetLogLevels(systems map[string]logging.LogLevel) error {
for sys, level := range systems {
l := zapcore.Level(level)
if sys == "*" {
for _, s := range logging.GetSubsystems() {
if err := logging.SetLogLevel(s, l.CapitalString()); err != nil {
return err
}
}
}
if err := logging.SetLogLevel(sys, l.CapitalString()); err != nil {
return err
}
}
return nil
}
func LoadKey(pth string) crypto.PrivKey {
var priv crypto.PrivKey
_, err := os.Stat(pth)
if os.IsNotExist(err) {
priv, _, err = crypto.GenerateKeyPair(crypto.Ed25519, 0)
if err != nil {
panic(err)
}
key, err := crypto.MarshalPrivateKey(priv)
if err != nil {
panic(err)
}
if err = ioutil.WriteFile(pth, key, 0400); err != nil {
panic(err)
}
} else if err != nil {
panic(err)
} else {
key, err := ioutil.ReadFile(pth)
if err != nil {
panic(err)
}
priv, err = crypto.UnmarshalPrivateKey(key)
if err != nil {
panic(err)
}
}
return priv
}
func DefaultBoostrapPeers() []peer.AddrInfo {
ipfspeers := ipfslite.DefaultBootstrapPeers()
textilepeers, err := ParseBootstrapPeers(bootstrapPeers)
if err != nil {
panic("coudn't parse default bootstrap peers")
}
return append(textilepeers, ipfspeers...)
}
func ParseBootstrapPeers(addrs []string) ([]peer.AddrInfo, error) {
maddrs := make([]ma.Multiaddr, len(addrs))
for i, addr := range addrs {
var err error
maddrs[i], err = ma.NewMultiaddr(addr)
if err != nil {
return nil, err
}
}
return peer.AddrInfosFromP2pAddrs(maddrs...)
}
func TCPAddrFromMultiAddr(maddr ma.Multiaddr) (addr string, err error) {
if maddr == nil {
err = fmt.Errorf("invalid address")
return
}
ip4, err := maddr.ValueForProtocol(ma.P_IP4)
if err != nil {
return
}
tcp, err := maddr.ValueForProtocol(ma.P_TCP)
if err != nil {
return
}
return fmt.Sprintf("%s:%s", ip4, tcp), nil
}
func MustParseAddr(str string) ma.Multiaddr {
addr, err := ma.NewMultiaddr(str)
if err != nil {
panic(err)
}
return addr
}
func FreeLocalAddr() ma.Multiaddr {
hostPort, err := freeport.GetFreePort()
if err != nil {
return nil
}
return MustParseAddr(fmt.Sprintf("/ip4/127.0.0.1/tcp/%d", hostPort))
}
func SchemaFromInstance(i interface{}, expandedStruct bool) *jsonschema.Schema {
reflector := jsonschema.Reflector{ExpandedStruct: expandedStruct}
return reflector.Reflect(i)
}
func SchemaFromSchemaString(s string) *jsonschema.Schema {
schemaBytes := []byte(s)
schema := &jsonschema.Schema{}
if err := json.Unmarshal(schemaBytes, schema); err != nil {
panic(err)
}
return schema
}
func JSONFromInstance(i interface{}) []byte {
JSON, err := json.Marshal(i)
if err != nil {
panic(err)
}
return JSON
}
func InstanceFromJSON(b []byte, i interface{}) {
if err := json.Unmarshal(b, i); err != nil {
panic(err)
}
}
func SetJSONProperty(name string, value interface{}, json []byte) []byte {
updated, err := sjson.SetBytes(json, name, value)
if err != nil {
panic(err)
}
return updated
}
func SetJSONID(id core.InstanceID, json []byte) []byte {
return SetJSONProperty("_id", id.String(), json)
}
func GenerateRandomBytes(n int) []byte {
b := make([]byte, n)
_, err := rand.Read(b)
if err != nil {
panic(err)
}
return b
}