Decodes and checks signature; returns NULL on error. */
| 844 | |
| 845 | /* Decodes and checks signature; returns NULL on error. */ |
| 846 | struct bolt11 *bolt11_decode(const tal_t *ctx, const char *str, |
| 847 | const struct feature_set *our_features, |
| 848 | const char *description, |
| 849 | const struct chainparams *must_be_chain, |
| 850 | char **fail) |
| 851 | { |
| 852 | u5 *sigdata; |
| 853 | size_t data_len; |
| 854 | u8 sig_and_recid[65]; |
| 855 | secp256k1_ecdsa_recoverable_signature sig; |
| 856 | struct bolt11 *b11; |
| 857 | struct sha256 hash; |
| 858 | bool have_n; |
| 859 | |
| 860 | b11 = bolt11_decode_nosig(ctx, str, our_features, description, |
| 861 | must_be_chain, &hash, &sigdata, &have_n, |
| 862 | fail); |
| 863 | if (!b11) |
| 864 | return NULL; |
| 865 | |
| 866 | /* BOLT #11: |
| 867 | * |
| 868 | * A writer...MUST set `signature` to a valid 512-bit |
| 869 | * secp256k1 signature of the SHA2 256-bit hash of the |
| 870 | * human-readable part, represented as UTF-8 bytes, |
| 871 | * concatenated with the data part (excluding the signature) |
| 872 | * with 0 bits appended to pad the data to the next byte |
| 873 | * boundary, with a trailing byte containing the recovery ID |
| 874 | * (0, 1, 2, or 3). |
| 875 | */ |
| 876 | data_len = tal_count(sigdata); |
| 877 | if (!pull_bits(NULL, &sigdata, &data_len, sig_and_recid, 520, false)) |
| 878 | return decode_fail(b11, fail, "signature truncated"); |
| 879 | |
| 880 | assert(data_len == 0); |
| 881 | |
| 882 | if (!secp256k1_ecdsa_recoverable_signature_parse_compact |
| 883 | (secp256k1_ctx, &sig, sig_and_recid, sig_and_recid[64])) |
| 884 | return decode_fail(b11, fail, "signature invalid"); |
| 885 | |
| 886 | secp256k1_ecdsa_recoverable_signature_convert(secp256k1_ctx, |
| 887 | &b11->sig, &sig); |
| 888 | |
| 889 | /* BOLT #11: |
| 890 | * |
| 891 | * A reader... MUST check that the `signature` is valid (see |
| 892 | * the `n` tagged field specified below). ... A reader... |
| 893 | * MUST use the `n` field to validate the signature instead of |
| 894 | * performing signature recovery. |
| 895 | */ |
| 896 | if (!have_n) { |
| 897 | struct pubkey k; |
| 898 | if (!secp256k1_ecdsa_recover(secp256k1_ctx, |
| 899 | &k.pubkey, |
| 900 | &sig, |
| 901 | (const u8 *)&hash)) |
| 902 | return decode_fail(b11, fail, |
| 903 | "signature recovery failed"); |