-
Notifications
You must be signed in to change notification settings - Fork 0
/
message.go
100 lines (76 loc) · 2.31 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// (c) 2019-2021, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package message
import (
"errors"
"github.com/Toinounet21/swapalanchego/codec"
"github.com/ethereum/go-ethereum/common"
"github.com/Toinounet21/swapalanchego/ids"
"github.com/Toinounet21/swapalanchego/utils/units"
)
const (
// EthMsgSoftCapSize is the ideal size of encoded transaction bytes we send in
// any [EthTxs] or [AtomicTx] message. We do not limit inbound messages to
// this size, however. Max inbound message size is enforced by the codec
// (512KB).
EthMsgSoftCapSize = common.StorageSize(64 * units.KiB)
atomicTxType = "atomic-tx"
ethTxsType = "eth-txs"
)
var (
_ Message = &AtomicTx{}
_ Message = &EthTxs{}
errUnexpectedCodecVersion = errors.New("unexpected codec version")
)
type Message interface {
// Handle this message with the correct message handler
Handle(handler GossipHandler, nodeID ids.ShortID) 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 returns user-friendly name for this object that can be used for logging
Type() string
}
type message []byte
func (m *message) initialize(bytes []byte) { *m = bytes }
func (m *message) Bytes() []byte { return *m }
type AtomicTx struct {
message
Tx []byte `serialize:"true"`
}
func (msg *AtomicTx) Handle(handler GossipHandler, nodeID ids.ShortID) error {
return handler.HandleAtomicTx(nodeID, msg)
}
func (msg *AtomicTx) Type() string {
return atomicTxType
}
type EthTxs struct {
message
Txs []byte `serialize:"true"`
}
func (msg *EthTxs) Handle(handler GossipHandler, nodeID ids.ShortID) error {
return handler.HandleEthTxs(nodeID, msg)
}
func (msg *EthTxs) Type() string {
return ethTxsType
}
func ParseMessage(codec codec.Manager, bytes []byte) (Message, error) {
var msg Message
version, err := codec.Unmarshal(bytes, &msg)
if err != nil {
return nil, err
}
if version != Version {
return nil, errUnexpectedCodecVersion
}
msg.initialize(bytes)
return msg, nil
}
func BuildMessage(codec codec.Manager, msg Message) ([]byte, error) {
bytes, err := codec.Marshal(Version, &msg)
msg.initialize(bytes)
return bytes, err
}