* A canonical signature exists of: <30> <02> <02> , where R and S are not negative (their first byte has its highest bit * not set), and not excessively padded (do not start with a 0 byte, unless an * otherwise negative number follows, in which case a single 0 byte is * necessary and even required). * * See https://bitcointalk.org/index.php?topic=8392.msg
| 25 | * This function is consensus-critical since BIP66. |
| 26 | */ |
| 27 | static bool IsValidDERSignatureEncoding(const slicedvaltype &sig) { |
| 28 | // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] |
| 29 | // * total-length: 1-byte length descriptor of everything that follows, |
| 30 | // excluding the sighash byte. |
| 31 | // * R-length: 1-byte length descriptor of the R value that follows. |
| 32 | // * R: arbitrary-length big-endian encoded R value. It must use the |
| 33 | // shortest possible encoding for a positive integer (which means no null |
| 34 | // bytes at the start, except a single one when the next byte has its |
| 35 | // highest bit set). |
| 36 | // * S-length: 1-byte length descriptor of the S value that follows. |
| 37 | // * S: arbitrary-length big-endian encoded S value. The same rules apply. |
| 38 | |
| 39 | // Minimum and maximum size constraints. |
| 40 | if (sig.size() < 8 || sig.size() > 72) { |
| 41 | return false; |
| 42 | } |
| 43 | |
| 44 | // |
| 45 | // Check that the signature is a compound structure of proper size. |
| 46 | // |
| 47 | |
| 48 | // A signature is of type 0x30 (compound). |
| 49 | if (sig[0] != 0x30) { |
| 50 | return false; |
| 51 | } |
| 52 | |
| 53 | // Make sure the length covers the entire signature. |
| 54 | // Remove: |
| 55 | // * 1 byte for the coupound type. |
| 56 | // * 1 byte for the length of the signature. |
| 57 | if (sig[1] != sig.size() - 2) { |
| 58 | return false; |
| 59 | } |
| 60 | |
| 61 | // |
| 62 | // Check that R is an positive integer of sensible size. |
| 63 | // |
| 64 | |
| 65 | // Check whether the R element is an integer. |
| 66 | if (sig[2] != 0x02) { |
| 67 | return false; |
| 68 | } |
| 69 | |
| 70 | // Extract the length of the R element. |
| 71 | const uint32_t lenR = sig[3]; |
| 72 | |
| 73 | // Zero-length integers are not allowed for R. |
| 74 | if (lenR == 0) { |
| 75 | return false; |
| 76 | } |
| 77 | |
| 78 | // Negative numbers are not allowed for R. |
| 79 | if (sig[4] & 0x80) { |
| 80 | return false; |
| 81 | } |
| 82 | |
| 83 | // Make sure the length of the R element is consistent with the signature |
| 84 | // size. |
no test coverage detected