-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.go
389 lines (340 loc) · 9.47 KB
/
common.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
// Package common provides utilities to set network options.
package common
import (
"context"
"fmt"
"os"
"path/filepath"
"time"
"github.com/dcnetio/gothreads-lib/core/app"
core "github.com/dcnetio/gothreads-lib/core/logstore"
badger "github.com/dcnetio/gothreads-lib/go-ds-badger"
"github.com/dcnetio/gothreads-lib/go-libp2p-pubsub-rpc/finalizer"
"github.com/dcnetio/gothreads-lib/logstore/lstoreds"
"github.com/dcnetio/gothreads-lib/logstore/lstorehybrid"
"github.com/dcnetio/gothreads-lib/logstore/lstoremem"
"github.com/dcnetio/gothreads-lib/net"
ipfslite "github.com/dcnetio/ipfs-lite"
ds "github.com/ipfs/go-datastore"
"github.com/libp2p/go-libp2p"
cconnmgr "github.com/libp2p/go-libp2p/core/connmgr"
"github.com/libp2p/go-libp2p/core/crypto"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2p/go-libp2p/p2p/host/peerstore/pstoremem"
connmgr "github.com/libp2p/go-libp2p/p2p/net/connmgr"
ma "github.com/multiformats/go-multiaddr"
"google.golang.org/grpc"
)
var HostKey crypto.PrivKey
type NetBoostrapper interface {
app.Net
GetIpfsLite() *ipfslite.Peer
Bootstrap(addrs []peer.AddrInfo)
}
// DefaultNetwork is a boostrapable default Net with sane defaults.
func DefaultNetwork(opts ...NetOption) (NetBoostrapper, error) {
var (
config NetConfig
fin = finalizer.NewFinalizer()
)
for _, opt := range opts {
if err := opt(&config); err != nil {
return nil, err
}
}
if err := setDefaults(&config); err != nil {
return nil, err
}
ctx, cancel := context.WithCancel(context.Background())
fin.Add(finalizer.NewContextCloser(cancel))
litestore, err := persistentStore(ctx, config, "ipfslite", fin)
if err != nil {
return nil, fin.Cleanup(err)
}
//Stores various basic information of connected peers and routing information of libp2p network add by ParkerXie
peerstore, err := persistentStore(ctx, config, "ipfspeer", fin)
if err != nil {
return nil, fin.Cleanup(err)
}
pstore, err := pstoremem.NewPeerstore()
if err != nil {
return nil, fin.Cleanup(err)
}
fin.Add(pstore)
HostKey, err = getIPFSHostKey(config)
if err != nil {
return nil, fin.Cleanup(err)
}
h, d, err := ipfslite.SetupLibp2p(
ctx,
HostKey,
nil,
[]ma.Multiaddr{config.HostAddr},
peerstore,
libp2p.Peerstore(pstore),
libp2p.ConnectionManager(config.ConnManager),
libp2p.DisableRelay(),
)
if err != nil {
return nil, fin.Cleanup(err)
}
lite, err := ipfslite.New(ctx, litestore, nil, h, d, nil)
if err != nil {
return nil, fin.Cleanup(err)
}
tstore, err := buildLogstore(ctx, config, fin)
if err != nil {
return nil, fin.Cleanup(err)
}
// Build a network
api, err := net.NewNetwork(ctx, h, lite.BlockStore(), lite, tstore, net.Config{
NetPullingLimit: config.NetPullingLimit,
NetPullingStartAfter: config.NetPullingStartAfter,
NetPullingInitialInterval: config.NetPullingInitialInterval,
NetPullingInterval: config.NetPullingInterval,
NoNetPulling: config.NoNetPulling,
NoExchangeEdgesMigration: config.NoExchangeEdgesMigration,
PubSub: config.PubSub,
Debug: config.Debug,
}, config.GRPCServerOptions, config.GRPCDialOptions, nil)
if err != nil {
return nil, fin.Cleanup(err)
}
fin.Add(h, d, api)
return &netBoostrapper{
Net: api,
litepeer: lite,
finalizer: fin,
}, nil
}
func buildLogstore(ctx context.Context, config NetConfig, fin *finalizer.Finalizer) (core.Logstore, error) {
switch config.LSType {
case LogstoreInMemory:
return lstoremem.NewLogstore(), nil
case LogstoreHybrid:
pls, err := persistentLogstore(ctx, config, fin)
if err != nil {
return nil, err
}
mls := lstoremem.NewLogstore()
return lstorehybrid.NewLogstore(pls, mls)
case LogstorePersistent:
return persistentLogstore(ctx, config, fin)
default:
return nil, fmt.Errorf("unsupported logstore type: %s", config.LSType)
}
}
func persistentLogstore(ctx context.Context, config NetConfig, fin *finalizer.Finalizer) (core.Logstore, error) {
pds, err := persistentStore(ctx, config, "logstore", fin)
if err != nil {
return nil, err
}
return lstoreds.NewLogstore(ctx, pds, lstoreds.DefaultOpts())
}
func persistentStore(ctx context.Context, config NetConfig, name string, fin *finalizer.Finalizer) (ds.Batching, error) {
return badgerStore(filepath.Join(config.BadgerRepoPath, name), fin)
}
func badgerStore(repoPath string, fin *finalizer.Finalizer) (ds.Batching, error) {
if err := os.MkdirAll(repoPath, os.ModePerm); err != nil {
return nil, err
}
opt := &badger.DefaultOptions
//opt.BypassLockGuard = true
opt.GcDiscardRatio = 0.05
opt.ValueLogFileSize = 1 << 30
opt.ValueThreshold = 1024
dstore, err := badger.NewDatastore(repoPath, opt)
if err != nil {
return nil, err
}
fin.Add(dstore)
return dstore, nil
}
func getIPFSHostKey(config NetConfig) (crypto.PrivKey, error) {
// If a local datastore is used, the key is written to a file
pth := filepath.Join(config.BadgerRepoPath, "key")
_, err := os.Stat(pth)
if os.IsNotExist(err) {
key, bytes, err := newIPFSHostKey()
if err != nil {
return nil, err
}
if err = os.WriteFile(pth, bytes, 0400); err != nil {
return nil, err
}
return key, nil
} else if err != nil {
return nil, err
} else {
bytes, err := os.ReadFile(pth)
if err != nil {
return nil, err
}
return crypto.UnmarshalPrivateKey(bytes)
}
}
func newIPFSHostKey() (crypto.PrivKey, []byte, error) {
priv, _, err := crypto.GenerateKeyPair(crypto.Ed25519, 0)
if err != nil {
return nil, nil, err
}
key, err := crypto.MarshalPrivateKey(priv)
if err != nil {
return nil, nil, err
}
return priv, key, nil
}
func setDefaults(config *NetConfig) (err error) {
if len(config.LSType) == 0 {
config.LSType = LogstorePersistent
}
if len(config.MongoDB) == 0 {
config.MongoDB = "threadnet"
}
if config.NetPullingLimit <= 0 {
config.NetPullingLimit = 10000
}
if config.NetPullingStartAfter <= 0 {
config.NetPullingStartAfter = time.Second
}
if config.NetPullingInitialInterval <= 0 {
config.NetPullingInitialInterval = time.Second
}
if config.NetPullingInterval <= 0 {
config.NetPullingInterval = time.Second * 10
}
if config.HostAddr == nil {
addr, err := ma.NewMultiaddr("/ip4/0.0.0.0/tcp/0")
if err != nil {
return err
}
config.HostAddr = addr
}
if config.ConnManager == nil {
opts := []connmgr.Option{
connmgr.WithGracePeriod(time.Second * 20),
connmgr.WithSilencePeriod(time.Minute * 5),
}
config.ConnManager, err = connmgr.NewConnManager(100, 400, opts...)
if err != nil {
return err
}
}
return nil
}
type LogstoreType string
const (
LogstoreInMemory LogstoreType = "in-memory"
LogstorePersistent LogstoreType = "persistent"
LogstoreHybrid LogstoreType = "hybrid"
)
type NetConfig struct {
NetPullingLimit uint
NetPullingStartAfter time.Duration
NetPullingInitialInterval time.Duration
NetPullingInterval time.Duration
NoNetPulling bool
NoExchangeEdgesMigration bool
PubSub bool
LSType LogstoreType
BadgerRepoPath string
MongoUri string
MongoDB string
HostAddr ma.Multiaddr
ConnManager cconnmgr.ConnManager
GRPCServerOptions []grpc.ServerOption
GRPCDialOptions []grpc.DialOption
Debug bool
}
type NetOption func(c *NetConfig) error
func WithNetPulling(threadLimit uint, startAfter, initialInterval, interval time.Duration) NetOption {
return func(c *NetConfig) error {
c.NetPullingLimit = threadLimit
c.NetPullingStartAfter = startAfter
c.NetPullingInitialInterval = initialInterval
c.NetPullingInterval = interval
return nil
}
}
func WithNoNetPulling(disable bool) NetOption {
return func(c *NetConfig) error {
c.NoNetPulling = disable
return nil
}
}
func WithNoExchangeEdgesMigration(disable bool) NetOption {
return func(c *NetConfig) error {
c.NoExchangeEdgesMigration = disable
return nil
}
}
func WithNetPubSub(enabled bool) NetOption {
return func(c *NetConfig) error {
c.PubSub = enabled
return nil
}
}
func WithNetLogstore(lt LogstoreType) NetOption {
return func(c *NetConfig) error {
c.LSType = lt
return nil
}
}
func WithNetBadgerPersistence(repoPath string) NetOption {
return func(c *NetConfig) error {
c.BadgerRepoPath = repoPath
return nil
}
}
func WithNetMongoPersistence(uri, db string) NetOption {
return func(c *NetConfig) error {
c.MongoUri = uri
c.MongoDB = db
return nil
}
}
func WithNetHostAddr(addr ma.Multiaddr) NetOption {
return func(c *NetConfig) error {
c.HostAddr = addr
return nil
}
}
func WithConnectionManager(cm cconnmgr.ConnManager) NetOption {
return func(c *NetConfig) error {
c.ConnManager = cm
return nil
}
}
func WithNetGRPCServerOptions(opts ...grpc.ServerOption) NetOption {
return func(c *NetConfig) error {
c.GRPCServerOptions = opts
return nil
}
}
func WithNetGRPCDialOptions(opts ...grpc.DialOption) NetOption {
return func(c *NetConfig) error {
c.GRPCDialOptions = opts
return nil
}
}
func WithNetDebug(enabled bool) NetOption {
return func(c *NetConfig) error {
c.Debug = enabled
return nil
}
}
type netBoostrapper struct {
app.Net
litepeer *ipfslite.Peer
finalizer *finalizer.Finalizer
}
var _ NetBoostrapper = (*netBoostrapper)(nil)
func (tsb *netBoostrapper) Bootstrap(addrs []peer.AddrInfo) {
tsb.litepeer.Bootstrap(addrs)
}
func (tsb *netBoostrapper) GetIpfsLite() *ipfslite.Peer {
return tsb.litepeer
}
func (tsb *netBoostrapper) Close() error {
return tsb.finalizer.Cleanup(nil)
}