P2P handshake handling (#2306)

* proto: illegal wireType 7 :(

* set addr to todo for now so somethign gets sent

* push latest progress

* Add feedback from @raulk. Stream never connects

* working handshake handler

* add exclusions for relay/bootstrap node

* fix tests, still need to add new ones

* remove race, fails coverage

* Add test for negotiation

* gazelle

* regen pb

* Update shared/p2p/handshake_handler.go

Co-Authored-By: prestonvanloon <preston@prysmaticlabs.com>
This commit is contained in:
Preston Van Loon
2019-04-27 15:08:27 -04:00
committed by Raul Jordan
parent 7a04af7621
commit 210edfc940
13 changed files with 515 additions and 95 deletions

View File

@@ -3,6 +3,7 @@ load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
go_library(
name = "go_default_library",
srcs = [
"fetch_contract_address.go",
"node.go",
"p2p_config.go",
],

View File

@@ -0,0 +1,41 @@
package node
import (
"io/ioutil"
"net/http"
"sync"
"github.com/prysmaticlabs/prysm/shared/params"
)
var cachedDepositAddress string
var fetchLock sync.Mutex
// fetchDepositContract from the cluster endpoint.
func fetchDepositContract() (string, error) {
fetchLock.Lock()
defer fetchLock.Unlock()
if cachedDepositAddress != "" {
return cachedDepositAddress, nil
}
log.WithField(
"endpoint",
params.BeaconConfig().TestnetContractEndpoint,
).Info("Fetching testnet cluster address")
resp, err := http.Get(params.BeaconConfig().TestnetContractEndpoint)
if err != nil {
return "", err
}
contractResponse, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
if err := resp.Body.Close(); err != nil {
return "", err
}
cachedDepositAddress = string(contractResponse)
return cachedDepositAddress, nil
}

View File

@@ -4,8 +4,6 @@ package node
import (
"context"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/signal"
"path"
@@ -248,22 +246,11 @@ func (b *BeaconNode) registerPOWChainService(cliCtx *cli.Context) error {
depAddress := cliCtx.GlobalString(utils.DepositContractFlag.Name)
if depAddress == "" {
log.Infof("Fetching testnet cluster address from %s...", params.BeaconConfig().TestnetContractEndpoint)
resp, err := http.Get(params.BeaconConfig().TestnetContractEndpoint)
var err error
depAddress, err = fetchDepositContract()
if err != nil {
log.Fatalf("Could not get latest deposit contract address: %v", err)
log.WithError(err).Fatal("Cannot fetch deposit contract")
}
defer func() {
if err := resp.Body.Close(); err != nil {
log.Fatal(err)
}
}()
contractResponse, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
depAddress = string(contractResponse)
}
if !common.IsHexAddress(depAddress) {

View File

@@ -2,6 +2,7 @@ package node
import (
"github.com/gogo/protobuf/proto"
"github.com/prysmaticlabs/prysm/beacon-chain/utils"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
"github.com/prysmaticlabs/prysm/shared/cmd"
"github.com/prysmaticlabs/prysm/shared/p2p"
@@ -27,11 +28,21 @@ var topicMappings = map[pb.Topic]proto.Message{
}
func configureP2P(ctx *cli.Context) (*p2p.Server, error) {
contractAddress := ctx.GlobalString(utils.DepositContractFlag.Name)
if contractAddress == "" {
var err error
contractAddress, err = fetchDepositContract()
if err != nil {
return nil, err
}
}
s, err := p2p.NewServer(&p2p.ServerConfig{
NoDiscovery: ctx.GlobalBool(cmd.NoDiscovery.Name),
BootstrapNodeAddr: ctx.GlobalString(cmd.BootstrapNode.Name),
RelayNodeAddr: ctx.GlobalString(cmd.RelayNode.Name),
Port: ctx.GlobalInt(cmd.P2PPort.Name),
NoDiscovery: ctx.GlobalBool(cmd.NoDiscovery.Name),
BootstrapNodeAddr: ctx.GlobalString(cmd.BootstrapNode.Name),
RelayNodeAddr: ctx.GlobalString(cmd.RelayNode.Name),
Port: ctx.GlobalInt(cmd.P2PPort.Name),
DepositContractAddress: contractAddress,
})
if err != nil {
return nil, err

View File

@@ -1435,6 +1435,53 @@ func (m *ExitResponse) GetVoluntaryExit() *VoluntaryExit {
return nil
}
type Handshake struct {
DepositContractAddress string `protobuf:"bytes,1,opt,name=deposit_contract_address,json=depositContractAddress,proto3" json:"deposit_contract_address,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *Handshake) Reset() { *m = Handshake{} }
func (m *Handshake) String() string { return proto.CompactTextString(m) }
func (*Handshake) ProtoMessage() {}
func (*Handshake) Descriptor() ([]byte, []int) {
return fileDescriptor_a1d590cda035b632, []int{27}
}
func (m *Handshake) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *Handshake) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_Handshake.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalTo(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *Handshake) XXX_Merge(src proto.Message) {
xxx_messageInfo_Handshake.Merge(m, src)
}
func (m *Handshake) XXX_Size() int {
return m.Size()
}
func (m *Handshake) XXX_DiscardUnknown() {
xxx_messageInfo_Handshake.DiscardUnknown(m)
}
var xxx_messageInfo_Handshake proto.InternalMessageInfo
func (m *Handshake) GetDepositContractAddress() string {
if m != nil {
return m.DepositContractAddress
}
return ""
}
func init() {
proto.RegisterEnum("ethereum.beacon.p2p.v1.Topic", Topic_name, Topic_value)
proto.RegisterType((*Envelope)(nil), "ethereum.beacon.p2p.v1.Envelope")
@@ -1464,68 +1511,71 @@ func init() {
proto.RegisterType((*ExitAnnounce)(nil), "ethereum.beacon.p2p.v1.ExitAnnounce")
proto.RegisterType((*ExitRequest)(nil), "ethereum.beacon.p2p.v1.ExitRequest")
proto.RegisterType((*ExitResponse)(nil), "ethereum.beacon.p2p.v1.ExitResponse")
proto.RegisterType((*Handshake)(nil), "ethereum.beacon.p2p.v1.Handshake")
}
func init() { proto.RegisterFile("proto/beacon/p2p/v1/messages.proto", fileDescriptor_a1d590cda035b632) }
var fileDescriptor_a1d590cda035b632 = []byte{
// 884 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x96, 0xd1, 0x72, 0xda, 0x46,
0x14, 0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2d, 0xbf, 0xed, 0x55, 0xd6, 0xd1, 0x01, 0x3c, 0x73, 0x9d, 0x4e, 0xa3, 0xe9, 0x9d, 0xe1, 0xcc,
0x53, 0x36, 0xd0, 0x21, 0x3c, 0xbf, 0x43, 0x61, 0x42, 0x1e, 0xa2, 0xa7, 0x80, 0x1a, 0x4d, 0xe7,
0xad, 0x8f, 0x9b, 0x9e, 0x73, 0x36, 0xb3, 0x16, 0xd0, 0x0e, 0x6c, 0xcf, 0xd5, 0x8d, 0x61, 0x13,
0xd5, 0x60, 0xcf, 0x64, 0xb5, 0x3b, 0x4e, 0xc7, 0xc3, 0x4d, 0xa7, 0xdd, 0xbc, 0x65, 0x7e, 0x94,
0x62, 0x8e, 0xfb, 0x49, 0x24, 0xa4, 0x50, 0x92, 0x8e, 0x09, 0x2d, 0x46, 0x26, 0xa7, 0xd3, 0xf1,
0xa2, 0xfa, 0xdb, 0x96, 0x7f, 0x1b, 0x57, 0x8a, 0xe6, 0x48, 0x77, 0x92, 0xb4, 0xad, 0x45, 0xcb,
0x2c, 0xac, 0xec, 0x96, 0xfe, 0xbe, 0xa9, 0x59, 0xff, 0xdc, 0xd4, 0xac, 0x7f, 0x6f, 0x6a, 0x56,
0xef, 0xa1, 0xfe, 0x4b, 0xf7, 0xfa, 0xbf, 0x00, 0x00, 0x00, 0xff, 0xff, 0xb1, 0xd9, 0xa8, 0x18,
0x31, 0x0a, 0x00, 0x00,
// 921 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x96, 0xdf, 0x72, 0xdb, 0x44,
0x14, 0xc6, 0x51, 0x93, 0xd4, 0xc9, 0xb1, 0xe3, 0xba, 0x1b, 0x48, 0x94, 0xd0, 0x3a, 0x89, 0x4a,
0x86, 0xc0, 0x4c, 0x9d, 0x69, 0x7a, 0x43, 0x2f, 0x18, 0x46, 0x72, 0x34, 0xb8, 0x6d, 0x90, 0x8b,
0x6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xc7, 0xf5, 0x6b, 0x2b,
0x0b, 0xe9, 0xbe, 0xdb, 0x79, 0xd7, 0xf6, 0x3a, 0x6e, 0x6d, 0x15, 0x1d, 0xc0, 0x13, 0xc7, 0xee,
0x36, 0x5b, 0xee, 0x19, 0x5e, 0x7a, 0xca, 0x1a, 0x3a, 0x84, 0xa7, 0xb7, 0x28, 0x74, 0xc8, 0x43,
0xb4, 0x0d, 0xa8, 0xd9, 0xb2, 0x5f, 0x7b, 0xb8, 0xe5, 0xda, 0x67, 0x53, 0x6b, 0x09, 0xed, 0xc0,
0xd6, 0x4c, 0x5d, 0x1b, 0xd6, 0x51, 0x1d, 0xf6, 0x74, 0x56, 0xa7, 0x6b, 0x77, 0x5d, 0xdc, 0xb2,
0x3b, 0xad, 0x1b, 0xe6, 0x8d, 0x1c, 0x73, 0xda, 0xcf, 0x22, 0x21, 0x87, 0x92, 0x75, 0x74, 0x68,
0x39, 0x31, 0xd9, 0xdd, 0xae, 0x9b, 0xd4, 0x5f, 0xb7, 0xbd, 0x9b, 0xb8, 0x4a, 0x32, 0x47, 0xbe,
0x93, 0xa5, 0x6d, 0xce, 0x5b, 0xa6, 0x61, 0x55, 0xa7, 0xf2, 0xf7, 0x75, 0xdd, 0xf8, 0xe7, 0xba,
0x6e, 0xfc, 0x7b, 0x5d, 0x37, 0xfa, 0x0f, 0xd5, 0x97, 0xe1, 0xcb, 0xff, 0x02, 0x00, 0x00, 0xff,
0xff, 0xec, 0x05, 0xc3, 0xc5, 0x78, 0x0a, 0x00, 0x00,
}
func (m *Envelope) Marshal() (dAtA []byte, err error) {
@@ -2350,6 +2400,33 @@ func (m *ExitResponse) MarshalTo(dAtA []byte) (int, error) {
return i, nil
}
func (m *Handshake) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *Handshake) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if len(m.DepositContractAddress) > 0 {
dAtA[i] = 0xa
i++
i = encodeVarintMessages(dAtA, i, uint64(len(m.DepositContractAddress)))
i += copy(dAtA[i:], m.DepositContractAddress)
}
if m.XXX_unrecognized != nil {
i += copy(dAtA[i:], m.XXX_unrecognized)
}
return i, nil
}
func encodeVarintMessages(dAtA []byte, offset int, v uint64) int {
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
@@ -2828,6 +2905,22 @@ func (m *ExitResponse) Size() (n int) {
return n
}
func (m *Handshake) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.DepositContractAddress)
if l > 0 {
n += 1 + l + sovMessages(uint64(l))
}
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func sovMessages(x uint64) (n int) {
for {
n++
@@ -5498,6 +5591,92 @@ func (m *ExitResponse) Unmarshal(dAtA []byte) error {
}
return nil
}
func (m *Handshake) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowMessages
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Handshake: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Handshake: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field DepositContractAddress", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowMessages
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthMessages
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthMessages
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.DepositContractAddress = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipMessages(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthMessages
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthMessages
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipMessages(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0

View File

@@ -138,3 +138,7 @@ message ExitResponse {
bytes hash = 1;
VoluntaryExit voluntary_exit = 2;
}
message Handshake {
string deposit_contract_address = 1;
}

View File

@@ -7,9 +7,11 @@ go_library(
"dial_relay_node.go",
"discovery.go",
"feed.go",
"handshake_handler.go",
"interfaces.go",
"message.go",
"monitoring.go",
"negotiation.go",
"options.go",
"p2p.go",
"service.go",
@@ -54,6 +56,7 @@ go_test(
"feed_test.go",
"message_test.go",
"monitoring_test.go",
"negotiation_test.go",
"options_test.go",
"register_topic_example_test.go",
"service_test.go",
@@ -71,6 +74,8 @@ go_test(
"@com_github_gogo_protobuf//proto:go_default_library",
"@com_github_golang_mock//gomock:go_default_library",
"@com_github_libp2p_go_libp2p_blankhost//:go_default_library",
"@com_github_libp2p_go_libp2p_net//:go_default_library",
"@com_github_libp2p_go_libp2p_peer//:go_default_library",
"@com_github_libp2p_go_libp2p_peerstore//:go_default_library",
"@com_github_libp2p_go_libp2p_protocol//:go_default_library",
"@com_github_libp2p_go_libp2p_pubsub//:go_default_library",

View File

@@ -37,11 +37,7 @@ func startDHTDiscovery(ctx context.Context, host host.Host, bootstrapAddr string
ctx, span := trace.StartSpan(ctx, "p2p_startDHTDiscovery")
defer span.End()
addr, err := iaddr.ParseString(bootstrapAddr)
if err != nil {
return err
}
peerinfo, err := ps.InfoFromP2pAddr(addr.Multiaddr())
peerinfo, err := peerInfoFromAddr(bootstrapAddr)
if err != nil {
return err
}
@@ -50,6 +46,14 @@ func startDHTDiscovery(ctx context.Context, host host.Host, bootstrapAddr string
return err
}
func peerInfoFromAddr(address string) (*ps.PeerInfo, error) {
addr, err := iaddr.ParseString(address)
if err != nil {
return nil, err
}
return ps.InfoFromP2pAddr(addr.Multiaddr())
}
// Discovery implements mDNS notifee interface.
type discovery struct {
ctx context.Context

View File

@@ -0,0 +1,23 @@
package p2p
import (
ggio "github.com/gogo/protobuf/io"
host "github.com/libp2p/go-libp2p-host"
inet "github.com/libp2p/go-libp2p-net"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
)
// setHandshakeHandler to respond to requests for p2p handshake messages.
func setHandshakeHandler(host host.Host, contractAddress string) {
host.SetStreamHandler(handshakeProtocol, func(stream inet.Stream) {
defer stream.Close()
log.Debug("Handling handshake stream")
w := ggio.NewDelimitedWriter(stream)
defer w.Close()
hs := &pb.Handshake{DepositContractAddress: contractAddress}
if err := w.WriteMsg(hs); err != nil {
log.WithError(err).Error("Failed to write handshake response")
}
})
}

93
shared/p2p/negotiation.go Normal file
View File

@@ -0,0 +1,93 @@
package p2p
import (
"context"
ggio "github.com/gogo/protobuf/io"
host "github.com/libp2p/go-libp2p-host"
inet "github.com/libp2p/go-libp2p-net"
peer "github.com/libp2p/go-libp2p-peer"
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
"github.com/sirupsen/logrus"
)
const handshakeProtocol = prysmProtocolPrefix + "/handshake"
// setupPeerNegotiation adds a "Connected" event handler which checks a peer's
// handshake to ensure the peer is on the same blockchain. This currently
// checks only the deposit contract address. Some peer IDs may be excluded.
// For example, a relay or bootnode will not support the handshake protocol,
// but we would not want to disconnect from those well known peer IDs.
func setupPeerNegotiation(h host.Host, contractAddress string, exclusions []peer.ID) {
h.Network().Notify(&inet.NotifyBundle{
ConnectedF: func(net inet.Network, conn inet.Conn) {
// Must be handled in a goroutine as this callback cannot be blocking.
go func() {
// Exclude bootstrap node, relay node, etc.
for _, exclusion := range exclusions {
if conn.RemotePeer() == exclusion {
return
}
}
log.WithField("peer", conn.RemotePeer()).Debug(
"Checking connection to peer",
)
s, err := h.NewStream(
context.Background(),
conn.RemotePeer(),
handshakeProtocol,
)
if err != nil {
log.WithError(err).WithField("peer", conn.RemotePeer()).Error(
"Failed to open stream with newly connected peer",
)
if err := h.Network().ClosePeer(conn.RemotePeer()); err != nil {
log.WithError(err).Error("failed to disconnect peer")
}
return
}
defer s.Close()
w := ggio.NewDelimitedWriter(s)
defer w.Close()
hs := &pb.Handshake{DepositContractAddress: contractAddress}
if err := w.WriteMsg(hs); err != nil {
log.WithError(err).Error("Failed to write handshake to peer")
if err := h.Network().ClosePeer(conn.RemotePeer()); err != nil {
log.WithError(err).Error("failed to disconnect peer")
}
return
}
r := ggio.NewDelimitedReader(s, maxMessageSize)
resp := &pb.Handshake{}
if err := r.ReadMsg(resp); err != nil {
log.WithError(err).Error("Failed to read message")
if err := h.Network().ClosePeer(conn.RemotePeer()); err != nil {
log.WithError(err).Error("failed to disconnect peer")
}
return
}
log.WithField("msg", resp).Debug("Handshake received")
if resp.DepositContractAddress != contractAddress {
log.WithFields(logrus.Fields{
"peerContract": resp.DepositContractAddress,
"expectedContract": contractAddress,
}).Warn("Disconnecting from peer on different contract")
if err := h.Network().ClosePeer(conn.RemotePeer()); err != nil {
log.WithError(err).Error("failed to disconnect peer")
}
}
}()
},
})
}

View File

@@ -0,0 +1,58 @@
package p2p
import (
"context"
"testing"
"time"
bhost "github.com/libp2p/go-libp2p-blankhost"
libp2pnet "github.com/libp2p/go-libp2p-net"
peer "github.com/libp2p/go-libp2p-peer"
pstore "github.com/libp2p/go-libp2p-peerstore"
swarmt "github.com/libp2p/go-libp2p-swarm/testing"
)
func TestNegotiation_AcceptsValidPeer(t *testing.T) {
ctx := context.Background()
hostA := bhost.NewBlankHost(swarmt.GenSwarm(t, ctx))
hostB := bhost.NewBlankHost(swarmt.GenSwarm(t, ctx))
address := "same"
setHandshakeHandler(hostA, address)
setHandshakeHandler(hostB, address)
setupPeerNegotiation(hostA, address, []peer.ID{})
setupPeerNegotiation(hostB, address, []peer.ID{})
if err := hostA.Connect(ctx, pstore.PeerInfo{ID: hostB.ID(), Addrs: hostB.Addrs()}); err != nil {
t.Fatal(err)
}
// Allow short delay for async negotiation.
time.Sleep(200 * time.Millisecond)
if hostA.Network().Connectedness(hostB.ID()) != libp2pnet.Connected {
t.Error("hosts are not connected")
}
}
func TestNegotiation_DisconnectsDifferentDepositContract(t *testing.T) {
ctx := context.Background()
hostA := bhost.NewBlankHost(swarmt.GenSwarm(t, ctx))
hostB := bhost.NewBlankHost(swarmt.GenSwarm(t, ctx))
setHandshakeHandler(hostA, "hostA")
setHandshakeHandler(hostB, "hostB")
setupPeerNegotiation(hostA, "hostA", []peer.ID{})
setupPeerNegotiation(hostB, "hostB", []peer.ID{})
if err := hostA.Connect(ctx, pstore.PeerInfo{ID: hostB.ID(), Addrs: hostB.Addrs()}); err != nil {
t.Fatal(err)
}
// Allow short delay for async negotiation.
time.Sleep(200 * time.Millisecond)
if hostA.Network().Connectedness(hostB.ID()) == libp2pnet.Connected {
t.Error("hosts are connected, but should not be connected")
}
}

View File

@@ -60,10 +60,11 @@ type Server struct {
// ServerConfig for peer to peer networking.
type ServerConfig struct {
NoDiscovery bool
BootstrapNodeAddr string
RelayNodeAddr string
Port int
NoDiscovery bool
BootstrapNodeAddr string
RelayNodeAddr string
Port int
DepositContractAddress string
}
// NewServer creates a new p2p server instance.
@@ -103,6 +104,22 @@ func NewServer(cfg *ServerConfig) (*Server, error) {
return nil, err
}
// Blockchain peering negitiation; excludes negotiating with bootstrap or
// relay nodes.
exclusions := []peer.ID{}
for _, addr := range []string{cfg.BootstrapNodeAddr, cfg.RelayNodeAddr} {
if addr == "" {
continue
}
info, err := peerInfoFromAddr(addr)
if err != nil {
return nil, err
}
exclusions = append(exclusions, info.ID)
}
setupPeerNegotiation(h, cfg.DepositContractAddress, exclusions)
setHandshakeHandler(h, cfg.DepositContractAddress)
return &Server{
ctx: ctx,
cancel: cancel,

View File

@@ -39,19 +39,14 @@ func init() {
logrus.SetLevel(logrus.DebugLevel)
}
func TestStartDialRelayNode_InvalidMultiaddress(t *testing.T) {
hook := logTest.NewGlobal()
s, err := NewServer(&ServerConfig{
func TestNewServer_InvalidMultiaddress(t *testing.T) {
_, err := NewServer(&ServerConfig{
RelayNodeAddr: "bad",
})
if err != nil {
t.Fatalf("Unable to create server: %v", err)
if err.Error() != "invalid multiaddr, must begin with /" {
t.Fatal("expected invalid multiaddr err")
}
s.Start()
logContains(t, hook, "Could not dial relay node: invalid multiaddr, must begin with /", logrus.ErrorLevel)
}
func TestP2P_PortTaken(t *testing.T) {
@@ -448,6 +443,8 @@ func simulateIncomingMessage(t *testing.T, s *Server, topic string, msg proto.Me
ctx := context.Background()
h := bhost.NewBlankHost(swarmt.GenSwarm(t, ctx))
setHandshakeHandler(h, "")
gsub, err := pubsub.NewFloodSub(ctx, h)
if err != nil {
return err