Skip to content

Commit 6c6ef58

Browse files
committed
Merge bitcoin/bitcoin#32436: test: refactor: negate signature-s using libsecp256k1
1ee698f test: refactor: negate signature-s using libsecp256k1 (Sebastian Falbesoner) Pull request description: This small PR gets rid of manual mod-n inversion of the ECDSA signature-s part in unit tests (introduced a long time ago in #5256, triggered by bitcoin-core/secp256k1#69) by using secp256k1 instead. The function wasn't available at that time, but was introduced about three years later, see bitcoin-core/secp256k1#408. Note that as the name suggests, `secp256k1_ec_seckey_negate` is meant to be used for secret keys, but it obviously works in general for scalars modulo the group order. ACKs for top commit: achow101: ACK 1ee698f laanwj: Code review ACK 1ee698f w0xlt: ACK bitcoin/bitcoin@1ee698f rkrux: tACK 1ee698f Tree-SHA512: dc36ea1572b538d11ae34e1871f310a1cda8083ffb753e93e7ee9d56e91ebd8ec78d35758dfb700254720914b734ef7a071eeef71b6239f19e1e2fb289fb5435
2 parents 9a05b45 + 1ee698f commit 6c6ef58

File tree

1 file changed

+9
-16
lines changed

1 file changed

+9
-16
lines changed

src/test/script_tests.cpp

Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030

3131
#include <boost/test/unit_test.hpp>
3232

33+
#include <secp256k1.h>
3334
#include <univalue.h>
3435

3536
// Uncomment if you want to output updated JSON tests.
@@ -144,25 +145,17 @@ void static NegateSignatureS(std::vector<unsigned char>& vchSig) {
144145
r = std::vector<unsigned char>(vchSig.begin() + 4, vchSig.begin() + 4 + vchSig[3]);
145146
s = std::vector<unsigned char>(vchSig.begin() + 6 + vchSig[3], vchSig.begin() + 6 + vchSig[3] + vchSig[5 + vchSig[3]]);
146147

147-
// Really ugly to implement mod-n negation here, but it would be feature creep to expose such functionality from libsecp256k1.
148-
static const unsigned char order[33] = {
149-
0x00,
150-
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
151-
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE,
152-
0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B,
153-
0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x41
154-
};
155148
while (s.size() < 33) {
156149
s.insert(s.begin(), 0x00);
157150
}
158-
int carry = 0;
159-
for (int p = 32; p >= 1; p--) {
160-
int n = (int)order[p] - s[p] - carry;
161-
s[p] = (n + 256) & 0xFF;
162-
carry = (n < 0);
163-
}
164-
assert(carry == 0);
165-
if (s.size() > 1 && s[0] == 0 && s[1] < 0x80) {
151+
assert(s[0] == 0);
152+
// Perform mod-n negation of s by (ab)using libsecp256k1
153+
// (note that this function is meant to be used for negating secret keys,
154+
// but it works for any non-zero scalar modulo the group order, i.e. also for s)
155+
int ret = secp256k1_ec_seckey_negate(secp256k1_context_static, s.data() + 1);
156+
assert(ret);
157+
158+
if (s[1] < 0x80) {
166159
s.erase(s.begin());
167160
}
168161

0 commit comments

Comments
 (0)