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

lightningnetwork / lnd / 9184489199

22 May 2024 02:34AM UTC coverage: 48.835% (-9.6%) from 58.452%
9184489199

push

github

web-flow
Merge pull request #8762 from ProofOfKeags/bugfix/ping-stability

Adjust ping parameters to improve tor stability

22 of 24 new or added lines in 2 files covered. (91.67%)

24816 existing lines in 399 files now uncovered.

91733 of 187843 relevant lines covered (48.83%)

1.04 hits per line

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

55.09
/zpay32/encode.go
1
package zpay32
2

3
import (
4
        "bytes"
5
        "encoding/binary"
6
        "fmt"
7

8
        "github.com/btcsuite/btcd/btcutil"
9
        "github.com/btcsuite/btcd/btcutil/bech32"
10
        "github.com/btcsuite/btcd/chaincfg"
11
        "github.com/btcsuite/btcd/chaincfg/chainhash"
12
        "github.com/lightningnetwork/lnd/lnwire"
13
)
14

15
// Encode takes the given MessageSigner and returns a string encoding this
16
// invoice signed by the node key of the signer.
17
func (invoice *Invoice) Encode(signer MessageSigner) (string, error) {
2✔
18
        // First check that this invoice is valid before starting the encoding.
2✔
19
        if err := validateInvoice(invoice); err != nil {
2✔
UNCOV
20
                return "", err
×
UNCOV
21
        }
×
22

23
        // The buffer will encoded the invoice data using 5-bit groups (base32).
24
        var bufferBase32 bytes.Buffer
2✔
25

2✔
26
        // The timestamp will be encoded using 35 bits, in base32.
2✔
27
        timestampBase32 := uint64ToBase32(uint64(invoice.Timestamp.Unix()))
2✔
28

2✔
29
        // The timestamp must be exactly 35 bits, which means 7 groups. If it
2✔
30
        // can fit into fewer groups we add leading zero groups, if it is too
2✔
31
        // big we fail early, as there is not possible to encode it.
2✔
32
        if len(timestampBase32) > timestampBase32Len {
2✔
33
                return "", fmt.Errorf("timestamp too big: %d",
×
34
                        invoice.Timestamp.Unix())
×
35
        }
×
36

37
        // Add zero bytes to the first timestampBase32Len-len(timestampBase32)
38
        // groups, then add the non-zero groups.
39
        zeroes := make([]byte, timestampBase32Len-len(timestampBase32))
2✔
40
        _, err := bufferBase32.Write(zeroes)
2✔
41
        if err != nil {
2✔
42
                return "", fmt.Errorf("unable to write to buffer: %w", err)
×
43
        }
×
44
        _, err = bufferBase32.Write(timestampBase32)
2✔
45
        if err != nil {
2✔
46
                return "", fmt.Errorf("unable to write to buffer: %w", err)
×
47
        }
×
48

49
        // We now write the tagged fields to the buffer, which will fill the
50
        // rest of the data part before the signature.
51
        if err := writeTaggedFields(&bufferBase32, invoice); err != nil {
2✔
52
                return "", err
×
53
        }
×
54

55
        // The human-readable part (hrp) is "ln" + net hrp + optional amount,
56
        // except for signet where we add an additional "s" to differentiate it
57
        // from the older testnet3 (Core devs decided to use the same hrp for
58
        // signet as for testnet3 which is not optimal for LN). See
59
        // https://github.com/lightningnetwork/lightning-rfc/pull/844 for more
60
        // information.
61
        hrp := "ln" + invoice.Net.Bech32HRPSegwit
2✔
62
        if invoice.Net.Name == chaincfg.SigNetParams.Name {
2✔
UNCOV
63
                hrp = "lntbs"
×
UNCOV
64
        }
×
65
        if invoice.MilliSat != nil {
4✔
66
                // Encode the amount using the fewest possible characters.
2✔
67
                am, err := encodeAmount(*invoice.MilliSat)
2✔
68
                if err != nil {
2✔
69
                        return "", err
×
70
                }
×
71
                hrp += am
2✔
72
        }
73

74
        // The signature is over the single SHA-256 hash of the hrp + the
75
        // tagged fields encoded in base256.
76
        taggedFieldsBytes, err := bech32.ConvertBits(bufferBase32.Bytes(), 5, 8, true)
2✔
77
        if err != nil {
2✔
78
                return "", err
×
79
        }
×
80

81
        toSign := append([]byte(hrp), taggedFieldsBytes...)
2✔
82

2✔
83
        // We use compact signature format, and also encoded the recovery ID
2✔
84
        // such that a reader of the invoice can recover our pubkey from the
2✔
85
        // signature.
2✔
86
        sign, err := signer.SignCompact(toSign)
2✔
87
        if err != nil {
2✔
88
                return "", err
×
89
        }
×
90

91
        // From the header byte we can extract the recovery ID, and the last 64
92
        // bytes encode the signature.
93
        recoveryID := sign[0] - 27 - 4
2✔
94
        sig, err := lnwire.NewSigFromWireECDSA(sign[1:])
2✔
95
        if err != nil {
2✔
96
                return "", err
×
97
        }
×
98

99
        // If the pubkey field was explicitly set, it must be set to the pubkey
100
        // used to create the signature.
101
        if invoice.Destination != nil {
2✔
UNCOV
102
                signature, err := sig.ToSignature()
×
UNCOV
103
                if err != nil {
×
104
                        return "", fmt.Errorf("unable to deserialize "+
×
105
                                "signature: %v", err)
×
106
                }
×
107

UNCOV
108
                hash := chainhash.HashB(toSign)
×
UNCOV
109
                valid := signature.Verify(hash, invoice.Destination)
×
UNCOV
110
                if !valid {
×
UNCOV
111
                        return "", fmt.Errorf("signature does not match " +
×
UNCOV
112
                                "provided pubkey")
×
UNCOV
113
                }
×
114
        }
115

116
        // Convert the signature to base32 before writing it to the buffer.
117
        signBase32, err := bech32.ConvertBits(
2✔
118
                append(sig.RawBytes(), recoveryID),
2✔
119
                8, 5, true,
2✔
120
        )
2✔
121
        if err != nil {
2✔
122
                return "", err
×
123
        }
×
124
        bufferBase32.Write(signBase32)
2✔
125

2✔
126
        // Now we can create the bech32 encoded string from the base32 buffer.
2✔
127
        b32, err := bech32.Encode(hrp, bufferBase32.Bytes())
2✔
128
        if err != nil {
2✔
129
                return "", err
×
130
        }
×
131

132
        // Before returning, check that the bech32 encoded string is not greater
133
        // than our largest supported invoice size.
134
        if len(b32) > maxInvoiceLength {
2✔
135
                return "", ErrInvoiceTooLarge
×
136
        }
×
137

138
        return b32, nil
2✔
139
}
140

141
// writeTaggedFields writes the non-nil tagged fields of the Invoice to the
142
// base32 buffer.
143
func writeTaggedFields(bufferBase32 *bytes.Buffer, invoice *Invoice) error {
2✔
144
        if invoice.PaymentHash != nil {
4✔
145
                err := writeBytes32(bufferBase32, fieldTypeP, *invoice.PaymentHash)
2✔
146
                if err != nil {
2✔
147
                        return err
×
148
                }
×
149
        }
150

151
        if invoice.Description != nil {
4✔
152
                base32, err := bech32.ConvertBits([]byte(*invoice.Description),
2✔
153
                        8, 5, true)
2✔
154
                if err != nil {
2✔
155
                        return err
×
156
                }
×
157
                err = writeTaggedField(bufferBase32, fieldTypeD, base32)
2✔
158
                if err != nil {
2✔
159
                        return err
×
160
                }
×
161
        }
162

163
        if invoice.DescriptionHash != nil {
2✔
UNCOV
164
                err := writeBytes32(
×
UNCOV
165
                        bufferBase32, fieldTypeH, *invoice.DescriptionHash,
×
UNCOV
166
                )
×
UNCOV
167
                if err != nil {
×
168
                        return err
×
169
                }
×
170
        }
171

172
        if invoice.Metadata != nil {
2✔
UNCOV
173
                base32, err := bech32.ConvertBits(invoice.Metadata, 8, 5, true)
×
UNCOV
174
                if err != nil {
×
175
                        return err
×
176
                }
×
UNCOV
177
                err = writeTaggedField(bufferBase32, fieldTypeM, base32)
×
UNCOV
178
                if err != nil {
×
179
                        return err
×
180
                }
×
181
        }
182

183
        if invoice.minFinalCLTVExpiry != nil {
4✔
184
                finalDelta := uint64ToBase32(*invoice.minFinalCLTVExpiry)
2✔
185
                err := writeTaggedField(bufferBase32, fieldTypeC, finalDelta)
2✔
186
                if err != nil {
2✔
187
                        return err
×
188
                }
×
189
        }
190

191
        if invoice.expiry != nil {
4✔
192
                seconds := invoice.expiry.Seconds()
2✔
193
                expiry := uint64ToBase32(uint64(seconds))
2✔
194
                err := writeTaggedField(bufferBase32, fieldTypeX, expiry)
2✔
195
                if err != nil {
2✔
196
                        return err
×
197
                }
×
198
        }
199

200
        if invoice.FallbackAddr != nil {
2✔
UNCOV
201
                var version byte
×
UNCOV
202
                switch addr := invoice.FallbackAddr.(type) {
×
UNCOV
203
                case *btcutil.AddressPubKeyHash:
×
UNCOV
204
                        version = 17
×
UNCOV
205
                case *btcutil.AddressScriptHash:
×
UNCOV
206
                        version = 18
×
UNCOV
207
                case *btcutil.AddressWitnessPubKeyHash:
×
UNCOV
208
                        version = addr.WitnessVersion()
×
UNCOV
209
                case *btcutil.AddressWitnessScriptHash:
×
UNCOV
210
                        version = addr.WitnessVersion()
×
211
                default:
×
212
                        return fmt.Errorf("unknown fallback address type")
×
213
                }
UNCOV
214
                base32Addr, err := bech32.ConvertBits(
×
UNCOV
215
                        invoice.FallbackAddr.ScriptAddress(), 8, 5, true)
×
UNCOV
216
                if err != nil {
×
217
                        return err
×
218
                }
×
219

UNCOV
220
                err = writeTaggedField(bufferBase32, fieldTypeF,
×
UNCOV
221
                        append([]byte{version}, base32Addr...))
×
UNCOV
222
                if err != nil {
×
223
                        return err
×
224
                }
×
225
        }
226

227
        for _, routeHint := range invoice.RouteHints {
4✔
228
                // Each hop hint is encoded using 51 bytes, so we'll make to
2✔
229
                // sure to allocate enough space for the whole route hint.
2✔
230
                routeHintBase256 := make([]byte, 0, hopHintLen*len(routeHint))
2✔
231

2✔
232
                for _, hopHint := range routeHint {
4✔
233
                        hopHintBase256 := make([]byte, hopHintLen)
2✔
234
                        copy(hopHintBase256[:33], hopHint.NodeID.SerializeCompressed())
2✔
235
                        binary.BigEndian.PutUint64(
2✔
236
                                hopHintBase256[33:41], hopHint.ChannelID,
2✔
237
                        )
2✔
238
                        binary.BigEndian.PutUint32(
2✔
239
                                hopHintBase256[41:45], hopHint.FeeBaseMSat,
2✔
240
                        )
2✔
241
                        binary.BigEndian.PutUint32(
2✔
242
                                hopHintBase256[45:49], hopHint.FeeProportionalMillionths,
2✔
243
                        )
2✔
244
                        binary.BigEndian.PutUint16(
2✔
245
                                hopHintBase256[49:51], hopHint.CLTVExpiryDelta,
2✔
246
                        )
2✔
247
                        routeHintBase256 = append(routeHintBase256, hopHintBase256...)
2✔
248
                }
2✔
249

250
                routeHintBase32, err := bech32.ConvertBits(
2✔
251
                        routeHintBase256, 8, 5, true,
2✔
252
                )
2✔
253
                if err != nil {
2✔
254
                        return err
×
255
                }
×
256

257
                err = writeTaggedField(bufferBase32, fieldTypeR, routeHintBase32)
2✔
258
                if err != nil {
2✔
259
                        return err
×
260
                }
×
261
        }
262

263
        if invoice.Destination != nil {
2✔
UNCOV
264
                // Convert 33 byte pubkey to 53 5-bit groups.
×
UNCOV
265
                pubKeyBase32, err := bech32.ConvertBits(
×
UNCOV
266
                        invoice.Destination.SerializeCompressed(), 8, 5, true)
×
UNCOV
267
                if err != nil {
×
268
                        return err
×
269
                }
×
270

UNCOV
271
                if len(pubKeyBase32) != pubKeyBase32Len {
×
272
                        return fmt.Errorf("invalid pubkey length: %d",
×
273
                                len(invoice.Destination.SerializeCompressed()))
×
274
                }
×
275

UNCOV
276
                err = writeTaggedField(bufferBase32, fieldTypeN, pubKeyBase32)
×
UNCOV
277
                if err != nil {
×
278
                        return err
×
279
                }
×
280
        }
281
        if invoice.PaymentAddr != nil {
4✔
282
                err := writeBytes32(
2✔
283
                        bufferBase32, fieldTypeS, *invoice.PaymentAddr,
2✔
284
                )
2✔
285
                if err != nil {
2✔
286
                        return err
×
287
                }
×
288
        }
289
        if invoice.Features.SerializeSize32() > 0 {
4✔
290
                var b bytes.Buffer
2✔
291
                err := invoice.Features.RawFeatureVector.EncodeBase32(&b)
2✔
292
                if err != nil {
2✔
293
                        return err
×
294
                }
×
295

296
                err = writeTaggedField(bufferBase32, fieldType9, b.Bytes())
2✔
297
                if err != nil {
2✔
298
                        return err
×
299
                }
×
300
        }
301

302
        return nil
2✔
303
}
304

305
// writeBytes32 encodes a 32-byte array as base32 and writes it to bufferBase32
306
// under the passed fieldType.
307
func writeBytes32(bufferBase32 *bytes.Buffer, fieldType byte, b [32]byte) error {
2✔
308
        // Convert 32 byte hash to 52 5-bit groups.
2✔
309
        base32, err := bech32.ConvertBits(b[:], 8, 5, true)
2✔
310
        if err != nil {
2✔
311
                return err
×
312
        }
×
313

314
        return writeTaggedField(bufferBase32, fieldType, base32)
2✔
315
}
316

317
// writeTaggedField takes the type of a tagged data field, and the data of
318
// the tagged field (encoded in base32), and writes the type, length and data
319
// to the buffer.
320
func writeTaggedField(bufferBase32 *bytes.Buffer, dataType byte, data []byte) error {
2✔
321
        // Length must be exactly 10 bits, so add leading zero groups if
2✔
322
        // needed.
2✔
323
        lenBase32 := uint64ToBase32(uint64(len(data)))
2✔
324
        for len(lenBase32) < 2 {
4✔
325
                lenBase32 = append([]byte{0}, lenBase32...)
2✔
326
        }
2✔
327

328
        if len(lenBase32) != 2 {
2✔
329
                return fmt.Errorf("data length too big to fit within 10 bits: %d",
×
330
                        len(data))
×
331
        }
×
332

333
        err := bufferBase32.WriteByte(dataType)
2✔
334
        if err != nil {
2✔
335
                return fmt.Errorf("unable to write to buffer: %w", err)
×
336
        }
×
337
        _, err = bufferBase32.Write(lenBase32)
2✔
338
        if err != nil {
2✔
339
                return fmt.Errorf("unable to write to buffer: %w", err)
×
340
        }
×
341
        _, err = bufferBase32.Write(data)
2✔
342
        if err != nil {
2✔
343
                return fmt.Errorf("unable to write to buffer: %w", err)
×
344
        }
×
345

346
        return nil
2✔
347
}
348

349
// uint64ToBase32 converts a uint64 to a base32 encoded integer encoded using
350
// as few 5-bit groups as possible.
351
func uint64ToBase32(num uint64) []byte {
2✔
352
        // Return at least one group.
2✔
353
        if num == 0 {
4✔
354
                return []byte{0}
2✔
355
        }
2✔
356

357
        // To fit an uint64, we need at most is ceil(64 / 5) = 13 groups.
358
        arr := make([]byte, 13)
2✔
359
        i := 13
2✔
360
        for num > 0 {
4✔
361
                i--
2✔
362
                arr[i] = byte(num & uint64(31)) // 0b11111 in binary
2✔
363
                num >>= 5
2✔
364
        }
2✔
365

366
        // We only return non-zero leading groups.
367
        return arr[i:]
2✔
368
}
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

© 2026 Coveralls, Inc