-
Notifications
You must be signed in to change notification settings - Fork 1
/
grpc.go
105 lines (82 loc) · 2.58 KB
/
grpc.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
package main
import (
"context"
"fmt"
"net"
"github.com/spectre-project/spectred/domain/consensus/model/externalapi"
"github.com/spectre-project/spectred/domain/consensus/utils/subnetworks"
"github.com/spectre-project/spectred/app/appmessage"
"github.com/spectre-project/spectred/infrastructure/network/dnsseed/pb"
"github.com/miekg/dns"
"github.com/pkg/errors"
"google.golang.org/grpc"
)
// GRPCServer contains methods to start and stop GRPC server
type GRPCServer interface {
Start(listenInterface string) error
Stop()
}
type grpcServer struct {
pb.UnimplementedPeerServiceServer
server *grpc.Server
amgr *Manager
}
// NewGRPCServer returns new GRPC server
func NewGRPCServer(amgr *Manager) GRPCServer {
return &grpcServer{amgr: amgr}
}
func (s *grpcServer) Start(listenInterface string) error {
s.server = grpc.NewServer()
pb.RegisterPeerServiceServer(s.server, s)
lis, err := net.Listen("tcp", fmt.Sprintf(listenInterface))
if err != nil {
return errors.WithStack(err)
}
spawn("gRPC server", func() {
err = s.server.Serve(lis)
if err != nil {
fmt.Printf("%+v", err)
}
})
return nil
}
func (s *grpcServer) Stop() {
s.server.Stop()
s.server = nil
}
func (s *grpcServer) GetPeersList(ctx context.Context, req *pb.GetPeersListRequest) (*pb.GetPeersListResponse, error) {
subnetworkID, err := FromProtobufSubnetworkID(req.SubnetworkID)
if err != nil {
return nil, err
}
// mb, we should move DNS-related logic out of manager?
ipv4Addresses := s.amgr.GoodAddresses(dns.TypeA, req.IncludeAllSubnetworks, subnetworkID)
ipv6Addresses := s.amgr.GoodAddresses(dns.TypeAAAA, req.IncludeAllSubnetworks, subnetworkID)
addresses := ToProtobufAddresses(append(ipv4Addresses, ipv6Addresses...))
log.Errorf("ADDRESSES: %+v", addresses)
return &pb.GetPeersListResponse{Addresses: addresses}, nil
}
// FromProtobufSubnetworkID returns new *externalapi.DomainSubnetworkID from proto
func FromProtobufSubnetworkID(proto []byte) (*externalapi.DomainSubnetworkID, error) {
if len(proto) == 0 {
return nil, nil
}
subnetworkID, err := subnetworks.FromBytes(proto)
if err != nil {
return nil, err
}
return subnetworkID, nil
}
// ToProtobufAddresses converts slice of *appmessage.NetAddress to slice of *pb.NetAddress
func ToProtobufAddresses(addresses []*appmessage.NetAddress) []*pb.NetAddress {
var protoAddresses []*pb.NetAddress
for _, addr := range addresses {
proto := &pb.NetAddress{
Timestamp: addr.Timestamp.UnixSeconds(),
IP: []byte(addr.IP),
Port: uint32(addr.Port),
}
protoAddresses = append(protoAddresses, proto)
}
return protoAddresses
}