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

lightningnetwork / lnd / 16181619122

09 Jul 2025 10:33PM UTC coverage: 55.326% (-2.3%) from 57.611%
16181619122

Pull #10060

github

web-flow
Merge d15e8671f into 0e830da9d
Pull Request #10060: sweep: fix expected spending events being missed

9 of 26 new or added lines in 2 files covered. (34.62%)

23695 existing lines in 280 files now uncovered.

108518 of 196143 relevant lines covered (55.33%)

22354.81 hits per line

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

93.66
/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,693✔
79
        switch t {
3,693✔
80
        case MsgUpdateAddHTLC:
930✔
81
                return true
930✔
82
        case MsgUpdateFulfillHTLC:
250✔
83
                return true
250✔
84
        case MsgUpdateFailHTLC:
138✔
85
                return true
138✔
86
        case MsgUpdateFailMalformedHTLC:
3✔
87
                return true
3✔
88
        case MsgUpdateFee:
3✔
89
                return true
3✔
90
        default:
2,369✔
91
                return false
2,369✔
92
        }
93
}
94

95
// ErrorEncodeMessage is used when failed to encode the message payload.
96
func ErrorEncodeMessage(err error) error {
4✔
97
        return fmt.Errorf("failed to encode message to buffer, got %w", err)
4✔
98
}
4✔
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 {
2✔
108
        return fmt.Errorf(
2✔
109
                "message payload is too large - encoded %d bytes, "+
2✔
110
                        "but maximum message payload is %d bytes",
2✔
111
                size, MaxMsgBody,
2✔
112
        )
2✔
113
}
2✔
114

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

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

270
        // Add the size of the message type.
271
        return uint32(buf.Len()) + MessageTypeSize, nil
62✔
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) {
19,199✔
277
        var msg Message
19,199✔
278

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

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

376
        return msg, nil
18,388✔
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) {
4,878✔
382
        return makeEmptyMessage(msgType)
4,878✔
383
}
4,878✔
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) {
12,828✔
394
        // Record the size of the bytes already written in buffer.
12,828✔
395
        oldByteSize := buf.Len()
12,828✔
396

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

405
        // Write the message type.
406
        var mType [2]byte
12,828✔
407
        binary.BigEndian.PutUint16(mType[:], uint16(msg.MsgType()))
12,828✔
408
        msgTypeBytes, err := buf.Write(mType[:])
12,828✔
409
        if err != nil {
12,828✔
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 {
12,831✔
415
                return cleanBrokenBytes(buf), ErrorEncodeMessage(err)
3✔
416
        }
3✔
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
12,825✔
423
        if lenp > MaxMsgBody {
12,826✔
424
                return cleanBrokenBytes(buf), ErrorPayloadTooLarge(lenp)
1✔
425
        }
1✔
426

427
        return buf.Len() - oldByteSize, nil
12,824✔
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) {
14,320✔
433
        // First, we'll read out the first two bytes of the message so we can
14,320✔
434
        // create the proper empty message.
14,320✔
435
        var mType [2]byte
14,320✔
436
        if _, err := io.ReadFull(r, mType[:]); err != nil {
14,320✔
437
                return nil, err
×
438
        }
×
439

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

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

452
        return msg, nil
12,191✔
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