-
Notifications
You must be signed in to change notification settings - Fork 199
/
message.go
65 lines (54 loc) · 1.81 KB
/
message.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
package libp2p
import (
"fmt"
"github.com/ElrondNetwork/elrond-go-core/core"
"github.com/ElrondNetwork/elrond-go-core/core/check"
"github.com/ElrondNetwork/elrond-go/p2p"
"github.com/ElrondNetwork/elrond-go/p2p/data"
"github.com/ElrondNetwork/elrond-go/p2p/message"
pubsub "github.com/ElrondNetwork/go-libp2p-pubsub"
"github.com/libp2p/go-libp2p-core/peer"
)
const currentTopicMessageVersion = uint32(1)
// NewMessage returns a new instance of a Message object
func NewMessage(msg *pubsub.Message, marshalizer p2p.Marshalizer) (*message.Message, error) {
if check.IfNil(marshalizer) {
return nil, p2p.ErrNilMarshalizer
}
if msg == nil {
return nil, p2p.ErrNilMessage
}
if msg.Topic == nil {
return nil, p2p.ErrNilTopic
}
newMsg := &message.Message{
FromField: msg.From,
PayloadField: msg.Data,
SeqNoField: msg.Seqno,
TopicField: *msg.Topic,
SignatureField: msg.Signature,
KeyField: msg.Key,
}
topicMessage := &data.TopicMessage{}
err := marshalizer.Unmarshal(topicMessage, msg.Data)
if err != nil {
return nil, fmt.Errorf("%w error: %s", p2p.ErrMessageUnmarshalError, err.Error())
}
// TODO change this area when new versions of the message will need to be implemented
if topicMessage.Version != currentTopicMessageVersion {
return nil, fmt.Errorf("%w, supported %d, got %d",
p2p.ErrUnsupportedMessageVersion, currentTopicMessageVersion, topicMessage.Version)
}
if len(topicMessage.SignatureOnPid)+len(topicMessage.Pk) > 0 {
return nil, fmt.Errorf("%w for topicMessage.SignatureOnPid and topicMessage.Pk",
p2p.ErrUnsupportedFields)
}
newMsg.DataField = topicMessage.Payload
newMsg.TimestampField = topicMessage.Timestamp
id, err := peer.IDFromBytes(newMsg.From())
if err != nil {
return nil, err
}
newMsg.PeerField = core.PeerID(id)
return newMsg, nil
}