lnwire: add new SerializedSize method to all wire messages
This'll be useful for the bandwidth based rate limiting we'll implement in the next commit.
This commit is contained in:
40 files changed
+453
-4
No files matched your search
@@ -12,6 +12,10 @@ import (
|
||||
"io"
|
||||
)
|
||||
|
||||
// MessageTypeSize is the size in bytes of the message type field in the header
|
||||
// of all messages.
|
||||
const MessageTypeSize = 2
|
||||
|
||||
// MessageType is the unique 2 byte big-endian integer that indicates the type
|
||||
// of message on the wire. All messages have a very simple header which
|
||||
// consists simply of 2-byte message type. We omit a length field, and checksum
|
||||
@@ -234,6 +238,31 @@ type LinkUpdater interface {
|
||||
TargetChanID() ChannelID
|
||||
}
|
||||
|
||||
// SizeableMessage is an interface that extends the base Message interface with
|
||||
// a method to calculate the serialized size of a message.
|
||||
type SizeableMessage interface {
|
||||
Message
|
||||
|
||||
// SerializedSize returns the serialized size of the message in bytes.
|
||||
// The returned size includes the message type header bytes.
|
||||
SerializedSize() (uint32, error)
|
||||
}
|
||||
|
||||
// MessageSerializedSize calculates the serialized size of a message in bytes.
|
||||
// This is a helper function that can be used by all message types to implement
|
||||
// the SerializedSize method.
|
||||
func MessageSerializedSize(msg Message) (uint32, error) {
|
||||
var buf bytes.Buffer
|
||||
|
||||
// Encode the message to the buffer.
|
||||
if err := msg.Encode(&buf, 0); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
// Add the size of the message type.
|
||||
return uint32(buf.Len()) + MessageTypeSize, nil
|
||||
}
|
||||
|
||||
// makeEmptyMessage creates a new empty message of the proper concrete type
|
||||
// based on the passed message type.
|
||||
func makeEmptyMessage(msgType MessageType) (Message, error) {
|
||||
@@ -337,6 +366,12 @@ func makeEmptyMessage(msgType MessageType) (Message, error) {
|
||||
return msg, nil
|
||||
}
|
||||
|
||||
// MakeEmptyMessage creates a new empty message of the proper concrete type
|
||||
// based on the passed message type. This is exported to be used in tests.
|
||||
func MakeEmptyMessage(msgType MessageType) (Message, error) {
|
||||
return makeEmptyMessage(msgType)
|
||||
}
|
||||
|
||||
// WriteMessage writes a lightning Message to a buffer including the necessary
|
||||
// header information and returns the number of bytes written. If any error is
|
||||
// encountered, the buffer passed will be reset to its original state since we
|
||||
|
||||
Reference in new issue
Block a user