-
Notifications
You must be signed in to change notification settings - Fork 661
/
message.go
84 lines (68 loc) · 1.9 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// Copyright (C) 2019-2023, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package message
import (
"errors"
"fmt"
"google.golang.org/protobuf/proto"
"github.com/ava-labs/avalanchego/ids"
pb "github.com/ava-labs/avalanchego/proto/pb/message"
)
var (
_ Message = (*Tx)(nil)
ErrUnexpectedCodecVersion = errors.New("unexpected codec version")
errUnknownMessageType = errors.New("unknown message type")
)
type Message interface {
// Handle this message with the correct message handler
Handle(handler Handler, nodeID ids.NodeID, requestID uint32) error
// initialize should be called whenever a message is built or parsed
initialize([]byte)
// Bytes returns the binary representation of this message
//
// Bytes should only be called after being initialized
Bytes() []byte
}
type message []byte
func (m *message) initialize(bytes []byte) {
*m = bytes
}
func (m *message) Bytes() []byte {
return *m
}
func Parse(bytes []byte) (Message, error) {
var (
msg Message
protoMsg pb.Message
)
if err := proto.Unmarshal(bytes, &protoMsg); err == nil {
// This message was encoded with proto.
switch m := protoMsg.GetMessage().(type) {
case *pb.Message_Tx:
msg = &Tx{
Tx: m.Tx.Tx,
}
default:
return nil, fmt.Errorf("%w: %T", errUnknownMessageType, protoMsg.GetMessage())
}
} else {
// This message wasn't encoded with proto.
// It must have been encoded with avalanchego's codec.
// TODO remove else statement remove once all nodes support proto encoding.
// i.e. when all nodes are on v1.11.0 or later.
version, err := c.Unmarshal(bytes, &msg)
if err != nil {
return nil, err
}
if version != codecVersion {
return nil, ErrUnexpectedCodecVersion
}
}
msg.initialize(bytes)
return msg, nil
}
func Build(msg Message) ([]byte, error) {
bytes, err := c.Marshal(codecVersion, &msg)
msg.initialize(bytes)
return bytes, err
}