I've noticed Lightning invoices can be 263 characters, 247 characters, and possibly other lengths. Is there a set range, and how (generally) are these numbers derived ?
Lightning invoices encode multiple pieces of information, some of which are optional, and some of which are variable-length. It is required that invoices use the shortest representation possible for each piece of data, and that each tagged data field must be a multiple of 5-bits in length, where they are zero-padded if the data is smaller than this length. Some data fields may also appear multiple times, and there are no arbitrary upper bounds on the number of times they appear, although each individual tagged data field is limited to 515 characters in length (inclusive of its type and length prefix).
An invoice must minimally encode these requirements:
- network prefix: 4 characters for mainnet
- amount: Variable length (typically 2-5 characters)
- '1'. Last instance of this character delimits the remaining information.
- timestamp: 7 characters
- payment_hash: 55 characters
- purpose: variable length (minimum empty description - 3 chars "dqq")
- min_cltv_expiry: variable, minimum 4 characters
- signature+recovery: 104 characters
- bech32 checksum: 6 characters
Thus the minimum possible length of an invoice is around 190 characters if the purpose field is left empty and no optional fields are specified.
As some of the optional fields appear an arbitrary number of times, there is no upper bound on invoice length.
It would be practical however to set some reasonable upper limit in any software implementation. In practice, an invoice is not going to need hundreds of additional routing fields, fallback addresses and optional features. A malicious hacker might craft unnecessarily large invoices in attempt exploit bugs in software which decodes BOLT#11 invoices. Rejecting overly large invoices before attempting parsing can trivially avoid such bugs. A reasonable upper bound would be to use the upper bound of information which can be encoded in a QR-code, since invoices are often transmitted this way.