-
Notifications
You must be signed in to change notification settings - Fork 0
/
p2pconnection.go
54 lines (43 loc) · 1.48 KB
/
p2pconnection.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
// Copyright (c) 2019 Laszlo Sari
//
// FileTribe 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.
//
// FileTribe 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 common
import (
"net"
"github.com/pkg/errors"
)
// P2PConn is tcp connection to an IPFS p2p dial/stream endpoint
type P2PConn net.TCPConn
// ReadMessage reads a message from the connection socket
func (conn *P2PConn) ReadMessage(addressBook *AddressBook) (*Message, error) {
data := make([]byte, 4096)
length, err := conn.Read(data)
if err != nil {
return nil, errors.Wrapf(err, "could not read from net.Conn")
}
data = data[:length]
msg, err := DecodeMessage(data)
if err != nil {
return nil, errors.Wrap(err, "could not unmarshal Message")
}
contact, err := addressBook.Get(msg.From)
if err != nil {
return nil, errors.Wrap(err, "could not get contact from address book")
}
if err := msg.Verify(contact); err != nil {
return nil, errors.Wrapf(err, "invalid message")
}
return msg, nil
}