This repository has been archived by the owner on Jul 30, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
/
executor.go
371 lines (311 loc) · 8.64 KB
/
executor.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
// Copyright (C) 2018 MediBloc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package testutil
import (
"context"
"io/ioutil"
"net"
"os"
"path/filepath"
"testing"
"sync"
"time"
"github.com/medibloc/go-medibloc/common"
"github.com/medibloc/go-medibloc/core"
"github.com/medibloc/go-medibloc/crypto/signature/secp256k1"
"github.com/medibloc/go-medibloc/medlet"
"github.com/medibloc/go-medibloc/util/logging"
"github.com/medibloc/go-medibloc/util/testutil/blockutil"
"github.com/medibloc/go-medibloc/util/testutil/keyutil"
"github.com/sirupsen/logrus/hooks/test"
"github.com/stretchr/testify/require"
)
// Node is node for testing.
type Node struct {
mu sync.RWMutex
t *testing.T
ctx context.Context
cancel context.CancelFunc
Med *medlet.Medlet
Config *NodeConfig
started bool
}
// NewNode creates node for test.
func NewNode(t *testing.T, cfg *NodeConfig) *Node {
med, err := medlet.New(cfg.Config)
require.Nil(t, err)
return &Node{
t: t,
Med: med,
Config: cfg,
started: false,
}
}
// Start starts test node.
func (node *Node) Start() {
node.mu.Lock()
defer node.mu.Unlock()
if node.started {
return
}
node.started = true
err := node.Med.Setup()
require.NoError(node.t, err)
ctx, cancel := context.WithCancel(context.Background())
node.cancel = cancel
err = node.Med.Start(ctx)
require.NoError(node.t, err)
startTime := time.Now()
for {
require.True(node.t, time.Now().Sub(startTime) < time.Duration(3*time.Second))
conn, err := net.Dial("tcp", node.Config.Config.Rpc.HttpListen[0])
if err != nil {
time.Sleep(10 * time.Millisecond)
} else {
require.NotNil(node.t, conn)
conn.Close()
return
}
}
}
// Stop stops test node.
func (node *Node) Stop() {
node.mu.Lock()
defer node.mu.Unlock()
if !node.started {
return
}
node.started = false
if node.cancel != nil {
node.cancel()
}
node.Med.Stop()
}
// Restart restart node
func (node *Node) Restart() {
node.Stop()
med, err := medlet.New(node.Config.Config)
require.Nil(node.t, err)
node.Med = med
node.Start()
}
// IsStarted returns whether it has been started.
func (node *Node) IsStarted() bool {
node.mu.RLock()
defer node.mu.RUnlock()
return node.started
}
// String returns summary of test node.
func (node *Node) String() string {
return node.Config.String()
}
// GenesisBlock returns genesis block.
func (node *Node) GenesisBlock() *core.Block {
block, err := node.Med.BlockManager().BlockByHeight(core.GenesisHeight)
require.NoError(node.t, err)
return block
}
// Tail returns tail block.
func (node *Node) Tail() *core.Block {
block := node.Med.BlockManager().TailBlock()
return block
}
// WaitUntilTailHeight waits until blockchain has a designated height or timeout
func (node *Node) WaitUntilTailHeight(height uint64, timeLimit time.Duration) error {
timeout := time.NewTimer(timeLimit)
defer timeout.Stop()
ticker := time.NewTicker(10 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-timeout.C:
return ErrExecutionTimeout
case <-ticker.C:
if node.Med.BlockManager().TailBlock().Height() == height {
return nil
}
}
}
}
// WaitUntilBlockAcceptedOnChain waits until the block is accepted on the blockchain
func (node *Node) WaitUntilBlockAcceptedOnChain(hash []byte, timeLimit time.Duration) error {
timeout := time.NewTimer(timeLimit)
defer timeout.Stop()
ticker := time.NewTicker(10 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-timeout.C:
return ErrExecutionTimeout
case <-ticker.C:
if node.Med.BlockManager().BlockByHash(hash) != nil {
return nil
}
}
}
}
// AddProposers adds multiple proposers.
func (node *Node) AddProposers(pairs keyutil.AddrKeyPairs) {
for _, pair := range pairs {
node.Config = node.Config.AddProposer(pair)
}
}
// Network is set of nodes.
type Network struct {
t *testing.T
logHook *test.Hook
DynastySize int
Seed *Node
Nodes []*Node
}
// NewNetwork creates network.
func NewNetwork(t *testing.T) *Network {
return NewNetworkWithDynastySize(t, blockutil.DynastySize)
}
// NewNetworkWithDynastySize creates network with dynasty size.
func NewNetworkWithDynastySize(t *testing.T, dynastySize int) *Network {
logHook := logging.InitTestLogger(filepath.Join("testdata", t.Name()))
return &Network{
t: t,
logHook: logHook,
DynastySize: dynastySize,
}
}
// NewSeedNode creates seed node.
func (n *Network) NewSeedNode() *Node {
cfg := NewConfig(n.t).
SetRandomGenesis(n.DynastySize)
return n.NewSeedNodeWithConfig(cfg)
}
// NewSeedNodeWithConfig creates seed node.
func (n *Network) NewSeedNodeWithConfig(cfg *NodeConfig) *Node {
node := NewNode(n.t, cfg)
n.Seed = node
n.Nodes = append(n.Nodes, node)
return node
}
// NewNode creates node.
func (n *Network) NewNode() *Node {
return n.NewNodeWithConfig(NewConfig(n.t))
}
// NewNodeWithConfig creates node with custom config
func (n *Network) NewNodeWithConfig(cfg *NodeConfig) *Node {
require.NotNil(n.t, n.Seed)
require.True(n.t, len(n.Nodes) > 0)
cfg.SetGenesisFrom(n.Seed).SetSeed(n.Seed)
node := NewNode(n.t, cfg)
n.Nodes = append(n.Nodes, node)
return node
}
// Start starts nodes in network.
func (n *Network) Start() {
if !n.Seed.IsStarted() {
n.Seed.Start()
}
for _, node := range n.Nodes {
if !node.IsStarted() {
node.Start()
}
}
}
// WaitForEstablished waits until connections between peers are established.
func (n *Network) WaitForEstablished() {
timer := time.NewTimer(10 * time.Second)
defer timer.Stop()
ticker := time.NewTicker(1000 * time.Millisecond)
defer ticker.Stop()
for _, node := range n.Nodes {
node.Med.NetService().Node().DHTSync()
for len(node.Med.NetService().Node().Peerstore().Peers()) != len(n.Nodes) {
select {
case <-timer.C:
n.t.Error("Failed to wait for established")
case <-ticker.C:
node.Med.NetService().Node().DHTSync()
}
}
}
}
// Stop stops nodes in network
func (n *Network) Stop() {
for _, node := range n.Nodes {
node.Stop()
}
}
// Cleanup cleans up directories and files.
func (n *Network) Cleanup() {
n.Stop()
n.logHook.Reset()
size, err := DirSize(filepath.Join("testdata", n.t.Name()))
require.NoError(n.t, err)
if n.t.Failed() {
n.t.Log("TestData size:", size)
wd, err := os.Getwd()
require.NoError(n.t, err)
n.t.Logf("Test Failed. LogDir:%s/%s", wd, filepath.Join("testdata", n.t.Name()))
logdata, err := ioutil.ReadFile(filepath.Join("testdata", n.t.Name(), "medibloc.log"))
require.NoError(n.t, err)
n.t.Log(string(logdata))
return
}
require.NoError(n.t, os.RemoveAll(filepath.Join("testdata", n.t.Name())))
infos, err := ioutil.ReadDir("testdata")
require.NoError(n.t, err)
if len(infos) == 0 {
require.NoError(n.t, os.RemoveAll("testdata"))
}
}
// LogTestHook returns test hook for log messages.
func (n *Network) LogTestHook() *test.Hook {
return n.logHook
}
// AddProposerFromDynasties chooses proposer from dynasties.
func (n *Network) AddProposerFromDynasties(node *Node) {
require.False(n.t, node.IsStarted())
exclude := n.assignedProposers()
node.Config.AddProposerFromDynasties(exclude)
}
// AddRandomProposer sets random proposer.
func (n *Network) AddRandomProposer(node *Node) {
require.False(n.t, node.IsStarted())
node.Config.AddRandomProposer()
}
func (n *Network) assignedProposers() []*keyutil.AddrKeyPair {
proposers := make([]*keyutil.AddrKeyPair, 0)
for _, node := range n.Nodes {
for _, p := range node.Config.Config.Chain.Proposers {
addr, err := common.HexToAddress(p.Proposer)
require.NoError(n.t, err)
privKey, err := secp256k1.NewPrivateKeyFromHex(p.Privkey)
require.NoError(n.t, err)
e := &keyutil.AddrKeyPair{
Addr: addr,
PrivKey: privKey,
}
proposers = append(proposers, e)
}
}
return proposers
}
// FindProposer returns block proposer for time stamp
func (n *Network) FindProposer(ts int64, parent *core.Block) *keyutil.AddrKeyPair {
dynasties := n.Seed.Config.Dynasties
d := n.Seed.Med.Consensus()
proposer, err := d.FindMintProposer(ts, parent)
require.Nil(n.t, err)
v := dynasties.FindPair(proposer)
require.NotNil(n.t, v, "Failed to find proposer's privateKey")
return v
}