protocol_test.go 6.4 KB
Newer Older
E
ethersphere 已提交
1
// Copyright 2016 The go-ethereum Authors
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package network
E
ethersphere 已提交
18 19 20 21 22 23 24 25 26 27

import (
	"flag"
	"fmt"
	"os"
	"sync"
	"testing"

	"github.com/ethereum/go-ethereum/log"
	"github.com/ethereum/go-ethereum/p2p"
28
	"github.com/ethereum/go-ethereum/p2p/enode"
E
ethersphere 已提交
29 30 31 32
	"github.com/ethereum/go-ethereum/p2p/protocols"
	p2ptest "github.com/ethereum/go-ethereum/p2p/testing"
)

33
const (
34
	TestProtocolVersion   = 7
35 36 37
	TestProtocolNetworkID = 3
)

E
ethersphere 已提交
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
var (
	loglevel = flag.Int("loglevel", 2, "verbosity of logs")
)

func init() {
	flag.Parse()
	log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(*loglevel), log.StreamHandler(os.Stderr, log.TerminalFormat(true))))
}

type testStore struct {
	sync.Mutex

	values map[string][]byte
}

func (t *testStore) Load(key string) ([]byte, error) {
	t.Lock()
	defer t.Unlock()
	v, ok := t.values[key]
	if !ok {
		return nil, fmt.Errorf("key not found: %s", key)
	}
	return v, nil
}

func (t *testStore) Save(key string, v []byte) error {
	t.Lock()
	defer t.Unlock()
	t.values[key] = v
	return nil
}

70
func HandshakeMsgExchange(lhs, rhs *HandshakeMsg, id enode.ID) []p2ptest.Exchange {
E
ethersphere 已提交
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

	return []p2ptest.Exchange{
		{
			Expects: []p2ptest.Expect{
				{
					Code: 0,
					Msg:  lhs,
					Peer: id,
				},
			},
		},
		{
			Triggers: []p2ptest.Trigger{
				{
					Code: 0,
					Msg:  rhs,
					Peer: id,
				},
			},
		},
	}
}

func newBzzBaseTester(t *testing.T, n int, addr *BzzAddr, spec *protocols.Spec, run func(*BzzPeer) error) *bzzTester {
	cs := make(map[string]chan bool)

	srv := func(p *BzzPeer) error {
		defer func() {
			if cs[p.ID().String()] != nil {
				close(cs[p.ID().String()])
			}
		}()
		return run(p)
	}

	protocol := func(p *p2p.Peer, rw p2p.MsgReadWriter) error {
107
		return srv(&BzzPeer{Peer: protocols.NewPeer(p, rw, spec), BzzAddr: NewAddr(p.Node())})
E
ethersphere 已提交
108 109
	}

110
	s := p2ptest.NewProtocolTester(t, addr.ID(), n, protocol)
E
ethersphere 已提交
111

112 113
	for _, node := range s.Nodes {
		cs[node.ID().String()] = make(chan bool)
E
ethersphere 已提交
114 115 116 117 118 119 120 121 122 123 124 125 126
	}

	return &bzzTester{
		addr:           addr,
		ProtocolTester: s,
		cs:             cs,
	}
}

type bzzTester struct {
	*p2ptest.ProtocolTester
	addr *BzzAddr
	cs   map[string]chan bool
127
	bzz  *Bzz
E
ethersphere 已提交
128 129
}

130
func newBzz(addr *BzzAddr, lightNode bool) *Bzz {
E
ethersphere 已提交
131 132 133 134 135
	config := &BzzConfig{
		OverlayAddr:  addr.Over(),
		UnderlayAddr: addr.Under(),
		HiveParams:   NewHiveParams(),
		NetworkID:    DefaultNetworkID,
136
		LightNode:    lightNode,
E
ethersphere 已提交
137 138 139
	}
	kad := NewKademlia(addr.OAddr, NewKadParams())
	bzz := NewBzz(config, kad, nil, nil, nil)
140 141
	return bzz
}
E
ethersphere 已提交
142

143 144
func newBzzHandshakeTester(t *testing.T, n int, addr *BzzAddr, lightNode bool) *bzzTester {
	bzz := newBzz(addr, lightNode)
145
	pt := p2ptest.NewProtocolTester(t, addr.ID(), n, bzz.runBzz)
E
ethersphere 已提交
146 147 148

	return &bzzTester{
		addr:           addr,
149 150
		ProtocolTester: pt,
		bzz:            bzz,
E
ethersphere 已提交
151 152 153 154 155
	}
}

// should test handshakes in one exchange? parallelisation
func (s *bzzTester) testHandshake(lhs, rhs *HandshakeMsg, disconnects ...*p2ptest.Disconnect) error {
156
	if err := s.TestExchanges(HandshakeMsgExchange(lhs, rhs, rhs.Addr.ID())...); err != nil {
E
ethersphere 已提交
157 158 159 160 161 162 163 164 165
		return err
	}

	if len(disconnects) > 0 {
		return s.TestDisconnected(disconnects...)
	}

	// If we don't expect disconnect, ensure peers remain connected
	err := s.TestDisconnected(&p2ptest.Disconnect{
166
		Peer:  s.Nodes[0].ID(),
E
ethersphere 已提交
167 168 169 170 171 172 173 174 175 176 177 178 179 180
		Error: nil,
	})

	if err == nil {
		return fmt.Errorf("Unexpected peer disconnect")
	}

	if err.Error() != "timed out waiting for peers to disconnect" {
		return err
	}

	return nil
}

181
func correctBzzHandshake(addr *BzzAddr, lightNode bool) *HandshakeMsg {
E
ethersphere 已提交
182
	return &HandshakeMsg{
183 184
		Version:   TestProtocolVersion,
		NetworkID: TestProtocolNetworkID,
E
ethersphere 已提交
185
		Addr:      addr,
186
		LightNode: lightNode,
E
ethersphere 已提交
187 188 189 190
	}
}

func TestBzzHandshakeNetworkIDMismatch(t *testing.T) {
191
	lightNode := false
E
ethersphere 已提交
192
	addr := RandomAddr()
193
	s := newBzzHandshakeTester(t, 1, addr, lightNode)
194
	node := s.Nodes[0]
E
ethersphere 已提交
195 196

	err := s.testHandshake(
197
		correctBzzHandshake(addr, lightNode),
198 199
		&HandshakeMsg{Version: TestProtocolVersion, NetworkID: 321, Addr: NewAddr(node)},
		&p2ptest.Disconnect{Peer: node.ID(), Error: fmt.Errorf("Handshake error: Message handler error: (msg code 0): network id mismatch 321 (!= 3)")},
E
ethersphere 已提交
200 201 202 203 204 205 206 207
	)

	if err != nil {
		t.Fatal(err)
	}
}

func TestBzzHandshakeVersionMismatch(t *testing.T) {
208
	lightNode := false
E
ethersphere 已提交
209
	addr := RandomAddr()
210
	s := newBzzHandshakeTester(t, 1, addr, lightNode)
211
	node := s.Nodes[0]
E
ethersphere 已提交
212 213

	err := s.testHandshake(
214
		correctBzzHandshake(addr, lightNode),
215 216
		&HandshakeMsg{Version: 0, NetworkID: TestProtocolNetworkID, Addr: NewAddr(node)},
		&p2ptest.Disconnect{Peer: node.ID(), Error: fmt.Errorf("Handshake error: Message handler error: (msg code 0): version mismatch 0 (!= %d)", TestProtocolVersion)},
E
ethersphere 已提交
217 218 219 220 221 222 223 224
	)

	if err != nil {
		t.Fatal(err)
	}
}

func TestBzzHandshakeSuccess(t *testing.T) {
225
	lightNode := false
E
ethersphere 已提交
226
	addr := RandomAddr()
227
	s := newBzzHandshakeTester(t, 1, addr, lightNode)
228
	node := s.Nodes[0]
E
ethersphere 已提交
229 230

	err := s.testHandshake(
231
		correctBzzHandshake(addr, lightNode),
232
		&HandshakeMsg{Version: TestProtocolVersion, NetworkID: TestProtocolNetworkID, Addr: NewAddr(node)},
E
ethersphere 已提交
233 234 235 236 237 238
	)

	if err != nil {
		t.Fatal(err)
	}
}
239 240 241 242 243 244 245 246 247 248 249 250 251 252

func TestBzzHandshakeLightNode(t *testing.T) {
	var lightNodeTests = []struct {
		name      string
		lightNode bool
	}{
		{"on", true},
		{"off", false},
	}

	for _, test := range lightNodeTests {
		t.Run(test.name, func(t *testing.T) {
			randomAddr := RandomAddr()
			pt := newBzzHandshakeTester(t, 1, randomAddr, false)
253 254
			node := pt.Nodes[0]
			addr := NewAddr(node)
255 256 257 258 259 260 261 262 263 264

			err := pt.testHandshake(
				correctBzzHandshake(randomAddr, false),
				&HandshakeMsg{Version: TestProtocolVersion, NetworkID: TestProtocolNetworkID, Addr: addr, LightNode: test.lightNode},
			)

			if err != nil {
				t.Fatal(err)
			}

265 266
			if pt.bzz.handshakes[node.ID()].LightNode != test.lightNode {
				t.Fatalf("peer LightNode flag is %v, should be %v", pt.bzz.handshakes[node.ID()].LightNode, test.lightNode)
267 268 269 270
			}
		})
	}
}