bolt11.c (20274B)
1 // 2 // bolt11.c 3 // damus 4 // 5 // Created by William Casarin on 2022-10-18. 6 // 7 8 #include "bolt11.h" 9 10 //#include "address.h" 11 //#include "script.h" 12 #include "bech32.h" 13 #include "utf8.h" 14 #include "compiler.h" 15 #include "endian.h" 16 #include "list.h" 17 #include "talstr.h" 18 #include "tal.h" 19 #include "node_id.h" 20 #include "bech32_util.h" 21 #include "bolt11.h" 22 #include "amount.h" 23 #include "array_size.h" 24 #include "structeq.h" 25 26 //#include "features.h" 27 #include <errno.h> 28 #include <inttypes.h> 29 #include <assert.h> 30 31 #define MSAT_PER_SAT ((u64)1000) 32 #define SAT_PER_BTC ((u64)100000000) 33 #define MSAT_PER_BTC (MSAT_PER_SAT * SAT_PER_BTC) 34 35 struct multiplier { 36 const char letter; 37 /* We can't represent p postfix to msat, so we multiply this by 10 */ 38 u64 m10; 39 }; 40 41 /* BOLT #11: 42 * 43 * The following `multiplier` letters are defined: 44 * 45 * * `m` (milli): multiply by 0.001 46 * * `u` (micro): multiply by 0.000001 47 * * `n` (nano): multiply by 0.000000001 48 * * `p` (pico): multiply by 0.000000000001 49 */ 50 static struct multiplier multipliers[] = { 51 { 'm', 10 * MSAT_PER_BTC / 1000 }, 52 { 'u', 10 * MSAT_PER_BTC / 1000000 }, 53 { 'n', 10 * MSAT_PER_BTC / 1000000000 }, 54 { 'p', 10 * MSAT_PER_BTC / 1000000000000ULL } 55 }; 56 57 /* If pad is false, we discard any bits which don't fit in the last byte. 58 * Otherwise we add an extra byte */ 59 static bool pull_bits(struct hash_u5 *hu5, 60 u5 **data, size_t *data_len, void *dst, size_t nbits, 61 bool pad) 62 { 63 size_t n5 = nbits / 5; 64 size_t len = 0; 65 66 if (nbits % 5) 67 n5++; 68 69 if (*data_len < n5) 70 return false; 71 if (!bech32_convert_bits(dst, &len, 8, *data, n5, 5, pad)) 72 return false; 73 if (hu5) 74 hash_u5(hu5, *data, n5); 75 *data += n5; 76 *data_len -= n5; 77 78 return true; 79 } 80 81 /* For pulling fields where we should have checked it will succeed already. */ 82 #ifndef NDEBUG 83 #define pull_bits_certain(hu5, data, data_len, dst, nbits, pad) \ 84 assert(pull_bits((hu5), (data), (data_len), (dst), (nbits), (pad))) 85 #else 86 #define pull_bits_certain pull_bits 87 #endif 88 89 /* Helper for pulling a variable-length big-endian int. */ 90 static bool pull_uint(struct hash_u5 *hu5, 91 u5 **data, size_t *data_len, 92 u64 *val, size_t databits) 93 { 94 be64 be_val; 95 96 /* Too big. */ 97 if (databits > sizeof(be_val) * CHAR_BIT) 98 return false; 99 if (!pull_bits(hu5, data, data_len, &be_val, databits, true)) 100 return false; 101 *val = be64_to_cpu(be_val) >> (sizeof(be_val) * CHAR_BIT - databits); 102 return true; 103 } 104 105 static size_t num_u8(size_t num_u5) 106 { 107 return (num_u5 * 5 + 4) / 8; 108 } 109 110 /* Frees bolt11, returns NULL. */ 111 static struct bolt11 *decode_fail(struct bolt11 *b11, char **fail, 112 const char *fmt, ...) 113 PRINTF_FMT(3,4); 114 115 static struct bolt11 *decode_fail(struct bolt11 *b11, char **fail, 116 const char *fmt, ...) 117 { 118 va_list ap; 119 120 va_start(ap, fmt); 121 *fail = tal_vfmt(tal_parent(b11), fmt, ap); 122 va_end(ap); 123 return tal_free(b11); 124 } 125 126 /* 127 * These handle specific fields in the payment request; returning the problem 128 * if any, or NULL. 129 */ 130 static char *unknown_field(struct bolt11 *b11, 131 struct hash_u5 *hu5, 132 u5 **data, size_t *data_len, 133 u5 type, size_t length) 134 { 135 struct bolt11_field *extra = tal(b11, struct bolt11_field); 136 u8 u8data[num_u8(length)]; 137 138 extra->tag = type; 139 extra->data = tal_dup_arr(extra, u5, *data, length, 0); 140 list_add_tail(&b11->extra_fields, &extra->list); 141 142 pull_bits_certain(hu5, data, data_len, u8data, length * 5, true); 143 return NULL; 144 } 145 146 /* BOLT #11: 147 * 148 * `p` (1): `data_length` 52. 256-bit SHA256 payment_hash. Preimage of this 149 * provides proof of payment 150 */ 151 static void decode_p(struct bolt11 *b11, 152 struct hash_u5 *hu5, 153 u5 **data, size_t *data_len, 154 size_t data_length, bool *have_p) 155 { 156 /* BOLT #11: 157 * 158 * A payer... SHOULD use the first `p` field that it did NOT 159 * skip as the payment hash. 160 */ 161 if (*have_p) { 162 unknown_field(b11, hu5, data, data_len, 'p', data_length); 163 return; 164 } 165 166 /* BOLT #11: 167 * 168 * A reader... MUST skip over unknown fields, OR an `f` field 169 * with unknown `version`, OR `p`, `h`, `s` or `n` fields that do 170 * NOT have `data_length`s of 52, 52, 52 or 53, respectively. 171 */ 172 if (data_length != 52) { 173 unknown_field(b11, hu5, data, data_len, 'p', data_length); 174 return; 175 } 176 177 pull_bits_certain(hu5, data, data_len, &b11->payment_hash, 256, false); 178 *have_p = true; 179 } 180 181 182 static char *utf8_str(const tal_t *ctx, const u8 *buf TAKES, size_t buflen) 183 { 184 char *ret; 185 186 if (!utf8_check(buf, buflen)) { 187 if (taken(buf)) 188 tal_free(buf); 189 return NULL; 190 } 191 192 /* Add one for nul term */ 193 ret = tal_dup_arr(ctx, char, (const char *)buf, buflen, 1); 194 ret[buflen] = '\0'; 195 return ret; 196 } 197 198 199 /* BOLT #11: 200 * 201 * `d` (13): `data_length` variable. Short description of purpose of payment 202 * (UTF-8), e.g. '1 cup of coffee' or 'ナンセンス 1杯' 203 */ 204 static char *decode_d(struct bolt11 *b11, 205 struct hash_u5 *hu5, 206 u5 **data, size_t *data_len, 207 size_t data_length, bool *have_d) 208 { 209 u8 *desc; 210 if (*have_d) 211 return unknown_field(b11, hu5, data, data_len, 'd', data_length); 212 213 desc = tal_arr(NULL, u8, data_length * 5 / 8); 214 pull_bits_certain(hu5, data, data_len, desc, data_length*5, false); 215 216 *have_d = true; 217 b11->description = utf8_str(b11, take(desc), tal_bytelen(desc)); 218 if (b11->description) 219 return NULL; 220 221 return tal_fmt(b11, "d: invalid utf8"); 222 } 223 224 /* BOLT #11: 225 * 226 * `h` (23): `data_length` 52. 256-bit description of purpose of payment 227 * (SHA256). This is used to commit to an associated description that is over 228 * 639 bytes, but the transport mechanism for the description in that case is 229 * transport specific and not defined here. 230 */ 231 static void decode_h(struct bolt11 *b11, 232 struct hash_u5 *hu5, 233 u5 **data, size_t *data_len, 234 size_t data_length, bool *have_h) 235 { 236 if (*have_h) { 237 unknown_field(b11, hu5, data, data_len, 'h', data_length); 238 return; 239 } 240 241 /* BOLT #11: 242 * 243 * A reader... MUST skip over unknown fields, OR an `f` field 244 * with unknown `version`, OR `p`, `h`, `s` or `n` fields that do 245 * NOT have `data_length`s of 52, 52, 52 or 53, respectively. */ 246 if (data_length != 52) { 247 unknown_field(b11, hu5, data, data_len, 'h', data_length); 248 return; 249 } 250 251 b11->description_hash = tal(b11, struct sha256); 252 pull_bits_certain(hu5, data, data_len, b11->description_hash, 256, 253 false); 254 *have_h = true; 255 } 256 257 /* BOLT #11: 258 * 259 * `x` (6): `data_length` variable. `expiry` time in seconds 260 * (big-endian). Default is 3600 (1 hour) if not specified. 261 */ 262 #define DEFAULT_X 3600 263 static char *decode_x(struct bolt11 *b11, 264 struct hash_u5 *hu5, 265 u5 **data, size_t *data_len, 266 size_t data_length, bool *have_x) 267 { 268 if (*have_x) 269 return unknown_field(b11, hu5, data, data_len, 'x', 270 data_length); 271 272 /* FIXME: Put upper limit in bolt 11 */ 273 if (!pull_uint(hu5, data, data_len, &b11->expiry, data_length * 5)) 274 return tal_fmt(b11, "x: length %zu chars is excessive", 275 *data_len); 276 277 *have_x = true; 278 return NULL; 279 } 280 281 /* BOLT #11: 282 * 283 * `c` (24): `data_length` variable. `min_final_cltv_expiry` to use for the 284 * last HTLC in the route. Default is 18 if not specified. 285 */ 286 static char *decode_c(struct bolt11 *b11, 287 struct hash_u5 *hu5, 288 u5 **data, size_t *data_len, 289 size_t data_length, bool *have_c) 290 { 291 u64 c; 292 if (*have_c) 293 return unknown_field(b11, hu5, data, data_len, 'c', 294 data_length); 295 296 /* FIXME: Put upper limit in bolt 11 */ 297 if (!pull_uint(hu5, data, data_len, &c, data_length * 5)) 298 return tal_fmt(b11, "c: length %zu chars is excessive", 299 *data_len); 300 b11->min_final_cltv_expiry = (u32)c; 301 /* Can overflow, since c is 64 bits but value must be < 32 bits */ 302 if (b11->min_final_cltv_expiry != c) 303 return tal_fmt(b11, "c: %"PRIu64" is too large", c); 304 305 *have_c = true; 306 return NULL; 307 } 308 309 static char *decode_n(struct bolt11 *b11, 310 struct hash_u5 *hu5, 311 u5 **data, size_t *data_len, 312 size_t data_length, bool *have_n) 313 { 314 if (*have_n) 315 return unknown_field(b11, hu5, data, data_len, 'n', 316 data_length); 317 318 /* BOLT #11: 319 * 320 * A reader... MUST skip over unknown fields, OR an `f` field 321 * with unknown `version`, OR `p`, `h`, `s` or `n` fields that do 322 * NOT have `data_length`s of 52, 52, 52 or 53, respectively. */ 323 if (data_length != 53) 324 return unknown_field(b11, hu5, data, data_len, 'n', 325 data_length); 326 327 pull_bits_certain(hu5, data, data_len, &b11->receiver_id.k, 328 data_length * 5, false); 329 /* 330 if (!node_id_valid(&b11->receiver_id)) 331 return tal_fmt(b11, "n: invalid pubkey %s", 332 node_id_to_hexstr(b11, &b11->receiver_id)); 333 */ 334 335 *have_n = true; 336 return NULL; 337 } 338 339 /* BOLT #11: 340 * 341 * `m` (27): `data_length` variable. Additional metadata to attach to 342 * the payment. Note that the size of this field is limited by the 343 * maximum hop payload size. Long metadata fields reduce the maximum 344 * route length. 345 */ 346 static char *decode_m(struct bolt11 *b11, 347 struct hash_u5 *hu5, 348 u5 **data, size_t *data_len, 349 size_t data_length, 350 bool *have_m) 351 { 352 size_t mlen = (data_length * 5) / 8; 353 354 if (*have_m) 355 return unknown_field(b11, hu5, data, data_len, 'm', 356 data_length); 357 358 b11->metadata = tal_arr(b11, u8, mlen); 359 pull_bits_certain(hu5, data, data_len, b11->metadata, 360 data_length * 5, false); 361 362 *have_m = true; 363 return NULL; 364 } 365 366 struct bolt11 *new_bolt11(const tal_t *ctx) 367 { 368 struct bolt11 *b11 = tal(ctx, struct bolt11); 369 370 list_head_init(&b11->extra_fields); 371 b11->description = NULL; 372 b11->description_hash = NULL; 373 b11->fallbacks = NULL; 374 b11->msat = NULL; 375 b11->expiry = DEFAULT_X; 376 b11->features = tal_arr(b11, u8, 0); 377 /* BOLT #11: 378 * - if the `c` field (`min_final_cltv_expiry`) is not provided: 379 * - MUST use an expiry delta of at least 18 when making the payment 380 */ 381 b11->min_final_cltv_expiry = 18; 382 //b11->payment_secret = NULL; 383 b11->metadata = NULL; 384 385 //if (msat) 386 //b11->msat = tal_dup(b11, struct amount_msat, msat); 387 return b11; 388 } 389 390 /* Define sha256_eq. */ 391 //STRUCTEQ_DEF(sha256, 0, u); 392 393 /* Extracts signature but does not check it. */ 394 struct bolt11 *bolt11_decode_nosig(const tal_t *ctx, const char *str, u5 **sig, char **fail) 395 { 396 char *hrp, *amountstr, *prefix; 397 u5 *data; 398 size_t data_len; 399 struct bolt11 *b11 = new_bolt11(ctx); 400 struct hash_u5 hu5; 401 bool have_p = false, have_d = false, have_h = false, have_n = false, 402 have_x = false, have_c = false, have_m = false; 403 404 /* BOLT #11: 405 * 406 * If a URI scheme is desired, the current recommendation is to either 407 * use 'lightning:' as a prefix before the BOLT-11 encoding 408 */ 409 if (strstarts(str, "lightning:") || strstarts(str, "LIGHTNING:")) 410 str += strlen("lightning:"); 411 412 if (strlen(str) < 8) 413 return decode_fail(b11, fail, "Bad bech32 string"); 414 415 hrp = tal_arr(b11, char, strlen(str) - 6); 416 data = tal_arr(b11, u5, strlen(str) - 8); 417 418 if (bech32_decode(hrp, data, &data_len, str, (size_t)-1) 419 != BECH32_ENCODING_BECH32) 420 return decode_fail(b11, fail, "Bad bech32 string"); 421 422 /* For signature checking at the end. */ 423 hash_u5_init(&hu5, hrp); 424 425 /* BOLT #11: 426 * 427 * The human-readable part of a Lightning invoice consists of two sections: 428 * 1. `prefix`: `ln` + BIP-0173 currency prefix (e.g. `lnbc` for Bitcoin mainnet, 429 * `lntb` for Bitcoin testnet, `lntbs` for Bitcoin signet, and `lnbcrt` for Bitcoin regtest) 430 * 1. `amount`: optional number in that currency, followed by an optional 431 * `multiplier` letter. The unit encoded here is the 'social' convention of a payment unit -- in the case of Bitcoin the unit is 'bitcoin' NOT satoshis. 432 */ 433 prefix = tal_strndup(b11, hrp, strcspn(hrp, "0123456789")); 434 435 /* BOLT #11: 436 * 437 * A reader...if it does NOT understand the `prefix`... MUST fail the payment. 438 */ 439 if (!strstarts(prefix, "ln")) 440 return decode_fail(b11, fail, 441 "Prefix '%s' does not start with ln", prefix); 442 443 /* BOLT #11: 444 * 445 * - if the `amount` is empty: 446 * */ 447 amountstr = tal_strdup(b11, hrp + strlen(prefix)); 448 if (streq(amountstr, "")) { 449 /* BOLT #11: 450 * 451 * - SHOULD indicate to the payer that amount is unspecified. 452 */ 453 b11->msat = NULL; 454 } else { 455 u64 m10 = 10 * MSAT_PER_BTC; /* Pico satoshis in a Bitcoin */ 456 u64 amount; 457 char *end; 458 459 /* Gather and trim multiplier */ 460 end = amountstr + strlen(amountstr)-1; 461 for (size_t i = 0; i < ARRAY_SIZE(multipliers); i++) { 462 if (*end == multipliers[i].letter) { 463 m10 = multipliers[i].m10; 464 *end = '\0'; 465 break; 466 } 467 } 468 469 /* BOLT #11: 470 * 471 * if `amount` contains a non-digit OR is followed by 472 * anything except a `multiplier` (see table above)... MUST fail the 473 * payment. 474 **/ 475 amount = strtoull(amountstr, &end, 10); 476 if (amount == ULLONG_MAX && errno == ERANGE) 477 return decode_fail(b11, fail, 478 "Invalid amount '%s'", amountstr); 479 if (!*amountstr || *end) 480 return decode_fail(b11, fail, 481 "Invalid amount postfix '%s'", end); 482 483 /* BOLT #11: 484 * 485 * if the `multiplier` is present... MUST multiply 486 * `amount` by the `multiplier` value to derive the 487 * amount required for payment. 488 */ 489 b11->msat = tal(b11, struct amount_msat); 490 /* BOLT #11: 491 * 492 * - if multiplier is `p` and the last decimal of `amount` is 493 * not 0: 494 * - MUST fail the payment. 495 */ 496 if (amount * m10 % 10 != 0) 497 return decode_fail(b11, fail, 498 "Invalid sub-millisatoshi amount" 499 " '%sp'", amountstr); 500 501 *b11->msat = amount_msat(amount * m10 / 10); 502 } 503 504 /* BOLT #11: 505 * 506 * The data part of a Lightning invoice consists of multiple sections: 507 * 508 * 1. `timestamp`: seconds-since-1970 (35 bits, big-endian) 509 * 1. zero or more tagged parts 510 * 1. `signature`: Bitcoin-style signature of above (520 bits) 511 */ 512 if (!pull_uint(&hu5, &data, &data_len, &b11->timestamp, 35)) 513 return decode_fail(b11, fail, "Can't get 35-bit timestamp"); 514 515 while (data_len > 520 / 5) { 516 const char *problem = NULL; 517 u64 type, data_length; 518 519 /* BOLT #11: 520 * 521 * Each Tagged Field is of the form: 522 * 523 * 1. `type` (5 bits) 524 * 1. `data_length` (10 bits, big-endian) 525 * 1. `data` (`data_length` x 5 bits) 526 */ 527 if (!pull_uint(&hu5, &data, &data_len, &type, 5) 528 || !pull_uint(&hu5, &data, &data_len, &data_length, 10)) 529 return decode_fail(b11, fail, 530 "Can't get tag and length"); 531 532 /* Can't exceed total data remaining. */ 533 if (data_length > data_len) 534 return decode_fail(b11, fail, "%c: truncated", 535 bech32_charset[type]); 536 537 switch (bech32_charset[type]) { 538 case 'p': 539 decode_p(b11, &hu5, &data, &data_len, data_length, 540 &have_p); 541 break; 542 543 case 'd': 544 problem = decode_d(b11, &hu5, &data, &data_len, 545 data_length, &have_d); 546 break; 547 548 case 'h': 549 decode_h(b11, &hu5, &data, &data_len, data_length, 550 &have_h); 551 break; 552 553 case 'n': 554 problem = decode_n(b11, &hu5, &data, 555 &data_len, data_length, 556 &have_n); 557 break; 558 559 case 'x': 560 problem = decode_x(b11, &hu5, &data, 561 &data_len, data_length, 562 &have_x); 563 break; 564 565 case 'c': 566 problem = decode_c(b11, &hu5, &data, 567 &data_len, data_length, 568 &have_c); 569 break; 570 571 /* 572 case 'f': 573 problem = decode_f(b11, &hu5, &data, 574 &data_len, data_length); 575 break; 576 case 'r': 577 problem = decode_r(b11, &hu5, &data, &data_len, 578 data_length); 579 break; 580 case '9': 581 problem = decode_9(b11, our_features, &hu5, 582 &data, &data_len, 583 data_length); 584 break; 585 case 's': 586 problem = decode_s(b11, &hu5, &data, &data_len, 587 data_length, &have_s); 588 break; 589 */ 590 case 'm': 591 problem = decode_m(b11, &hu5, &data, &data_len, 592 data_length, &have_m); 593 break; 594 default: 595 unknown_field(b11, &hu5, &data, &data_len, 596 bech32_charset[type], data_length); 597 } 598 if (problem) 599 return decode_fail(b11, fail, "%s", problem); 600 } 601 602 if (!have_p) 603 return decode_fail(b11, fail, "No valid 'p' field found"); 604 605 *sig = tal_dup_arr(ctx, u5, data, data_len, 0); 606 return b11; 607 } 608 609 /* Decodes and checks signature; returns NULL on error. */ 610 struct bolt11 *bolt11_decode(const tal_t *ctx, const char *str, char **fail) 611 { 612 u5 *sigdata; 613 size_t data_len; 614 u8 sig_and_recid[65]; 615 //secp256k1_ecdsa_recoverable_signature sig; 616 struct bolt11 *b11; 617 618 b11 = bolt11_decode_nosig(ctx, str, &sigdata, fail); 619 if (!b11) 620 return NULL; 621 622 /* BOLT #11: 623 * 624 * A writer...MUST set `signature` to a valid 512-bit 625 * secp256k1 signature of the SHA2 256-bit hash of the 626 * human-readable part, represented as UTF-8 bytes, 627 * concatenated with the data part (excluding the signature) 628 * with 0 bits appended to pad the data to the next byte 629 * boundary, with a trailing byte containing the recovery ID 630 * (0, 1, 2, or 3). 631 */ 632 data_len = tal_count(sigdata); 633 if (!pull_bits(NULL, &sigdata, &data_len, sig_and_recid, 520, false)) 634 return decode_fail(b11, fail, "signature truncated"); 635 636 assert(data_len == 0); 637 638 /* 639 if (!secp256k1_ecdsa_recoverable_signature_parse_compact 640 (secp256k1_ctx, &sig, sig_and_recid, sig_and_recid[64])) 641 return decode_fail(b11, fail, "signature invalid"); 642 643 secp256k1_ecdsa_recoverable_signature_convert(secp256k1_ctx, 644 &b11->sig, &sig); 645 */ 646 647 /* BOLT #11: 648 * 649 * A reader... MUST check that the `signature` is valid (see 650 * the `n` tagged field specified below). ... A reader... 651 * MUST use the `n` field to validate the signature instead of 652 * performing signature recovery. 653 */ 654 /* 655 if (!have_n) { 656 struct pubkey k; 657 if (!secp256k1_ecdsa_recover(secp256k1_ctx, 658 &k.pubkey, 659 &sig, 660 (const u8 *)&hash)) 661 return decode_fail(b11, fail, 662 "signature recovery failed"); 663 node_id_from_pubkey(&b11->receiver_id, &k); 664 } else { 665 struct pubkey k; 666 if (!pubkey_from_node_id(&k, &b11->receiver_id)) 667 abort(); 668 if (!secp256k1_ecdsa_verify(secp256k1_ctx, &b11->sig, 669 (const u8 *)&hash, 670 &k.pubkey)) 671 return decode_fail(b11, fail, "invalid signature"); 672 } 673 */ 674 675 return b11; 676 }