-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathipfs.go
851 lines (712 loc) · 19.4 KB
/
ipfs.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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
package ipfs
import (
"bytes"
"context"
"fmt"
"github.com/idena-network/idena-go/common"
"github.com/idena-network/idena-go/common/eventbus"
"github.com/idena-network/idena-go/common/math"
"github.com/idena-network/idena-go/config"
"github.com/idena-network/idena-go/crypto"
"github.com/idena-network/idena-go/events"
"github.com/idena-network/idena-go/log"
"github.com/ipfs/go-blockservice"
"github.com/ipfs/go-cid"
"github.com/ipfs/go-ipfs-files"
dag "github.com/ipfs/go-merkledag"
dagtest "github.com/ipfs/go-merkledag/test"
"github.com/ipfs/go-mfs"
ft "github.com/ipfs/go-unixfs"
"github.com/ipfs/interface-go-ipfs-core/options"
"github.com/ipfs/interface-go-ipfs-core/path"
ipfsConf "github.com/ipfs/kubo/config"
serialize "github.com/ipfs/kubo/config/serialize"
"github.com/ipfs/kubo/core"
"github.com/ipfs/kubo/core/coreapi"
"github.com/ipfs/kubo/core/corerepo"
"github.com/ipfs/kubo/core/coreunix"
"github.com/ipfs/kubo/plugin/loader"
"github.com/ipfs/kubo/repo/fsrepo"
core2 "github.com/libp2p/go-libp2p-core"
pubsub "github.com/libp2p/go-libp2p-pubsub"
"github.com/multiformats/go-multihash"
"github.com/patrickmn/go-cache"
"github.com/pkg/errors"
"github.com/whyrusleeping/go-logging"
"io"
"io/ioutil"
"math/rand"
"net"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
)
const (
CidLength = 36
ZeroPeersTimeout = 2 * time.Minute
)
type DataType = uint32
const (
Block DataType = 1
Flip DataType = 2
Profile DataType = 3
TxReceipt DataType = 4
CustomData DataType = 5
)
var (
EmptyCid cid.Cid
MinCid [CidLength]byte
MaxCid [CidLength]byte
TooBigErr = errors.New("ipfs data is too big")
)
func init() {
e, _ := cid.Decode("bafkreihdwdcefgh4dqkjv67uzcmw7ojee6xedzdetojuzjevtenxquvyku")
EmptyCid = e
for i := range MaxCid {
MaxCid[i] = 0xFF
}
}
type Proxy interface {
Add(data []byte, pin bool) (cid.Cid, error)
Get(key []byte, dataType DataType) ([]byte, error)
LoadTo(key []byte, to io.Writer, ctx context.Context, onLoading func(size, loaded int64)) error
Pin(key []byte) error
Unpin(key []byte) error
Cid(data []byte) (cid.Cid, error)
Port() int
PeerId() string
AddFile(absPath string, data io.ReadCloser, fi os.FileInfo) (cid.Cid, error)
Host() core2.Host
ShouldPin(dataType DataType) bool
GetWithSizeLimit(key []byte, dataType DataType, size int64) ([]byte, error)
PubSub() *pubsub.PubSub
GC() (ctx context.Context, cancel context.CancelFunc)
}
type ipfsProxy struct {
node *core.IpfsNode
log log.Logger
cidCache *cache.Cache
rwLock sync.RWMutex
cfg *config.IpfsConfig
nodeCtx context.Context
nodeCtxCancel context.CancelFunc
nilNode *core.IpfsNode
lastPeersUpdatedTime time.Time
bus eventbus.Bus
gcMutex sync.RWMutex
}
func (p *ipfsProxy) Host() core2.Host {
return p.node.PeerHost
}
func (p *ipfsProxy) PubSub() *pubsub.PubSub {
return p.node.PubSub
}
func NewIpfsProxy(cfg *config.IpfsConfig, bus eventbus.Bus) (Proxy, error) {
logging.SetLevel(0, "core")
err := loadPlugins(cfg)
if err != nil {
return nil, err
}
logger := log.New()
node, ctx, cancelCtx, err := createNode(cfg, bus)
if err != nil {
return nil, err
}
nilNode, err := core.NewNode(context.Background(), &core.BuildCfg{
NilRepo: true,
})
if err != nil {
return nil, err
}
logger.Info("Ipfs initialized", "peerId", node.PeerHost.ID().Pretty())
c := cache.New(2*time.Minute, 5*time.Minute)
p := &ipfsProxy{
node: node,
log: logger,
cfg: cfg,
cidCache: c,
nodeCtx: ctx,
nodeCtxCancel: cancelCtx,
lastPeersUpdatedTime: time.Now().UTC(),
nilNode: nilNode,
bus: bus,
}
go p.watchPeers()
return p, nil
}
func createNode(cfg *config.IpfsConfig, eventBus eventbus.Bus) (*core.IpfsNode, context.Context, context.CancelFunc, error) {
dataDir, _ := filepath.Abs(cfg.DataDir)
if ln, err := net.Listen("tcp", ":"+strconv.Itoa(cfg.IpfsPort)); err == nil {
ln.Close()
} else {
return nil, nil, func() {}, errors.Errorf("cannot start IPFS node on port %v, err: %v", cfg.IpfsPort, err.Error())
}
_, err := configureIpfs(cfg, eventBus)
if err != nil {
return nil, nil, func() {}, err
}
ctx, cancelCtx := context.WithCancel(context.Background())
node, err := core.NewNode(ctx, getNodeConfig(dataDir))
if err != nil {
cancelCtx()
return nil, nil, func() {}, err
}
return node, ctx, cancelCtx, nil
}
func (p *ipfsProxy) GC() (ctx context.Context, cancel context.CancelFunc) {
ctx, cancel = context.WithCancel(p.nodeCtx)
go p.gc(ctx, cancel)
return
}
func (p *ipfsProxy) gc(ctx context.Context, cancel context.CancelFunc) {
p.gcMutex.Lock()
defer p.gcMutex.Unlock()
if err := corerepo.ConditionalGC(ctx, p.node, 0); err != nil {
p.log.Debug("ipfs gc error", "err", err)
}
cancel()
}
func (p *ipfsProxy) changePort() {
p.rwLock.Lock()
defer p.rwLock.Unlock()
p.log.Info("Start changing IPFS port", "current", p.cfg.IpfsPort)
p.nodeCtxCancel()
c, cancel := context.WithTimeout(context.Background(), time.Second*30)
defer cancel()
select {
case <-c.Done():
p.log.Error("timeout while stopping IPFS")
case <-p.nodeCtx.Done():
}
for {
p.cfg.IpfsPort += 1
node, ctx, cancelCtx, err := createNode(p.cfg, p.bus)
if err != nil {
continue
}
p.node = node
p.nodeCtx = ctx
p.nodeCtxCancel = cancelCtx
p.bus.Publish(&events.IpfsPortChangedEvent{Host: node.PeerHost, PubSub: node.PubSub})
p.log.Info("Finish changing IPFS port", "new", p.cfg.IpfsPort)
break
}
}
func (p *ipfsProxy) watchPeers() {
api, _ := coreapi.NewCoreAPI(p.node)
logger := log.New("component", "ipfs watch")
for {
if !p.cfg.StaticPort && time.Now().UTC().Sub(p.lastPeersUpdatedTime) > ZeroPeersTimeout {
p.changePort()
api, _ = coreapi.NewCoreAPI(p.node)
p.lastPeersUpdatedTime = time.Now().UTC()
}
info, err := api.Swarm().Peers(context.Background())
if err != nil {
logger.Info("peers info", "err", err)
}
if len(info) > 0 {
p.lastPeersUpdatedTime = time.Now().UTC()
}
if p.cfg.PublishPeers {
p.bus.Publish(&events.PeersEvent{
PeersData: info,
Time: time.Now(),
})
}
logger.Trace("last time with non-peers", "time", p.lastPeersUpdatedTime, "peers count", len(info))
time.Sleep(time.Second * 10)
}
}
func (p *ipfsProxy) ShouldPin(dataType DataType) bool {
q := rand.Float32()
if dataType == Block {
return q <= p.cfg.BlockPinThreshold
}
if dataType == Flip {
return q <= p.cfg.FlipPinThreshold
}
return true
}
func (p *ipfsProxy) maxSize(dataType DataType) int64 {
switch dataType {
case Flip:
return common.MaxFlipSize
case Profile:
return common.MaxProfileSize
case CustomData:
return common.MaxCustomDataSize
default:
return -1
}
}
func (p *ipfsProxy) Add(data []byte, pin bool) (cid.Cid, error) {
if len(data) == 0 {
return EmptyCid, nil
}
p.gcMutex.RLock()
defer p.gcMutex.RUnlock()
p.rwLock.RLock()
defer p.rwLock.RUnlock()
api, _ := coreapi.NewCoreAPI(p.node)
file := files.NewBytesFile(data)
defer file.Close()
var ipfsPath path.Resolved
var err error
for num := 5; num > 0; num-- {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
ipfsPath, err = api.Unixfs().Add(ctx, file, options.Unixfs.Pin(pin), options.Unixfs.CidVersion(1))
select {
case <-ctx.Done():
err = errors.New("timeout while writing data to ipfs")
default:
break
}
cancel()
if err == nil {
break
}
file = files.NewBytesFile(data)
defer file.Close()
time.Sleep(1 * time.Second)
}
if err != nil {
return cid.Cid{}, err
}
p.log.Debug("Add ipfs data", "cid", ipfsPath.Cid().String())
return ipfsPath.Cid(), nil
}
func (p *ipfsProxy) AddFile(absPath string, data io.ReadCloser, fi os.FileInfo) (cid.Cid, error) {
p.rwLock.RLock()
defer p.rwLock.RUnlock()
p.gcMutex.RLock()
defer p.gcMutex.RUnlock()
api, _ := coreapi.NewCoreAPI(p.node)
ctx, cancel := context.WithTimeout(context.Background(), time.Hour*1)
defer cancel()
file, _ := files.NewReaderPathFile(absPath, data, fi)
defer file.Close()
path, err := api.Unixfs().Add(ctx, file, options.Unixfs.Pin(true), options.Unixfs.Nocopy(true), options.Unixfs.CidVersion(1))
select {
case <-ctx.Done():
err = errors.New("timeout while writing data to ipfs from reader")
default:
break
}
if err != nil {
return cid.Cid{}, err
}
p.log.Debug("Add ipfs data from reader", "cid", path.Cid().String())
return path.Cid(), nil
}
func (p *ipfsProxy) Get(key []byte, dataType DataType) ([]byte, error) {
if len(key) == 0 {
return []byte{}, nil
}
c, err := cid.Cast(key)
if err != nil {
return nil, err
}
if c == EmptyCid {
return []byte{}, nil
}
return p.get(path.IpfsPath(c), dataType, 0)
}
func (p *ipfsProxy) GetWithSizeLimit(key []byte, dataType DataType, maxSize int64) ([]byte, error) {
if len(key) == 0 {
return []byte{}, nil
}
c, err := cid.Cast(key)
if err != nil {
return nil, err
}
if c == EmptyCid {
return []byte{}, nil
}
return p.get(path.IpfsPath(c), dataType, maxSize)
}
func (p *ipfsProxy) get(path path.Path, dataType DataType, maxSize int64) ([]byte, error) {
p.rwLock.RLock()
defer p.rwLock.RUnlock()
p.gcMutex.RLock()
defer p.gcMutex.RUnlock()
api, _ := coreapi.NewCoreAPI(p.node)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
defer cancel()
f, err := api.Unixfs().Get(ctx, path)
select {
case <-ctx.Done():
err = errors.New("timeout while reading data from ipfs")
default:
break
}
if err != nil {
info, _ := api.Swarm().Peers(context.Background())
p.log.Error("fail to read from ipfs", "cid", path.String(), "err", err, "peers", len(info))
return nil, err
}
file := files.ToFile(f)
defer file.Close()
if maxSize == 0 {
maxSize = p.maxSize(dataType)
} else {
dataTypeMaxSize := p.maxSize(dataType)
if dataTypeMaxSize > 0 {
maxSize = int64(math.MinInt(int(maxSize), int(dataTypeMaxSize)))
}
}
if maxSize > 0 {
size, err := file.Size()
if err != nil {
return nil, err
}
if size > maxSize {
return nil, TooBigErr
}
}
buf := new(bytes.Buffer)
_, err = buf.ReadFrom(file)
if err != nil {
return nil, err
}
p.log.Debug("read data from ipfs", "cid", path.String())
return buf.Bytes(), nil
}
func (p *ipfsProxy) LoadTo(key []byte, to io.Writer, ctx context.Context, onLoading func(size, loaded int64)) error {
if len(key) == 0 {
return nil
}
c, err := cid.Cast(key)
if err != nil {
return err
}
if c == EmptyCid {
return nil
}
p.rwLock.RLock()
defer p.rwLock.RUnlock()
p.gcMutex.RLock()
defer p.gcMutex.RUnlock()
api, _ := coreapi.NewCoreAPI(p.node)
f, err := api.Unixfs().Get(ctx, path.IpfsPath(c))
select {
case <-ctx.Done():
return errors.New("ipfs load: context canceled")
default:
break
}
file := files.ToFile(f)
defer file.Close()
size, err := file.Size()
if err != nil {
return err
}
_, err = io.Copy(to, &progressReader{r: file, size: size, onLoading: onLoading})
return err
}
func (p *ipfsProxy) Pin(key []byte) error {
p.rwLock.RLock()
defer p.rwLock.RUnlock()
api, _ := coreapi.NewCoreAPI(p.node)
c, err := cid.Cast(key)
if err != nil {
return err
}
p.gcMutex.RLock()
defer p.gcMutex.RUnlock()
ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
defer cancel()
err = api.Pin().Add(ctx, path.IpfsPath(c))
select {
case <-ctx.Done():
err = errors.Errorf("timeout while pinning data to ipfs, key: %v", c.String())
default:
break
}
return err
}
func (p *ipfsProxy) Unpin(key []byte) error {
p.rwLock.RLock()
defer p.rwLock.RUnlock()
api, _ := coreapi.NewCoreAPI(p.node)
c, err := cid.Cast(key)
if err != nil {
return err
}
p.gcMutex.RLock()
defer p.gcMutex.RUnlock()
ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
defer cancel()
err = api.Pin().Rm(ctx, path.IpfsPath(c))
select {
case <-ctx.Done():
err = errors.Errorf("timeout while unpin data from ipfs, key: %v", c.String())
default:
break
}
return err
}
func (p *ipfsProxy) Port() int {
return p.cfg.IpfsPort
}
func (p *ipfsProxy) PeerId() string {
return p.node.PeerHost.ID().Pretty()
}
func (p *ipfsProxy) Cid(data []byte) (cid.Cid, error) {
if len(data) == 0 {
return EmptyCid, nil
}
hash := crypto.Hash(data)
cacheKey := string(hash[:])
if value, ok := p.cidCache.Get(cacheKey); ok {
return value.(cid.Cid), nil
}
nilnode := p.nilNode
addblockstore := nilnode.Blockstore
exch := nilnode.Exchange
pinning := nilnode.Pinning
bserv := blockservice.New(addblockstore, exch) // hash security 001
dserv := dag.NewDAGService(bserv)
ctx := context.Background()
fileAdder, err := coreunix.NewAdder(ctx, pinning, addblockstore, dserv)
if err != nil {
return EmptyCid, err
}
settings, prefix, err := options.UnixfsAddOptions(options.Unixfs.CidVersion(1))
fileAdder.Chunker = settings.Chunker
fileAdder.Pin = false
fileAdder.RawLeaves = settings.RawLeaves
fileAdder.CidBuilder = prefix
md := dagtest.Mock()
emptyDirNode := ft.EmptyDirNode()
// Use the same prefix for the "empty" MFS root as for the file adder.
emptyDirNode.SetCidBuilder(fileAdder.CidBuilder)
mr, err := mfs.NewRoot(ctx, md, emptyDirNode, nil)
if err != nil {
return EmptyCid, err
}
fileAdder.SetMfsRoot(mr)
file := files.NewBytesFile(data)
defer file.Close()
nd, err := fileAdder.AddAllAndPin(ctx, file)
if err != nil {
return EmptyCid, err
}
p.cidCache.Set(cacheKey, nd.Cid(), cache.DefaultExpiration)
return nd.Cid(), nil
}
func configureIpfs(cfg *config.IpfsConfig, eventBus eventbus.Bus) (*ipfsConf.Config, error) {
updateIpfsConfig := func(ipfsConfig *ipfsConf.Config) error {
ipfsConfig.Addresses.Swarm = []string{
fmt.Sprintf("/ip4/0.0.0.0/tcp/%d", cfg.IpfsPort),
fmt.Sprintf("/ip6/::/tcp/%d", cfg.IpfsPort),
}
bps, err := ipfsConf.ParseBootstrapPeers(cfg.BootNodes)
if err != nil {
return err
}
ipfsConfig.Bootstrap = ipfsConf.BootstrapPeerStrings(bps)
ipfsConfig.Swarm.DisableBandwidthMetrics = true
ipfsConfig.Routing.Type = ipfsConf.NewOptionalString(cfg.Routing)
ipfsConfig.Swarm.ConnMgr.GracePeriod = cfg.GracePeriod
ipfsConfig.Swarm.ConnMgr.LowWater = cfg.LowWater
ipfsConfig.Swarm.ConnMgr.HighWater = cfg.HighWater
ipfsConfig.Reprovider.Interval = cfg.ReproviderInterval
ipfsConfig.Reprovider.Strategy = "pinned"
ipfsConfig.Swarm.Transports.Security.Noise = ipfsConf.Disabled
ipfsConfig.Swarm.RelayClient.Enabled = ipfsConf.True
ipfsConfig.Swarm.EnableHolePunching = ipfsConf.True
ipfsConfig.Swarm.EnableAutoRelay = false
if cfg.Profile != "" {
transformer, ok := ipfsConf.Profiles[cfg.Profile]
if !ok {
return fmt.Errorf("invalid IPFS configuration profile: %s", cfg.Profile)
}
if err := transformer.Transform(ipfsConfig); err != nil {
return err
}
}
return nil
}
var ipfsConfig *ipfsConf.Config
datadir, _ := filepath.Abs(cfg.DataDir)
if !fsrepo.IsInitialized(datadir) {
ipfsConfig, err := ipfsConf.Init(os.Stdout, 2048)
if err != nil {
return nil, err
}
ipfsConfig.Experimental.FilestoreEnabled = true
ipfsConfig.Swarm.RelayClient.Enabled = ipfsConf.True
ipfsConfig.Swarm.EnableHolePunching = ipfsConf.True
transformer, _ := ipfsConf.Profiles["badgerds"]
if err := transformer.Transform(ipfsConfig); err != nil {
return nil, err
}
err = updateIpfsConfig(ipfsConfig)
if err != nil {
return nil, err
}
if err := fsrepo.Init(datadir, ipfsConfig); err != nil {
return nil, err
}
} else {
ipfsConfig, err := configAt(datadir)
if err != nil {
if strings.Contains(err.Error(), "failure to decode config") {
configFilename, err := ipfsConf.Filename(datadir, "")
if err != nil {
return nil, err
}
if err := os.Remove(configFilename); err != nil {
return nil, err
}
return configureIpfs(cfg, eventBus)
}
return nil, err
}
err = updateIpfsConfig(ipfsConfig)
if err != nil {
return nil, err
}
repo, err := fsrepo.Open(datadir)
if err != nil {
return nil, err
}
if err := repo.SetConfig(ipfsConfig); err != nil {
return nil, err
}
}
writeSwarmKey(datadir, cfg.SwarmKey)
return ipfsConfig, nil
}
func writeSwarmKey(dataDir string, swarmKey string) {
swarmPath := filepath.Join(dataDir, "swarm.key")
err := ioutil.WriteFile(swarmPath, []byte(fmt.Sprintf("/key/swarm/psk/1.0.0/\n/base16/\n%v", swarmKey)), 0644)
if err != nil {
log.Error(fmt.Sprintf("Failed to persist swarm file: %v", err))
}
}
func getNodeConfig(dataDir string) *core.BuildCfg {
repo, _ := fsrepo.Open(dataDir)
return &core.BuildCfg{
Repo: repo,
Permanent: true,
Online: true,
DisableEncryptedConnections: false,
ExtraOpts: map[string]bool{
"pubsub": true,
"ipnsps": false,
"mplex": false,
},
}
}
func loadPlugins(cfg *config.IpfsConfig) error {
dataDir, _ := filepath.Abs(cfg.DataDir)
pluginPath := filepath.Join(dataDir, "plugins")
var plugins *loader.PluginLoader
plugins, err := loader.NewPluginLoader(pluginPath)
if err != nil {
return errors.WithMessage(err, "ipfs plugin loader error")
}
if err := plugins.Initialize(); err != nil {
return errors.WithMessage(err, "ipfs plugin initialization error")
}
if err := plugins.Inject(); err != nil {
return errors.WithMessage(err, "ipfs plugin inject error")
}
return nil
}
func NewMemoryIpfsProxy() Proxy {
return &memoryIpfs{
values: make(map[cid.Cid][]byte),
}
}
type memoryIpfs struct {
values map[cid.Cid][]byte
}
func (i *memoryIpfs) PubSub() *pubsub.PubSub {
panic("implement me")
}
func (i *memoryIpfs) ShouldPin(dataType DataType) bool {
return true
}
func (i *memoryIpfs) Host() core2.Host {
panic("implement me")
}
func (i *memoryIpfs) LoadTo(key []byte, to io.Writer, ctx context.Context, onLoading func(size, loaded int64)) error {
panic("implement me")
}
func (i *memoryIpfs) AddFile(absPath string, data io.ReadCloser, fi os.FileInfo) (cid.Cid, error) {
panic("implement me")
}
func (i *memoryIpfs) Unpin(key []byte) error {
return nil
}
func (i *memoryIpfs) Add(data []byte, pin bool) (cid.Cid, error) {
cid, _ := i.Cid(data)
i.values[cid] = data
return cid, nil
}
func (i *memoryIpfs) Get(key []byte, dataType DataType) ([]byte, error) {
if len(key) == 0 {
return []byte{}, nil
}
c, err := cid.Parse(key)
if err != nil {
return nil, err
}
if v, ok := i.values[c]; ok {
return v, nil
}
return nil, errors.New("not found")
}
func (i *memoryIpfs) GetWithSizeLimit(key []byte, dataType DataType, size int64) ([]byte, error) {
panic("implement me")
}
func (*memoryIpfs) Pin(key []byte) error {
return nil
}
func (*memoryIpfs) PeerId() string {
return ""
}
func (*memoryIpfs) Port() int {
return 0
}
func (*memoryIpfs) Cid(data []byte) (cid.Cid, error) {
var v1CidPrefix = cid.Prefix{
Codec: cid.Raw,
MhLength: -1,
MhType: multihash.SHA2_256,
Version: 1,
}
return v1CidPrefix.Sum(data)
}
type progressReader struct {
r io.Reader
read int
size int64
onLoading func(size, loaded int64)
}
func (r *progressReader) Read(p []byte) (n int, err error) {
n, err = r.r.Read(p)
if err == nil {
r.read += n
if r.onLoading != nil {
r.onLoading(r.size, int64(r.read))
}
}
return n, err
}
func configAt(repoPath string) (*ipfsConf.Config, error) {
configFilename, err := ipfsConf.Filename(repoPath, "")
if err != nil {
return nil, err
}
return serialize.Load(configFilename)
}
func (i *memoryIpfs) GC() (ctx context.Context, cancel context.CancelFunc) {
panic("implement me")
}