-
Notifications
You must be signed in to change notification settings - Fork 976
/
Copy pathswamp.go
319 lines (270 loc) · 9.65 KB
/
swamp.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
package swamp
import (
"context"
"fmt"
"math/rand"
"net"
"testing"
"time"
"github.com/cosmos/cosmos-sdk/client"
"github.com/libp2p/go-libp2p-core/host"
"github.com/libp2p/go-libp2p-core/peer"
mocknet "github.com/libp2p/go-libp2p/p2p/net/mock"
ma "github.com/multiformats/go-multiaddr"
"github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/libs/bytes"
tmrand "github.com/tendermint/tendermint/libs/rand"
"github.com/tendermint/tendermint/types"
"go.uber.org/fx"
"github.com/celestiaorg/celestia-app/testutil/testnode"
"github.com/celestiaorg/celestia-node/libs/keystore"
"github.com/celestiaorg/celestia-node/logs"
"github.com/celestiaorg/celestia-node/nodebuilder"
coremodule "github.com/celestiaorg/celestia-node/nodebuilder/core"
"github.com/celestiaorg/celestia-node/nodebuilder/node"
"github.com/celestiaorg/celestia-node/nodebuilder/p2p"
"github.com/celestiaorg/celestia-node/nodebuilder/state"
"github.com/celestiaorg/celestia-node/params"
)
var blackholeIP6 = net.ParseIP("100::")
var queryEvent string = types.QueryForEvent(types.EventNewBlock).String()
// Swamp represents the main functionality that is needed for the test-case:
// - Network to link the nodes
// - CoreClient to share between Bridge nodes
// - Slices of created Bridge/Full/Light Nodes
// - trustedHash taken from the CoreClient and shared between nodes
type Swamp struct {
t *testing.T
Network mocknet.Mocknet
BridgeNodes []*nodebuilder.Node
FullNodes []*nodebuilder.Node
LightNodes []*nodebuilder.Node
trustedHash string
comps *Components
ClientContext client.Context
accounts []string
}
// NewSwamp creates a new instance of Swamp.
func NewSwamp(t *testing.T, options ...Option) *Swamp {
if testing.Verbose() {
logs.SetDebugLogging()
}
ic := DefaultComponents()
for _, option := range options {
option(ic)
}
var err error
ctx := context.Background()
// we create an arbitray number of funded accounts
accounts := make([]string, 100)
for i := 0; i < 10; i++ {
accounts = append(accounts, tmrand.Str(9))
}
// TODO(@Bidon15): CoreClient(limitation)
// Now, we are making an assumption that consensus mechanism is already tested out
// so, we are not creating bridge nodes with each one containing its own core client
// instead we are assigning all created BNs to 1 Core from the swamp
tmNode, app, cctx, err := testnode.New(t, ic.CoreCfg, false, accounts...)
require.NoError(t, err)
cctx, cleanupCoreNode, err := testnode.StartNode(tmNode, cctx)
require.NoError(t, err)
cctx, cleanupGRPCServer, err := testnode.StartGRPCServer(app, testnode.DefaultAppConfig(), cctx)
swp := &Swamp{
t: t,
Network: mocknet.New(),
ClientContext: cctx,
comps: ic,
accounts: accounts,
}
swp.trustedHash = swp.getTrustedHash(ctx)
swp.t.Cleanup(func() {
swp.stopAllNodes(ctx, swp.BridgeNodes, swp.FullNodes, swp.LightNodes)
cleanupCoreNode()
cleanupGRPCServer()
})
return swp
}
// stopAllNodes goes through all received slices of Nodes and stops one-by-one
// this eliminates a manual clean-up in the test-cases itself in the end
func (s *Swamp) stopAllNodes(ctx context.Context, allNodes ...[]*nodebuilder.Node) {
for _, nodes := range allNodes {
for _, node := range nodes {
require.NoError(s.t, node.Stop(ctx))
}
}
}
// GetCoreBlockHashByHeight returns a tendermint block's hash by provided height
func (s *Swamp) GetCoreBlockHashByHeight(ctx context.Context, height int64) bytes.HexBytes {
b, err := s.ClientContext.Client.Block(ctx, &height)
require.NoError(s.t, err)
return b.BlockID.Hash
}
// WaitTillHeight holds the test execution until the given amount of blocks
// has been produced by the CoreClient.
func (s *Swamp) WaitTillHeight(ctx context.Context, height int64) bytes.HexBytes {
require.Greater(s.t, height, int64(0))
t := time.NewTicker(time.Millisecond * 50)
defer t.Stop()
for {
select {
case <-ctx.Done():
require.NoError(s.t, ctx.Err())
case <-t.C:
status, err := s.ClientContext.Client.Status(ctx)
require.NoError(s.t, err)
latest := status.SyncInfo.LatestBlockHeight
switch {
case latest == height:
return status.SyncInfo.LatestBlockHash
case latest > height:
res, err := s.ClientContext.Client.Block(ctx, &height)
require.NoError(s.t, err)
return res.BlockID.Hash
}
}
}
}
// createPeer is a helper for celestia nodes to initialize
// with a real key instead of using a bogus one.
func (s *Swamp) createPeer(ks keystore.Keystore) host.Host {
key, err := p2p.Key(ks)
require.NoError(s.t, err)
// IPv6 will be starting with 100:0
token := make([]byte, 12)
rand.Read(token) //nolint:gosec
ip := append(net.IP{}, blackholeIP6...)
copy(ip[net.IPv6len-len(token):], token)
// reference to GenPeer func in libp2p/p2p/net/mock/mock_net.go
// on how we generate new multiaddr for new peer
a, err := ma.NewMultiaddr(fmt.Sprintf("/ip6/%s/tcp/4242", ip))
require.NoError(s.t, err)
host, err := s.Network.AddPeer(key, a)
require.NoError(s.t, err)
require.NoError(s.t, s.Network.LinkAll())
return host
}
// getTrustedHash is needed for celestia nodes to get the trustedhash
// from CoreClient. This is required to initialize and start correctly.
func (s *Swamp) getTrustedHash(ctx context.Context) string {
return s.WaitTillHeight(ctx, 1).String()
}
// NewBridgeNode creates a new instance of a BridgeNode providing a default config
// and a mockstore to the NewNodeWithStore method
func (s *Swamp) NewBridgeNode(options ...fx.Option) *nodebuilder.Node {
cfg := nodebuilder.DefaultConfig(node.Bridge)
store := nodebuilder.MockStore(s.t, cfg)
return s.NewNodeWithStore(node.Bridge, store, options...)
}
// NewFullNode creates a new instance of a FullNode providing a default config
// and a mockstore to the NewNodeWithStore method
func (s *Swamp) NewFullNode(options ...fx.Option) *nodebuilder.Node {
cfg := nodebuilder.DefaultConfig(node.Full)
store := nodebuilder.MockStore(s.t, cfg)
return s.NewNodeWithStore(node.Full, store, options...)
}
// NewLightNode creates a new instance of a LightNode providing a default config
// and a mockstore to the NewNodeWithStore method
func (s *Swamp) NewLightNode(options ...fx.Option) *nodebuilder.Node {
cfg := nodebuilder.DefaultConfig(node.Light)
store := nodebuilder.MockStore(s.t, cfg)
return s.NewNodeWithStore(node.Light, store, options...)
}
func (s *Swamp) NewNodeWithConfig(nodeType node.Type, cfg *nodebuilder.Config, options ...fx.Option) *nodebuilder.Node {
store := nodebuilder.MockStore(s.t, cfg)
return s.NewNodeWithStore(nodeType, store, options...)
}
// NewNodeWithStore creates a new instance of Node with predefined Store.
// Afterwards, the instance is stored in the swamp's Nodes' slice according to the
// node's type provided from the user.
func (s *Swamp) NewNodeWithStore(
t node.Type,
store nodebuilder.Store,
options ...fx.Option,
) *nodebuilder.Node {
var n *nodebuilder.Node
options = append(options,
state.WithKeyringSigner(nodebuilder.TestKeyringSigner(s.t)),
)
switch t {
case node.Bridge:
options = append(options,
coremodule.WithClient(s.ClientContext.Client),
)
n = s.newNode(node.Bridge, store, options...)
s.BridgeNodes = append(s.BridgeNodes, n)
case node.Full:
n = s.newNode(node.Full, store, options...)
s.FullNodes = append(s.FullNodes, n)
case node.Light:
n = s.newNode(node.Light, store, options...)
s.LightNodes = append(s.LightNodes, n)
}
return n
}
func (s *Swamp) newNode(t node.Type, store nodebuilder.Store, options ...fx.Option) *nodebuilder.Node {
ks, err := store.Keystore()
require.NoError(s.t, err)
// TODO(@Bidon15): If for some reason, we receive one of existing options
// like <core, host, hash> from the test case, we need to check them and not use
// default that are set here
cfg, _ := store.Config()
cfg.Header.TrustedHash = s.trustedHash
cfg.RPC.Port = "0"
options = append(options,
p2p.WithHost(s.createPeer(ks)),
nodebuilder.WithNetwork(params.Private),
)
node, err := nodebuilder.New(t, store, options...)
require.NoError(s.t, err)
return node
}
// RemoveNode removes a node from the swamp's node slice
// this allows reusage of the same var in the test scenario
// if the user needs to stop and start the same node
func (s *Swamp) RemoveNode(n *nodebuilder.Node, t node.Type) error {
var err error
switch t {
case node.Light:
s.LightNodes, err = s.remove(n, s.LightNodes)
return err
case node.Bridge:
s.BridgeNodes, err = s.remove(n, s.BridgeNodes)
return err
case node.Full:
s.FullNodes, err = s.remove(n, s.FullNodes)
return err
default:
return fmt.Errorf("no such type or node")
}
}
func (s *Swamp) remove(rn *nodebuilder.Node, sn []*nodebuilder.Node) ([]*nodebuilder.Node, error) {
if len(sn) == 1 {
return nil, nil
}
initSize := len(sn)
for i := 0; i < len(sn); i++ {
if sn[i] == rn {
sn = append(sn[:i], sn[i+1:]...)
i--
}
}
if initSize <= len(sn) {
return sn, fmt.Errorf("cannot delete the node")
}
return sn, nil
}
// Connect allows to connect peers after hard disconnection.
func (s *Swamp) Connect(t *testing.T, peerA, peerB peer.ID) {
_, err := s.Network.LinkPeers(peerA, peerB)
require.NoError(t, err)
_, err = s.Network.ConnectPeers(peerA, peerB)
require.NoError(t, err)
}
// Disconnect allows to break a connection between two peers without any possibility to re-establish it.
// Order is very important here. We have to unlink peers first, and only after that call disconnect.
// This is hard disconnect and peers will not be able to reconnect.
// In order to reconnect peers again, please use swamp.Connect
func (s *Swamp) Disconnect(t *testing.T, peerA, peerB peer.ID) {
require.NoError(t, s.Network.UnlinkPeers(peerA, peerB))
require.NoError(t, s.Network.DisconnectPeers(peerA, peerB))
}