master
go 105 lines 2.56 KB
Raw
1 package coremock
2
3 import (
4 "context"
5 "fmt"
6 "io"
7
8 libp2p2 "github.com/ipfs/kubo/core/node/libp2p"
9
10 "github.com/ipfs/kubo/commands"
11 "github.com/ipfs/kubo/core"
12 "github.com/ipfs/kubo/repo"
13
14 "github.com/ipfs/go-datastore"
15 syncds "github.com/ipfs/go-datastore/sync"
16 config "github.com/ipfs/kubo/config"
17
18 "github.com/libp2p/go-libp2p"
19 testutil "github.com/libp2p/go-libp2p-testing/net"
20 "github.com/libp2p/go-libp2p/core/host"
21 "github.com/libp2p/go-libp2p/core/peer"
22 pstore "github.com/libp2p/go-libp2p/core/peerstore"
23
24 mocknet "github.com/libp2p/go-libp2p/p2p/net/mock"
25 )
26
27 // NewMockNode constructs an IpfsNode for use in tests.
28 func NewMockNode() (*core.IpfsNode, error) {
29 // effectively offline, only peer in its network
30 return core.NewNode(context.Background(), &core.BuildCfg{
31 Online: true,
32 Host: MockHostOption(mocknet.New()),
33 })
34 }
35
36 func MockHostOption(mn mocknet.Mocknet) libp2p2.HostOption {
37 return func(id peer.ID, ps pstore.Peerstore, opts ...libp2p.Option) (host.Host, error) {
38 var cfg libp2p.Config
39 if err := cfg.Apply(opts...); err != nil {
40 return nil, err
41 }
42
43 // The mocknet does not use the provided libp2p.Option. This options include
44 // the listening addresses we want our peer listening on. Therefore, we have
45 // to manually parse the configuration and add them here.
46 ps.AddAddrs(id, cfg.ListenAddrs, pstore.PermanentAddrTTL)
47 return mn.AddPeerWithPeerstore(id, ps)
48 }
49 }
50
51 func MockCmdsCtx() (commands.Context, error) {
52 // Generate Identity
53 ident, err := testutil.RandIdentity()
54 if err != nil {
55 return commands.Context{}, err
56 }
57 p := ident.ID()
58
59 conf := config.Config{
60 Identity: config.Identity{
61 PeerID: p.String(),
62 },
63 }
64
65 r := &repo.Mock{
66 D: syncds.MutexWrap(datastore.NewMapDatastore()),
67 C: conf,
68 }
69
70 node, err := core.NewNode(context.Background(), &core.BuildCfg{
71 Repo: r,
72 })
73 if err != nil {
74 return commands.Context{}, err
75 }
76
77 return commands.Context{
78 ConfigRoot: "/tmp/.mockipfsconfig",
79 ConstructNode: func() (*core.IpfsNode, error) {
80 return node, nil
81 },
82 }, nil
83 }
84
85 func MockPublicNode(ctx context.Context, mn mocknet.Mocknet) (*core.IpfsNode, error) {
86 ds := syncds.MutexWrap(datastore.NewMapDatastore())
87 cfg, err := config.Init(io.Discard, 2048)
88 if err != nil {
89 return nil, err
90 }
91 count := len(mn.Peers())
92 cfg.Addresses.Swarm = []string{
93 fmt.Sprintf("/ip4/18.0.%d.%d/tcp/4001", count>>16, count&0xFF),
94 }
95 cfg.Datastore = config.Datastore{}
96 return core.NewNode(ctx, &core.BuildCfg{
97 Online: true,
98 Routing: libp2p2.DHTServerOption,
99 Repo: &repo.Mock{
100 C: *cfg,
101 D: ds,
102 },
103 Host: MockHostOption(mn),
104 })
105 }