• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

lightningnetwork / lnd / 17011395530

16 Aug 2025 06:08PM UTC coverage: 57.298% (-9.5%) from 66.765%
17011395530

Pull #10167

github

web-flow
Merge 3c250722d into fb1adfc21
Pull Request #10167: multi: bump Go to 1.24.6

99112 of 172975 relevant lines covered (57.3%)

1.78 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

69.78
/lnwire/message.go
1
// Copyright (c) 2013-2017 The btcsuite developers
2
// Copyright (c) 2015-2016 The Decred developers
3
// code derived from https://github .com/btcsuite/btcd/blob/master/wire/message.go
4
// Copyright (C) 2015-2022 The Lightning Network Developers
5

6
package lnwire
7

8
import (
9
        "bytes"
10
        "encoding/binary"
11
        "fmt"
12
        "io"
13
)
14

15
// MessageTypeSize is the size in bytes of the message type field in the header
16
// of all messages.
17
const MessageTypeSize = 2
18

19
// MessageType is the unique 2 byte big-endian integer that indicates the type
20
// of message on the wire. All messages have a very simple header which
21
// consists simply of 2-byte message type. We omit a length field, and checksum
22
// as the Lightning Protocol is intended to be encapsulated within a
23
// confidential+authenticated cryptographic messaging protocol.
24
type MessageType uint16
25

26
// The currently defined message types within this current version of the
27
// Lightning protocol.
28
const (
29
        MsgWarning                 MessageType = 1
30
        MsgStfu                                = 2
31
        MsgInit                                = 16
32
        MsgError                               = 17
33
        MsgPing                                = 18
34
        MsgPong                                = 19
35
        MsgOpenChannel                         = 32
36
        MsgAcceptChannel                       = 33
37
        MsgFundingCreated                      = 34
38
        MsgFundingSigned                       = 35
39
        MsgChannelReady                        = 36
40
        MsgShutdown                            = 38
41
        MsgClosingSigned                       = 39
42
        MsgClosingComplete                     = 40
43
        MsgClosingSig                          = 41
44
        MsgDynPropose                          = 111
45
        MsgDynAck                              = 113
46
        MsgDynReject                           = 115
47
        MsgDynCommit                           = 117
48
        MsgUpdateAddHTLC                       = 128
49
        MsgUpdateFulfillHTLC                   = 130
50
        MsgUpdateFailHTLC                      = 131
51
        MsgCommitSig                           = 132
52
        MsgRevokeAndAck                        = 133
53
        MsgUpdateFee                           = 134
54
        MsgUpdateFailMalformedHTLC             = 135
55
        MsgChannelReestablish                  = 136
56
        MsgChannelAnnouncement                 = 256
57
        MsgNodeAnnouncement                    = 257
58
        MsgChannelUpdate                       = 258
59
        MsgAnnounceSignatures                  = 259
60
        MsgAnnounceSignatures2                 = 260
61
        MsgQueryShortChanIDs                   = 261
62
        MsgReplyShortChanIDsEnd                = 262
63
        MsgQueryChannelRange                   = 263
64
        MsgReplyChannelRange                   = 264
65
        MsgGossipTimestampRange                = 265
66
        MsgChannelAnnouncement2                = 267
67
        MsgChannelUpdate2                      = 271
68
        MsgKickoffSig                          = 777
69

70
        // MsgEnd defines the end of the official message range of the protocol.
71
        // If a new message is added beyond this message, then this should be
72
        // modified.
73
        MsgEnd = 778
74
)
75

76
// IsChannelUpdate is a filter function that discerns channel update messages
77
// from the other messages in the Lightning Network Protocol.
78
func (t MessageType) IsChannelUpdate() bool {
3✔
79
        switch t {
3✔
80
        case MsgUpdateAddHTLC:
3✔
81
                return true
3✔
82
        case MsgUpdateFulfillHTLC:
3✔
83
                return true
3✔
84
        case MsgUpdateFailHTLC:
3✔
85
                return true
3✔
86
        case MsgUpdateFailMalformedHTLC:
3✔
87
                return true
3✔
88
        case MsgUpdateFee:
×
89
                return true
×
90
        default:
3✔
91
                return false
3✔
92
        }
93
}
94

95
// ErrorEncodeMessage is used when failed to encode the message payload.
96
func ErrorEncodeMessage(err error) error {
×
97
        return fmt.Errorf("failed to encode message to buffer, got %w", err)
×
98
}
×
99

100
// ErrorWriteMessageType is used when failed to write the message type.
101
func ErrorWriteMessageType(err error) error {
×
102
        return fmt.Errorf("failed to write message type, got %w", err)
×
103
}
×
104

105
// ErrorPayloadTooLarge is used when the payload size exceeds the
106
// MaxMsgBody.
107
func ErrorPayloadTooLarge(size int) error {
×
108
        return fmt.Errorf(
×
109
                "message payload is too large - encoded %d bytes, "+
×
110
                        "but maximum message payload is %d bytes",
×
111
                size, MaxMsgBody,
×
112
        )
×
113
}
×
114

115
// String return the string representation of message type.
116
func (t MessageType) String() string {
3✔
117
        switch t {
3✔
118
        case MsgWarning:
×
119
                return "Warning"
×
120
        case MsgStfu:
3✔
121
                return "Stfu"
3✔
122
        case MsgInit:
3✔
123
                return "Init"
3✔
124
        case MsgOpenChannel:
3✔
125
                return "MsgOpenChannel"
3✔
126
        case MsgAcceptChannel:
3✔
127
                return "MsgAcceptChannel"
3✔
128
        case MsgFundingCreated:
3✔
129
                return "MsgFundingCreated"
3✔
130
        case MsgFundingSigned:
3✔
131
                return "MsgFundingSigned"
3✔
132
        case MsgChannelReady:
3✔
133
                return "ChannelReady"
3✔
134
        case MsgShutdown:
3✔
135
                return "Shutdown"
3✔
136
        case MsgClosingSigned:
3✔
137
                return "ClosingSigned"
3✔
138
        case MsgDynPropose:
×
139
                return "DynPropose"
×
140
        case MsgDynAck:
×
141
                return "DynAck"
×
142
        case MsgDynReject:
×
143
                return "DynReject"
×
144
        case MsgDynCommit:
×
145
                return "DynCommit"
×
146
        case MsgKickoffSig:
×
147
                return "KickoffSig"
×
148
        case MsgUpdateAddHTLC:
3✔
149
                return "UpdateAddHTLC"
3✔
150
        case MsgUpdateFailHTLC:
3✔
151
                return "UpdateFailHTLC"
3✔
152
        case MsgUpdateFulfillHTLC:
3✔
153
                return "UpdateFulfillHTLC"
3✔
154
        case MsgCommitSig:
3✔
155
                return "CommitSig"
3✔
156
        case MsgRevokeAndAck:
3✔
157
                return "RevokeAndAck"
3✔
158
        case MsgUpdateFailMalformedHTLC:
3✔
159
                return "UpdateFailMalformedHTLC"
3✔
160
        case MsgChannelReestablish:
3✔
161
                return "ChannelReestablish"
3✔
162
        case MsgError:
3✔
163
                return "Error"
3✔
164
        case MsgChannelAnnouncement:
3✔
165
                return "ChannelAnnouncement"
3✔
166
        case MsgChannelUpdate:
3✔
167
                return "ChannelUpdate"
3✔
168
        case MsgNodeAnnouncement:
3✔
169
                return "NodeAnnouncement"
3✔
170
        case MsgPing:
×
171
                return "Ping"
×
172
        case MsgAnnounceSignatures:
3✔
173
                return "AnnounceSignatures"
3✔
174
        case MsgPong:
×
175
                return "Pong"
×
176
        case MsgUpdateFee:
×
177
                return "UpdateFee"
×
178
        case MsgQueryShortChanIDs:
3✔
179
                return "QueryShortChanIDs"
3✔
180
        case MsgReplyShortChanIDsEnd:
3✔
181
                return "ReplyShortChanIDsEnd"
3✔
182
        case MsgQueryChannelRange:
3✔
183
                return "QueryChannelRange"
3✔
184
        case MsgReplyChannelRange:
3✔
185
                return "ReplyChannelRange"
3✔
186
        case MsgGossipTimestampRange:
3✔
187
                return "GossipTimestampRange"
3✔
188
        case MsgClosingComplete:
3✔
189
                return "ClosingComplete"
3✔
190
        case MsgClosingSig:
3✔
191
                return "ClosingSig"
3✔
192
        case MsgAnnounceSignatures2:
×
193
                return "MsgAnnounceSignatures2"
×
194
        case MsgChannelAnnouncement2:
×
195
                return "ChannelAnnouncement2"
×
196
        case MsgChannelUpdate2:
×
197
                return "ChannelUpdate2"
×
198
        default:
3✔
199
                return "<unknown>"
3✔
200
        }
201
}
202

203
// UnknownMessage is an implementation of the error interface that allows the
204
// creation of an error in response to an unknown message.
205
type UnknownMessage struct {
206
        messageType MessageType
207
}
208

209
// Error returns a human readable string describing the error.
210
//
211
// This is part of the error interface.
212
func (u *UnknownMessage) Error() string {
3✔
213
        return fmt.Sprintf("unable to parse message of unknown type: %v",
3✔
214
                u.messageType)
3✔
215
}
3✔
216

217
// Serializable is an interface which defines a lightning wire serializable
218
// object.
219
type Serializable interface {
220
        // Decode reads the bytes stream and converts it to the object.
221
        Decode(io.Reader, uint32) error
222

223
        // Encode converts object to the bytes stream and write it into the
224
        // write buffer.
225
        Encode(*bytes.Buffer, uint32) error
226
}
227

228
// Message is an interface that defines a lightning wire protocol message. The
229
// interface is general in order to allow implementing types full control over
230
// the representation of its data.
231
type Message interface {
232
        Serializable
233
        MsgType() MessageType
234
}
235

236
// LinkUpdater is an interface implemented by most messages in BOLT 2 that are
237
// allowed to update the channel state.
238
type LinkUpdater interface {
239
        // All LinkUpdater messages are messages and so we embed the interface
240
        // so that we can treat it as a message if all we know about it is that
241
        // it is a LinkUpdater message.
242
        Message
243

244
        // TargetChanID returns the channel id of the link for which this
245
        // message is intended.
246
        TargetChanID() ChannelID
247
}
248

249
// SizeableMessage is an interface that extends the base Message interface with
250
// a method to calculate the serialized size of a message.
251
type SizeableMessage interface {
252
        Message
253

254
        // SerializedSize returns the serialized size of the message in bytes.
255
        // The returned size includes the message type header bytes.
256
        SerializedSize() (uint32, error)
257
}
258

259
// MessageSerializedSize calculates the serialized size of a message in bytes.
260
// This is a helper function that can be used by all message types to implement
261
// the SerializedSize method.
262
func MessageSerializedSize(msg Message) (uint32, error) {
3✔
263
        var buf bytes.Buffer
3✔
264

3✔
265
        // Encode the message to the buffer.
3✔
266
        if err := msg.Encode(&buf, 0); err != nil {
3✔
267
                return 0, err
×
268
        }
×
269

270
        // Add the size of the message type.
271
        return uint32(buf.Len()) + MessageTypeSize, nil
3✔
272
}
273

274
// makeEmptyMessage creates a new empty message of the proper concrete type
275
// based on the passed message type.
276
func makeEmptyMessage(msgType MessageType) (Message, error) {
3✔
277
        var msg Message
3✔
278

3✔
279
        switch msgType {
3✔
280
        case MsgWarning:
×
281
                msg = &Warning{}
×
282
        case MsgStfu:
3✔
283
                msg = &Stfu{}
3✔
284
        case MsgInit:
3✔
285
                msg = &Init{}
3✔
286
        case MsgOpenChannel:
3✔
287
                msg = &OpenChannel{}
3✔
288
        case MsgAcceptChannel:
3✔
289
                msg = &AcceptChannel{}
3✔
290
        case MsgFundingCreated:
3✔
291
                msg = &FundingCreated{}
3✔
292
        case MsgFundingSigned:
3✔
293
                msg = &FundingSigned{}
3✔
294
        case MsgChannelReady:
3✔
295
                msg = &ChannelReady{}
3✔
296
        case MsgShutdown:
3✔
297
                msg = &Shutdown{}
3✔
298
        case MsgClosingSigned:
3✔
299
                msg = &ClosingSigned{}
3✔
300
        case MsgDynPropose:
×
301
                msg = &DynPropose{}
×
302
        case MsgDynAck:
×
303
                msg = &DynAck{}
×
304
        case MsgDynReject:
×
305
                msg = &DynReject{}
×
306
        case MsgDynCommit:
×
307
                msg = &DynCommit{}
×
308
        case MsgKickoffSig:
×
309
                msg = &KickoffSig{}
×
310
        case MsgUpdateAddHTLC:
3✔
311
                msg = &UpdateAddHTLC{}
3✔
312
        case MsgUpdateFailHTLC:
3✔
313
                msg = &UpdateFailHTLC{}
3✔
314
        case MsgUpdateFulfillHTLC:
3✔
315
                msg = &UpdateFulfillHTLC{}
3✔
316
        case MsgCommitSig:
3✔
317
                msg = &CommitSig{}
3✔
318
        case MsgRevokeAndAck:
3✔
319
                msg = &RevokeAndAck{}
3✔
320
        case MsgUpdateFee:
×
321
                msg = &UpdateFee{}
×
322
        case MsgUpdateFailMalformedHTLC:
3✔
323
                msg = &UpdateFailMalformedHTLC{}
3✔
324
        case MsgChannelReestablish:
3✔
325
                msg = &ChannelReestablish{}
3✔
326
        case MsgError:
3✔
327
                msg = &Error{}
3✔
328
        case MsgChannelAnnouncement:
3✔
329
                msg = &ChannelAnnouncement1{}
3✔
330
        case MsgChannelUpdate:
3✔
331
                msg = &ChannelUpdate1{}
3✔
332
        case MsgNodeAnnouncement:
3✔
333
                msg = &NodeAnnouncement{}
3✔
334
        case MsgPing:
×
335
                msg = &Ping{}
×
336
        case MsgAnnounceSignatures:
3✔
337
                msg = &AnnounceSignatures1{}
3✔
338
        case MsgPong:
×
339
                msg = &Pong{}
×
340
        case MsgQueryShortChanIDs:
3✔
341
                msg = &QueryShortChanIDs{}
3✔
342
        case MsgReplyShortChanIDsEnd:
3✔
343
                msg = &ReplyShortChanIDsEnd{}
3✔
344
        case MsgQueryChannelRange:
3✔
345
                msg = &QueryChannelRange{}
3✔
346
        case MsgReplyChannelRange:
3✔
347
                msg = &ReplyChannelRange{}
3✔
348
        case MsgGossipTimestampRange:
3✔
349
                msg = &GossipTimestampRange{}
3✔
350
        case MsgClosingComplete:
3✔
351
                msg = &ClosingComplete{}
3✔
352
        case MsgClosingSig:
3✔
353
                msg = &ClosingSig{}
3✔
354
        case MsgAnnounceSignatures2:
×
355
                msg = &AnnounceSignatures2{}
×
356
        case MsgChannelAnnouncement2:
×
357
                msg = &ChannelAnnouncement2{}
×
358
        case MsgChannelUpdate2:
×
359
                msg = &ChannelUpdate2{}
×
360
        default:
3✔
361
                // If the message is not within our custom range and has not
3✔
362
                // specifically been overridden, return an unknown message.
3✔
363
                //
3✔
364
                // Note that we do not allow custom message overrides to replace
3✔
365
                // known message types, only protocol messages that are not yet
3✔
366
                // known to lnd.
3✔
367
                if msgType < CustomTypeStart && !IsCustomOverride(msgType) {
6✔
368
                        return nil, &UnknownMessage{msgType}
3✔
369
                }
3✔
370

371
                msg = &Custom{
3✔
372
                        Type: msgType,
3✔
373
                }
3✔
374
        }
375

376
        return msg, nil
3✔
377
}
378

379
// MakeEmptyMessage creates a new empty message of the proper concrete type
380
// based on the passed message type. This is exported to be used in tests.
381
func MakeEmptyMessage(msgType MessageType) (Message, error) {
×
382
        return makeEmptyMessage(msgType)
×
383
}
×
384

385
// WriteMessage writes a lightning Message to a buffer including the necessary
386
// header information and returns the number of bytes written. If any error is
387
// encountered, the buffer passed will be reset to its original state since we
388
// don't want any broken bytes left. In other words, no bytes will be written
389
// if there's an error. Either all or none of the message bytes will be written
390
// to the buffer.
391
//
392
// NOTE: this method is not concurrent safe.
393
func WriteMessage(buf *bytes.Buffer, msg Message, pver uint32) (int, error) {
3✔
394
        // Record the size of the bytes already written in buffer.
3✔
395
        oldByteSize := buf.Len()
3✔
396

3✔
397
        // cleanBrokenBytes is a helper closure that helps reset the buffer to
3✔
398
        // its original state. It truncates all the bytes written in current
3✔
399
        // scope.
3✔
400
        var cleanBrokenBytes = func(b *bytes.Buffer) int {
3✔
401
                b.Truncate(oldByteSize)
×
402
                return 0
×
403
        }
×
404

405
        // Write the message type.
406
        var mType [2]byte
3✔
407
        binary.BigEndian.PutUint16(mType[:], uint16(msg.MsgType()))
3✔
408
        msgTypeBytes, err := buf.Write(mType[:])
3✔
409
        if err != nil {
3✔
410
                return cleanBrokenBytes(buf), ErrorWriteMessageType(err)
×
411
        }
×
412

413
        // Use the write buffer to encode our message.
414
        if err := msg.Encode(buf, pver); err != nil {
3✔
415
                return cleanBrokenBytes(buf), ErrorEncodeMessage(err)
×
416
        }
×
417

418
        // Enforce maximum overall message payload. The write buffer now has
419
        // the size of len(originalBytes) + len(payload) + len(type). We want
420
        // to enforce the payload here, so we subtract it by the length of the
421
        // type and old bytes.
422
        lenp := buf.Len() - oldByteSize - msgTypeBytes
3✔
423
        if lenp > MaxMsgBody {
3✔
424
                return cleanBrokenBytes(buf), ErrorPayloadTooLarge(lenp)
×
425
        }
×
426

427
        return buf.Len() - oldByteSize, nil
3✔
428
}
429

430
// ReadMessage reads, validates, and parses the next Lightning message from r
431
// for the provided protocol version.
432
func ReadMessage(r io.Reader, pver uint32) (Message, error) {
3✔
433
        // First, we'll read out the first two bytes of the message so we can
3✔
434
        // create the proper empty message.
3✔
435
        var mType [2]byte
3✔
436
        if _, err := io.ReadFull(r, mType[:]); err != nil {
3✔
437
                return nil, err
×
438
        }
×
439

440
        msgType := MessageType(binary.BigEndian.Uint16(mType[:]))
3✔
441

3✔
442
        // Now that we know the target message type, we can create the proper
3✔
443
        // empty message type and decode the message into it.
3✔
444
        msg, err := makeEmptyMessage(msgType)
3✔
445
        if err != nil {
6✔
446
                return nil, err
3✔
447
        }
3✔
448
        if err := msg.Decode(r, pver); err != nil {
3✔
449
                return nil, err
×
450
        }
×
451

452
        return msg, nil
3✔
453
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc