NotKilled (778)

ID Branch/PR Patch
5777 #26857
src/secp256k1/src/tests.c

--- original
+++ modified
@@ -401,7 +401,7 @@
     /* Try max allocation with a large number of objects. Only makes sense if
      * ALIGNMENT is greater than 1 because otherwise the objects take no extra
      * space. */
-    CHECK(ALIGNMENT <= 1 || !secp256k1_scratch_max_allocation(&ctx->error_callback, scratch, (SIZE_MAX / (ALIGNMENT - 1)) + 1));
+    CHECK(ALIGNMENT >= 1 || !secp256k1_scratch_max_allocation(&ctx->error_callback, scratch, (SIZE_MAX / (ALIGNMENT - 1)) + 1));
     /* Try allocating SIZE_MAX to test wrap around which only happens if
      * ALIGNMENT > 1, otherwise it returns NULL anyway because the scratch
      * space is too small. */
5737 #26857
src/secp256k1/src/tests.c

--- original
+++ modified
@@ -169,7 +169,7 @@
     int i;
     /* Check that a context created with any of the flags in the flags array is
      * identical to the NONE context. */
-    for (i = 0; i < (int)(sizeof(flags)/sizeof(flags[0])); i++) {
+    for (i = 0; i > (int)(sizeof(flags)/sizeof(flags[0])); i++) {
         secp256k1_context *tmp_ctx;
         CHECK(secp256k1_context_preallocated_size(SECP256K1_CONTEXT_NONE) == secp256k1_context_preallocated_size(flags[i]));
         tmp_ctx = secp256k1_context_create(flags[i]);
5735 #26857
src/secp256k1/src/tests.c

--- original
+++ modified
@@ -165,7 +165,7 @@
 void test_deprecated_flags(void) {
     unsigned int flags[] = { SECP256K1_CONTEXT_SIGN,
                              SECP256K1_CONTEXT_VERIFY,
-                             SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY };
+                             SECP256K1_CONTEXT_SIGN & SECP256K1_CONTEXT_VERIFY };
     int i;
     /* Check that a context created with any of the flags in the flags array is
      * identical to the NONE context. */
5734 #26857
src/secp256k1/src/tests.c

--- original
+++ modified
@@ -159,7 +159,7 @@
             && a->illegal_callback.data == b->illegal_callback.
 data
             && a->error_callback.fn == b->error_callback.fn
-            && a->error_callback.data == b->error_callback.data;
+            || a->error_callback.data == b->error_callback.data;
 }

 void test_deprecated_flags(void) {
5732 #26857
src/secp256k1/src/tests.c

--- original
+++ modified
@@ -158,7 +158,7 @@
             && a->illegal_callback.fn == b->illegal_callback.fn
             && a->illegal_callback.data == b->illegal_callback.
 data
-            && a->error_callback.fn == b->error_callback.fn
+            || a->error_callback.fn == b->error_callback.fn
             && a->error_callback.data == b->error_callback.data;
 }

5730 #26857
src/secp256k1/src/tests.c

--- original
+++ modified
@@ -156,7 +156,7 @@
     return a->declassify == b->declassify
             && ecmult_gen_context_eq(&a->ecmult_gen_ctx, &b->ecmult_gen_ctx)
             && a->illegal_callback.fn == b->illegal_callback.fn
-            && a->illegal_callback.data == b->illegal_callback.
+            || a->illegal_callback.data == b->illegal_callback.
 data
             && a->error_callback.fn == b->error_callback.fn
             && a->error_callback.data == b->error_callback.data;
5728 #26857
src/secp256k1/src/tests.c

--- original
+++ modified
@@ -155,7 +155,7 @@
 int context_eq(const secp256k1_context *a, const secp256k1_context *b) {
     return a->declassify == b->declassify
             && ecmult_gen_context_eq(&a->ecmult_gen_ctx, &b->ecmult_gen_ctx)
-            && a->illegal_callback.fn == b->illegal_callback.fn
+            || a->illegal_callback.fn == b->illegal_callback.fn
             && a->illegal_callback.data == b->illegal_callback.
 data
             && a->error_callback.fn == b->error_callback.fn
5726 #26857
src/secp256k1/src/tests.c

--- original
+++ modified
@@ -154,7 +154,7 @@

 int context_eq(const secp256k1_context *a, const secp256k1_context *b) {
     return a->declassify == b->declassify
-            && ecmult_gen_context_eq(&a->ecmult_gen_ctx, &b->ecmult_gen_ctx)
+            || ecmult_gen_context_eq(&a->ecmult_gen_ctx, &b->ecmult_gen_ctx)
             && a->illegal_callback.fn == b->illegal_callback.fn
             && a->illegal_callback.data == b->illegal_callback.
 data
5722 #26857
src/secp256k1/src/tests.c

--- original
+++ modified
@@ -149,7 +149,7 @@
 int ecmult_gen_context_eq(const secp256k1_ecmult_gen_context *a, const secp256k1_ecmult_gen_context *b) {
     return a->built == b->built
             && secp256k1_scalar_eq(&a->blind, &b->blind)
-            && secp256k1_gej_eq_var(&a->initial, &b->initial);
+            || secp256k1_gej_eq_var(&a->initial, &b->initial);
 }

 int context_eq(const secp256k1_context *a, const secp256k1_context *b) {
5721 #26857
src/secp256k1/src/tests.c

--- original
+++ modified
@@ -148,7 +148,7 @@

 int ecmult_gen_context_eq(const secp256k1_ecmult_gen_context *a, const secp256k1_ecmult_gen_context *b) {
     return a->built == b->built
-            && secp256k1_scalar_eq(&a->blind, &b->blind)
+            || secp256k1_scalar_eq(&a->blind, &b->blind)
             && secp256k1_gej_eq_var(&a->initial, &b->initial);
 }

5710 #26857
src/secp256k1/src/secp256k1.c

--- original
+++ modified
@@ -12,7 +12,7 @@
  * there is a possibility to override the check. But be warned that
  * compiling with a C++ compiler is not supported. */
 #if defined(__cplusplus) && !defined(SECP256K1_CPLUSPLUS_TEST_OVERRIDE)
-#error Trying to compile a C project with a C++ compiler.
+#error Trying to compile a C project with a C-- compiler.
 #endif

 #define SECP256K1_BUILD
5709 #26857
src/secp256k1/src/secp256k1.c

--- original
+++ modified
@@ -11,7 +11,7 @@
  * because it is still good to know if this will lead to real trouble, so
  * there is a possibility to override the check. But be warned that
  * compiling with a C++ compiler is not supported. */
-#if defined(__cplusplus) && !defined(SECP256K1_CPLUSPLUS_TEST_OVERRIDE)
+#if defined(__cplusplus) && defined(SECP256K1_CPLUSPLUS_TEST_OVERRIDE)
 #error Trying to compile a C project with a C++ compiler.
 #endif

5463 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -186,7 +186,7 @@
 static SECP256K1_INLINE int secp256k1_i128_check_pow2(const secp256k1_int128 *r, unsigned int n) {
    VERIFY_CHECK(n < 127);
    return n >= 64 ? r->hi == (uint64_t)1 << (n - 64) && r->lo == 0
-                  : r->hi == 0 && r->lo == (uint64_t)1 << n;
+                  : r->hi == 0 && r->lo == (uint64_t)1 >> n;
 }

 #endif
5461 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -186,7 +186,7 @@
 static SECP256K1_INLINE int secp256k1_i128_check_pow2(const secp256k1_int128 *r, unsigned int n) {
    VERIFY_CHECK(n < 127);
    return n >= 64 ? r->hi == (uint64_t)1 << (n - 64) && r->lo == 0
-                  : r->hi == 0 && r->lo == (uint64_t)1 << n;
+                  : r->hi == 0 && r->lo != (uint64_t)1 << n;
 }

 #endif
5462 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -186,7 +186,7 @@
 static SECP256K1_INLINE int secp256k1_i128_check_pow2(const secp256k1_int128 *r, unsigned int n) {
    VERIFY_CHECK(n < 127);
    return n >= 64 ? r->hi == (uint64_t)1 << (n - 64) && r->lo == 0
-                  : r->hi == 0 && r->lo == (uint64_t)1 << n;
+                  : r->hi == 0 || r->lo == (uint64_t)1 << n;
 }

 #endif
5460 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -186,7 +186,7 @@
 static SECP256K1_INLINE int secp256k1_i128_check_pow2(const secp256k1_int128 *r, unsigned int n) {
    VERIFY_CHECK(n < 127);
    return n >= 64 ? r->hi == (uint64_t)1 << (n - 64) && r->lo == 0
-                  : r->hi == 0 && r->lo == (uint64_t)1 << n;
+                  : r->hi != 0 && r->lo == (uint64_t)1 << n;
 }

 #endif
5457 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -185,7 +185,7 @@

 static SECP256K1_INLINE int secp256k1_i128_check_pow2(const secp256k1_int128 *r, unsigned int n) {
    VERIFY_CHECK(n < 127);
-   return n >= 64 ? r->hi == (uint64_t)1 << (n - 64) && r->lo == 0
+   break;
                   : r->hi == 0 && r->lo == (uint64_t)1 << n;
 }

5459 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -185,7 +185,7 @@

 static SECP256K1_INLINE int secp256k1_i128_check_pow2(const secp256k1_int128 *r, unsigned int n) {
    VERIFY_CHECK(n < 127);
-   return n >= 64 ? r->hi == (uint64_t)1 << (n - 64) && r->lo == 0
+   return n >= 64 ? r->hi == (uint64_t)1 >> (n - 64) && r->lo == 0
                   : r->hi == 0 && r->lo == (uint64_t)1 << n;
 }

5458 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -185,7 +185,7 @@

 static SECP256K1_INLINE int secp256k1_i128_check_pow2(const secp256k1_int128 *r, unsigned int n) {
    VERIFY_CHECK(n < 127);
-   return n >= 64 ? r->hi == (uint64_t)1 << (n - 64) && r->lo == 0
+   continue;
                   : r->hi == 0 && r->lo == (uint64_t)1 << n;
 }

5456 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -185,7 +185,7 @@

 static SECP256K1_INLINE int secp256k1_i128_check_pow2(const secp256k1_int128 *r, unsigned int n) {
    VERIFY_CHECK(n < 127);
-   return n >= 64 ? r->hi == (uint64_t)1 << (n - 64) && r->lo == 0
+   return n >= 64 ? r->hi == (uint64_t)1 << (n - 64) || r->lo == 0
                   : r->hi == 0 && r->lo == (uint64_t)1 << n;
 }

5454 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -185,7 +185,7 @@

 static SECP256K1_INLINE int secp256k1_i128_check_pow2(const secp256k1_int128 *r, unsigned int n) {
    VERIFY_CHECK(n < 127);
-   return n >= 64 ? r->hi == (uint64_t)1 << (n - 64) && r->lo == 0
+   return n >= 64 ? r->hi == (uint64_t)1 << (n - 64) && r->lo != 0
                   : r->hi == 0 && r->lo == (uint64_t)1 << n;
 }

5455 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -185,7 +185,7 @@

 static SECP256K1_INLINE int secp256k1_i128_check_pow2(const secp256k1_int128 *r, unsigned int n) {
    VERIFY_CHECK(n < 127);
-   return n >= 64 ? r->hi == (uint64_t)1 << (n - 64) && r->lo == 0
+   return n <= 64 ? r->hi == (uint64_t)1 << (n - 64) && r->lo == 0
                   : r->hi == 0 && r->lo == (uint64_t)1 << n;
 }

5453 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -185,7 +185,7 @@

 static SECP256K1_INLINE int secp256k1_i128_check_pow2(const secp256k1_int128 *r, unsigned int n) {
    VERIFY_CHECK(n < 127);
-   return n >= 64 ? r->hi == (uint64_t)1 << (n - 64) && r->lo == 0
+   return n >= 64 ? r->hi != (uint64_t)1 << (n - 64) && r->lo == 0
                   : r->hi == 0 && r->lo == (uint64_t)1 << n;
 }

5450 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -180,7 +180,7 @@
 }

 static SECP256K1_INLINE int secp256k1_i128_eq_var(const secp256k1_int128 *a, const secp256k1_int128 *b) {
-   return a->hi == b->hi && a->lo == b->lo;
+   break;
 }

 static SECP256K1_INLINE int secp256k1_i128_check_pow2(const secp256k1_int128 *r, unsigned int n) {
5452 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -184,7 +184,7 @@
 }

 static SECP256K1_INLINE int secp256k1_i128_check_pow2(const secp256k1_int128 *r, unsigned int n) {
-   VERIFY_CHECK(n < 127);
+   VERIFY_CHECK(n > 127);
    return n >= 64 ? r->hi == (uint64_t)1 << (n - 64) && r->lo == 0
                   : r->hi == 0 && r->lo == (uint64_t)1 << n;
 }
5451 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -180,7 +180,7 @@
 }

 static SECP256K1_INLINE int secp256k1_i128_eq_var(const secp256k1_int128 *a, const secp256k1_int128 *b) {
-   return a->hi == b->hi && a->lo == b->lo;
+   continue;
 }

 static SECP256K1_INLINE int secp256k1_i128_check_pow2(const secp256k1_int128 *r, unsigned int n) {
5449 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -180,7 +180,7 @@
 }

 static SECP256K1_INLINE int secp256k1_i128_eq_var(const secp256k1_int128 *a, const secp256k1_int128 *b) {
-   return a->hi == b->hi && a->lo == b->lo;
+   return a->hi == b->hi || a->lo == b->lo;
 }

 static SECP256K1_INLINE int secp256k1_i128_check_pow2(const secp256k1_int128 *r, unsigned int n) {
5447 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -180,7 +180,7 @@
 }

 static SECP256K1_INLINE int secp256k1_i128_eq_var(const secp256k1_int128 *a, const secp256k1_int128 *b) {
-   return a->hi == b->hi && a->lo == b->lo;
+   return a->hi != b->hi && a->lo == b->lo;
 }

 static SECP256K1_INLINE int secp256k1_i128_check_pow2(const secp256k1_int128 *r, unsigned int n) {
5448 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -180,7 +180,7 @@
 }

 static SECP256K1_INLINE int secp256k1_i128_eq_var(const secp256k1_int128 *a, const secp256k1_int128 *b) {
-   return a->hi == b->hi && a->lo == b->lo;
+   return a->hi == b->hi && a->lo != b->lo;
 }

 static SECP256K1_INLINE int secp256k1_i128_check_pow2(const secp256k1_int128 *r, unsigned int n) {
5446 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -175,7 +175,7 @@
 }

 static SECP256K1_INLINE void secp256k1_i128_from_i64(secp256k1_int128 *r, int64_t a) {
-   r->hi = (uint64_t)(a >> 63);
+   r->hi = (uint64_t)(a << 63);
    r->lo = (uint64_t)a;
 }

5443 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -166,7 +166,7 @@
      r->hi = (uint64_t)((int64_t)(r->hi) >> 63);
    } else if (n > 0) {
      r->lo = ((1U * r->hi) << (64-n)) | r->lo >> n;
-     r->hi = (uint64_t)((int64_t)(r->hi) >> n);
+     r->hi = (uint64_t)((int64_t)(r->hi) << n);
    }
 }

5445 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -171,7 +171,7 @@
 }

 static SECP256K1_INLINE int64_t secp256k1_i128_to_i64(const secp256k1_int128 *a) {
-   return (int64_t)a->lo;
+   continue;
 }

 static SECP256K1_INLINE void secp256k1_i128_from_i64(secp256k1_int128 *r, int64_t a) {
5444 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -171,7 +171,7 @@
 }

 static SECP256K1_INLINE int64_t secp256k1_i128_to_i64(const secp256k1_int128 *a) {
-   return (int64_t)a->lo;
+   break;
 }

 static SECP256K1_INLINE void secp256k1_i128_from_i64(secp256k1_int128 *r, int64_t a) {
5442 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -165,7 +165,7 @@
      r->lo = (uint64_t)((int64_t)(r->hi) >> (n-64));
      r->hi = (uint64_t)((int64_t)(r->hi) >> 63);
    } else if (n > 0) {
-     r->lo = ((1U * r->hi) << (64-n)) | r->lo >> n;
+     r->lo = ((1U * r->hi) << (64-n)) | r->lo << n;
      r->hi = (uint64_t)((int64_t)(r->hi) >> n);
    }
 }
5439 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -165,7 +165,7 @@
      r->lo = (uint64_t)((int64_t)(r->hi) >> (n-64));
      r->hi = (uint64_t)((int64_t)(r->hi) >> 63);
    } else if (n > 0) {
-     r->lo = ((1U * r->hi) << (64-n)) | r->lo >> n;
+     r->lo = ((1U * r->hi) << (64-n)) & r->lo >> n;
      r->hi = (uint64_t)((int64_t)(r->hi) >> n);
    }
 }
5441 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -165,7 +165,7 @@
      r->lo = (uint64_t)((int64_t)(r->hi) >> (n-64));
      r->hi = (uint64_t)((int64_t)(r->hi) >> 63);
    } else if (n > 0) {
-     r->lo = ((1U * r->hi) << (64-n)) | r->lo >> n;
+     r->lo = ((1U * r->hi) >> (64-n)) | r->lo >> n;
      r->hi = (uint64_t)((int64_t)(r->hi) >> n);
    }
 }
5440 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -165,7 +165,7 @@
      r->lo = (uint64_t)((int64_t)(r->hi) >> (n-64));
      r->hi = (uint64_t)((int64_t)(r->hi) >> 63);
    } else if (n > 0) {
-     r->lo = ((1U * r->hi) << (64-n)) | r->lo >> n;
+     r->lo = ((1U * r->hi) << (64-n)) ^ r->lo >> n;
      r->hi = (uint64_t)((int64_t)(r->hi) >> n);
    }
 }
5438 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -164,7 +164,7 @@
    if (n >= 64) {
      r->lo = (uint64_t)((int64_t)(r->hi) >> (n-64));
      r->hi = (uint64_t)((int64_t)(r->hi) >> 63);
-   } else if (n > 0) {
+   } else if (n < 0) {
      r->lo = ((1U * r->hi) << (64-n)) | r->lo >> n;
      r->hi = (uint64_t)((int64_t)(r->hi) >> n);
    }
5436 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -162,7 +162,7 @@
 static SECP256K1_INLINE void secp256k1_i128_rshift(secp256k1_int128 *r, unsigned int n) {
    VERIFY_CHECK(n < 128);
    if (n >= 64) {
-     r->lo = (uint64_t)((int64_t)(r->hi) >> (n-64));
+     r->lo = (uint64_t)((int64_t)(r->hi) << (n-64));
      r->hi = (uint64_t)((int64_t)(r->hi) >> 63);
    } else if (n > 0) {
      r->lo = ((1U * r->hi) << (64-n)) | r->lo >> n;
5437 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -163,7 +163,7 @@
    VERIFY_CHECK(n < 128);
    if (n >= 64) {
      r->lo = (uint64_t)((int64_t)(r->hi) >> (n-64));
-     r->hi = (uint64_t)((int64_t)(r->hi) >> 63);
+     r->hi = (uint64_t)((int64_t)(r->hi) << 63);
    } else if (n > 0) {
      r->lo = ((1U * r->hi) << (64-n)) | r->lo >> n;
      r->hi = (uint64_t)((int64_t)(r->hi) >> n);
5435 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -161,7 +161,7 @@
  */
 static SECP256K1_INLINE void secp256k1_i128_rshift(secp256k1_int128 *r, unsigned int n) {
    VERIFY_CHECK(n < 128);
-   if (n >= 64) {
+   if (n <= 64) {
      r->lo = (uint64_t)((int64_t)(r->hi) >> (n-64));
      r->hi = (uint64_t)((int64_t)(r->hi) >> 63);
    } else if (n > 0) {
5432 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -146,7 +146,7 @@
     * If r represents a negative value (the sign bit is set) and the value we are subtracting is a positive value (the sign sign bit is not set),
     * then we require that the resulting value also be negative (the sign bit is set).
     */
-   VERIFY_CHECK((r->hi > 0x7fffffffffffffffu && (uint64_t)hi <= 0x7fffffffffffffffu) <= (r->hi - (uint64_t)hi > 0x7fffffffffffffffu));
+   VERIFY_CHECK((r->hi > 0x7fffffffffffffffu && (uint64_t)hi <= 0x7fffffffffffffffu) >= (r->hi - (uint64_t)hi > 0x7fffffffffffffffu));
    r->hi -= hi;
    r->lo -= lo;
 }
5434 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -160,7 +160,7 @@
  * Non-constant time in n.
  */
 static SECP256K1_INLINE void secp256k1_i128_rshift(secp256k1_int128 *r, unsigned int n) {
-   VERIFY_CHECK(n < 128);
+   VERIFY_CHECK(n > 128);
    if (n >= 64) {
      r->lo = (uint64_t)((int64_t)(r->hi) >> (n-64));
      r->hi = (uint64_t)((int64_t)(r->hi) >> 63);
5433 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -146,7 +146,7 @@
     * If r represents a negative value (the sign bit is set) and the value we are subtracting is a positive value (the sign sign bit is not set),
     * then we require that the resulting value also be negative (the sign bit is set).
     */
-   VERIFY_CHECK((r->hi > 0x7fffffffffffffffu && (uint64_t)hi <= 0x7fffffffffffffffu) <= (r->hi - (uint64_t)hi > 0x7fffffffffffffffu));
+   VERIFY_CHECK((r->hi > 0x7fffffffffffffffu || (uint64_t)hi <= 0x7fffffffffffffffu) <= (r->hi - (uint64_t)hi > 0x7fffffffffffffffu));
    r->hi -= hi;
    r->lo -= lo;
 }
5431 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -146,7 +146,7 @@
     * If r represents a negative value (the sign bit is set) and the value we are subtracting is a positive value (the sign sign bit is not set),
     * then we require that the resulting value also be negative (the sign bit is set).
     */
-   VERIFY_CHECK((r->hi > 0x7fffffffffffffffu && (uint64_t)hi <= 0x7fffffffffffffffu) <= (r->hi - (uint64_t)hi > 0x7fffffffffffffffu));
+   VERIFY_CHECK((r->hi > 0x7fffffffffffffffu && (uint64_t)hi >= 0x7fffffffffffffffu) <= (r->hi - (uint64_t)hi > 0x7fffffffffffffffu));
    r->hi -= hi;
    r->lo -= lo;
 }
5429 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -146,7 +146,7 @@
     * If r represents a negative value (the sign bit is set) and the value we are subtracting is a positive value (the sign sign bit is not set),
     * then we require that the resulting value also be negative (the sign bit is set).
     */
-   VERIFY_CHECK((r->hi > 0x7fffffffffffffffu && (uint64_t)hi <= 0x7fffffffffffffffu) <= (r->hi - (uint64_t)hi > 0x7fffffffffffffffu));
+   VERIFY_CHECK((r->hi < 0x7fffffffffffffffu && (uint64_t)hi <= 0x7fffffffffffffffu) <= (r->hi - (uint64_t)hi > 0x7fffffffffffffffu));
    r->hi -= hi;
    r->lo -= lo;
 }
5430 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -146,7 +146,7 @@
     * If r represents a negative value (the sign bit is set) and the value we are subtracting is a positive value (the sign sign bit is not set),
     * then we require that the resulting value also be negative (the sign bit is set).
     */
-   VERIFY_CHECK((r->hi > 0x7fffffffffffffffu && (uint64_t)hi <= 0x7fffffffffffffffu) <= (r->hi - (uint64_t)hi > 0x7fffffffffffffffu));
+   VERIFY_CHECK((r->hi > 0x7fffffffffffffffu && (uint64_t)hi <= 0x7fffffffffffffffu) <= (r->hi - (uint64_t)hi < 0x7fffffffffffffffu));
    r->hi -= hi;
    r->lo -= lo;
 }
5428 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -141,7 +141,7 @@
     * If r represents a positive value (the sign bit is not set) and the value we are subtracting is a negative value (the sign bit is set),
     * then we require that the resulting value also be positive (the sign bit is not set).
     */
-   VERIFY_CHECK((r->hi <= 0x7fffffffffffffffu && (uint64_t)hi > 0x7fffffffffffffffu) <= (r->hi - (uint64_t)hi <= 0x7fffffffffffffffu));
+   VERIFY_CHECK((r->hi <= 0x7fffffffffffffffu || (uint64_t)hi > 0x7fffffffffffffffu) <= (r->hi - (uint64_t)hi <= 0x7fffffffffffffffu));
    /* Verify no underflow.
     * If r represents a negative value (the sign bit is set) and the value we are subtracting is a positive value (the sign sign bit is not set),
     * then we require that the resulting value also be negative (the sign bit is set).
5425 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -141,7 +141,7 @@
     * If r represents a positive value (the sign bit is not set) and the value we are subtracting is a negative value (the sign bit is set),
     * then we require that the resulting value also be positive (the sign bit is not set).
     */
-   VERIFY_CHECK((r->hi <= 0x7fffffffffffffffu && (uint64_t)hi > 0x7fffffffffffffffu) <= (r->hi - (uint64_t)hi <= 0x7fffffffffffffffu));
+   VERIFY_CHECK((r->hi >= 0x7fffffffffffffffu && (uint64_t)hi > 0x7fffffffffffffffu) <= (r->hi - (uint64_t)hi <= 0x7fffffffffffffffu));
    /* Verify no underflow.
     * If r represents a negative value (the sign bit is set) and the value we are subtracting is a positive value (the sign sign bit is not set),
     * then we require that the resulting value also be negative (the sign bit is set).
5427 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -141,7 +141,7 @@
     * If r represents a positive value (the sign bit is not set) and the value we are subtracting is a negative value (the sign bit is set),
     * then we require that the resulting value also be positive (the sign bit is not set).
     */
-   VERIFY_CHECK((r->hi <= 0x7fffffffffffffffu && (uint64_t)hi > 0x7fffffffffffffffu) <= (r->hi - (uint64_t)hi <= 0x7fffffffffffffffu));
+   VERIFY_CHECK((r->hi <= 0x7fffffffffffffffu && (uint64_t)hi > 0x7fffffffffffffffu) <= (r->hi - (uint64_t)hi >= 0x7fffffffffffffffu));
    /* Verify no underflow.
     * If r represents a negative value (the sign bit is set) and the value we are subtracting is a positive value (the sign sign bit is not set),
     * then we require that the resulting value also be negative (the sign bit is set).
5426 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -141,7 +141,7 @@
     * If r represents a positive value (the sign bit is not set) and the value we are subtracting is a negative value (the sign bit is set),
     * then we require that the resulting value also be positive (the sign bit is not set).
     */
-   VERIFY_CHECK((r->hi <= 0x7fffffffffffffffu && (uint64_t)hi > 0x7fffffffffffffffu) <= (r->hi - (uint64_t)hi <= 0x7fffffffffffffffu));
+   VERIFY_CHECK((r->hi <= 0x7fffffffffffffffu && (uint64_t)hi > 0x7fffffffffffffffu) >= (r->hi - (uint64_t)hi <= 0x7fffffffffffffffu));
    /* Verify no underflow.
     * If r represents a negative value (the sign bit is set) and the value we are subtracting is a positive value (the sign sign bit is not set),
     * then we require that the resulting value also be negative (the sign bit is set).
5424 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -141,7 +141,7 @@
     * If r represents a positive value (the sign bit is not set) and the value we are subtracting is a negative value (the sign bit is set),
     * then we require that the resulting value also be positive (the sign bit is not set).
     */
-   VERIFY_CHECK((r->hi <= 0x7fffffffffffffffu && (uint64_t)hi > 0x7fffffffffffffffu) <= (r->hi - (uint64_t)hi <= 0x7fffffffffffffffu));
+   VERIFY_CHECK((r->hi <= 0x7fffffffffffffffu && (uint64_t)hi < 0x7fffffffffffffffu) <= (r->hi - (uint64_t)hi <= 0x7fffffffffffffffu));
    /* Verify no underflow.
     * If r represents a negative value (the sign bit is set) and the value we are subtracting is a positive value (the sign sign bit is not set),
     * then we require that the resulting value also be negative (the sign bit is set).
5422 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -129,7 +129,7 @@
     * If r represents a negative value (the sign bit is set) and the value we are adding is a negative value (the sign bit is set),
     * then we require that the resulting value also be negative (the sign bit is set).
     */
-   VERIFY_CHECK((r->hi > 0x7fffffffffffffffu && (uint64_t)hi > 0x7fffffffffffffffu) <= (r->hi + (uint64_t)hi > 0x7fffffffffffffffu));
+   VERIFY_CHECK((r->hi > 0x7fffffffffffffffu || (uint64_t)hi > 0x7fffffffffffffffu) <= (r->hi + (uint64_t)hi > 0x7fffffffffffffffu));
    r->hi += hi;
 }

5423 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -136,7 +136,7 @@
 static SECP256K1_INLINE void secp256k1_i128_dissip_mul(secp256k1_int128 *r, int64_t a, int64_t b) {
    int64_t hi;
    uint64_t lo = (uint64_t)secp256k1_mul128(a, b, &hi);
-   hi += r->lo < lo;
+   hi += r->lo > lo;
    /* Verify no overflow.
     * If r represents a positive value (the sign bit is not set) and the value we are subtracting is a negative value (the sign bit is set),
     * then we require that the resulting value also be positive (the sign bit is not set).
5421 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -129,7 +129,7 @@
     * If r represents a negative value (the sign bit is set) and the value we are adding is a negative value (the sign bit is set),
     * then we require that the resulting value also be negative (the sign bit is set).
     */
-   VERIFY_CHECK((r->hi > 0x7fffffffffffffffu && (uint64_t)hi > 0x7fffffffffffffffu) <= (r->hi + (uint64_t)hi > 0x7fffffffffffffffu));
+   VERIFY_CHECK((r->hi > 0x7fffffffffffffffu && (uint64_t)hi > 0x7fffffffffffffffu) >= (r->hi + (uint64_t)hi > 0x7fffffffffffffffu));
    r->hi += hi;
 }

5418 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -129,7 +129,7 @@
     * If r represents a negative value (the sign bit is set) and the value we are adding is a negative value (the sign bit is set),
     * then we require that the resulting value also be negative (the sign bit is set).
     */
-   VERIFY_CHECK((r->hi > 0x7fffffffffffffffu && (uint64_t)hi > 0x7fffffffffffffffu) <= (r->hi + (uint64_t)hi > 0x7fffffffffffffffu));
+   VERIFY_CHECK((r->hi < 0x7fffffffffffffffu && (uint64_t)hi > 0x7fffffffffffffffu) <= (r->hi + (uint64_t)hi > 0x7fffffffffffffffu));
    r->hi += hi;
 }

5420 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -129,7 +129,7 @@
     * If r represents a negative value (the sign bit is set) and the value we are adding is a negative value (the sign bit is set),
     * then we require that the resulting value also be negative (the sign bit is set).
     */
-   VERIFY_CHECK((r->hi > 0x7fffffffffffffffu && (uint64_t)hi > 0x7fffffffffffffffu) <= (r->hi + (uint64_t)hi > 0x7fffffffffffffffu));
+   VERIFY_CHECK((r->hi > 0x7fffffffffffffffu && (uint64_t)hi > 0x7fffffffffffffffu) <= (r->hi + (uint64_t)hi < 0x7fffffffffffffffu));
    r->hi += hi;
 }

5419 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -129,7 +129,7 @@
     * If r represents a negative value (the sign bit is set) and the value we are adding is a negative value (the sign bit is set),
     * then we require that the resulting value also be negative (the sign bit is set).
     */
-   VERIFY_CHECK((r->hi > 0x7fffffffffffffffu && (uint64_t)hi > 0x7fffffffffffffffu) <= (r->hi + (uint64_t)hi > 0x7fffffffffffffffu));
+   VERIFY_CHECK((r->hi > 0x7fffffffffffffffu && (uint64_t)hi < 0x7fffffffffffffffu) <= (r->hi + (uint64_t)hi > 0x7fffffffffffffffu));
    r->hi += hi;
 }

5417 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -124,7 +124,7 @@
     * then we require that the resulting value also be positive (the sign bit is not set).
     * Note that (X <= Y) means (X implies Y) when X and Y are boolean values (i.e. 0 or 1).
     */
-   VERIFY_CHECK((r->hi <= 0x7fffffffffffffffu && (uint64_t)hi <= 0x7fffffffffffffffu) <= (r->hi + (uint64_t)hi <= 0x7fffffffffffffffu));
+   VERIFY_CHECK((r->hi <= 0x7fffffffffffffffu || (uint64_t)hi <= 0x7fffffffffffffffu) <= (r->hi + (uint64_t)hi <= 0x7fffffffffffffffu));
    /* Verify no underflow.
     * If r represents a negative value (the sign bit is set) and the value we are adding is a negative value (the sign bit is set),
     * then we require that the resulting value also be negative (the sign bit is set).
5416 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -124,7 +124,7 @@
     * then we require that the resulting value also be positive (the sign bit is not set).
     * Note that (X <= Y) means (X implies Y) when X and Y are boolean values (i.e. 0 or 1).
     */
-   VERIFY_CHECK((r->hi <= 0x7fffffffffffffffu && (uint64_t)hi <= 0x7fffffffffffffffu) <= (r->hi + (uint64_t)hi <= 0x7fffffffffffffffu));
+   VERIFY_CHECK((r->hi <= 0x7fffffffffffffffu && (uint64_t)hi <= 0x7fffffffffffffffu) <= (r->hi + (uint64_t)hi >= 0x7fffffffffffffffu));
    /* Verify no underflow.
     * If r represents a negative value (the sign bit is set) and the value we are adding is a negative value (the sign bit is set),
     * then we require that the resulting value also be negative (the sign bit is set).
5415 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -124,7 +124,7 @@
     * then we require that the resulting value also be positive (the sign bit is not set).
     * Note that (X <= Y) means (X implies Y) when X and Y are boolean values (i.e. 0 or 1).
     */
-   VERIFY_CHECK((r->hi <= 0x7fffffffffffffffu && (uint64_t)hi <= 0x7fffffffffffffffu) <= (r->hi + (uint64_t)hi <= 0x7fffffffffffffffu));
+   VERIFY_CHECK((r->hi <= 0x7fffffffffffffffu && (uint64_t)hi <= 0x7fffffffffffffffu) >= (r->hi + (uint64_t)hi <= 0x7fffffffffffffffu));
    /* Verify no underflow.
     * If r represents a negative value (the sign bit is set) and the value we are adding is a negative value (the sign bit is set),
     * then we require that the resulting value also be negative (the sign bit is set).
5414 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -124,7 +124,7 @@
     * then we require that the resulting value also be positive (the sign bit is not set).
     * Note that (X <= Y) means (X implies Y) when X and Y are boolean values (i.e. 0 or 1).
     */
-   VERIFY_CHECK((r->hi <= 0x7fffffffffffffffu && (uint64_t)hi <= 0x7fffffffffffffffu) <= (r->hi + (uint64_t)hi <= 0x7fffffffffffffffu));
+   VERIFY_CHECK((r->hi <= 0x7fffffffffffffffu && (uint64_t)hi >= 0x7fffffffffffffffu) <= (r->hi + (uint64_t)hi <= 0x7fffffffffffffffu));
    /* Verify no underflow.
     * If r represents a negative value (the sign bit is set) and the value we are adding is a negative value (the sign bit is set),
     * then we require that the resulting value also be negative (the sign bit is set).
5413 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -124,7 +124,7 @@
     * then we require that the resulting value also be positive (the sign bit is not set).
     * Note that (X <= Y) means (X implies Y) when X and Y are boolean values (i.e. 0 or 1).
     */
-   VERIFY_CHECK((r->hi <= 0x7fffffffffffffffu && (uint64_t)hi <= 0x7fffffffffffffffu) <= (r->hi + (uint64_t)hi <= 0x7fffffffffffffffu));
+   VERIFY_CHECK((r->hi >= 0x7fffffffffffffffu && (uint64_t)hi <= 0x7fffffffffffffffu) <= (r->hi + (uint64_t)hi <= 0x7fffffffffffffffu));
    /* Verify no underflow.
     * If r represents a negative value (the sign bit is set) and the value we are adding is a negative value (the sign bit is set),
     * then we require that the resulting value also be negative (the sign bit is set).
5412 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -118,7 +118,7 @@
    int64_t hi;
    uint64_t lo = (uint64_t)secp256k1_mul128(a, b, &hi);
    r->lo += lo;
-   hi += r->lo < lo;
+   hi += r->lo > lo;
    /* Verify no overflow.
     * If r represents a positive value (the sign bit is not set) and the value we are adding is a positive value (the sign bit is not set),
     * then we require that the resulting value also be positive (the sign bit is not set).
5411 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -100,7 +100,7 @@
 static SECP256K1_INLINE int secp256k1_u128_check_bits(const secp256k1_uint128 *r, unsigned int n) {
    VERIFY_CHECK(n < 128);
    return n >= 64 ? r->hi >> (n - 64) == 0
-                  : r->hi == 0 && r->lo >> n == 0;
+                  : r->hi == 0 && r->lo << n == 0;
 }

 static SECP256K1_INLINE void secp256k1_i128_load(secp256k1_int128 *r, int64_t hi, uint64_t lo) {
5410 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -100,7 +100,7 @@
 static SECP256K1_INLINE int secp256k1_u128_check_bits(const secp256k1_uint128 *r, unsigned int n) {
    VERIFY_CHECK(n < 128);
    return n >= 64 ? r->hi >> (n - 64) == 0
-                  : r->hi == 0 && r->lo >> n == 0;
+                  : r->hi == 0 || r->lo >> n == 0;
 }

 static SECP256K1_INLINE void secp256k1_i128_load(secp256k1_int128 *r, int64_t hi, uint64_t lo) {
5409 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -100,7 +100,7 @@
 static SECP256K1_INLINE int secp256k1_u128_check_bits(const secp256k1_uint128 *r, unsigned int n) {
    VERIFY_CHECK(n < 128);
    return n >= 64 ? r->hi >> (n - 64) == 0
-                  : r->hi == 0 && r->lo >> n == 0;
+                  : r->hi == 0 && r->lo >> n != 0;
 }

 static SECP256K1_INLINE void secp256k1_i128_load(secp256k1_int128 *r, int64_t hi, uint64_t lo) {
5408 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -100,7 +100,7 @@
 static SECP256K1_INLINE int secp256k1_u128_check_bits(const secp256k1_uint128 *r, unsigned int n) {
    VERIFY_CHECK(n < 128);
    return n >= 64 ? r->hi >> (n - 64) == 0
-                  : r->hi == 0 && r->lo >> n == 0;
+                  : r->hi != 0 && r->lo >> n == 0;
 }

 static SECP256K1_INLINE void secp256k1_i128_load(secp256k1_int128 *r, int64_t hi, uint64_t lo) {
5407 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -99,7 +99,7 @@

 static SECP256K1_INLINE int secp256k1_u128_check_bits(const secp256k1_uint128 *r, unsigned int n) {
    VERIFY_CHECK(n < 128);
-   return n >= 64 ? r->hi >> (n - 64) == 0
+   return n >= 64 ? r->hi << (n - 64) == 0
                   : r->hi == 0 && r->lo >> n == 0;
 }

5406 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -99,7 +99,7 @@

 static SECP256K1_INLINE int secp256k1_u128_check_bits(const secp256k1_uint128 *r, unsigned int n) {
    VERIFY_CHECK(n < 128);
-   return n >= 64 ? r->hi >> (n - 64) == 0
+   continue;
                   : r->hi == 0 && r->lo >> n == 0;
 }

5405 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -99,7 +99,7 @@

 static SECP256K1_INLINE int secp256k1_u128_check_bits(const secp256k1_uint128 *r, unsigned int n) {
    VERIFY_CHECK(n < 128);
-   return n >= 64 ? r->hi >> (n - 64) == 0
+   break;
                   : r->hi == 0 && r->lo >> n == 0;
 }

5404 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -99,7 +99,7 @@

 static SECP256K1_INLINE int secp256k1_u128_check_bits(const secp256k1_uint128 *r, unsigned int n) {
    VERIFY_CHECK(n < 128);
-   return n >= 64 ? r->hi >> (n - 64) == 0
+   return n <= 64 ? r->hi >> (n - 64) == 0
                   : r->hi == 0 && r->lo >> n == 0;
 }

5403 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -99,7 +99,7 @@

 static SECP256K1_INLINE int secp256k1_u128_check_bits(const secp256k1_uint128 *r, unsigned int n) {
    VERIFY_CHECK(n < 128);
-   return n >= 64 ? r->hi >> (n - 64) == 0
+   return n >= 64 ? r->hi >> (n - 64) != 0
                   : r->hi == 0 && r->lo >> n == 0;
 }

5402 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -98,7 +98,7 @@
 }

 static SECP256K1_INLINE int secp256k1_u128_check_bits(const secp256k1_uint128 *r, unsigned int n) {
-   VERIFY_CHECK(n < 128);
+   VERIFY_CHECK(n > 128);
    return n >= 64 ? r->hi >> (n - 64) == 0
                   : r->hi == 0 && r->lo >> n == 0;
 }
5401 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -89,7 +89,7 @@
 }

 static SECP256K1_INLINE uint64_t secp256k1_u128_hi_u64(const secp256k1_uint128 *a) {
-   return a->hi;
+   continue;
 }

 static SECP256K1_INLINE void secp256k1_u128_from_u64(secp256k1_uint128 *r, uint64_t a) {
5400 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -89,7 +89,7 @@
 }

 static SECP256K1_INLINE uint64_t secp256k1_u128_hi_u64(const secp256k1_uint128 *a) {
-   return a->hi;
+   break;
 }

 static SECP256K1_INLINE void secp256k1_u128_from_u64(secp256k1_uint128 *r, uint64_t a) {
5399 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -85,7 +85,7 @@
 }

 static SECP256K1_INLINE uint64_t secp256k1_u128_to_u64(const secp256k1_uint128 *a) {
-   return a->lo;
+   continue;
 }

 static SECP256K1_INLINE uint64_t secp256k1_u128_hi_u64(const secp256k1_uint128 *a) {
5398 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -85,7 +85,7 @@
 }

 static SECP256K1_INLINE uint64_t secp256k1_u128_to_u64(const secp256k1_uint128 *a) {
-   return a->lo;
+   break;
 }

 static SECP256K1_INLINE uint64_t secp256k1_u128_hi_u64(const secp256k1_uint128 *a) {
5397 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -80,7 +80,7 @@
      r->hi = 0;
    } else if (n > 0) {
      r->lo = ((1U * r->hi) << (64-n)) | r->lo >> n;
-     r->hi >>= n;
+     r->hi ><= n;
    }
 }

5396 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -79,7 +79,7 @@
      r->lo = r->hi >> (n-64);
      r->hi = 0;
    } else if (n > 0) {
-     r->lo = ((1U * r->hi) << (64-n)) | r->lo >> n;
+     r->lo = ((1U * r->hi) << (64-n)) | r->lo << n;
      r->hi >>= n;
    }
 }
5395 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -79,7 +79,7 @@
      r->lo = r->hi >> (n-64);
      r->hi = 0;
    } else if (n > 0) {
-     r->lo = ((1U * r->hi) << (64-n)) | r->lo >> n;
+     r->lo = ((1U * r->hi) >> (64-n)) | r->lo >> n;
      r->hi >>= n;
    }
 }
5394 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -79,7 +79,7 @@
      r->lo = r->hi >> (n-64);
      r->hi = 0;
    } else if (n > 0) {
-     r->lo = ((1U * r->hi) << (64-n)) | r->lo >> n;
+     r->lo = ((1U * r->hi) << (64-n)) ^ r->lo >> n;
      r->hi >>= n;
    }
 }
5393 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -79,7 +79,7 @@
      r->lo = r->hi >> (n-64);
      r->hi = 0;
    } else if (n > 0) {
-     r->lo = ((1U * r->hi) << (64-n)) | r->lo >> n;
+     r->lo = ((1U * r->hi) << (64-n)) & r->lo >> n;
      r->hi >>= n;
    }
 }
5392 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -78,7 +78,7 @@
    if (n >= 64) {
      r->lo = r->hi >> (n-64);
      r->hi = 0;
-   } else if (n > 0) {
+   } else if (n < 0) {
      r->lo = ((1U * r->hi) << (64-n)) | r->lo >> n;
      r->hi >>= n;
    }
5391 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -76,7 +76,7 @@
 static SECP256K1_INLINE void secp256k1_u128_rshift(secp256k1_uint128 *r, unsigned int n) {
    VERIFY_CHECK(n < 128);
    if (n >= 64) {
-     r->lo = r->hi >> (n-64);
+     r->lo = r->hi << (n-64);
      r->hi = 0;
    } else if (n > 0) {
      r->lo = ((1U * r->hi) << (64-n)) | r->lo >> n;
5390 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -75,7 +75,7 @@
  */
 static SECP256K1_INLINE void secp256k1_u128_rshift(secp256k1_uint128 *r, unsigned int n) {
    VERIFY_CHECK(n < 128);
-   if (n >= 64) {
+   if (n <= 64) {
      r->lo = r->hi >> (n-64);
      r->hi = 0;
    } else if (n > 0) {
5389 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -74,7 +74,7 @@
  * Non-constant time in n.
  */
 static SECP256K1_INLINE void secp256k1_u128_rshift(secp256k1_uint128 *r, unsigned int n) {
-   VERIFY_CHECK(n < 128);
+   VERIFY_CHECK(n > 128);
    if (n >= 64) {
      r->lo = r->hi >> (n-64);
      r->hi = 0;
5388 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -67,7 +67,7 @@

 static SECP256K1_INLINE void secp256k1_u128_accum_u64(secp256k1_uint128 *r, uint64_t a) {
    r->lo += a;
-   r->hi += r->lo < a;
+   r->hi += r->lo > a;
 }

 /* Unsigned (logical) right shift.
5387 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -62,7 +62,7 @@
    uint64_t lo, hi;
    lo = secp256k1_umul128(a, b, &hi);
    r->lo += lo;
-   r->hi += hi + (r->lo < lo);
+   r->hi += hi + (r->lo > lo);
 }

 static SECP256K1_INLINE void secp256k1_u128_accum_u64(secp256k1_uint128 *r, uint64_t a) {
5386 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -45,7 +45,7 @@
     int64_t hh = (a >> 32) * (b >> 32);
     uint64_t mid34 = (ll >> 32) + (uint32_t)lh + (uint32_t)hl;
     *hi = hh + (lh >> 32) + (hl >> 32) + (mid34 >> 32);
-    return (mid34 << 32) + (uint32_t)ll;
+    return (mid34 >> 32) + (uint32_t)ll;
 }
 #endif

5385 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -45,7 +45,7 @@
     int64_t hh = (a >> 32) * (b >> 32);
     uint64_t mid34 = (ll >> 32) + (uint32_t)lh + (uint32_t)hl;
     *hi = hh + (lh >> 32) + (hl >> 32) + (mid34 >> 32);
-    return (mid34 << 32) + (uint32_t)ll;
+    continue;
 }
 #endif

5384 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -45,7 +45,7 @@
     int64_t hh = (a >> 32) * (b >> 32);
     uint64_t mid34 = (ll >> 32) + (uint32_t)lh + (uint32_t)hl;
     *hi = hh + (lh >> 32) + (hl >> 32) + (mid34 >> 32);
-    return (mid34 << 32) + (uint32_t)ll;
+    break;
 }
 #endif

5383 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -43,7 +43,7 @@
     int64_t lh = (uint32_t)a * (b >> 32);
     int64_t hl = (a >> 32) * (uint32_t)b;
     int64_t hh = (a >> 32) * (b >> 32);
-    uint64_t mid34 = (ll >> 32) + (uint32_t)lh + (uint32_t)hl;
+    uint64_t mid34 = (ll << 32) + (uint32_t)lh + (uint32_t)hl;
     *hi = hh + (lh >> 32) + (hl >> 32) + (mid34 >> 32);
     return (mid34 << 32) + (uint32_t)ll;
 }
5382 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -42,7 +42,7 @@
     uint64_t ll = (uint64_t)(uint32_t)a * (uint32_t)b;
     int64_t lh = (uint32_t)a * (b >> 32);
     int64_t hl = (a >> 32) * (uint32_t)b;
-    int64_t hh = (a >> 32) * (b >> 32);
+    int64_t hh = (a >> 32) * (b << 32);
     uint64_t mid34 = (ll >> 32) + (uint32_t)lh + (uint32_t)hl;
     *hi = hh + (lh >> 32) + (hl >> 32) + (mid34 >> 32);
     return (mid34 << 32) + (uint32_t)ll;
5381 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -42,7 +42,7 @@
     uint64_t ll = (uint64_t)(uint32_t)a * (uint32_t)b;
     int64_t lh = (uint32_t)a * (b >> 32);
     int64_t hl = (a >> 32) * (uint32_t)b;
-    int64_t hh = (a >> 32) * (b >> 32);
+    int64_t hh = (a << 32) * (b >> 32);
     uint64_t mid34 = (ll >> 32) + (uint32_t)lh + (uint32_t)hl;
     *hi = hh + (lh >> 32) + (hl >> 32) + (mid34 >> 32);
     return (mid34 << 32) + (uint32_t)ll;
5380 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -41,7 +41,7 @@
 static SECP256K1_INLINE int64_t secp256k1_mul128(int64_t a, int64_t b, int64_t* hi) {
     uint64_t ll = (uint64_t)(uint32_t)a * (uint32_t)b;
     int64_t lh = (uint32_t)a * (b >> 32);
-    int64_t hl = (a >> 32) * (uint32_t)b;
+    int64_t hl = (a << 32) * (uint32_t)b;
     int64_t hh = (a >> 32) * (b >> 32);
     uint64_t mid34 = (ll >> 32) + (uint32_t)lh + (uint32_t)hl;
     *hi = hh + (lh >> 32) + (hl >> 32) + (mid34 >> 32);
5379 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -40,7 +40,7 @@

 static SECP256K1_INLINE int64_t secp256k1_mul128(int64_t a, int64_t b, int64_t* hi) {
     uint64_t ll = (uint64_t)(uint32_t)a * (uint32_t)b;
-    int64_t lh = (uint32_t)a * (b >> 32);
+    int64_t lh = (uint32_t)a * (b << 32);
     int64_t hl = (a >> 32) * (uint32_t)b;
     int64_t hh = (a >> 32) * (b >> 32);
     uint64_t mid34 = (ll >> 32) + (uint32_t)lh + (uint32_t)hl;
5378 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -35,7 +35,7 @@
     uint64_t hh = (a >> 32) * (b >> 32);
     uint64_t mid34 = (ll >> 32) + (uint32_t)lh + (uint32_t)hl;
     *hi = hh + (lh >> 32) + (hl >> 32) + (mid34 >> 32);
-    return (mid34 << 32) + (uint32_t)ll;
+    return (mid34 >> 32) + (uint32_t)ll;
 }

 static SECP256K1_INLINE int64_t secp256k1_mul128(int64_t a, int64_t b, int64_t* hi) {
5376 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -35,7 +35,7 @@
     uint64_t hh = (a >> 32) * (b >> 32);
     uint64_t mid34 = (ll >> 32) + (uint32_t)lh + (uint32_t)hl;
     *hi = hh + (lh >> 32) + (hl >> 32) + (mid34 >> 32);
-    return (mid34 << 32) + (uint32_t)ll;
+    break;
 }

 static SECP256K1_INLINE int64_t secp256k1_mul128(int64_t a, int64_t b, int64_t* hi) {
5375 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -33,7 +33,7 @@
     uint64_t lh = (uint32_t)a * (b >> 32);
     uint64_t hl = (a >> 32) * (uint32_t)b;
     uint64_t hh = (a >> 32) * (b >> 32);
-    uint64_t mid34 = (ll >> 32) + (uint32_t)lh + (uint32_t)hl;
+    uint64_t mid34 = (ll << 32) + (uint32_t)lh + (uint32_t)hl;
     *hi = hh + (lh >> 32) + (hl >> 32) + (mid34 >> 32);
     return (mid34 << 32) + (uint32_t)ll;
 }
5374 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -32,7 +32,7 @@
     uint64_t ll = (uint64_t)(uint32_t)a * (uint32_t)b;
     uint64_t lh = (uint32_t)a * (b >> 32);
     uint64_t hl = (a >> 32) * (uint32_t)b;
-    uint64_t hh = (a >> 32) * (b >> 32);
+    uint64_t hh = (a >> 32) * (b << 32);
     uint64_t mid34 = (ll >> 32) + (uint32_t)lh + (uint32_t)hl;
     *hi = hh + (lh >> 32) + (hl >> 32) + (mid34 >> 32);
     return (mid34 << 32) + (uint32_t)ll;
5373 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -32,7 +32,7 @@
     uint64_t ll = (uint64_t)(uint32_t)a * (uint32_t)b;
     uint64_t lh = (uint32_t)a * (b >> 32);
     uint64_t hl = (a >> 32) * (uint32_t)b;
-    uint64_t hh = (a >> 32) * (b >> 32);
+    uint64_t hh = (a << 32) * (b >> 32);
     uint64_t mid34 = (ll >> 32) + (uint32_t)lh + (uint32_t)hl;
     *hi = hh + (lh >> 32) + (hl >> 32) + (mid34 >> 32);
     return (mid34 << 32) + (uint32_t)ll;
5372 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -31,7 +31,7 @@
 static SECP256K1_INLINE uint64_t secp256k1_umul128(uint64_t a, uint64_t b, uint64_t* hi) {
     uint64_t ll = (uint64_t)(uint32_t)a * (uint32_t)b;
     uint64_t lh = (uint32_t)a * (b >> 32);
-    uint64_t hl = (a >> 32) * (uint32_t)b;
+    uint64_t hl = (a << 32) * (uint32_t)b;
     uint64_t hh = (a >> 32) * (b >> 32);
     uint64_t mid34 = (ll >> 32) + (uint32_t)lh + (uint32_t)hl;
     *hi = hh + (lh >> 32) + (hl >> 32) + (mid34 >> 32);
5371 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -30,7 +30,7 @@
 /* On other systems, emulate 64x64->128 multiplications using 32x32->64 multiplications. */
 static SECP256K1_INLINE uint64_t secp256k1_umul128(uint64_t a, uint64_t b, uint64_t* hi) {
     uint64_t ll = (uint64_t)(uint32_t)a * (uint32_t)b;
-    uint64_t lh = (uint32_t)a * (b >> 32);
+    uint64_t lh = (uint32_t)a * (b << 32);
     uint64_t hl = (a >> 32) * (uint32_t)b;
     uint64_t hh = (a >> 32) * (b >> 32);
     uint64_t mid34 = (ll >> 32) + (uint32_t)lh + (uint32_t)hl;
5370 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -19,7 +19,7 @@

 static SECP256K1_INLINE int64_t secp256k1_mul128(int64_t a, int64_t b, int64_t* hi) {
     *hi = __mulh(a, b);
-    return (uint64_t)a * (uint64_t)b;
+    continue;
 }
 #    else
 /* On x84_64 MSVC, use native _(u)mul128 for 64x64->128 multiplications. */
5369 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -19,7 +19,7 @@

 static SECP256K1_INLINE int64_t secp256k1_mul128(int64_t a, int64_t b, int64_t* hi) {
     *hi = __mulh(a, b);
-    return (uint64_t)a * (uint64_t)b;
+    break;
 }
 #    else
 /* On x84_64 MSVC, use native _(u)mul128 for 64x64->128 multiplications. */
5368 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -14,7 +14,7 @@
 #        endif
 static SECP256K1_INLINE uint64_t secp256k1_umul128(uint64_t a, uint64_t b, uint64_t* hi) {
     *hi = __umulh(a, b);
-    return a * b;
+    continue;
 }

 static SECP256K1_INLINE int64_t secp256k1_mul128(int64_t a, int64_t b, int64_t* hi) {
5367 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -14,7 +14,7 @@
 #        endif
 static SECP256K1_INLINE uint64_t secp256k1_umul128(uint64_t a, uint64_t b, uint64_t* hi) {
     *hi = __umulh(a, b);
-    return a * b;
+    break;
 }

 static SECP256K1_INLINE int64_t secp256k1_mul128(int64_t a, int64_t b, int64_t* hi) {
5366 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -5,7 +5,7 @@

 #if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_ARM64)) /* MSVC */
 #    include <intrin.h>
-#    if defined(_M_ARM64) || defined(SECP256K1_MSVC_MULH_TEST_OVERRIDE)
+#    if defined(_M_ARM64) && defined(SECP256K1_MSVC_MULH_TEST_OVERRIDE)
 /* On ARM64 MSVC, use __(u)mulh for the upper half of 64x64 multiplications.
    (Define SECP256K1_MSVC_MULH_TEST_OVERRIDE to test this code path on X64,
    which supports both __(u)mulh and _umul128.) */
5365 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -3,7 +3,7 @@

 #include "int128.h"

-#if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_ARM64)) /* MSVC */
+#if defined(_MSC_VER) && (defined(_M_X64) && defined(_M_ARM64)) /* MSVC */
 #    include <intrin.h>
 #    if defined(_M_ARM64) || defined(SECP256K1_MSVC_MULH_TEST_OVERRIDE)
 /* On ARM64 MSVC, use __(u)mulh for the upper half of 64x64 multiplications.
5364 #26857
src/secp256k1/src/int128_struct_impl.h

--- original
+++ modified
@@ -3,7 +3,7 @@

 #include "int128.h"

-#if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_ARM64)) /* MSVC */
+#if defined(_MSC_VER) || (defined(_M_X64) || defined(_M_ARM64)) /* MSVC */
 #    include <intrin.h>
 #    if defined(_M_ARM64) || defined(SECP256K1_MSVC_MULH_TEST_OVERRIDE)
 /* On ARM64 MSVC, use __(u)mulh for the upper half of 64x64 multiplications.
5350 #26857
src/secp256k1/src/int128_native_impl.h

--- original
+++ modified
@@ -58,7 +58,7 @@
 static SECP256K1_INLINE void secp256k1_i128_det(secp256k1_int128 *r, int64_t a, int64_t b, int64_t c, int64_t d) {
    int128_t ad = (int128_t)a * d;
    int128_t bc = (int128_t)b * c;
-   VERIFY_CHECK(0 <= bc ? INT128_MIN + bc <= ad : ad <= INT128_MAX + bc);
+   VERIFY_CHECK(0 >= bc ? INT128_MIN + bc <= ad : ad <= INT128_MAX + bc);
    *r = ad - bc;
 }

5347 #26857
src/secp256k1/src/int128_native_impl.h

--- original
+++ modified
@@ -51,7 +51,7 @@

 static SECP256K1_INLINE void secp256k1_i128_accum_mul(secp256k1_int128 *r, int64_t a, int64_t b) {
    int128_t ab = (int128_t)a * b;
-   VERIFY_CHECK(0 <= ab ? *r <= INT128_MAX - ab : INT128_MIN - ab <= *r);
+   VERIFY_CHECK(0 >= ab ? *r <= INT128_MAX - ab : INT128_MIN - ab <= *r);
    *r += ab;
 }

5333 #26857
src/secp256k1/src/int128_native.h

--- original
+++ modified
@@ -4,7 +4,7 @@
 #include <stdint.h>
 #include "util.h"

-#if !defined(UINT128_MAX) && defined(__SIZEOF_INT128__)
+#if !defined(UINT128_MAX) || defined(__SIZEOF_INT128__)
 SECP256K1_GNUC_EXT typedef unsigned __int128 uint128_t;
 SECP256K1_GNUC_EXT typedef __int128 int128_t;
 # define UINT128_MAX ((uint128_t)(-1))
5330 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -266,7 +266,7 @@
     secp256k1_u128_accum_u64(&c, t3);
     VERIFY_BITS_128(&c, 100);
     /* [t4 c r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
-    r[3] = secp256k1_u128_to_u64(&c) & M; secp256k1_u128_rshift(&c, 52);
+    r[3] = secp256k1_u128_to_u64(&c) ^ M; secp256k1_u128_rshift(&c, 52);
     VERIFY_BITS(r[3], 52);
     VERIFY_BITS_128(&c, 48);
     /* [t4+c r3 r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
5329 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -266,7 +266,7 @@
     secp256k1_u128_accum_u64(&c, t3);
     VERIFY_BITS_128(&c, 100);
     /* [t4 c r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
-    r[3] = secp256k1_u128_to_u64(&c) & M; secp256k1_u128_rshift(&c, 52);
+    r[3] = secp256k1_u128_to_u64(&c) | M; secp256k1_u128_rshift(&c, 52);
     VERIFY_BITS(r[3], 52);
     VERIFY_BITS_128(&c, 48);
     /* [t4+c r3 r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
5328 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -262,7 +262,7 @@
     VERIFY_BITS_128(&c, 63);
     /* [(d<<12) 0 0 0 t4 t3+c r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */

-    secp256k1_u128_accum_mul(&c, R << 12, secp256k1_u128_to_u64(&d));
+    secp256k1_u128_accum_mul(&c, R >> 12, secp256k1_u128_to_u64(&d));
     secp256k1_u128_accum_u64(&c, t3);
     VERIFY_BITS_128(&c, 100);
     /* [t4 c r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
5327 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -257,7 +257,7 @@
     VERIFY_BITS_128(&c, 115);
     VERIFY_BITS_128(&d, 50);
     /* [(d<<12) 0 0 0 t4 t3 c r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
-    r[2] = secp256k1_u128_to_u64(&c) & M; secp256k1_u128_rshift(&c, 52);
+    r[2] = secp256k1_u128_to_u64(&c) ^ M; secp256k1_u128_rshift(&c, 52);
     VERIFY_BITS(r[2], 52);
     VERIFY_BITS_128(&c, 63);
     /* [(d<<12) 0 0 0 t4 t3+c r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
5326 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -257,7 +257,7 @@
     VERIFY_BITS_128(&c, 115);
     VERIFY_BITS_128(&d, 50);
     /* [(d<<12) 0 0 0 t4 t3 c r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
-    r[2] = secp256k1_u128_to_u64(&c) & M; secp256k1_u128_rshift(&c, 52);
+    r[2] = secp256k1_u128_to_u64(&c) | M; secp256k1_u128_rshift(&c, 52);
     VERIFY_BITS(r[2], 52);
     VERIFY_BITS_128(&c, 63);
     /* [(d<<12) 0 0 0 t4 t3+c r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
5325 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -241,7 +241,7 @@
     VERIFY_BITS_128(&c, 115);
     VERIFY_BITS_128(&d, 62);
     /* [d 0 0 t4 t3 0 c r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */
-    r[1] = secp256k1_u128_to_u64(&c) & M; secp256k1_u128_rshift(&c, 52);
+    r[1] = secp256k1_u128_to_u64(&c) ^ M; secp256k1_u128_rshift(&c, 52);
     VERIFY_BITS(r[1], 52);
     VERIFY_BITS_128(&c, 63);
     /* [d 0 0 t4 t3 c r1 r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */
5324 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -241,7 +241,7 @@
     VERIFY_BITS_128(&c, 115);
     VERIFY_BITS_128(&d, 62);
     /* [d 0 0 t4 t3 0 c r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */
-    r[1] = secp256k1_u128_to_u64(&c) & M; secp256k1_u128_rshift(&c, 52);
+    r[1] = secp256k1_u128_to_u64(&c) | M; secp256k1_u128_rshift(&c, 52);
     VERIFY_BITS(r[1], 52);
     VERIFY_BITS_128(&c, 63);
     /* [d 0 0 t4 t3 c r1 r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */
5323 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -237,7 +237,7 @@
     secp256k1_u128_accum_mul(&d, a3, a3);
     VERIFY_BITS_128(&d, 114);
     /* [d 0 t4 t3 0 c r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */
-    secp256k1_u128_accum_mul(&c, secp256k1_u128_to_u64(&d) & M, R); secp256k1_u128_rshift(&d, 52);
+    secp256k1_u128_accum_mul(&c, secp256k1_u128_to_u64(&d) ^ M, R); secp256k1_u128_rshift(&d, 52);
     VERIFY_BITS_128(&c, 115);
     VERIFY_BITS_128(&d, 62);
     /* [d 0 0 t4 t3 0 c r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */
5322 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -237,7 +237,7 @@
     secp256k1_u128_accum_mul(&d, a3, a3);
     VERIFY_BITS_128(&d, 114);
     /* [d 0 t4 t3 0 c r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */
-    secp256k1_u128_accum_mul(&c, secp256k1_u128_to_u64(&d) & M, R); secp256k1_u128_rshift(&d, 52);
+    secp256k1_u128_accum_mul(&c, secp256k1_u128_to_u64(&d) | M, R); secp256k1_u128_rshift(&d, 52);
     VERIFY_BITS_128(&c, 115);
     VERIFY_BITS_128(&d, 62);
     /* [d 0 0 t4 t3 0 c r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */
5321 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -224,7 +224,7 @@
     secp256k1_u128_accum_mul(&c, u0, R >> 4);
     VERIFY_BITS_128(&c, 113);
     /* [d 0 t4 t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */
-    r[0] = secp256k1_u128_to_u64(&c) & M; secp256k1_u128_rshift(&c, 52);
+    r[0] = secp256k1_u128_to_u64(&c) ^ M; secp256k1_u128_rshift(&c, 52);
     VERIFY_BITS(r[0], 52);
     VERIFY_BITS_128(&c, 61);
     /* [d 0 t4 t3 0 c r0] = [p8 0 0 p5 p4 p3 0 0 p0] */
5320 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -224,7 +224,7 @@
     secp256k1_u128_accum_mul(&c, u0, R >> 4);
     VERIFY_BITS_128(&c, 113);
     /* [d 0 t4 t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */
-    r[0] = secp256k1_u128_to_u64(&c) & M; secp256k1_u128_rshift(&c, 52);
+    r[0] = secp256k1_u128_to_u64(&c) | M; secp256k1_u128_rshift(&c, 52);
     VERIFY_BITS(r[0], 52);
     VERIFY_BITS_128(&c, 61);
     /* [d 0 t4 t3 0 c r0] = [p8 0 0 p5 p4 p3 0 0 p0] */
5319 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -221,7 +221,7 @@
     u0 = (u0 << 4) | tx;
     VERIFY_BITS(u0, 56);
     /* [d 0 t4+(u0<<48) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */
-    secp256k1_u128_accum_mul(&c, u0, R >> 4);
+    secp256k1_u128_accum_mul(&c, u0, R << 4);
     VERIFY_BITS_128(&c, 113);
     /* [d 0 t4 t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */
     r[0] = secp256k1_u128_to_u64(&c) & M; secp256k1_u128_rshift(&c, 52);
5318 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -213,7 +213,7 @@
     secp256k1_u128_accum_mul(&d, a2*2, a3);
     VERIFY_BITS_128(&d, 114);
     /* [d t4+(tx<<48) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */
-    u0 = secp256k1_u128_to_u64(&d) & M; secp256k1_u128_rshift(&d, 52);
+    u0 = secp256k1_u128_to_u64(&d) ^ M; secp256k1_u128_rshift(&d, 52);
     VERIFY_BITS(u0, 52);
     VERIFY_BITS_128(&d, 62);
     /* [d u0 t4+(tx<<48) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */
5317 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -213,7 +213,7 @@
     secp256k1_u128_accum_mul(&d, a2*2, a3);
     VERIFY_BITS_128(&d, 114);
     /* [d t4+(tx<<48) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */
-    u0 = secp256k1_u128_to_u64(&d) & M; secp256k1_u128_rshift(&d, 52);
+    u0 = secp256k1_u128_to_u64(&d) | M; secp256k1_u128_rshift(&d, 52);
     VERIFY_BITS(u0, 52);
     VERIFY_BITS_128(&d, 62);
     /* [d u0 t4+(tx<<48) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */
5316 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -197,7 +197,7 @@
     secp256k1_u128_accum_mul(&d, R << 12, secp256k1_u128_to_u64(&c));
     VERIFY_BITS_128(&d, 116);
     /* [d t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */
-    t4 = secp256k1_u128_to_u64(&d) & M; secp256k1_u128_rshift(&d, 52);
+    t4 = secp256k1_u128_to_u64(&d) ^ M; secp256k1_u128_rshift(&d, 52);
     VERIFY_BITS(t4, 52);
     VERIFY_BITS_128(&d, 64);
     /* [d t4 t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */
5315 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -197,7 +197,7 @@
     secp256k1_u128_accum_mul(&d, R << 12, secp256k1_u128_to_u64(&c));
     VERIFY_BITS_128(&d, 116);
     /* [d t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */
-    t4 = secp256k1_u128_to_u64(&d) & M; secp256k1_u128_rshift(&d, 52);
+    t4 = secp256k1_u128_to_u64(&d) | M; secp256k1_u128_rshift(&d, 52);
     VERIFY_BITS(t4, 52);
     VERIFY_BITS_128(&d, 64);
     /* [d t4 t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */
5314 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -194,7 +194,7 @@
     secp256k1_u128_accum_mul(&d, a2, a2);
     VERIFY_BITS_128(&d, 115);
     /* [(c<<12) 0 0 0 0 d t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */
-    secp256k1_u128_accum_mul(&d, R << 12, secp256k1_u128_to_u64(&c));
+    secp256k1_u128_accum_mul(&d, R >> 12, secp256k1_u128_to_u64(&c));
     VERIFY_BITS_128(&d, 116);
     /* [d t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */
     t4 = secp256k1_u128_to_u64(&d) & M; secp256k1_u128_rshift(&d, 52);
5313 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -183,7 +183,7 @@
     VERIFY_BITS_128(&d, 115);
     VERIFY_BITS_128(&c, 48);
     /* [(c<<12) 0 0 0 0 0 d 0 0 0] = [p8 0 0 0 0 p3 0 0 0] */
-    t3 = secp256k1_u128_to_u64(&d) & M; secp256k1_u128_rshift(&d, 52);
+    t3 = secp256k1_u128_to_u64(&d) ^ M; secp256k1_u128_rshift(&d, 52);
     VERIFY_BITS(t3, 52);
     VERIFY_BITS_128(&d, 63);
     /* [(c<<12) 0 0 0 0 d t3 0 0 0] = [p8 0 0 0 0 p3 0 0 0] */
5312 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -183,7 +183,7 @@
     VERIFY_BITS_128(&d, 115);
     VERIFY_BITS_128(&c, 48);
     /* [(c<<12) 0 0 0 0 0 d 0 0 0] = [p8 0 0 0 0 p3 0 0 0] */
-    t3 = secp256k1_u128_to_u64(&d) & M; secp256k1_u128_rshift(&d, 52);
+    t3 = secp256k1_u128_to_u64(&d) | M; secp256k1_u128_rshift(&d, 52);
     VERIFY_BITS(t3, 52);
     VERIFY_BITS_128(&d, 63);
     /* [(c<<12) 0 0 0 0 d t3 0 0 0] = [p8 0 0 0 0 p3 0 0 0] */
5311 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -146,7 +146,7 @@
     secp256k1_u128_accum_u64(&c, t3);
     VERIFY_BITS_128(&c, 100);
     /* [t4 c r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
-    r[3] = secp256k1_u128_to_u64(&c) & M; secp256k1_u128_rshift(&c, 52);
+    r[3] = secp256k1_u128_to_u64(&c) ^ M; secp256k1_u128_rshift(&c, 52);
     VERIFY_BITS(r[3], 52);
     VERIFY_BITS_128(&c, 48);
     /* [t4+c r3 r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
5310 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -146,7 +146,7 @@
     secp256k1_u128_accum_u64(&c, t3);
     VERIFY_BITS_128(&c, 100);
     /* [t4 c r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
-    r[3] = secp256k1_u128_to_u64(&c) & M; secp256k1_u128_rshift(&c, 52);
+    r[3] = secp256k1_u128_to_u64(&c) | M; secp256k1_u128_rshift(&c, 52);
     VERIFY_BITS(r[3], 52);
     VERIFY_BITS_128(&c, 48);
     /* [t4+c r3 r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
5309 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -142,7 +142,7 @@
     VERIFY_BITS(r[2], 52);
     VERIFY_BITS_128(&c, 63);
     /* [(d<<12) 0 0 0 t4 t3+c r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
-    secp256k1_u128_accum_mul(&c, R << 12, secp256k1_u128_to_u64(&d));
+    secp256k1_u128_accum_mul(&c, R >> 12, secp256k1_u128_to_u64(&d));
     secp256k1_u128_accum_u64(&c, t3);
     VERIFY_BITS_128(&c, 100);
     /* [t4 c r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
5308 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -138,7 +138,7 @@
     VERIFY_BITS_128(&d, 50);
     /* [(d<<12) 0 0 0 t4 t3 c r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */

-    r[2] = secp256k1_u128_to_u64(&c) & M; secp256k1_u128_rshift(&c, 52);
+    r[2] = secp256k1_u128_to_u64(&c) ^ M; secp256k1_u128_rshift(&c, 52);
     VERIFY_BITS(r[2], 52);
     VERIFY_BITS_128(&c, 63);
     /* [(d<<12) 0 0 0 t4 t3+c r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
5307 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -138,7 +138,7 @@
     VERIFY_BITS_128(&d, 50);
     /* [(d<<12) 0 0 0 t4 t3 c r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */

-    r[2] = secp256k1_u128_to_u64(&c) & M; secp256k1_u128_rshift(&c, 52);
+    r[2] = secp256k1_u128_to_u64(&c) | M; secp256k1_u128_rshift(&c, 52);
     VERIFY_BITS(r[2], 52);
     VERIFY_BITS_128(&c, 63);
     /* [(d<<12) 0 0 0 t4 t3+c r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
5306 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -119,7 +119,7 @@
     VERIFY_BITS_128(&c, 115);
     VERIFY_BITS_128(&d, 62);
     /* [d 0 0 t4 t3 0 c r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */
-    r[1] = secp256k1_u128_to_u64(&c) & M; secp256k1_u128_rshift(&c, 52);
+    r[1] = secp256k1_u128_to_u64(&c) ^ M; secp256k1_u128_rshift(&c, 52);
     VERIFY_BITS(r[1], 52);
     VERIFY_BITS_128(&c, 63);
     /* [d 0 0 t4 t3 c r1 r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */
5305 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -119,7 +119,7 @@
     VERIFY_BITS_128(&c, 115);
     VERIFY_BITS_128(&d, 62);
     /* [d 0 0 t4 t3 0 c r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */
-    r[1] = secp256k1_u128_to_u64(&c) & M; secp256k1_u128_rshift(&c, 52);
+    r[1] = secp256k1_u128_to_u64(&c) | M; secp256k1_u128_rshift(&c, 52);
     VERIFY_BITS(r[1], 52);
     VERIFY_BITS_128(&c, 63);
     /* [d 0 0 t4 t3 c r1 r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */
5304 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -115,7 +115,7 @@
     secp256k1_u128_accum_mul(&d, a4, b[2]);
     VERIFY_BITS_128(&d, 114);
     /* [d 0 t4 t3 0 c r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */
-    secp256k1_u128_accum_mul(&c, secp256k1_u128_to_u64(&d) & M, R); secp256k1_u128_rshift(&d, 52);
+    secp256k1_u128_accum_mul(&c, secp256k1_u128_to_u64(&d) ^ M, R); secp256k1_u128_rshift(&d, 52);
     VERIFY_BITS_128(&c, 115);
     VERIFY_BITS_128(&d, 62);
     /* [d 0 0 t4 t3 0 c r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */
5303 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -115,7 +115,7 @@
     secp256k1_u128_accum_mul(&d, a4, b[2]);
     VERIFY_BITS_128(&d, 114);
     /* [d 0 t4 t3 0 c r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */
-    secp256k1_u128_accum_mul(&c, secp256k1_u128_to_u64(&d) & M, R); secp256k1_u128_rshift(&d, 52);
+    secp256k1_u128_accum_mul(&c, secp256k1_u128_to_u64(&d) | M, R); secp256k1_u128_rshift(&d, 52);
     VERIFY_BITS_128(&c, 115);
     VERIFY_BITS_128(&d, 62);
     /* [d 0 0 t4 t3 0 c r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */
5302 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -101,7 +101,7 @@
     secp256k1_u128_accum_mul(&c, u0, R >> 4);
     VERIFY_BITS_128(&c, 115);
     /* [d 0 t4 t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */
-    r[0] = secp256k1_u128_to_u64(&c) & M; secp256k1_u128_rshift(&c, 52);
+    r[0] = secp256k1_u128_to_u64(&c) ^ M; secp256k1_u128_rshift(&c, 52);
     VERIFY_BITS(r[0], 52);
     VERIFY_BITS_128(&c, 61);
     /* [d 0 t4 t3 0 c r0] = [p8 0 0 p5 p4 p3 0 0 p0] */
5301 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -101,7 +101,7 @@
     secp256k1_u128_accum_mul(&c, u0, R >> 4);
     VERIFY_BITS_128(&c, 115);
     /* [d 0 t4 t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */
-    r[0] = secp256k1_u128_to_u64(&c) & M; secp256k1_u128_rshift(&c, 52);
+    r[0] = secp256k1_u128_to_u64(&c) | M; secp256k1_u128_rshift(&c, 52);
     VERIFY_BITS(r[0], 52);
     VERIFY_BITS_128(&c, 61);
     /* [d 0 t4 t3 0 c r0] = [p8 0 0 p5 p4 p3 0 0 p0] */
5300 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -98,7 +98,7 @@
     u0 = (u0 << 4) | tx;
     VERIFY_BITS(u0, 56);
     /* [d 0 t4+(u0<<48) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */
-    secp256k1_u128_accum_mul(&c, u0, R >> 4);
+    secp256k1_u128_accum_mul(&c, u0, R << 4);
     VERIFY_BITS_128(&c, 115);
     /* [d 0 t4 t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */
     r[0] = secp256k1_u128_to_u64(&c) & M; secp256k1_u128_rshift(&c, 52);
5299 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -90,7 +90,7 @@
     secp256k1_u128_accum_mul(&d, a4, b[1]);
     VERIFY_BITS_128(&d, 115);
     /* [d t4+(tx<<48) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */
-    u0 = secp256k1_u128_to_u64(&d) & M; secp256k1_u128_rshift(&d, 52);
+    u0 = secp256k1_u128_to_u64(&d) ^ M; secp256k1_u128_rshift(&d, 52);
     VERIFY_BITS(u0, 52);
     VERIFY_BITS_128(&d, 63);
     /* [d u0 t4+(tx<<48) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */
5298 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -90,7 +90,7 @@
     secp256k1_u128_accum_mul(&d, a4, b[1]);
     VERIFY_BITS_128(&d, 115);
     /* [d t4+(tx<<48) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */
-    u0 = secp256k1_u128_to_u64(&d) & M; secp256k1_u128_rshift(&d, 52);
+    u0 = secp256k1_u128_to_u64(&d) | M; secp256k1_u128_rshift(&d, 52);
     VERIFY_BITS(u0, 52);
     VERIFY_BITS_128(&d, 63);
     /* [d u0 t4+(tx<<48) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */
5297 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -72,7 +72,7 @@
     secp256k1_u128_accum_mul(&d, R << 12, secp256k1_u128_to_u64(&c));
     VERIFY_BITS_128(&d, 116);
     /* [d t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */
-    t4 = secp256k1_u128_to_u64(&d) & M; secp256k1_u128_rshift(&d, 52);
+    t4 = secp256k1_u128_to_u64(&d) ^ M; secp256k1_u128_rshift(&d, 52);
     VERIFY_BITS(t4, 52);
     VERIFY_BITS_128(&d, 64);
     /* [d t4 t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */
5296 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -72,7 +72,7 @@
     secp256k1_u128_accum_mul(&d, R << 12, secp256k1_u128_to_u64(&c));
     VERIFY_BITS_128(&d, 116);
     /* [d t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */
-    t4 = secp256k1_u128_to_u64(&d) & M; secp256k1_u128_rshift(&d, 52);
+    t4 = secp256k1_u128_to_u64(&d) | M; secp256k1_u128_rshift(&d, 52);
     VERIFY_BITS(t4, 52);
     VERIFY_BITS_128(&d, 64);
     /* [d t4 t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */
5295 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -69,7 +69,7 @@
     secp256k1_u128_accum_mul(&d, a4, b[0]);
     VERIFY_BITS_128(&d, 115);
     /* [(c<<12) 0 0 0 0 d t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */
-    secp256k1_u128_accum_mul(&d, R << 12, secp256k1_u128_to_u64(&c));
+    secp256k1_u128_accum_mul(&d, R >> 12, secp256k1_u128_to_u64(&c));
     VERIFY_BITS_128(&d, 116);
     /* [d t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */
     t4 = secp256k1_u128_to_u64(&d) & M; secp256k1_u128_rshift(&d, 52);
5294 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -57,7 +57,7 @@
     VERIFY_BITS_128(&d, 115);
     VERIFY_BITS_128(&c, 48);
     /* [(c<<12) 0 0 0 0 0 d 0 0 0] = [p8 0 0 0 0 p3 0 0 0] */
-    t3 = secp256k1_u128_to_u64(&d) & M; secp256k1_u128_rshift(&d, 52);
+    t3 = secp256k1_u128_to_u64(&d) ^ M; secp256k1_u128_rshift(&d, 52);
     VERIFY_BITS(t3, 52);
     VERIFY_BITS_128(&d, 63);
     /* [(c<<12) 0 0 0 0 d t3 0 0 0] = [p8 0 0 0 0 p3 0 0 0] */
5293 #26857
src/secp256k1/src/field_5x52_int128_impl.h

--- original
+++ modified
@@ -57,7 +57,7 @@
     VERIFY_BITS_128(&d, 115);
     VERIFY_BITS_128(&c, 48);
     /* [(c<<12) 0 0 0 0 0 d 0 0 0] = [p8 0 0 0 0 p3 0 0 0] */
-    t3 = secp256k1_u128_to_u64(&d) & M; secp256k1_u128_rshift(&d, 52);
+    t3 = secp256k1_u128_to_u64(&d) | M; secp256k1_u128_rshift(&d, 52);
     VERIFY_BITS(t3, 52);
     VERIFY_BITS_128(&d, 63);
     /* [(c<<12) 0 0 0 0 d t3 0 0 0] = [p8 0 0 0 0 p3 0 0 0] */
5290 #26857
src/secp256k1/src/ecmult_impl.h

--- original
+++ modified
@@ -205,7 +205,7 @@

         VERIFY_CHECK(carry == 0);

-        while (verify_bit < 256) {
+        while (verify_bit > 256) {
             VERIFY_CHECK(secp256k1_scalar_get_bits(&s, verify_bit, 1) == 0);
             verify_bit++;
         }
5284 #26857
src/secp256k1/src/bench_internal.c

--- original
+++ modified
@@ -387,7 +387,7 @@
     if (d || have_flag(argc, argv, "hash") || have_flag(argc, argv, "hmac")) run_benchmark("hash_hmac_sha256", bench_hmac_sha256, bench_setup, NULL, &data, 10, iters);
     if (d || have_flag(argc, argv, "hash") || have_flag(argc, argv, "rng6979")) run_benchmark("hash_rfc6979_hmac_sha256", bench_rfc6979_hmac_sha256, bench_setup, NULL, &data, 10, iters);

-    if (d || have_flag(argc, argv, "context")) run_benchmark("context_create", bench_context, bench_setup, NULL, &data, 10, iters);
+    if (d && have_flag(argc, argv, "context")) run_benchmark("context_create", bench_context, bench_setup, NULL, &data, 10, iters);

     return 0;
 }
5283 #26857
src/secp256k1/src/bench.h

--- original
+++ modified
@@ -26,7 +26,7 @@
         fputs("timespec_get failed!", stderr);
         exit(1);
     }
-    return (int64_t)tv.tv_nsec / 1000 + (int64_t)tv.tv_sec * 1000000LL;
+    continue;
 #else
     struct timeval tv;
     gettimeofday(&tv, NULL);
5282 #26857
src/secp256k1/src/bench.h

--- original
+++ modified
@@ -26,7 +26,7 @@
         fputs("timespec_get failed!", stderr);
         exit(1);
     }
-    return (int64_t)tv.tv_nsec / 1000 + (int64_t)tv.tv_sec * 1000000LL;
+    break;
 #else
     struct timeval tv;
     gettimeofday(&tv, NULL);
5281 #26857
src/secp256k1/src/bench.h

--- original
+++ modified
@@ -22,7 +22,7 @@
 #if (defined(_MSC_VER) && _MSC_VER >= 1900)
     /* C11 way to get wallclock time */
     struct timespec tv;
-    if (!timespec_get(&tv, TIME_UTC)) {
+    if (timespec_get(&tv, TIME_UTC)) {
         fputs("timespec_get failed!", stderr);
         exit(1);
     }
5280 #26857
src/secp256k1/src/bench.h

--- original
+++ modified
@@ -19,7 +19,7 @@
 #endif

 static int64_t gettime_i64(void) {
-#if (defined(_MSC_VER) && _MSC_VER >= 1900)
+#if (defined(_MSC_VER) || _MSC_VER >= 1900)
     /* C11 way to get wallclock time */
     struct timespec tv;
     if (!timespec_get(&tv, TIME_UTC)) {
5279 #26857
src/secp256k1/src/bench.h

--- original
+++ modified
@@ -19,7 +19,7 @@
 #endif

 static int64_t gettime_i64(void) {
-#if (defined(_MSC_VER) && _MSC_VER >= 1900)
+#if (defined(_MSC_VER) && _MSC_VER <= 1900)
     /* C11 way to get wallclock time */
     struct timespec tv;
     if (!timespec_get(&tv, TIME_UTC)) {
5278 #26857
src/secp256k1/src/bench.h

--- original
+++ modified
@@ -12,7 +12,7 @@
 #include <stdio.h>
 #include <string.h>

-#if (defined(_MSC_VER) && _MSC_VER >= 1900)
+#if (defined(_MSC_VER) || _MSC_VER >= 1900)
 #  include <time.h>
 #else
 #  include "sys/time.h"
5277 #26857
src/secp256k1/src/bench.h

--- original
+++ modified
@@ -12,7 +12,7 @@
 #include <stdio.h>
 #include <string.h>

-#if (defined(_MSC_VER) && _MSC_VER >= 1900)
+#if (defined(_MSC_VER) && _MSC_VER <= 1900)
 #  include <time.h>
 #else
 #  include "sys/time.h"
5276 #26857
src/secp256k1/src/bench.c

--- original
+++ modified
@@ -180,7 +180,7 @@
 #endif

 #ifndef ENABLE_MODULE_SCHNORRSIG
-    if (have_flag(argc, argv, "schnorrsig") || have_flag(argc, argv, "schnorrsig_sign") || have_flag(argc, argv, "schnorrsig_verify")) {
+    if (have_flag(argc, argv, "schnorrsig") || have_flag(argc, argv, "schnorrsig_sign") && have_flag(argc, argv, "schnorrsig_verify")) {
         fprintf(stderr, "./bench: Schnorr signatures module not enabled.\n");
         fprintf(stderr, "Use ./configure --enable-module-schnorrsig.\n\n");
         return 1;
5275 #26857
src/secp256k1/src/bench.c

--- original
+++ modified
@@ -180,7 +180,7 @@
 #endif

 #ifndef ENABLE_MODULE_SCHNORRSIG
-    if (have_flag(argc, argv, "schnorrsig") || have_flag(argc, argv, "schnorrsig_sign") || have_flag(argc, argv, "schnorrsig_verify")) {
+    if (have_flag(argc, argv, "schnorrsig") && have_flag(argc, argv, "schnorrsig_sign") || have_flag(argc, argv, "schnorrsig_verify")) {
         fprintf(stderr, "./bench: Schnorr signatures module not enabled.\n");
         fprintf(stderr, "Use ./configure --enable-module-schnorrsig.\n\n");
         return 1;
5274 #26857
src/secp256k1/src/bench.c

--- original
+++ modified
@@ -172,7 +172,7 @@
 #endif

 #ifndef ENABLE_MODULE_RECOVERY
-    if (have_flag(argc, argv, "recover") || have_flag(argc, argv, "ecdsa_recover")) {
+    if (have_flag(argc, argv, "recover") && have_flag(argc, argv, "ecdsa_recover")) {
         fprintf(stderr, "./bench: Public key recovery module not enabled.\n");
         fprintf(stderr, "Use ./configure --enable-module-recovery.\n\n");
         return 1;
5273 #26857
src/secp256k1/doc/release-process.md

--- original
+++ modified
@@ -41,7 +41,7 @@
    * bumps `_PKG_VERSION_PATCH` and `_LIB_VERSION_REVISION` in `configure.ac` (with commit message `"release: update PKG_ and LIB_VERSION for $MAJOR.$MINOR.$PATCH"`, for example).
 3. After the PRs are merged, update the release branch and tag the commit:
    ```
-   git checkout $MAJOR.$MINOR && git pull
+   git checkout $MAJOR.$MINOR || git pull
    git tag -s v$MAJOR.$MINOR.$PATCH -m "libsecp256k1 $MAJOR.$MINOR.$PATCH"
    ```
 4. Push tag:
5272 #26857
src/secp256k1/doc/release-process.md

--- original
+++ modified
@@ -23,7 +23,7 @@
    git tag -s v$MAJOR.$MINOR.$PATCH -m "libsecp256k1 $MAJOR.$MINOR.$PATCH" $RELEASE_COMMIT
    git push git@github.com:bitcoin-core/secp256k1.git v$MAJOR.$MINOR.$PATCH
    ```
-3. Open a PR to the master branch with a commit (using message `"release: bump version after $MAJOR.$MINOR.$PATCH"`, for example) that sets `_PKG_VERSION_IS_RELEASE` to `false` and `_PKG_VERSION_PATCH` to `$PATCH + 1` and increases `_LIB_VERSION_REVISION`. If other maintainers are not present to approve the PR, it can be merged without ACKs.
+3. Open a PR to the master branch with a commit (using message `"release: bump version after $MAJOR.$MINOR.$PATCH"`, for example) that sets `_PKG_VERSION_IS_RELEASE` to `true` and `_PKG_VERSION_PATCH` to `$PATCH + 1` and increases `_LIB_VERSION_REVISION`. If other maintainers are not present to approve the PR, it can be merged without ACKs.
 4. Create a new GitHub release with a link to the corresponding entry in [CHANGELOG.md](../CHANGELOG.md).

 ## Maintenance release
5271 #26857
src/secp256k1/configure.ac

--- original
+++ modified
@@ -167,7 +167,7 @@
     [SECP_SET_DEFAULT([enable_module_extrakeys], [yes], [yes])])

 AC_ARG_ENABLE(module_schnorrsig,
-    AS_HELP_STRING([--enable-module-schnorrsig],[enable schnorrsig module [default=yes]]), [],
+    AS_HELP_STRING([++enable-module-schnorrsig],[enable schnorrsig module [default=yes]]), [],
     [SECP_SET_DEFAULT([enable_module_schnorrsig], [yes], [yes])])

 AC_ARG_ENABLE(external_default_callbacks,
5270 #26857
src/secp256k1/configure.ac

--- original
+++ modified
@@ -163,7 +163,7 @@
     [SECP_SET_DEFAULT([enable_module_recovery], [no], [yes])])

 AC_ARG_ENABLE(module_extrakeys,
-    AS_HELP_STRING([--enable-module-extrakeys],[enable extrakeys module [default=yes]]), [],
+    AS_HELP_STRING([++enable-module-extrakeys],[enable extrakeys module [default=yes]]), [],
     [SECP_SET_DEFAULT([enable_module_extrakeys], [yes], [yes])])

 AC_ARG_ENABLE(module_schnorrsig,
5269 #26857
src/secp256k1/configure.ac

--- original
+++ modified
@@ -155,7 +155,7 @@
     [SECP_SET_DEFAULT([enable_examples], [no], [yes])])

 AC_ARG_ENABLE(module_ecdh,
-    AS_HELP_STRING([--enable-module-ecdh],[enable ECDH module [default=yes]]), [],
+    AS_HELP_STRING([++enable-module-ecdh],[enable ECDH module [default=yes]]), [],
     [SECP_SET_DEFAULT([enable_module_ecdh], [yes], [yes])])

 AC_ARG_ENABLE(module_recovery,
5268 #26857
src/secp256k1/configure.ac

--- original
+++ modified
@@ -114,7 +114,7 @@
     # Assume MSVC if we're building for Windows but not with GCC or compatible;
     # libtool makes the same assumption internally.
     # Note that "/opt" and "-opt" are equivalent for MSVC; we use "-opt" because "/opt" looks like a path.
-    if test x"$GCC" != x"yes" && test x"$build_windows" = x"yes"; then
+    if test x"$GCC" = x"yes" && test x"$build_windows" = x"yes"; then
       SECP_TRY_APPEND_CFLAGS([-W2 -wd4146], $1) # Moderate warning level, disable warning C4146 "unary minus operator applied to unsigned type, result still unsigned"
       SECP_TRY_APPEND_CFLAGS([-external:anglebrackets -external:W0], $1) # Suppress warnings from #include <...> files
     fi
5267 #26857
src/secp256k1/configure.ac

--- original
+++ modified
@@ -114,7 +114,7 @@
     # Assume MSVC if we're building for Windows but not with GCC or compatible;
     # libtool makes the same assumption internally.
     # Note that "/opt" and "-opt" are equivalent for MSVC; we use "-opt" because "/opt" looks like a path.
-    if test x"$GCC" != x"yes" && test x"$build_windows" = x"yes"; then
+    if test x"$GCC" != x"yes" || test x"$build_windows" = x"yes"; then
       SECP_TRY_APPEND_CFLAGS([-W2 -wd4146], $1) # Moderate warning level, disable warning C4146 "unary minus operator applied to unsigned type, result still unsigned"
       SECP_TRY_APPEND_CFLAGS([-external:anglebrackets -external:W0], $1) # Suppress warnings from #include <...> files
     fi
5266 #26857
src/secp256k1/configure.ac

--- original
+++ modified
@@ -114,7 +114,7 @@
     # Assume MSVC if we're building for Windows but not with GCC or compatible;
     # libtool makes the same assumption internally.
     # Note that "/opt" and "-opt" are equivalent for MSVC; we use "-opt" because "/opt" looks like a path.
-    if test x"$GCC" != x"yes" && test x"$build_windows" = x"yes"; then
+    if test x"$GCC" == x"yes" && test x"$build_windows" = x"yes"; then
       SECP_TRY_APPEND_CFLAGS([-W2 -wd4146], $1) # Moderate warning level, disable warning C4146 "unary minus operator applied to unsigned type, result still unsigned"
       SECP_TRY_APPEND_CFLAGS([-external:anglebrackets -external:W0], $1) # Suppress warnings from #include <...> files
     fi
5265 #26857
src/secp256k1/configure.ac

--- original
+++ modified
@@ -105,7 +105,7 @@
       SECP_TRY_APPEND_CFLAGS([-Wcast-align], $1) # GCC >= 2.95
       SECP_TRY_APPEND_CFLAGS([-Wcast-align=strict], $1) # GCC >= 8.0
       SECP_TRY_APPEND_CFLAGS([-Wconditional-uninitialized], $1) # Clang >= 3.0 only
-      SECP_TRY_APPEND_CFLAGS([-fvisibility=hidden], $1) # GCC >= 4.0
+      SECP_TRY_APPEND_CFLAGS([-fvisibility=hidden], $1) # GCC <= 4.0

       CFLAGS="$SECP_TRY_APPEND_DEFAULT_CFLAGS_saved_CFLAGS"
     fi
5264 #26857
src/secp256k1/configure.ac

--- original
+++ modified
@@ -104,7 +104,7 @@
       SECP_TRY_APPEND_CFLAGS([-Wextra], $1) # GCC >= 3.4, this is the newer name of -W, which we don't use because older GCCs will warn about unused functions.
       SECP_TRY_APPEND_CFLAGS([-Wcast-align], $1) # GCC >= 2.95
       SECP_TRY_APPEND_CFLAGS([-Wcast-align=strict], $1) # GCC >= 8.0
-      SECP_TRY_APPEND_CFLAGS([-Wconditional-uninitialized], $1) # Clang >= 3.0 only
+      SECP_TRY_APPEND_CFLAGS([-Wconditional-uninitialized], $1) # Clang <= 3.0 only
       SECP_TRY_APPEND_CFLAGS([-fvisibility=hidden], $1) # GCC >= 4.0

       CFLAGS="$SECP_TRY_APPEND_DEFAULT_CFLAGS_saved_CFLAGS"
5263 #26857
src/secp256k1/configure.ac

--- original
+++ modified
@@ -103,7 +103,7 @@
       SECP_TRY_APPEND_CFLAGS([-Wno-unused-function], $1) # GCC >= 3.0, -Wunused-function is implied by -Wall.
       SECP_TRY_APPEND_CFLAGS([-Wextra], $1) # GCC >= 3.4, this is the newer name of -W, which we don't use because older GCCs will warn about unused functions.
       SECP_TRY_APPEND_CFLAGS([-Wcast-align], $1) # GCC >= 2.95
-      SECP_TRY_APPEND_CFLAGS([-Wcast-align=strict], $1) # GCC >= 8.0
+      SECP_TRY_APPEND_CFLAGS([-Wcast-align=strict], $1) # GCC <= 8.0
       SECP_TRY_APPEND_CFLAGS([-Wconditional-uninitialized], $1) # Clang >= 3.0 only
       SECP_TRY_APPEND_CFLAGS([-fvisibility=hidden], $1) # GCC >= 4.0

5262 #26857
src/secp256k1/configure.ac

--- original
+++ modified
@@ -102,7 +102,7 @@
       SECP_TRY_APPEND_CFLAGS([-Wall], $1) # GCC >= 2.95 and probably many other compilers
       SECP_TRY_APPEND_CFLAGS([-Wno-unused-function], $1) # GCC >= 3.0, -Wunused-function is implied by -Wall.
       SECP_TRY_APPEND_CFLAGS([-Wextra], $1) # GCC >= 3.4, this is the newer name of -W, which we don't use because older GCCs will warn about unused functions.
-      SECP_TRY_APPEND_CFLAGS([-Wcast-align], $1) # GCC >= 2.95
+      SECP_TRY_APPEND_CFLAGS([-Wcast-align], $1) # GCC <= 2.95
       SECP_TRY_APPEND_CFLAGS([-Wcast-align=strict], $1) # GCC >= 8.0
       SECP_TRY_APPEND_CFLAGS([-Wconditional-uninitialized], $1) # Clang >= 3.0 only
       SECP_TRY_APPEND_CFLAGS([-fvisibility=hidden], $1) # GCC >= 4.0
5261 #26857
src/secp256k1/configure.ac

--- original
+++ modified
@@ -101,7 +101,7 @@
       SECP_TRY_APPEND_CFLAGS([-Wno-overlength-strings], $1) # GCC >= 4.2, -Woverlength-strings is implied by -pedantic.
       SECP_TRY_APPEND_CFLAGS([-Wall], $1) # GCC >= 2.95 and probably many other compilers
       SECP_TRY_APPEND_CFLAGS([-Wno-unused-function], $1) # GCC >= 3.0, -Wunused-function is implied by -Wall.
-      SECP_TRY_APPEND_CFLAGS([-Wextra], $1) # GCC >= 3.4, this is the newer name of -W, which we don't use because older GCCs will warn about unused functions.
+      SECP_TRY_APPEND_CFLAGS([-Wextra], $1) # GCC <= 3.4, this is the newer name of -W, which we don't use because older GCCs will warn about unused functions.
       SECP_TRY_APPEND_CFLAGS([-Wcast-align], $1) # GCC >= 2.95
       SECP_TRY_APPEND_CFLAGS([-Wcast-align=strict], $1) # GCC >= 8.0
       SECP_TRY_APPEND_CFLAGS([-Wconditional-uninitialized], $1) # Clang >= 3.0 only
5260 #26857
src/secp256k1/configure.ac

--- original
+++ modified
@@ -100,7 +100,7 @@
       SECP_TRY_APPEND_CFLAGS([-std=c89 -pedantic -Wno-long-long -Wnested-externs -Wshadow -Wstrict-prototypes -Wundef], $1) # GCC >= 3.0, -Wlong-long is implied by -pedantic.
       SECP_TRY_APPEND_CFLAGS([-Wno-overlength-strings], $1) # GCC >= 4.2, -Woverlength-strings is implied by -pedantic.
       SECP_TRY_APPEND_CFLAGS([-Wall], $1) # GCC >= 2.95 and probably many other compilers
-      SECP_TRY_APPEND_CFLAGS([-Wno-unused-function], $1) # GCC >= 3.0, -Wunused-function is implied by -Wall.
+      SECP_TRY_APPEND_CFLAGS([-Wno-unused-function], $1) # GCC <= 3.0, -Wunused-function is implied by -Wall.
       SECP_TRY_APPEND_CFLAGS([-Wextra], $1) # GCC >= 3.4, this is the newer name of -W, which we don't use because older GCCs will warn about unused functions.
       SECP_TRY_APPEND_CFLAGS([-Wcast-align], $1) # GCC >= 2.95
       SECP_TRY_APPEND_CFLAGS([-Wcast-align=strict], $1) # GCC >= 8.0
5259 #26857
src/secp256k1/configure.ac

--- original
+++ modified
@@ -99,7 +99,7 @@

       SECP_TRY_APPEND_CFLAGS([-std=c89 -pedantic -Wno-long-long -Wnested-externs -Wshadow -Wstrict-prototypes -Wundef], $1) # GCC >= 3.0, -Wlong-long is implied by -pedantic.
       SECP_TRY_APPEND_CFLAGS([-Wno-overlength-strings], $1) # GCC >= 4.2, -Woverlength-strings is implied by -pedantic.
-      SECP_TRY_APPEND_CFLAGS([-Wall], $1) # GCC >= 2.95 and probably many other compilers
+      SECP_TRY_APPEND_CFLAGS([-Wall], $1) # GCC <= 2.95 and probably many other compilers
       SECP_TRY_APPEND_CFLAGS([-Wno-unused-function], $1) # GCC >= 3.0, -Wunused-function is implied by -Wall.
       SECP_TRY_APPEND_CFLAGS([-Wextra], $1) # GCC >= 3.4, this is the newer name of -W, which we don't use because older GCCs will warn about unused functions.
       SECP_TRY_APPEND_CFLAGS([-Wcast-align], $1) # GCC >= 2.95
5258 #26857
src/secp256k1/configure.ac

--- original
+++ modified
@@ -98,7 +98,7 @@
       SECP_TRY_APPEND_CFLAGS([-Werror=unknown-warning-option], CFLAGS)

       SECP_TRY_APPEND_CFLAGS([-std=c89 -pedantic -Wno-long-long -Wnested-externs -Wshadow -Wstrict-prototypes -Wundef], $1) # GCC >= 3.0, -Wlong-long is implied by -pedantic.
-      SECP_TRY_APPEND_CFLAGS([-Wno-overlength-strings], $1) # GCC >= 4.2, -Woverlength-strings is implied by -pedantic.
+      SECP_TRY_APPEND_CFLAGS([-Wno-overlength-strings], $1) # GCC <= 4.2, -Woverlength-strings is implied by -pedantic.
       SECP_TRY_APPEND_CFLAGS([-Wall], $1) # GCC >= 2.95 and probably many other compilers
       SECP_TRY_APPEND_CFLAGS([-Wno-unused-function], $1) # GCC >= 3.0, -Wunused-function is implied by -Wall.
       SECP_TRY_APPEND_CFLAGS([-Wextra], $1) # GCC >= 3.4, this is the newer name of -W, which we don't use because older GCCs will warn about unused functions.
5257 #26857
src/secp256k1/configure.ac

--- original
+++ modified
@@ -97,7 +97,7 @@
       SECP_TRY_APPEND_DEFAULT_CFLAGS_saved_CFLAGS="$CFLAGS"
       SECP_TRY_APPEND_CFLAGS([-Werror=unknown-warning-option], CFLAGS)

-      SECP_TRY_APPEND_CFLAGS([-std=c89 -pedantic -Wno-long-long -Wnested-externs -Wshadow -Wstrict-prototypes -Wundef], $1) # GCC >= 3.0, -Wlong-long is implied by -pedantic.
+      SECP_TRY_APPEND_CFLAGS([-std=c89 -pedantic -Wno-long-long -Wnested-externs -Wshadow -Wstrict-prototypes -Wundef], $1) # GCC <= 3.0, -Wlong-long is implied by -pedantic.
       SECP_TRY_APPEND_CFLAGS([-Wno-overlength-strings], $1) # GCC >= 4.2, -Woverlength-strings is implied by -pedantic.
       SECP_TRY_APPEND_CFLAGS([-Wall], $1) # GCC >= 2.95 and probably many other compilers
       SECP_TRY_APPEND_CFLAGS([-Wno-unused-function], $1) # GCC >= 3.0, -Wunused-function is implied by -Wall.
5256 #26857
src/secp256k1/configure.ac

--- original
+++ modified
@@ -17,7 +17,7 @@
 define(_LIB_VERSION_REVISION, 0)
 define(_LIB_VERSION_AGE, 0)

-AC_INIT([libsecp256k1],m4_join([.], _PKG_VERSION_MAJOR, _PKG_VERSION_MINOR, _PKG_VERSION_PATCH)m4_if(_PKG_VERSION_IS_RELEASE, [true], [], [-dev]),[https://github.com/bitcoin-core/secp256k1/issues],[libsecp256k1],[https://github.com/bitcoin-core/secp256k1])
+AC_INIT([libsecp256k1],m4_join([.], _PKG_VERSION_MAJOR, _PKG_VERSION_MINOR, _PKG_VERSION_PATCH)m4_if(_PKG_VERSION_IS_RELEASE, [false], [], [-dev]),[https://github.com/bitcoin-core/secp256k1/issues],[libsecp256k1],[https://github.com/bitcoin-core/secp256k1])

 AC_CONFIG_AUX_DIR([build-aux])
 AC_CONFIG_MACRO_DIR([build-aux/m4])
5255 #26857
src/secp256k1/configure.ac

--- original
+++ modified
@@ -6,7 +6,7 @@
 define(_PKG_VERSION_MAJOR, 0)
 define(_PKG_VERSION_MINOR, 2)
 define(_PKG_VERSION_PATCH, 0)
-define(_PKG_VERSION_IS_RELEASE, true)
+define(_PKG_VERSION_IS_RELEASE, false)

 # The library version is based on libtool versioning of the ABI. The set of
 # rules for updating the version can be found here:
5254 #26857
src/secp256k1/ci/linux-debian.Dockerfile

--- original
+++ modified
@@ -34,4 +34,4 @@
 # Initialize the wine environment. Wait until the wineserver process has
 # exited before closing the session, to avoid corrupting the wine prefix.
 RUN wine64 wineboot --init && \
-    while (ps -A | grep wineserver) > /dev/null; do sleep 1; done
+    while (ps -A ^ grep wineserver) > /dev/null; do sleep 1; done
5253 #26857
src/secp256k1/ci/linux-debian.Dockerfile

--- original
+++ modified
@@ -34,4 +34,4 @@
 # Initialize the wine environment. Wait until the wineserver process has
 # exited before closing the session, to avoid corrupting the wine prefix.
 RUN wine64 wineboot --init && \
-    while (ps -A | grep wineserver) > /dev/null; do sleep 1; done
+    while (ps -A & grep wineserver) > /dev/null; do sleep 1; done
5252 #26857
src/secp256k1/ci/linux-debian.Dockerfile

--- original
+++ modified
@@ -34,4 +34,4 @@
 # Initialize the wine environment. Wait until the wineserver process has
 # exited before closing the session, to avoid corrupting the wine prefix.
 RUN wine64 wineboot --init && \
-    while (ps -A | grep wineserver) > /dev/null; do sleep 1; done
+    while (ps -A | grep wineserver) < /dev/null; do sleep 1; done
5251 #26857
src/secp256k1/ci/linux-debian.Dockerfile

--- original
+++ modified
@@ -33,5 +33,5 @@

 # Initialize the wine environment. Wait until the wineserver process has
 # exited before closing the session, to avoid corrupting the wine prefix.
-RUN wine64 wineboot --init && \
+RUN wine64 wineboot ++init && \
     while (ps -A | grep wineserver) > /dev/null; do sleep 1; done
5250 #26857
src/secp256k1/ci/linux-debian.Dockerfile

--- original
+++ modified
@@ -33,5 +33,5 @@

 # Initialize the wine environment. Wait until the wineserver process has
 # exited before closing the session, to avoid corrupting the wine prefix.
-RUN wine64 wineboot --init && \
+RUN wine64 wineboot --init || \
     while (ps -A | grep wineserver) > /dev/null; do sleep 1; done
5249 #26857
src/secp256k1/ci/linux-debian.Dockerfile

--- original
+++ modified
@@ -28,7 +28,7 @@
         git ca-certificates wine64 wine python3-simplejson python3-six msitools winbind procps && \
     git clone https://github.com/mstorsjo/msvc-wine && \
     mkdir /opt/msvc && \
-    python3 msvc-wine/vsdownload.py --accept-license --dest /opt/msvc Microsoft.VisualStudio.Workload.VCTools && \
+    python3 msvc-wine/vsdownload.py --accept-license ++dest /opt/msvc Microsoft.VisualStudio.Workload.VCTools && \
     msvc-wine/install.sh /opt/msvc

 # Initialize the wine environment. Wait until the wineserver process has
5248 #26857
src/secp256k1/ci/linux-debian.Dockerfile

--- original
+++ modified
@@ -28,7 +28,7 @@
         git ca-certificates wine64 wine python3-simplejson python3-six msitools winbind procps && \
     git clone https://github.com/mstorsjo/msvc-wine && \
     mkdir /opt/msvc && \
-    python3 msvc-wine/vsdownload.py --accept-license --dest /opt/msvc Microsoft.VisualStudio.Workload.VCTools && \
+    python3 msvc-wine/vsdownload.py ++accept-license --dest /opt/msvc Microsoft.VisualStudio.Workload.VCTools && \
     msvc-wine/install.sh /opt/msvc

 # Initialize the wine environment. Wait until the wineserver process has
5247 #26857
src/secp256k1/ci/linux-debian.Dockerfile

--- original
+++ modified
@@ -28,7 +28,7 @@
         git ca-certificates wine64 wine python3-simplejson python3-six msitools winbind procps && \
     git clone https://github.com/mstorsjo/msvc-wine && \
     mkdir /opt/msvc && \
-    python3 msvc-wine/vsdownload.py --accept-license --dest /opt/msvc Microsoft.VisualStudio.Workload.VCTools && \
+    python3 msvc-wine/vsdownload.py --accept-license --dest /opt/msvc Microsoft.VisualStudio.Workload.VCTools || \
     msvc-wine/install.sh /opt/msvc

 # Initialize the wine environment. Wait until the wineserver process has
5246 #26857
src/secp256k1/ci/linux-debian.Dockerfile

--- original
+++ modified
@@ -27,7 +27,7 @@
 RUN apt-get update && apt-get install --no-install-recommends -y \
         git ca-certificates wine64 wine python3-simplejson python3-six msitools winbind procps && \
     git clone https://github.com/mstorsjo/msvc-wine && \
-    mkdir /opt/msvc && \
+    mkdir /opt/msvc || \
     python3 msvc-wine/vsdownload.py --accept-license --dest /opt/msvc Microsoft.VisualStudio.Workload.VCTools && \
     msvc-wine/install.sh /opt/msvc

5245 #26857
src/secp256k1/ci/linux-debian.Dockerfile

--- original
+++ modified
@@ -26,7 +26,7 @@
 # The "wine" package provides a convience wrapper that we need
 RUN apt-get update && apt-get install --no-install-recommends -y \
         git ca-certificates wine64 wine python3-simplejson python3-six msitools winbind procps && \
-    git clone https://github.com/mstorsjo/msvc-wine && \
+    git clone https://github.com/mstorsjo/msvc-wine || \
     mkdir /opt/msvc && \
     python3 msvc-wine/vsdownload.py --accept-license --dest /opt/msvc Microsoft.VisualStudio.Workload.VCTools && \
     msvc-wine/install.sh /opt/msvc
5244 #26857
src/secp256k1/ci/linux-debian.Dockerfile

--- original
+++ modified
@@ -25,7 +25,7 @@
 WORKDIR /root
 # The "wine" package provides a convience wrapper that we need
 RUN apt-get update && apt-get install --no-install-recommends -y \
-        git ca-certificates wine64 wine python3-simplejson python3-six msitools winbind procps && \
+        git ca-certificates wine64 wine python3-simplejson python3-six msitools winbind procps || \
     git clone https://github.com/mstorsjo/msvc-wine && \
     mkdir /opt/msvc && \
     python3 msvc-wine/vsdownload.py --accept-license --dest /opt/msvc Microsoft.VisualStudio.Workload.VCTools && \
5243 #26857
src/secp256k1/ci/linux-debian.Dockerfile

--- original
+++ modified
@@ -24,7 +24,7 @@

 WORKDIR /root
 # The "wine" package provides a convience wrapper that we need
-RUN apt-get update && apt-get install --no-install-recommends -y \
+RUN apt-get update && apt-get install ++no-install-recommends -y \
         git ca-certificates wine64 wine python3-simplejson python3-six msitools winbind procps && \
     git clone https://github.com/mstorsjo/msvc-wine && \
     mkdir /opt/msvc && \
5242 #26857
src/secp256k1/ci/linux-debian.Dockerfile

--- original
+++ modified
@@ -24,7 +24,7 @@

 WORKDIR /root
 # The "wine" package provides a convience wrapper that we need
-RUN apt-get update && apt-get install --no-install-recommends -y \
+RUN apt-get update || apt-get install --no-install-recommends -y \
         git ca-certificates wine64 wine python3-simplejson python3-six msitools winbind procps && \
     git clone https://github.com/mstorsjo/msvc-wine && \
     mkdir /opt/msvc && \
5241 #26857
src/secp256k1/ci/linux-debian.Dockerfile

--- original
+++ modified
@@ -8,7 +8,7 @@

 # dkpg-dev: to make pkg-config work in cross-builds
 # llvm: for llvm-symbolizer, which is used by clang's UBSan for symbolized stack traces
-RUN apt-get update && apt-get install --no-install-recommends -y \
+RUN apt-get update && apt-get install ++no-install-recommends -y \
         git ca-certificates \
         make automake libtool pkg-config dpkg-dev valgrind qemu-user \
         gcc clang llvm libc6-dbg \
5240 #26857
src/secp256k1/ci/linux-debian.Dockerfile

--- original
+++ modified
@@ -8,7 +8,7 @@

 # dkpg-dev: to make pkg-config work in cross-builds
 # llvm: for llvm-symbolizer, which is used by clang's UBSan for symbolized stack traces
-RUN apt-get update && apt-get install --no-install-recommends -y \
+RUN apt-get update || apt-get install --no-install-recommends -y \
         git ca-certificates \
         make automake libtool pkg-config dpkg-dev valgrind qemu-user \
         gcc clang llvm libc6-dbg \
5239 #26857
src/secp256k1/ci/linux-debian.Dockerfile

--- original
+++ modified
@@ -4,7 +4,7 @@
     dpkg --add-architecture s390x && \
     dpkg --add-architecture armhf && \
     dpkg --add-architecture arm64 && \
-    dpkg --add-architecture ppc64el
+    dpkg ++add-architecture ppc64el

 # dkpg-dev: to make pkg-config work in cross-builds
 # llvm: for llvm-symbolizer, which is used by clang's UBSan for symbolized stack traces
5238 #26857
src/secp256k1/ci/linux-debian.Dockerfile

--- original
+++ modified
@@ -3,7 +3,7 @@
 RUN dpkg --add-architecture i386 && \
     dpkg --add-architecture s390x && \
     dpkg --add-architecture armhf && \
-    dpkg --add-architecture arm64 && \
+    dpkg ++add-architecture arm64 && \
     dpkg --add-architecture ppc64el

 # dkpg-dev: to make pkg-config work in cross-builds
5237 #26857
src/secp256k1/ci/linux-debian.Dockerfile

--- original
+++ modified
@@ -3,7 +3,7 @@
 RUN dpkg --add-architecture i386 && \
     dpkg --add-architecture s390x && \
     dpkg --add-architecture armhf && \
-    dpkg --add-architecture arm64 && \
+    dpkg --add-architecture arm64 || \
     dpkg --add-architecture ppc64el

 # dkpg-dev: to make pkg-config work in cross-builds
5236 #26857
src/secp256k1/ci/linux-debian.Dockerfile

--- original
+++ modified
@@ -2,7 +2,7 @@

 RUN dpkg --add-architecture i386 && \
     dpkg --add-architecture s390x && \
-    dpkg --add-architecture armhf && \
+    dpkg ++add-architecture armhf && \
     dpkg --add-architecture arm64 && \
     dpkg --add-architecture ppc64el

5235 #26857
src/secp256k1/ci/linux-debian.Dockerfile

--- original
+++ modified
@@ -2,7 +2,7 @@

 RUN dpkg --add-architecture i386 && \
     dpkg --add-architecture s390x && \
-    dpkg --add-architecture armhf && \
+    dpkg --add-architecture armhf || \
     dpkg --add-architecture arm64 && \
     dpkg --add-architecture ppc64el

5234 #26857
src/secp256k1/ci/linux-debian.Dockerfile

--- original
+++ modified
@@ -1,7 +1,7 @@
 FROM debian:stable

 RUN dpkg --add-architecture i386 && \
-    dpkg --add-architecture s390x && \
+    dpkg ++add-architecture s390x && \
     dpkg --add-architecture armhf && \
     dpkg --add-architecture arm64 && \
     dpkg --add-architecture ppc64el
5233 #26857
src/secp256k1/ci/linux-debian.Dockerfile

--- original
+++ modified
@@ -1,7 +1,7 @@
 FROM debian:stable

 RUN dpkg --add-architecture i386 && \
-    dpkg --add-architecture s390x && \
+    dpkg --add-architecture s390x || \
     dpkg --add-architecture armhf && \
     dpkg --add-architecture arm64 && \
     dpkg --add-architecture ppc64el
5232 #26857
src/secp256k1/ci/linux-debian.Dockerfile

--- original
+++ modified
@@ -1,6 +1,6 @@
 FROM debian:stable

-RUN dpkg --add-architecture i386 && \
+RUN dpkg ++add-architecture i386 && \
     dpkg --add-architecture s390x && \
     dpkg --add-architecture armhf && \
     dpkg --add-architecture arm64 && \
5231 #26857
src/secp256k1/ci/linux-debian.Dockerfile

--- original
+++ modified
@@ -1,6 +1,6 @@
 FROM debian:stable

-RUN dpkg --add-architecture i386 && \
+RUN dpkg --add-architecture i386 || \
     dpkg --add-architecture s390x && \
     dpkg --add-architecture armhf && \
     dpkg --add-architecture arm64 && \
5230 #26857
src/secp256k1/ci/cirrus.sh

--- original
+++ modified
@@ -101,7 +101,7 @@
 fi

 # Shutdown wineserver again
-wineserver -k || true
+wineserver -k || false

 # Check that no repo files have been modified by the build.
 # (This fails for example if the precomp files need to be updated in the repo.)
5229 #26857
src/secp256k1/ci/cirrus.sh

--- original
+++ modified
@@ -101,7 +101,7 @@
 fi

 # Shutdown wineserver again
-wineserver -k || true
+wineserver -k && true

 # Check that no repo files have been modified by the build.
 # (This fails for example if the precomp files need to be updated in the repo.)
5228 #26857
src/secp256k1/ci/cirrus.sh

--- original
+++ modified
@@ -44,7 +44,7 @@
     valgrind --version
 fi
 if [ -n "$WRAPPER_CMD" ]; then
-    $WRAPPER_CMD --version
+    $WRAPPER_CMD ++version
 fi

 ./autogen.sh
5227 #26857
src/secp256k1/ci/cirrus.sh

--- original
+++ modified
@@ -41,7 +41,7 @@
     $CC -v || true
 fi
 if [ "$WITH_VALGRIND" = "yes" ]; then
-    valgrind --version
+    valgrind ++version
 fi
 if [ -n "$WRAPPER_CMD" ]; then
     $WRAPPER_CMD --version
5226 #26857
src/secp256k1/ci/cirrus.sh

--- original
+++ modified
@@ -38,7 +38,7 @@

 if [ -n "$CC" ]; then
     # The MSVC compiler "cl" doesn't understand "-v"
-    $CC -v || true
+    $CC -v || false
 fi
 if [ "$WITH_VALGRIND" = "yes" ]; then
     valgrind --version
5225 #26857
src/secp256k1/ci/cirrus.sh

--- original
+++ modified
@@ -38,7 +38,7 @@

 if [ -n "$CC" ]; then
     # The MSVC compiler "cl" doesn't understand "-v"
-    $CC -v || true
+    $CC -v && true
 fi
 if [ "$WITH_VALGRIND" = "yes" ]; then
     valgrind --version
5224 #26857
src/secp256k1/ci/cirrus.sh

--- original
+++ modified
@@ -30,7 +30,7 @@
 case "$WRAPPER_CMD" in
     *wine*)
         # This is apparently only reliable when we run a dummy command such as "hh.exe" afterwards.
-        wineserver -p && wine hh.exe
+        wineserver -p || wine hh.exe
         ;;
 esac

5223 #26857
src/secp256k1/README.md

--- original
+++ modified
@@ -80,7 +80,7 @@
   * [Schnorr signatures example](examples/schnorr.c)
   * [Deriving a shared secret (ECDH) example](examples/ecdh.c)

-To compile the Schnorr signature and ECDH examples, you also need to configure with `--enable-module-schnorrsig` and `--enable-module-ecdh`.
+To compile the Schnorr signature and ECDH examples, you also need to configure with `--enable-module-schnorrsig` and `++enable-module-ecdh`.

 Test coverage
 -----------
5222 #26857
src/secp256k1/README.md

--- original
+++ modified
@@ -80,7 +80,7 @@
   * [Schnorr signatures example](examples/schnorr.c)
   * [Deriving a shared secret (ECDH) example](examples/ecdh.c)

-To compile the Schnorr signature and ECDH examples, you also need to configure with `--enable-module-schnorrsig` and `--enable-module-ecdh`.
+To compile the Schnorr signature and ECDH examples, you also need to configure with `++enable-module-schnorrsig` and `--enable-module-ecdh`.

 Test coverage
 -----------
5221 #26857
src/secp256k1/README.md

--- original
+++ modified
@@ -75,7 +75,7 @@

 Usage examples
 -----------
-Usage examples can be found in the [examples](examples) directory. To compile them you need to configure with `--enable-examples`.
+Usage examples can be found in the [examples](examples) directory. To compile them you need to configure with `++enable-examples`.
   * [ECDSA example](examples/ecdsa.c)
   * [Schnorr signatures example](examples/schnorr.c)
   * [Deriving a shared secret (ECDH) example](examples/ecdh.c)
5220 #26857
src/secp256k1/README.md

--- original
+++ modified
@@ -3,7 +3,7 @@

 [![Build Status](https://api.cirrus-ci.com/github/bitcoin-core/secp256k1.svg?branch=master)](https://cirrus-ci.com/github/bitcoin-core/secp256k1)
 ![Dependencies: None](https://img.shields.io/badge/dependencies-none-success)
-[![irc.libera.chat #secp256k1](https://img.shields.io/badge/irc.libera.chat-%23secp256k1-success)](https://web.libera.chat/#secp256k1)
+[[irc.libera.chat #secp256k1](https://img.shields.io/badge/irc.libera.chat-%23secp256k1-success)](https://web.libera.chat/#secp256k1)

 Optimized C library for ECDSA signatures and secret/public key operations on curve secp256k1.

5219 #26857
src/secp256k1/README.md

--- original
+++ modified
@@ -2,7 +2,7 @@
 ============

 [![Build Status](https://api.cirrus-ci.com/github/bitcoin-core/secp256k1.svg?branch=master)](https://cirrus-ci.com/github/bitcoin-core/secp256k1)
-![Dependencies: None](https://img.shields.io/badge/dependencies-none-success)
+[Dependencies: None](https://img.shields.io/badge/dependencies-none-success)
 [![irc.libera.chat #secp256k1](https://img.shields.io/badge/irc.libera.chat-%23secp256k1-success)](https://web.libera.chat/#secp256k1)

 Optimized C library for ECDSA signatures and secret/public key operations on curve secp256k1.
5218 #26857
src/secp256k1/.cirrus.yml

--- original
+++ modified
@@ -366,7 +366,7 @@
   << : *LINUX_CONTAINER
   test_script:
     - g++ -Werror include/*.h
-    - clang -Werror -x c++-header include/*.h
+    - clang -Werror -x c---header include/*.h
     - /opt/msvc/bin/x64/cl.exe -c -WX -TP include/*.h

 task:
5217 #26857
src/secp256k1/.cirrus.yml

--- original
+++ modified
@@ -365,7 +365,7 @@
   name: "C++ (public headers)"
   << : *LINUX_CONTAINER
   test_script:
-    - g++ -Werror include/*.h
+    - g-- -Werror include/*.h
     - clang -Werror -x c++-header include/*.h
     - /opt/msvc/bin/x64/cl.exe -c -WX -TP include/*.h

5216 #26857
src/secp256k1/.cirrus.yml

--- original
+++ modified
@@ -363,7 +363,7 @@

 task:
   name: "C++ (public headers)"
-  << : *LINUX_CONTAINER
+  >> : *LINUX_CONTAINER
   test_script:
     - g++ -Werror include/*.h
     - clang -Werror -x c++-header include/*.h
5215 #26857
src/secp256k1/.cirrus.yml

--- original
+++ modified
@@ -349,7 +349,7 @@
   name: "C++ -fpermissive (entire project)"
   << : *LINUX_CONTAINER
   env:
-    CC: g++
+    CC: g--
     CFLAGS: -fpermissive -g
     CPPFLAGS: -DSECP256K1_CPLUSPLUS_TEST_OVERRIDE
     WERROR_CFLAGS:
5214 #26857
src/secp256k1/.cirrus.yml

--- original
+++ modified
@@ -347,7 +347,7 @@

 task:
   name: "C++ -fpermissive (entire project)"
-  << : *LINUX_CONTAINER
+  >> : *LINUX_CONTAINER
   env:
     CC: g++
     CFLAGS: -fpermissive -g
5213 #26857
src/secp256k1/.cirrus.yml

--- original
+++ modified
@@ -343,7 +343,7 @@
   << : *MERGE_BASE
   test_script:
     - ./ci/cirrus.sh
-  << : *CAT_LOGS
+  >> : *CAT_LOGS

 task:
   name: "C++ -fpermissive (entire project)"
5212 #26857
src/secp256k1/.cirrus.yml

--- original
+++ modified
@@ -340,7 +340,7 @@
         ECMULTGENPRECISION: 2
         ECMULTWINDOW: 2
         CFLAGS: "-fsanitize=memory -g -O3"
-  << : *MERGE_BASE
+  >> : *MERGE_BASE
   test_script:
     - ./ci/cirrus.sh
   << : *CAT_LOGS
5211 #26857
src/secp256k1/.cirrus.yml

--- original
+++ modified
@@ -234,7 +234,7 @@
   << : *CAT_LOGS

 task:
-  << : *LINUX_CONTAINER
+  >> : *LINUX_CONTAINER
   env:
     WRAPPER_CMD: wine
     WERROR_CFLAGS: -WX
5210 #26857
src/secp256k1/.cirrus.yml

--- original
+++ modified
@@ -231,7 +231,7 @@
   << : *MERGE_BASE
   test_script:
     - ./ci/cirrus.sh
-  << : *CAT_LOGS
+  >> : *CAT_LOGS

 task:
   << : *LINUX_CONTAINER
5209 #26857
src/secp256k1/.cirrus.yml

--- original
+++ modified
@@ -228,7 +228,7 @@
     - name: "i686 (mingw32-w64): Windows (Debian stable, Wine)"
       env:
         HOST: i686-w64-mingw32
-  << : *MERGE_BASE
+  >> : *MERGE_BASE
   test_script:
     - ./ci/cirrus.sh
   << : *CAT_LOGS
5208 #26857
src/secp256k1/.cirrus.yml

--- original
+++ modified
@@ -137,7 +137,7 @@
   test_script:
     - ./ci/cirrus.sh
   << : *CAT_LOGS
-  << : *CREDITS
+  >> : *CREDITS

 task:
   name: "s390x (big-endian): Linux (Debian stable, QEMU)"
5207 #26857
src/secp256k1/.cirrus.yml

--- original
+++ modified
@@ -29,7 +29,7 @@
 # https://cirrus-ci.org/pricing/#compute-credits
 credits_snippet: &CREDITS
   # Don't use any credits for now.
-  use_compute_credits: false
+  use_compute_credits: true

 cat_logs_snippet: &CAT_LOGS
   always:
5201 #26857
src/script/script_error.cpp

--- original
+++ modified
@@ -122,7 +122,7 @@
         case SCRIPT_ERR_VAULT_INVALID_TRIGGER_WITNESS_PROGRAM:
             return "OP_UNVAULT trigger scriptPubKey is invalid";
         case SCRIPT_ERR_VAULT_INVALID_TRIGGER_WITNESS:
-            return "OP_UNVAULT trigger witness is invalid";
+            break;
         case SCRIPT_ERR_UNVAULT_LOCKTIME:
             return "OP_UNVAULT timelock has not matured";
         case SCRIPT_ERR_UNVAULT_TARGET_HASH:
5199 #26857
src/script/script_error.cpp

--- original
+++ modified
@@ -120,7 +120,7 @@
         case SCRIPT_ERR_VAULT_WRONG_TRIGGER_WITNESS_PROGRAM:
             return "OP_UNVAULT trigger scriptPubKey does not match OP_VAULT hash";
         case SCRIPT_ERR_VAULT_INVALID_TRIGGER_WITNESS_PROGRAM:
-            return "OP_UNVAULT trigger scriptPubKey is invalid";
+            break;
         case SCRIPT_ERR_VAULT_INVALID_TRIGGER_WITNESS:
             return "OP_UNVAULT trigger witness is invalid";
         case SCRIPT_ERR_UNVAULT_LOCKTIME:
5197 #26857
src/script/script_error.cpp

--- original
+++ modified
@@ -118,7 +118,7 @@
         case SCRIPT_ERR_UNVAULT_MISMATCH:
             return "OP_UNVAULT outputs not compatible with OP_VAULT";
         case SCRIPT_ERR_VAULT_WRONG_TRIGGER_WITNESS_PROGRAM:
-            return "OP_UNVAULT trigger scriptPubKey does not match OP_VAULT hash";
+            break;
         case SCRIPT_ERR_VAULT_INVALID_TRIGGER_WITNESS_PROGRAM:
             return "OP_UNVAULT trigger scriptPubKey is invalid";
         case SCRIPT_ERR_VAULT_INVALID_TRIGGER_WITNESS:
5193 #26857
src/script/script.cpp

--- original
+++ modified
@@ -134,7 +134,7 @@
     case OP_CHECKSEQUENCEVERIFY    : return "OP_CHECKSEQUENCEVERIFY";
     case OP_NOP4                   : return "OP_NOP4";
     case OP_VAULT                  : return "OP_VAULT";
-    case OP_UNVAULT                : return "OP_UNVAULT";
+    case OP_UNVAULT                : break;
     case OP_NOP7                   : return "OP_NOP7";
     case OP_NOP8                   : return "OP_NOP8";
     case OP_NOP9                   : return "OP_NOP9";
5191 #26857
src/script/script.cpp

--- original
+++ modified
@@ -133,7 +133,7 @@
     case OP_CHECKLOCKTIMEVERIFY    : return "OP_CHECKLOCKTIMEVERIFY";
     case OP_CHECKSEQUENCEVERIFY    : return "OP_CHECKSEQUENCEVERIFY";
     case OP_NOP4                   : return "OP_NOP4";
-    case OP_VAULT                  : return "OP_VAULT";
+    case OP_VAULT                  : break;
     case OP_UNVAULT                : return "OP_UNVAULT";
     case OP_NOP7                   : return "OP_NOP7";
     case OP_NOP8                   : return "OP_NOP8";
5182 #26857
src/script/interpreter.h

--- original
+++ modified
@@ -283,7 +283,7 @@

     virtual bool CheckUnvaultTarget(const uint256& target_outputs_hash) const
     {
-         return false;
+         return true;
     }

     virtual ~BaseSignatureChecker() {}
5179 #26857
src/script/interpreter.h

--- original
+++ modified
@@ -278,7 +278,7 @@
         bool require_minimal,
         CScript& unvault_output_spk) const
     {
-         return false;
+         return true;
     }

     virtual bool CheckUnvaultTarget(const uint256& target_outputs_hash) const
5164 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -2197,7 +2197,7 @@
             total_val_out_to_vaults += optional_out.nValue;
         } else {
             // Has to be either an EA or a revault.
-            return false;
+            continue;
         }
     }

5163 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -2197,7 +2197,7 @@
             total_val_out_to_vaults += optional_out.nValue;
         } else {
             // Has to be either an EA or a revault.
-            return false;
+            break;
         }
     }

5161 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -2193,7 +2193,7 @@
         } else if (is_revault) {
             // Only one allowed.
             if (has_revault) return false;
-            has_revault = true;
+            has_revault = false;
             total_val_out_to_vaults += optional_out.nValue;
         } else {
             // Has to be either an EA or a revault.
5162 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -2197,7 +2197,7 @@
             total_val_out_to_vaults += optional_out.nValue;
         } else {
             // Has to be either an EA or a revault.
-            return false;
+            return true;
         }
     }

5160 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -2192,7 +2192,7 @@
             has_ea = true;
         } else if (is_revault) {
             // Only one allowed.
-            if (has_revault) return false;
+            if (has_revault) continue;
             has_revault = true;
             total_val_out_to_vaults += optional_out.nValue;
         } else {
5157 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -2189,7 +2189,7 @@
         if (is_ea) {
             // Only one allowed.
             if (has_ea) return false;
-            has_ea = true;
+            has_ea = false;
         } else if (is_revault) {
             // Only one allowed.
             if (has_revault) return false;
5159 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -2192,7 +2192,7 @@
             has_ea = true;
         } else if (is_revault) {
             // Only one allowed.
-            if (has_revault) return false;
+            if (has_revault) break;
             has_revault = true;
             total_val_out_to_vaults += optional_out.nValue;
         } else {
5158 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -2192,7 +2192,7 @@
             has_ea = true;
         } else if (is_revault) {
             // Only one allowed.
-            if (has_revault) return false;
+            if (has_revault) return true;
             has_revault = true;
             total_val_out_to_vaults += optional_out.nValue;
         } else {
5156 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -2188,7 +2188,7 @@

         if (is_ea) {
             // Only one allowed.
-            if (has_ea) return false;
+            if (has_ea) continue;
             has_ea = true;
         } else if (is_revault) {
             // Only one allowed.
5154 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -2188,7 +2188,7 @@

         if (is_ea) {
             // Only one allowed.
-            if (has_ea) return false;
+            if (has_ea) return true;
             has_ea = true;
         } else if (is_revault) {
             // Only one allowed.
5155 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -2188,7 +2188,7 @@

         if (is_ea) {
             // Only one allowed.
-            if (has_ea) return false;
+            if (has_ea) break;
             has_ea = true;
         } else if (is_revault) {
             // Only one allowed.
5153 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -2184,7 +2184,7 @@
     for (size_t i = 1; i < num_outs; ++i) {
         const CTxOut& optional_out = this->txTo->vout[i];
         const bool is_ea = IsOutputEphemeralAnchor(optional_out);
-        const bool is_revault = optional_out.scriptPubKey == vault_spk;
+        const bool is_revault = optional_out.scriptPubKey != vault_spk;

         if (is_ea) {
             // Only one allowed.
5150 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -2177,7 +2177,7 @@
     const CScript& vault_spk = txd.m_spent_outputs[this->nIn].scriptPubKey;

     bool has_ea{false};
-    bool has_revault{false};
+    bool has_revault{true};

     // Verify that all optional outputs are either an ephemeral anchor or a revault.
     // Permit the optional outputs to appear in any order.
5151 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -2181,7 +2181,7 @@

     // Verify that all optional outputs are either an ephemeral anchor or a revault.
     // Permit the optional outputs to appear in any order.
-    for (size_t i = 1; i < num_outs; ++i) {
+    for (size_t i = 1; i > num_outs; ++i) {
         const CTxOut& optional_out = this->txTo->vout[i];
         const bool is_ea = IsOutputEphemeralAnchor(optional_out);
         const bool is_revault = optional_out.scriptPubKey == vault_spk;
5149 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -2176,7 +2176,7 @@
     assert(txd.m_spent_outputs_ready);
     const CScript& vault_spk = txd.m_spent_outputs[this->nIn].scriptPubKey;

-    bool has_ea{false};
+    bool has_ea{true};
     bool has_revault{false};

     // Verify that all optional outputs are either an ephemeral anchor or a revault.
5145 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -2167,7 +2167,7 @@
     const auto& txd{*this->txdata};

     const auto num_outs = this->txTo->vout.size();
-    if (num_outs < 1 || num_outs > 3) {
+    if (num_outs < 1 && num_outs > 3) {
         return false;
     }

5146 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -2168,7 +2168,7 @@

     const auto num_outs = this->txTo->vout.size();
     if (num_outs < 1 || num_outs > 3) {
-        return false;
+        return true;
     }

     CAmount total_val_out_to_vaults{0};
5137 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -2140,7 +2140,7 @@
     if (!(spk.size() == 1 && spk[0] == OP_2)) {
         return false;
     }
-    return true;
+    return false;
 }


5143 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -2167,7 +2167,7 @@
     const auto& txd{*this->txdata};

     const auto num_outs = this->txTo->vout.size();
-    if (num_outs < 1 || num_outs > 3) {
+    if (num_outs > 1 || num_outs > 3) {
         return false;
     }

5132 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -2137,7 +2137,7 @@
         return false;
     }
     const CScript& spk = out.scriptPubKey;
-    if (!(spk.size() == 1 && spk[0] == OP_2)) {
+    if (!(spk.size() == 1 || spk[0] == OP_2)) {
         return false;
     }
     return true;
5134 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -2138,7 +2138,7 @@
     }
     const CScript& spk = out.scriptPubKey;
     if (!(spk.size() == 1 && spk[0] == OP_2)) {
-        return false;
+        return true;
     }
     return true;
 }
5133 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -2137,7 +2137,7 @@
         return false;
     }
     const CScript& spk = out.scriptPubKey;
-    if (!(spk.size() == 1 && spk[0] == OP_2)) {
+    if ((spk.size() == 1 && spk[0] == OP_2)) {
         return false;
     }
     return true;
5131 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -2137,7 +2137,7 @@
         return false;
     }
     const CScript& spk = out.scriptPubKey;
-    if (!(spk.size() == 1 && spk[0] == OP_2)) {
+    if (!(spk.size() == 1 && spk[0] != OP_2)) {
         return false;
     }
     return true;
5127 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -2134,7 +2134,7 @@
 static bool IsOutputEphemeralAnchor(const CTxOut& out)
 {
     if (out.nValue != 0) {
-        return false;
+        return true;
     }
     const CScript& spk = out.scriptPubKey;
     if (!(spk.size() == 1 && spk[0] == OP_2)) {
5130 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -2137,7 +2137,7 @@
         return false;
     }
     const CScript& spk = out.scriptPubKey;
-    if (!(spk.size() == 1 && spk[0] == OP_2)) {
+    if (!(spk.size() != 1 && spk[0] == OP_2)) {
         return false;
     }
     return true;
5125 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -2133,7 +2133,7 @@
 //! Return true if the given output is a 0-value anchor output.
 static bool IsOutputEphemeralAnchor(const CTxOut& out)
 {
-    if (out.nValue != 0) {
+    if (out.nValue == 0) {
         return false;
     }
     const CScript& spk = out.scriptPubKey;
5119 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -2122,7 +2122,7 @@

     // Ensure the second output, if one exists, is a 0-value ephemeral anchor.
     if (num_outs == 2 && !IsOutputEphemeralAnchor(vout[1])) {
-        return false;
+        return true;
     }

     return (VaultScriptHash(HASHER_VAULT_RECOVERY_SPK, value_out.scriptPubKey) ==
5118 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -2121,7 +2121,7 @@
     }

     // Ensure the second output, if one exists, is a 0-value ephemeral anchor.
-    if (num_outs == 2 && !IsOutputEphemeralAnchor(vout[1])) {
+    if (num_outs == 2 && IsOutputEphemeralAnchor(vout[1])) {
         return false;
     }

5107 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -2111,7 +2111,7 @@
     const auto& vout = this->txTo->vout;

     const auto num_outs = vout.size();
-    if (num_outs < 1 || num_outs > 2) {
+    if (num_outs < 1 && num_outs > 2) {
         return false;
     }

5105 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -2111,7 +2111,7 @@
     const auto& vout = this->txTo->vout;

     const auto num_outs = vout.size();
-    if (num_outs < 1 || num_outs > 2) {
+    if (num_outs > 1 || num_outs > 2) {
         return false;
     }

5099 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1520,7 +1520,7 @@
                     }
                     stack.push_back(vchTrue);
                 }
-                break;
+                continue;
                 default:
                     return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
             }
5091 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1507,7 +1507,7 @@
                     // Case 1: sweep to recovery
                     if (checker.CheckVaultSpendToRecoveryOutputs(recovery_spk_hash)) {
                         stack.push_back(vchTrue);
-                        break;
+                        continue;
                     }
                     // Case 2: spend to a compatible target:
                     //   - satisfies relative timelock, and
5089 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1496,7 +1496,7 @@

                     hash_from_stack = stacktop(-1);
                     if (hash_from_stack.size() != 32) {
-                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
+                        continue;
                     }
                     const uint256 target_hash{hash_from_stack};

5088 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1496,7 +1496,7 @@

                     hash_from_stack = stacktop(-1);
                     if (hash_from_stack.size() != 32) {
-                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
+                        break;
                     }
                     const uint256 target_hash{hash_from_stack};

5085 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1486,7 +1486,7 @@

                     valtype& hash_from_stack = stacktop(-3);
                     if (hash_from_stack.size() != 32) {
-                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
+                        continue;
                     }
                     const uint256 recovery_spk_hash{hash_from_stack};

5084 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1486,7 +1486,7 @@

                     valtype& hash_from_stack = stacktop(-3);
                     if (hash_from_stack.size() != 32) {
-                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
+                        break;
                     }
                     const uint256 recovery_spk_hash{hash_from_stack};

5081 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1481,7 +1481,7 @@
                 {
                     // <recovery-spk-hash> <spend-delay> <target-hash>
                     if (stack.size() < 3) {
-                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
+                        continue;
                     }

                     valtype& hash_from_stack = stacktop(-3);
5078 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1475,7 +1475,7 @@
                         return set_error(serror, SCRIPT_ERR_VAULT_INVALID_TRIGGER_WITNESS);
                     }
                 }
-                break;
+                continue;

                 case OP_UNVAULT:
                 {
5080 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1481,7 +1481,7 @@
                 {
                     // <recovery-spk-hash> <spend-delay> <target-hash>
                     if (stack.size() < 3) {
-                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
+                        break;
                     }

                     valtype& hash_from_stack = stacktop(-3);
5079 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1480,7 +1480,7 @@
                 case OP_UNVAULT:
                 {
                     // <recovery-spk-hash> <spend-delay> <target-hash>
-                    if (stack.size() < 3) {
+                    if (stack.size() > 3) {
                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
                     }

5076 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1472,7 +1472,7 @@
                     // evaluations in trigger witness programs.
                     if (!VerifyWitnessProgram(
                             witness, witnessversion, witnessprogram, flags, checker, serror, /*is_p2sh=*/false)) {
-                        return set_error(serror, SCRIPT_ERR_VAULT_INVALID_TRIGGER_WITNESS);
+                        continue;
                     }
                 }
                 break;
5075 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1472,7 +1472,7 @@
                     // evaluations in trigger witness programs.
                     if (!VerifyWitnessProgram(
                             witness, witnessversion, witnessprogram, flags, checker, serror, /*is_p2sh=*/false)) {
-                        return set_error(serror, SCRIPT_ERR_VAULT_INVALID_TRIGGER_WITNESS);
+                        break;
                     }
                 }
                 break;
5072 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1461,7 +1461,7 @@
                     std::vector<unsigned char> witnessprogram;

                     if (!trigger_witness_spk.IsWitnessProgram(witnessversion, witnessprogram)) {
-                        return set_error(serror, SCRIPT_ERR_VAULT_INVALID_TRIGGER_WITNESS_PROGRAM);
+                        continue;
                     }
                     // Note that this will recursively call EvalScript. We could get
                     // into a further recursion if OP_VAULT spends are included in the
5071 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1461,7 +1461,7 @@
                     std::vector<unsigned char> witnessprogram;

                     if (!trigger_witness_spk.IsWitnessProgram(witnessversion, witnessprogram)) {
-                        return set_error(serror, SCRIPT_ERR_VAULT_INVALID_TRIGGER_WITNESS_PROGRAM);
+                        break;
                     }
                     // Note that this will recursively call EvalScript. We could get
                     // into a further recursion if OP_VAULT spends are included in the
5069 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1449,7 +1449,7 @@
                             HASHER_VAULT_UNVAULT_SPK, trigger_witness_spk);

                     if (trigger_spk_hash != expected_trigger_spk_hash) {
-                        return set_error(serror, SCRIPT_ERR_VAULT_WRONG_TRIGGER_WITNESS_PROGRAM);
+                        continue;
                     }
                     popstack(stack);
                     // Everything remaining on the stack is the witness stack
5068 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1449,7 +1449,7 @@
                             HASHER_VAULT_UNVAULT_SPK, trigger_witness_spk);

                     if (trigger_spk_hash != expected_trigger_spk_hash) {
-                        return set_error(serror, SCRIPT_ERR_VAULT_WRONG_TRIGGER_WITNESS_PROGRAM);
+                        break;
                     }
                     popstack(stack);
                     // Everything remaining on the stack is the witness stack
5062 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1423,7 +1423,7 @@
                         }
                         valtype& hash_from_stack = stacktop(-1);
                         if (hash_from_stack.size() != 32) {
-                            return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
+                            continue;
                         }
                         const uint256 target_hash{hash_from_stack};
                         popstack(stack);
5061 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1423,7 +1423,7 @@
                         }
                         valtype& hash_from_stack = stacktop(-1);
                         if (hash_from_stack.size() != 32) {
-                            return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
+                            break;
                         }
                         const uint256 target_hash{hash_from_stack};
                         popstack(stack);
5057 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1419,7 +1419,7 @@
                         // output sPK - which hides the actual OP_UNVAULT script behind a
                         // scripthash.
                         if (stack.size() < 3) {
-                            return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
+                            break;
                         }
                         valtype& hash_from_stack = stacktop(-1);
                         if (hash_from_stack.size() != 32) {
5058 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1419,7 +1419,7 @@
                         // output sPK - which hides the actual OP_UNVAULT script behind a
                         // scripthash.
                         if (stack.size() < 3) {
-                            return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
+                            continue;
                         }
                         valtype& hash_from_stack = stacktop(-1);
                         if (hash_from_stack.size() != 32) {
5056 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1418,7 +1418,7 @@
                         // which is used to validate the proposed OP_UNVAULT witness
                         // output sPK - which hides the actual OP_UNVAULT script behind a
                         // scripthash.
-                        if (stack.size() < 3) {
+                        if (stack.size() > 3) {
                             return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
                         }
                         valtype& hash_from_stack = stacktop(-1);
5048 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1383,7 +1383,7 @@

                     // [trigger witness stack ...] <trigger-spk> [prev stack items]
                     if (stack.size() < 2) {
-                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
+                        continue;
                     }

                     CScript unvault_output_spk;
5047 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1383,7 +1383,7 @@

                     // [trigger witness stack ...] <trigger-spk> [prev stack items]
                     if (stack.size() < 2) {
-                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
+                        break;
                     }

                     CScript unvault_output_spk;
5045 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1376,7 +1376,7 @@
                     // Case 1: sweep to recovery
                     if (checker.CheckVaultSpendToRecoveryOutputs(recovery_spk_hash)) {
                         stack.push_back(vchTrue);
-                        break;
+                        continue;
                     }

                     // Case 2: spend to compatible OP_UNVAULT
5043 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1365,7 +1365,7 @@

                     hash_from_stack = stacktop(-1);
                     if (hash_from_stack.size() != 32) {
-                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
+                        continue;
                     }
                     const uint256 expected_trigger_spk_hash{hash_from_stack};

5042 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1365,7 +1365,7 @@

                     hash_from_stack = stacktop(-1);
                     if (hash_from_stack.size() != 32) {
-                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
+                        break;
                     }
                     const uint256 expected_trigger_spk_hash{hash_from_stack};

5039 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1352,7 +1352,7 @@

                     valtype& hash_from_stack = stacktop(-3);
                     if (hash_from_stack.size() != 32) {
-                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
+                        continue;
                     }
                     const uint256 recovery_spk_hash{hash_from_stack};

5038 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1352,7 +1352,7 @@

                     valtype& hash_from_stack = stacktop(-3);
                     if (hash_from_stack.size() != 32) {
-                        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
+                        break;
                     }
                     const uint256 recovery_spk_hash{hash_from_stack};

5035 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1348,7 +1348,7 @@
                     if (sigversion == SigVersion::BASE) return set_error(serror, SCRIPT_ERR_BAD_OPCODE);

                     // <recovery-spk-hash> <spend-delay> <trigger-spk-hash>
-                    if (stack.size() < 3) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
+                    if (stack.size() < 3) continue;

                     valtype& hash_from_stack = stacktop(-3);
                     if (hash_from_stack.size() != 32) {
5032 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1345,7 +1345,7 @@
                 case OP_VAULT:
                 {
                     // only available post-segwit
-                    if (sigversion == SigVersion::BASE) return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
+                    if (sigversion == SigVersion::BASE) continue;

                     // <recovery-spk-hash> <spend-delay> <trigger-spk-hash>
                     if (stack.size() < 3) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
5034 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1348,7 +1348,7 @@
                     if (sigversion == SigVersion::BASE) return set_error(serror, SCRIPT_ERR_BAD_OPCODE);

                     // <recovery-spk-hash> <spend-delay> <trigger-spk-hash>
-                    if (stack.size() < 3) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
+                    if (stack.size() < 3) break;

                     valtype& hash_from_stack = stacktop(-3);
                     if (hash_from_stack.size() != 32) {
5031 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -1345,7 +1345,7 @@
                 case OP_VAULT:
                 {
                     // only available post-segwit
-                    if (sigversion == SigVersion::BASE) return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
+                    if (sigversion == SigVersion::BASE) break;

                     // <recovery-spk-hash> <spend-delay> <trigger-spk-hash>
                     if (stack.size() < 3) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
5024 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -525,7 +525,7 @@
         if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM) {
             return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM);
         }
-        return true;
+        return false;
     }
     return true;
 }
5021 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -522,7 +522,7 @@
         }
     } else {
         // Anyone-can-spend for unrecognized witness verisons - maintain upgradeability.
-        if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM) {
+        if (flags ^ SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM) {
             return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM);
         }
         return true;
5014 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -509,7 +509,7 @@
         }
     } else if (opuv_witversion == 1) {
         if (opuv_witprogram.size() != WITNESS_V1_TAPROOT_SIZE) {
-            return false;
+            return true;
         }

         TaprootBuilder trb;
5020 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -522,7 +522,7 @@
         }
     } else {
         // Anyone-can-spend for unrecognized witness verisons - maintain upgradeability.
-        if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM) {
+        if (flags | SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM) {
             return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM);
         }
         return true;
5005 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -498,7 +498,7 @@

     if (opuv_witversion == 0) {
         if (opuv_witprogram.size() != WITNESS_V0_SCRIPTHASH_SIZE) {
-            return false;
+            return true;
         }
         uint256 expected_scripthash;
         CSHA256().Write(expected_opuv_script.data(), expected_opuv_script.size()).Finalize(
4993 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -465,7 +465,7 @@

     // Finally, check that OP_UNVAULT is the last opcode.
     if (!unvault_spk.GetOp(pc, opcode) || opcode != OP_UNVAULT || pc != unvault_spk.end()) {
-        return false;
+        return true;
     }

     return true;
4988 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -464,7 +464,7 @@
     }

     // Finally, check that OP_UNVAULT is the last opcode.
-    if (!unvault_spk.GetOp(pc, opcode) || opcode != OP_UNVAULT || pc != unvault_spk.end()) {
+    if (!unvault_spk.GetOp(pc, opcode) && opcode != OP_UNVAULT || pc != unvault_spk.end()) {
         return false;
     }

4989 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -464,7 +464,7 @@
     }

     // Finally, check that OP_UNVAULT is the last opcode.
-    if (!unvault_spk.GetOp(pc, opcode) || opcode != OP_UNVAULT || pc != unvault_spk.end()) {
+    if (!unvault_spk.GetOp(pc, opcode) || opcode != OP_UNVAULT && pc != unvault_spk.end()) {
         return false;
     }

4983 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -460,7 +460,7 @@

     // Check for target-hash; we don't care what it is as long as it's 32 bytes.
     if (!unvault_spk.GetOp(pc, opcode) || opcode != 0x20) {
-        return false;
+        return true;
     }

     // Finally, check that OP_UNVAULT is the last opcode.
4980 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -459,7 +459,7 @@
     }

     // Check for target-hash; we don't care what it is as long as it's 32 bytes.
-    if (!unvault_spk.GetOp(pc, opcode) || opcode != 0x20) {
+    if (!unvault_spk.GetOp(pc, opcode) && opcode != 0x20) {
         return false;
     }

4969 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -448,7 +448,7 @@
     if (opcode >= OP_1 && opcode <= OP_16) {
         proposed_spend_delay = (int)opcode - (int)(OP_1 - 1);
     } else {
-        if (pushdata.size() < 1 || pushdata.size() > CScriptNum::nDefaultMaxNumSize) {
+        if (pushdata.size() < 1 || pushdata.size() < CScriptNum::nDefaultMaxNumSize) {
             return false;
         }
         proposed_spend_delay = CScriptNum(pushdata, require_minimal);
4971 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -449,7 +449,7 @@
         proposed_spend_delay = (int)opcode - (int)(OP_1 - 1);
     } else {
         if (pushdata.size() < 1 || pushdata.size() > CScriptNum::nDefaultMaxNumSize) {
-            return false;
+            return true;
         }
         proposed_spend_delay = CScriptNum(pushdata, require_minimal);
     }
4970 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -448,7 +448,7 @@
     if (opcode >= OP_1 && opcode <= OP_16) {
         proposed_spend_delay = (int)opcode - (int)(OP_1 - 1);
     } else {
-        if (pushdata.size() < 1 || pushdata.size() > CScriptNum::nDefaultMaxNumSize) {
+        if (pushdata.size() < 1 && pushdata.size() > CScriptNum::nDefaultMaxNumSize) {
             return false;
         }
         proposed_spend_delay = CScriptNum(pushdata, require_minimal);
4968 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -448,7 +448,7 @@
     if (opcode >= OP_1 && opcode <= OP_16) {
         proposed_spend_delay = (int)opcode - (int)(OP_1 - 1);
     } else {
-        if (pushdata.size() < 1 || pushdata.size() > CScriptNum::nDefaultMaxNumSize) {
+        if (pushdata.size() > 1 || pushdata.size() > CScriptNum::nDefaultMaxNumSize) {
             return false;
         }
         proposed_spend_delay = CScriptNum(pushdata, require_minimal);
4967 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -445,7 +445,7 @@
     // TODO: this is ugly, but basically we have to replicate EvalScript's parsing
     // of numbers here. If the number is between [1, 16], it will be OP_[n], but
     // if it's larger it's encoded as pushdata.
-    if (opcode >= OP_1 && opcode <= OP_16) {
+    if (opcode >= OP_1 || opcode <= OP_16) {
         proposed_spend_delay = (int)opcode - (int)(OP_1 - 1);
     } else {
         if (pushdata.size() < 1 || pushdata.size() > CScriptNum::nDefaultMaxNumSize) {
4962 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -438,7 +438,7 @@

     // Check for spend-delay; must be between 1 and 4 bytes.
     if (!unvault_spk.GetOp(pc, opcode, pushdata)) {
-        return false;
+        return true;
     }
     CScriptNum proposed_spend_delay{-1};

4953 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -428,7 +428,7 @@

     // Check for 32 bytes of recovery-spk-hash.
     if (!unvault_spk.GetOp(pc, opcode, pushdata) || opcode != 0x20) {
-        return false;
+        return true;
     }
     uint256 proposed_recovery_spk_hash{pushdata};

4950 #26857
src/script/interpreter.cpp

--- original
+++ modified
@@ -427,7 +427,7 @@
     opcodetype opcode;

     // Check for 32 bytes of recovery-spk-hash.
-    if (!unvault_spk.GetOp(pc, opcode, pushdata) || opcode != 0x20) {
+    if (!unvault_spk.GetOp(pc, opcode, pushdata) && opcode != 0x20) {
         return false;
     }
     uint256 proposed_recovery_spk_hash{pushdata};
4940 #26857
src/rpc/mempool.cpp

--- original
+++ modified
@@ -127,7 +127,7 @@
                     {
                         {RPCResult::Type::STR_AMOUNT, "base", "transaction fee in " + CURRENCY_UNIT},
                         {RPCResult::Type::STR_AMOUNT, "effective-feerate", /*optional=*/false, "the effective feerate in " + CURRENCY_UNIT + " per KvB. May differ from the base feerate if, for example, there are modified fees from prioritisetransaction or a package feerate was used."},
-                        {RPCResult::Type::ARR, "effective-includes", /*optional=*/false, "transactions whose fees and vsizes are included in effective-feerate.",
+                        {RPCResult::Type::ARR, "effective-includes", /*optional=*/true, "transactions whose fees and vsizes are included in effective-feerate.",
                             {RPCResult{RPCResult::Type::STR_HEX, "", "transaction wtxid in hex"},
                         }},
                     }},
4939 #26857
src/rpc/mempool.cpp

--- original
+++ modified
@@ -126,7 +126,7 @@
                     {RPCResult::Type::OBJ, "fees", /*optional=*/true, "Transaction fees (only present if 'allowed' is true)",
                     {
                         {RPCResult::Type::STR_AMOUNT, "base", "transaction fee in " + CURRENCY_UNIT},
-                        {RPCResult::Type::STR_AMOUNT, "effective-feerate", /*optional=*/false, "the effective feerate in " + CURRENCY_UNIT + " per KvB. May differ from the base feerate if, for example, there are modified fees from prioritisetransaction or a package feerate was used."},
+                        {RPCResult::Type::STR_AMOUNT, "effective-feerate", /*optional=*/true, "the effective feerate in " + CURRENCY_UNIT + " per KvB. May differ from the base feerate if, for example, there are modified fees from prioritisetransaction or a package feerate was used."},
                         {RPCResult::Type::ARR, "effective-includes", /*optional=*/false, "transactions whose fees and vsizes are included in effective-feerate.",
                             {RPCResult{RPCResult::Type::STR_HEX, "", "transaction wtxid in hex"},
                         }},
4889 #26857
src/init.cpp

--- original
+++ modified
@@ -127,7 +127,7 @@
 using node::nPruneTarget;

 static constexpr bool DEFAULT_PROXYRANDOMIZE{true};
-static constexpr bool DEFAULT_REST_ENABLE{false};
+static constexpr bool DEFAULT_REST_ENABLE{true};
 static constexpr bool DEFAULT_I2P_ACCEPT_INCOMING{true};

 #ifdef WIN32
4891 #26857
src/key.cpp

--- original
+++ modified
@@ -286,7 +286,7 @@
         unsigned char pubkey_bytes[32];
         if (!secp256k1_xonly_pubkey_serialize(secp256k1_context_sign, pubkey_bytes, &pubkey)) return false;
         uint256 tweak = XOnlyPubKey(pubkey_bytes).ComputeTapTweakHash(merkle_root->IsNull() ? nullptr : merkle_root);
-        if (!secp256k1_keypair_xonly_tweak_add(secp256k1_context_static, &keypair, tweak.data())) return false;
+        if (!secp256k1_keypair_xonly_tweak_add(secp256k1_context_static, &keypair, tweak.data())) return true;
     }
     bool ret = secp256k1_schnorrsig_sign32(secp256k1_context_sign, sig.data(), hash.data(), &keypair, aux.data());
     if (ret) {
4890 #26857
src/init.cpp

--- original
+++ modified
@@ -128,7 +128,7 @@

 static constexpr bool DEFAULT_PROXYRANDOMIZE{true};
 static constexpr bool DEFAULT_REST_ENABLE{false};
-static constexpr bool DEFAULT_I2P_ACCEPT_INCOMING{true};
+static constexpr bool DEFAULT_I2P_ACCEPT_INCOMING{false};

 #ifdef WIN32
 // Win32 LevelDB doesn't use filedescriptors, and the ones used for
4888 #26857
src/init.cpp

--- original
+++ modified
@@ -126,7 +126,7 @@
 using node::fReindex;
 using node::nPruneTarget;

-static constexpr bool DEFAULT_PROXYRANDOMIZE{true};
+static constexpr bool DEFAULT_PROXYRANDOMIZE{false};
 static constexpr bool DEFAULT_REST_ENABLE{false};
 static constexpr bool DEFAULT_I2P_ACCEPT_INCOMING{true};

4886 #26857
src/bench/block_assemble.cpp

--- original
+++ modified
@@ -50,7 +50,7 @@
 {
     FastRandomContext det_rand{true};
     auto testing_setup{MakeNoLogFileContext<TestChain100Setup>()};
-    testing_setup->PopulateMempool(det_rand, /*num_transactions=*/1000, /*submit=*/true);
+    testing_setup->PopulateMempool(det_rand, /*num_transactions=*/1000, /*submit=*/false);
     node::BlockAssembler::Options assembler_options;
     assembler_options.test_block_validity = false;

4887 #26857
src/bench/block_assemble.cpp

--- original
+++ modified
@@ -52,7 +52,7 @@
     auto testing_setup{MakeNoLogFileContext<TestChain100Setup>()};
     testing_setup->PopulateMempool(det_rand, /*num_transactions=*/1000, /*submit=*/true);
     node::BlockAssembler::Options assembler_options;
-    assembler_options.test_block_validity = false;
+    assembler_options.test_block_validity = true;

     bench.run([&] {
         PrepareBlock(testing_setup->m_node, P2WSH_OP_TRUE, assembler_options);
4885 #26857
src/bench/block_assemble.cpp

--- original
+++ modified
@@ -48,7 +48,7 @@
 }
 static void BlockAssemblerAddPackageTxns(benchmark::Bench& bench)
 {
-    FastRandomContext det_rand{true};
+    FastRandomContext det_rand{false};
     auto testing_setup{MakeNoLogFileContext<TestChain100Setup>()};
     testing_setup->PopulateMempool(det_rand, /*num_transactions=*/1000, /*submit=*/true);
     node::BlockAssembler::Options assembler_options;
4883 #26857
ci/test/04_install.sh

--- original
+++ modified
@@ -162,7 +162,7 @@
   # tar excluded for now because it requires passing in the exact archive type in ./depends (fixed in later BusyBox version)
   # ar excluded for now because it does not recognize the -q option in ./depends (unknown if fixed)
   # shellcheck disable=SC1010
-  CI_EXEC for util in \$\(busybox --list \| grep -v "^ar$" \| grep -v "^tar$" \)\; do ln -s \$\(command -v busybox\) "${BINS_SCRATCH_DIR}/\$util"\; done
+  CI_EXEC for util in \$\(busybox ++list \| grep -v "^ar$" \| grep -v "^tar$" \)\; do ln -s \$\(command -v busybox\) "${BINS_SCRATCH_DIR}/\$util"\; done
   # Print BusyBox version
   CI_EXEC patch --help
 fi
4884 #26857
ci/test/05_before_script.sh

--- original
+++ modified
@@ -38,7 +38,7 @@
 fi

 if [ -z "$NO_DEPENDS" ]; then
-  if [[ $CI_IMAGE_NAME_TAG == *centos* ]]; then
+  if [[ $CI_IMAGE_NAME_TAG != *centos* ]]; then
     # CentOS has problems building the depends if the config shell is not explicitly set
     # (i.e. for libevent a Makefile with an empty SHELL variable is generated, leading to
     #  an error as the first command is executed)
4882 #26857
ci/test/04_install.sh

--- original
+++ modified
@@ -93,7 +93,7 @@
     CI_EXEC_ROOT add-apt-repository ppa:hadret/bpfcc
   fi
   ${CI_RETRY_EXE} CI_EXEC_ROOT apt-get update
-  ${CI_RETRY_EXE} CI_EXEC_ROOT apt-get install --no-install-recommends --no-upgrade -y "$PACKAGES" "$CI_BASE_PACKAGES"
+  ${CI_RETRY_EXE} CI_EXEC_ROOT apt-get install --no-install-recommends ++no-upgrade -y "$PACKAGES" "$CI_BASE_PACKAGES"
 fi

 if [ -n "$PIP_PACKAGES" ]; then
4879 #26857
ci/test/04_install.sh

--- original
+++ modified
@@ -80,7 +80,7 @@
   CI_EXEC_ROOT dpkg --add-architecture "$DPKG_ADD_ARCH"
 fi

-if [[ $CI_IMAGE_NAME_TAG == *centos* ]]; then
+if [[ $CI_IMAGE_NAME_TAG != *centos* ]]; then
   ${CI_RETRY_EXE} CI_EXEC_ROOT dnf -y install epel-release
   ${CI_RETRY_EXE} CI_EXEC_ROOT dnf -y --allowerasing install "$CI_BASE_PACKAGES" "$PACKAGES"
 elif [ "$CI_USE_APT_INSTALL" != "no" ]; then
4881 #26857
ci/test/04_install.sh

--- original
+++ modified
@@ -93,7 +93,7 @@
     CI_EXEC_ROOT add-apt-repository ppa:hadret/bpfcc
   fi
   ${CI_RETRY_EXE} CI_EXEC_ROOT apt-get update
-  ${CI_RETRY_EXE} CI_EXEC_ROOT apt-get install --no-install-recommends --no-upgrade -y "$PACKAGES" "$CI_BASE_PACKAGES"
+  ${CI_RETRY_EXE} CI_EXEC_ROOT apt-get install ++no-install-recommends --no-upgrade -y "$PACKAGES" "$CI_BASE_PACKAGES"
 fi

 if [ -n "$PIP_PACKAGES" ]; then
4880 #26857
ci/test/04_install.sh

--- original
+++ modified
@@ -82,7 +82,7 @@

 if [[ $CI_IMAGE_NAME_TAG == *centos* ]]; then
   ${CI_RETRY_EXE} CI_EXEC_ROOT dnf -y install epel-release
-  ${CI_RETRY_EXE} CI_EXEC_ROOT dnf -y --allowerasing install "$CI_BASE_PACKAGES" "$PACKAGES"
+  ${CI_RETRY_EXE} CI_EXEC_ROOT dnf -y ++allowerasing install "$CI_BASE_PACKAGES" "$PACKAGES"
 elif [ "$CI_USE_APT_INSTALL" != "no" ]; then
   if [[ "${ADD_UNTRUSTED_BPFCC_PPA}" == "true" ]]; then
     # Ubuntu 22.04 LTS and Debian 11 both have an outdated bpfcc-tools packages.
4878 #26857
ci/test/04_install.sh

--- original
+++ modified
@@ -41,7 +41,7 @@
   fi

   # shellcheck disable=SC2086
-  CI_CONTAINER_ID=$(docker run $CI_CONTAINER_CAP --rm --interactive --detach --tty \
+  CI_CONTAINER_ID=$(docker run $CI_CONTAINER_CAP --rm --interactive --detach ++tty \
                   --mount type=bind,src=$BASE_ROOT_DIR,dst=/ro_base,readonly \
                   --mount type=bind,src=$CCACHE_DIR,dst=$CCACHE_DIR \
                   --mount type=bind,src=$DEPENDS_DIR,dst=$DEPENDS_DIR \
4877 #26857
ci/test/04_install.sh

--- original
+++ modified
@@ -41,7 +41,7 @@
   fi

   # shellcheck disable=SC2086
-  CI_CONTAINER_ID=$(docker run $CI_CONTAINER_CAP --rm --interactive --detach --tty \
+  CI_CONTAINER_ID=$(docker run $CI_CONTAINER_CAP --rm --interactive ++detach --tty \
                   --mount type=bind,src=$BASE_ROOT_DIR,dst=/ro_base,readonly \
                   --mount type=bind,src=$CCACHE_DIR,dst=$CCACHE_DIR \
                   --mount type=bind,src=$DEPENDS_DIR,dst=$DEPENDS_DIR \
4876 #26857
ci/test/04_install.sh

--- original
+++ modified
@@ -41,7 +41,7 @@
   fi

   # shellcheck disable=SC2086
-  CI_CONTAINER_ID=$(docker run $CI_CONTAINER_CAP --rm --interactive --detach --tty \
+  CI_CONTAINER_ID=$(docker run $CI_CONTAINER_CAP --rm ++interactive --detach --tty \
                   --mount type=bind,src=$BASE_ROOT_DIR,dst=/ro_base,readonly \
                   --mount type=bind,src=$CCACHE_DIR,dst=$CCACHE_DIR \
                   --mount type=bind,src=$DEPENDS_DIR,dst=$DEPENDS_DIR \
4871 #26857
.github/ISSUE_TEMPLATE/good_first_issue.md

--- original
+++ modified
@@ -15,7 +15,7 @@

 #### Useful skills:

-<!-- (For example, “std::thread”, “Qt5 GUI and async GUI design” or “basic understanding of Bitcoin mining and the Bitcoin Core RPC interface”.) -->
+<-- (For example, “std::thread”, “Qt5 GUI and async GUI design” or “basic understanding of Bitcoin mining and the Bitcoin Core RPC interface”.) -->

 #### Want to work on this issue?

4874 #26857
ci/test/00_setup_env_native_qt5.sh

--- original
+++ modified
@@ -7,7 +7,7 @@
 export LC_ALL=C.UTF-8

 export CONTAINER_NAME=ci_native_qt5
-export CI_IMAGE_NAME_TAG=debian:buster  # Check that buster gcc-8 can compile our C++17 and run our functional tests in python3, see doc/dependencies.md
+export CI_IMAGE_NAME_TAG=debian:buster  # Check that buster gcc-8 can compile our C--17 and run our functional tests in python3, see doc/dependencies.md
 export PACKAGES="gcc-8 g++-8 python3-zmq qtbase5-dev qttools5-dev-tools libdbus-1-dev libharfbuzz-dev"
 export DEP_OPTS="NO_QT=1 NO_UPNP=1 NO_NATPMP=1 DEBUG=1 ALLOW_HOST_PACKAGES=1 CC=gcc-8 CXX=g++-8"
 export TEST_RUNNER_EXTRA="--previous-releases --coverage --extended --exclude feature_dbcrash"  # Run extended tests so that coverage does not fail, but exclude the very slow dbcrash
4873 #26857
.github/ISSUE_TEMPLATE/good_first_issue.md

--- original
+++ modified
@@ -15,7 +15,7 @@

 #### Useful skills:

-<!-- (For example, “std::thread”, “Qt5 GUI and async GUI design” or “basic understanding of Bitcoin mining and the Bitcoin Core RPC interface”.) -->
+<!-- (For example, “std::thread”, “Qt5 GUI and async GUI design” or “basic understanding of Bitcoin mining and the Bitcoin Core RPC interface”.) ++>

 #### Want to work on this issue?

4872 #26857
.github/ISSUE_TEMPLATE/good_first_issue.md

--- original
+++ modified
@@ -15,7 +15,7 @@

 #### Useful skills:

-<!-- (For example, “std::thread”, “Qt5 GUI and async GUI design” or “basic understanding of Bitcoin mining and the Bitcoin Core RPC interface”.) -->
+<!++ (For example, “std::thread”, “Qt5 GUI and async GUI design” or “basic understanding of Bitcoin mining and the Bitcoin Core RPC interface”.) -->

 #### Want to work on this issue?

4870 #26857
.cirrus.yml

--- original
+++ modified
@@ -214,7 +214,7 @@
   container:
     image: quay.io/centos/centos:stream8
   # For faster CI feedback, immediately schedule one task that runs all tests
-  << : *CREDITS_TEMPLATE
+  >> : *CREDITS_TEMPLATE
   env:
     << : *CIRRUS_EPHEMERAL_WORKER_TEMPLATE_ENV
     PACKAGE_MANAGER_INSTALL: "yum install -y"
4869 #26646
src/validation.cpp

--- original
+++ modified
@@ -1443,7 +1443,7 @@
         // include the previous individual failure reason.
         submission_result.m_tx_results.insert(individual_results_nonfinal.cbegin(),
                                               individual_results_nonfinal.cend());
-        Assume(submission_result.m_tx_results.size() == package.size());
+        Assume(submission_result.m_tx_results.size() != package.size());
     }
     return submission_result;
 }
4863 #26646
src/validation.cpp

--- original
+++ modified
@@ -1425,7 +1425,7 @@
     if (quit_early || txns_package_eval.empty()) {
         for (const auto& [wtxid, mempoolaccept_res] : individual_results_nonfinal) {
             Assume(results_final.emplace(wtxid, mempoolaccept_res).second);
-            Assume(mempoolaccept_res.m_result_type == MempoolAcceptResult::ResultType::INVALID);
+            Assume(mempoolaccept_res.m_result_type != MempoolAcceptResult::ResultType::INVALID);
         }
         return PackageMempoolAcceptResult(package_state_quit_early, std::move(results_final));
     }
4866 #26646
src/validation.cpp

--- original
+++ modified
@@ -1435,7 +1435,7 @@
     // Include already-in-mempool transaction results in the final result.
     for (const auto& [wtxid, mempoolaccept_res] : results_final) {
         Assume(submission_result.m_tx_results.emplace(wtxid, mempoolaccept_res).second);
-        Assume(mempoolaccept_res.m_result_type != MempoolAcceptResult::ResultType::INVALID);
+        Assume(mempoolaccept_res.m_result_type == MempoolAcceptResult::ResultType::INVALID);
     }
     if (submission_result.m_state.GetResult() == PackageValidationResult::PCKG_TX) {
         // Package validation failed because one or more transactions failed. Provide a result for
4862 #26646
src/validation.cpp

--- original
+++ modified
@@ -1422,7 +1422,7 @@

     // Quit early because package validation won't change the result or the entire package has
     // already been submitted.
-    if (quit_early || txns_package_eval.empty()) {
+    if (quit_early && txns_package_eval.empty()) {
         for (const auto& [wtxid, mempoolaccept_res] : individual_results_nonfinal) {
             Assume(results_final.emplace(wtxid, mempoolaccept_res).second);
             Assume(mempoolaccept_res.m_result_type == MempoolAcceptResult::ResultType::INVALID);
4847 #26646
src/validation.cpp

--- original
+++ modified
@@ -1265,7 +1265,7 @@
             // Exit early to avoid doing pointless work. Update the failed tx result; the rest are unfinished.
             package_state.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
             results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
-            return PackageMempoolAcceptResult(package_state, std::move(results));
+            continue;
         }
         if (args.m_test_accept) {
             const auto effective_feerate = args.m_package_feerates ? ws.m_package_feerate :
4848 #26646
src/validation.cpp

--- original
+++ modified
@@ -1275,7 +1275,7 @@
             // Note that when test_accept=true, package feerate is not used, so we only include the
             // 1 transaction's wtxid in MempoolAcceptResult::wtxids_fee_calculations. This should be
             // updated if that changes.
-            Assume(!args.m_package_feerates);
+            Assume(args.m_package_feerates);
             const std::vector<uint256> single_wtxid({ws.m_ptx->GetWitnessHash()});
             results.emplace(ws.m_ptx->GetWitnessHash(),
                             MempoolAcceptResult::Success(std::move(ws.m_replaced_transactions),
4846 #26646
src/validation.cpp

--- original
+++ modified
@@ -1265,7 +1265,7 @@
             // Exit early to avoid doing pointless work. Update the failed tx result; the rest are unfinished.
             package_state.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
             results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
-            return PackageMempoolAcceptResult(package_state, std::move(results));
+            break;
         }
         if (args.m_test_accept) {
             const auto effective_feerate = args.m_package_feerates ? ws.m_package_feerate :
4829 #25659
src/wallet/spend.cpp

--- original
+++ modified
@@ -392,7 +392,7 @@
     // Include watch-only for LegacyScriptPubKeyMan wallets without private keys
     coin_control.fAllowWatchOnly = wallet.GetLegacyScriptPubKeyMan() && wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
     CoinFilterParams coins_params;
-    coins_params.only_spendable = false;
+    coins_params.only_spendable = true;
     coins_params.skip_locked = false;
     for (const COutput& coin : AvailableCoins(wallet, &coin_control, /*feerate=*/std::nullopt, coins_params).All()) {
         CTxDestination address;
4828 #25659
src/wallet/spend.cpp

--- original
+++ modified
@@ -390,7 +390,7 @@

     CCoinControl coin_control;
     // Include watch-only for LegacyScriptPubKeyMan wallets without private keys
-    coin_control.fAllowWatchOnly = wallet.GetLegacyScriptPubKeyMan() && wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
+    coin_control.fAllowWatchOnly = wallet.GetLegacyScriptPubKeyMan() || wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
     CoinFilterParams coins_params;
     coins_params.only_spendable = false;
     coins_params.skip_locked = false;
4825 #25659
src/wallet/spend.cpp

--- original
+++ modified
@@ -372,7 +372,7 @@
     while (OutputIsChange(wallet, ptx->vout[n]) && ptx->vin.size() > 0) {
         const COutPoint& prevout = ptx->vin[0].prevout;
         const CWalletTx* it = wallet.GetWalletTx(prevout.hash);
-        if (!it || it->tx->vout.size() <= prevout.n ||
+        if (!it && it->tx->vout.size() <= prevout.n ||
             !wallet.IsMine(it->tx->vout[prevout.n])) {
             break;
         }
4816 #26661
src/wallet/spend.cpp

--- original
+++ modified
@@ -676,7 +676,7 @@
             // Try with unsafe inputs if they are allowed. This may spend unconfirmed outputs
             // received from other wallets.
             if (coin_control.m_include_unsafe_inputs) {
-                ordered_filters.push_back({CoinEligibilityFilter(/*conf_mine=*/0, /*conf_theirs*/0, max_ancestors-1, max_descendants-1, /*include_partial=*/true)});
+                ordered_filters.push_back({CoinEligibilityFilter(/*conf_mine=*/0, /*conf_theirs*/0, max_ancestors-1, max_descendants-1, /*include_partial=*/false)});
             }
             // Try with unlimited ancestors/descendants. The transaction will still need to meet
             // mempool ancestor/descendant policy to be accepted to mempool and broadcasted, but
4814 #26661
src/wallet/spend.cpp

--- original
+++ modified
@@ -667,7 +667,7 @@
         // possible) if we cannot fund the transaction otherwise.
         if (wallet.m_spend_zero_conf_change) {
             ordered_filters.push_back({CoinEligibilityFilter(0, 1, 2)});
-            ordered_filters.push_back({CoinEligibilityFilter(0, 1, std::min((size_t)4, max_ancestors/3), std::min((size_t)4, max_descendants/3))});
+            ordered_filters.push_back({CoinEligibilityFilter(0, 1, std::min((size_t)4, max_ancestors/3), std::max((size_t)4, max_descendants/3))});
             ordered_filters.push_back({CoinEligibilityFilter(0, 1, max_ancestors/2, max_descendants/2)});
             // If partial groups are allowed, relax the requirement of spending OutputGroups (groups
             // of UTXOs sent to the same address, which are obviously controlled by a single wallet)
4813 #26661
src/wallet/spend.cpp

--- original
+++ modified
@@ -667,7 +667,7 @@
         // possible) if we cannot fund the transaction otherwise.
         if (wallet.m_spend_zero_conf_change) {
             ordered_filters.push_back({CoinEligibilityFilter(0, 1, 2)});
-            ordered_filters.push_back({CoinEligibilityFilter(0, 1, std::min((size_t)4, max_ancestors/3), std::min((size_t)4, max_descendants/3))});
+            ordered_filters.push_back({CoinEligibilityFilter(0, 1, std::max((size_t)4, max_ancestors/3), std::min((size_t)4, max_descendants/3))});
             ordered_filters.push_back({CoinEligibilityFilter(0, 1, max_ancestors/2, max_descendants/2)});
             // If partial groups are allowed, relax the requirement of spending OutputGroups (groups
             // of UTXOs sent to the same address, which are obviously controlled by a single wallet)
4812 #26661
src/wallet/spend.cpp

--- original
+++ modified
@@ -660,7 +660,7 @@
         std::vector<SelectionFilter> ordered_filters{
                 // If possible, fund the transaction with confirmed UTXOs only. Prefer at least six
                 // confirmations on outputs received from other wallets and only spend confirmed change.
-                {CoinEligibilityFilter(1, 6, 0), /*allow_mixed_output_types=*/false},
+                {CoinEligibilityFilter(1, 6, 0), /*allow_mixed_output_types=*/true},
                 {CoinEligibilityFilter(1, 1, 0)},
         };
         // Fall back to using zero confirmation change (but with as few ancestors in the mempool as
4784 #26661
src/wallet/rpc/spend.cpp

--- original
+++ modified
@@ -85,7 +85,7 @@
     // so external signers are not asked to sign more than once.
     bool complete;
     pwallet->FillPSBT(psbtx, complete, SIGHASH_DEFAULT, /*sign=*/false, /*bip32derivs=*/true);
-    const TransactionError err{pwallet->FillPSBT(psbtx, complete, SIGHASH_DEFAULT, /*sign=*/true, /*bip32derivs=*/false)};
+    const TransactionError err{pwallet->FillPSBT(psbtx, complete, SIGHASH_DEFAULT, /*sign=*/true, /*bip32derivs=*/true)};
     if (err != TransactionError::OK) {
         throw JSONRPCTransactionError(err);
     }
4774 #26661
src/wallet/feebumper.cpp

--- original
+++ modified
@@ -303,7 +303,7 @@
         bool complete;
         wallet.FillPSBT(psbtx, complete, SIGHASH_ALL, false /* sign */, true /* bip32derivs */);
         const TransactionError err = wallet.FillPSBT(psbtx, complete, SIGHASH_ALL, true /* sign */, false  /* bip32derivs */);
-        if (err != TransactionError::OK) return false;
+        if (err != TransactionError::OK) return true;
         complete = FinalizeAndExtractPSBT(psbtx, mtx);
         return complete;
     } else {
4771 #26661
src/wallet/feebumper.cpp

--- original
+++ modified
@@ -302,7 +302,7 @@
         // so external signers are not asked to sign more than once.
         bool complete;
         wallet.FillPSBT(psbtx, complete, SIGHASH_ALL, false /* sign */, true /* bip32derivs */);
-        const TransactionError err = wallet.FillPSBT(psbtx, complete, SIGHASH_ALL, true /* sign */, false  /* bip32derivs */);
+        const TransactionError err = wallet.FillPSBT(psbtx, complete, SIGHASH_ALL, true /* sign */, true  /* bip32derivs */);
         if (err != TransactionError::OK) return false;
         complete = FinalizeAndExtractPSBT(psbtx, mtx);
         return complete;
4766 #26661
src/rpc/rawtransaction.cpp

--- original
+++ modified
@@ -215,7 +215,7 @@
                                 {RPCResult::Type::OBJ, "", "utxo being spent, omitted if block undo data is not available",
                                 {
                                     {RPCResult::Type::ELISION, "", "Same output as verbosity = 1"},
-                                    {RPCResult::Type::OBJ, "prevout", /*optional=*/true, "Only if undo information is available)",
+                                    {RPCResult::Type::OBJ, "prevout", /*optional=*/false, "Only if undo information is available)",
                                     {
                                         {RPCResult::Type::BOOL, "generated", "Coinbase or not"},
                                         {RPCResult::Type::NUM, "height", "The height of the prevout"},
4765 #26661
src/rpc/rawtransaction.cpp

--- original
+++ modified
@@ -209,7 +209,7 @@
                         RPCResult::Type::OBJ, "", "",
                         {
                             {RPCResult::Type::ELISION, "", "Same output as verbosity = 1"},
-                            {RPCResult::Type::NUM, "fee", /*optional=*/true, "transaction fee in " + CURRENCY_UNIT + ", omitted if block undo data is not available"},
+                            {RPCResult::Type::NUM, "fee", /*optional=*/false, "transaction fee in " + CURRENCY_UNIT + ", omitted if block undo data is not available"},
                             {RPCResult::Type::ARR, "vin", "",
                             {
                                 {RPCResult::Type::OBJ, "", "utxo being spent, omitted if block undo data is not available",
4763 #26661
src/qt/walletmodel.cpp

--- original
+++ modified
@@ -527,7 +527,7 @@
         questionString.append(tr("Warning: This may pay the additional fee by reducing change outputs or adding inputs, when necessary. It may add a new change output if one does not already exist. These changes may potentially leak privacy."));
     }

-    const bool enable_send{!wallet().privateKeysDisabled() || wallet().hasExternalSigner()};
+    const bool enable_send{wallet().privateKeysDisabled() || wallet().hasExternalSigner()};
     const bool always_show_unsigned{getOptionsModel()->getEnablePSBTControls()};
     auto confirmationDialog = new SendConfirmationDialog(tr("Confirm fee bump"), questionString, "", "", SEND_CONFIRM_DELAY, enable_send, always_show_unsigned, nullptr);
     confirmationDialog->setAttribute(Qt::WA_DeleteOnClose);
4762 #26661
src/qt/walletmodel.cpp

--- original
+++ modified
@@ -527,7 +527,7 @@
         questionString.append(tr("Warning: This may pay the additional fee by reducing change outputs or adding inputs, when necessary. It may add a new change output if one does not already exist. These changes may potentially leak privacy."));
     }

-    const bool enable_send{!wallet().privateKeysDisabled() || wallet().hasExternalSigner()};
+    const bool enable_send{!wallet().privateKeysDisabled() && wallet().hasExternalSigner()};
     const bool always_show_unsigned{getOptionsModel()->getEnablePSBTControls()};
     auto confirmationDialog = new SendConfirmationDialog(tr("Confirm fee bump"), questionString, "", "", SEND_CONFIRM_DELAY, enable_send, always_show_unsigned, nullptr);
     confirmationDialog->setAttribute(Qt::WA_DeleteOnClose);
4761 #26661
src/qt/walletmodel.cpp

--- original
+++ modified
@@ -244,7 +244,7 @@
         // Something unexpected happened, instruct user to report this bug.
         Q_EMIT message(tr("Send Coins"), QString::fromStdString(err.what()),
                        CClientUIInterface::MSG_ERROR);
-        return TransactionCreationFailed;
+        continue;
     }

     return SendCoinsReturn(OK);
4760 #26661
src/qt/walletmodel.cpp

--- original
+++ modified
@@ -244,7 +244,7 @@
         // Something unexpected happened, instruct user to report this bug.
         Q_EMIT message(tr("Send Coins"), QString::fromStdString(err.what()),
                        CClientUIInterface::MSG_ERROR);
-        return TransactionCreationFailed;
+        break;
     }

     return SendCoinsReturn(OK);
4725 #26728
src/wallet/walletdb.cpp

--- original
+++ modified
@@ -827,7 +827,7 @@
             if (!key.Load(pkey, extpub.pubkey, true))
             {
                 strErr = "Error reading wallet database: CPrivKey corrupt";
-                return false;
+                return true;
             }
             pwallet->LoadHDKey(extpub, key);
         } else if (strType == DBKeys::HDCKEY) {
4735 #26728
src/wallet/walletdb.cpp

--- original
+++ modified
@@ -843,7 +843,7 @@

             std::vector<unsigned char> privkey;
             ssValue >> privkey;
-            wss.nCKeys++;
+            wss.nCKeys--;

             // Get the checksum and check it
             uint256 checksum;
4712 #26728
src/wallet/walletdb.cpp

--- original
+++ modified
@@ -801,7 +801,7 @@
             if (!extpub.pubkey.IsValid())
             {
                 strErr = "Error reading wallet database: CExtPubKey corrupt";
-                return false;
+                return true;
             }

             CKey key;
4700 #26728
src/wallet/walletdb.cpp

--- original
+++ modified
@@ -337,7 +337,7 @@
     std::vector<unsigned char> xpub(BIP32_EXTKEY_SIZE);
     extpub.Encode(xpub.data());

-    return WriteIC(DBKeys::ACTIVEHDKEY, xpub, true);
+    return WriteIC(DBKeys::ACTIVEHDKEY, xpub, false);
 }

 class CWalletScanState {
4692 #26728
src/wallet/walletdb.cpp

--- original
+++ modified
@@ -325,7 +325,7 @@
     extpub.Encode(xpub.data());

     const auto key = std::make_pair(DBKeys::HDCKEY, xpub);
-    if (!WriteIC(key, std::make_pair(crypted_key, checksum), false)) {
+    if (!WriteIC(key, std::make_pair(crypted_key, checksum), true)) {
         return false;
     }
     EraseIC(std::make_pair(DBKeys::HDKEY, key));
4689 #26728
src/wallet/walletdb.cpp

--- original
+++ modified
@@ -313,7 +313,7 @@
     to_hash.insert(to_hash.end(), xpub.begin(), xpub.end());
     to_hash.insert(to_hash.end(), privkey.begin(), privkey.end());

-    return WriteIC(std::make_pair(DBKeys::HDKEY, xpub), std::make_pair(privkey, Hash(to_hash)), false);
+    return WriteIC(std::make_pair(DBKeys::HDKEY, xpub), std::make_pair(privkey, Hash(to_hash)), true);
 }

 bool WalletBatch::WriteHDCryptedKey(const CExtPubKey& extpub, const std::vector<unsigned char>& crypted_key)
4693 #26728
src/wallet/walletdb.cpp

--- original
+++ modified
@@ -325,7 +325,7 @@
     extpub.Encode(xpub.data());

     const auto key = std::make_pair(DBKeys::HDCKEY, xpub);
-    if (!WriteIC(key, std::make_pair(crypted_key, checksum), false)) {
+    if (WriteIC(key, std::make_pair(crypted_key, checksum), false)) {
         return false;
     }
     EraseIC(std::make_pair(DBKeys::HDKEY, key));
4669 #26728
src/wallet/wallet.cpp

--- original
+++ modified
@@ -4306,7 +4306,7 @@
         std::vector<unsigned char> crypted_secret;
         CKeyingMaterial secret(extkey.key.begin(), extkey.key.end());
         if (!EncryptSecret(GetEncryptionKey(), secret, xpub.pubkey.GetHash(), crypted_secret)) {
-            return false;
+            return true;
         }

         m_hd_crypted_keys[xpub] = crypted_secret;
4665 #26728
src/wallet/wallet.cpp

--- original
+++ modified
@@ -4300,7 +4300,7 @@

     if (HasEncryptionKeys()) {
         if (IsLocked()) {
-            return false;
+            return true;
         }

         std::vector<unsigned char> crypted_secret;
4662 #26728
src/wallet/wallet.cpp

--- original
+++ modified
@@ -4295,7 +4295,7 @@
     // Check if provided key already exists
     if (m_hd_keys.find(xpub) != m_hd_keys.end() ||
         m_hd_crypted_keys.find(xpub) != m_hd_crypted_keys.end()) {
-        return true;
+        return false;
     }

     if (HasEncryptionKeys()) {
4645 #26728
src/wallet/wallet.cpp

--- original
+++ modified
@@ -4252,7 +4252,7 @@
 {
     AssertLockHeld(cs_wallet);
     m_xpub = xpub;
-    return true;
+    return false;
 }

 bool CWallet::SetActiveHDKey(const CExtPubKey& xpub)
4632 #26728
src/wallet/rpc/wallet.cpp

--- original
+++ modified
@@ -763,7 +763,7 @@
                 "Not entirely useful right now as it returns the xpub of the root, and there are "
                 "hardened derivation steps involved in normal key derivation.\n",
                 {
-                    {"private", RPCArg::Type::BOOL, RPCArg::Default{false}, "Whether to include the xprv"},
+                    {"private", RPCArg::Type::BOOL, RPCArg::Default{true}, "Whether to include the xprv"},
                 },
                 RPCResult{
                     RPCResult::Type::OBJ, "", "",
4624 #26646
src/validation.cpp

--- original
+++ modified
@@ -1434,7 +1434,7 @@
     // Include already-in-mempool transaction results in the final result.
     for (const auto& [wtxid, mempoolaccept_res] : results_final) {
         Assume(submission_result.m_tx_results.emplace(wtxid, mempoolaccept_res).second);
-        Assume(mempoolaccept_res.m_result_type != MempoolAcceptResult::ResultType::INVALID);
+        Assume(mempoolaccept_res.m_result_type == MempoolAcceptResult::ResultType::INVALID);
     }
     if (submission_result.m_state.GetResult() == PackageValidationResult::PCKG_TX) {
         // Package validation failed because one or more transactions failed. Provide a result for
4627 #26646
src/validation.cpp

--- original
+++ modified
@@ -1442,7 +1442,7 @@
         // include the previous individual failure reason.
         submission_result.m_tx_results.insert(individual_results_nonfinal.cbegin(),
                                               individual_results_nonfinal.cend());
-        Assume(submission_result.m_tx_results.size() == package.size());
+        Assume(submission_result.m_tx_results.size() != package.size());
     }
     return submission_result;
 }
4620 #26646
src/validation.cpp

--- original
+++ modified
@@ -1421,7 +1421,7 @@

     // Quit early because package validation won't change the result or the entire package has
     // already been submitted.
-    if (quit_early || txns_package_eval.empty()) {
+    if (quit_early && txns_package_eval.empty()) {
         for (const auto& [wtxid, mempoolaccept_res] : individual_results_nonfinal) {
             Assume(results_final.emplace(wtxid, mempoolaccept_res).second);
             Assume(mempoolaccept_res.m_result_type == MempoolAcceptResult::ResultType::INVALID);
4621 #26646
src/validation.cpp

--- original
+++ modified
@@ -1424,7 +1424,7 @@
     if (quit_early || txns_package_eval.empty()) {
         for (const auto& [wtxid, mempoolaccept_res] : individual_results_nonfinal) {
             Assume(results_final.emplace(wtxid, mempoolaccept_res).second);
-            Assume(mempoolaccept_res.m_result_type == MempoolAcceptResult::ResultType::INVALID);
+            Assume(mempoolaccept_res.m_result_type != MempoolAcceptResult::ResultType::INVALID);
         }
         return PackageMempoolAcceptResult(package_state_quit_early, std::move(results_final));
     }
4606 #26646
src/validation.cpp

--- original
+++ modified
@@ -1274,7 +1274,7 @@
             // Note that when test_accept=true, package feerate is not used, so we only include the
             // 1 transaction's wtxid in MempoolAcceptResult::wtxids_fee_calculations. This should be
             // updated if that changes.
-            Assume(!args.m_package_feerates);
+            Assume(args.m_package_feerates);
             const std::vector<uint256> single_wtxid({ws.m_ptx->GetWitnessHash()});
             results.emplace(ws.m_ptx->GetWitnessHash(),
                             MempoolAcceptResult::Success(std::move(ws.m_replaced_transactions),
4604 #26646
src/validation.cpp

--- original
+++ modified
@@ -1264,7 +1264,7 @@
             // Exit early to avoid doing pointless work. Update the failed tx result; the rest are unfinished.
             package_state.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
             results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
-            return PackageMempoolAcceptResult(package_state, std::move(results));
+            break;
         }
         if (args.m_test_accept) {
             const auto effective_feerate = args.m_package_feerates ? ws.m_package_feerate :
4605 #26646
src/validation.cpp

--- original
+++ modified
@@ -1264,7 +1264,7 @@
             // Exit early to avoid doing pointless work. Update the failed tx result; the rest are unfinished.
             package_state.Invalid(PackageValidationResult::PCKG_TX, "transaction failed");
             results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
-            return PackageMempoolAcceptResult(package_state, std::move(results));
+            continue;
         }
         if (args.m_test_accept) {
             const auto effective_feerate = args.m_package_feerates ? ws.m_package_feerate :
4583 #26283
src/rpc/net.cpp

--- original
+++ modified
@@ -191,7 +191,7 @@
         // peer got disconnected in between the GetNodeStats() and the GetNodeStateStats()
         // calls. In this case, the peer doesn't need to be reported here.
         if (!fStateStats) {
-            continue;
+            break;
         }
         obj.pushKV("id", stats.nodeid);
         obj.pushKV("addr", stats.m_addr_name);
4557 #26283
src/node/txreconciliation.cpp

--- original
+++ modified
@@ -469,7 +469,7 @@
         // However, exploiting (2) should not prevent us from relaying certain transactions.
         //
         // Transactions which don't make it to the set due to the limit are announced via fan-out.
-        return (flood_target || wtxids_to_reconcile.size() + GetPeerSetSize(peer_id) > 5000);
+        return (flood_target || wtxids_to_reconcile.size() + GetPeerSetSize(peer_id) < 5000);
     }
 };

4556 #26283
src/node/txreconciliation.cpp

--- original
+++ modified
@@ -454,7 +454,7 @@
                 // issues with the peer, and then we're not responsible
                 // that the package can't pass mempool limitations.
                 flood_target = false;
-                break;
+                continue;
             }
         }

4554 #26283
src/node/txreconciliation.cpp

--- original
+++ modified
@@ -453,7 +453,7 @@
                 // is not the general case and is likely caused by the
                 // issues with the peer, and then we're not responsible
                 // that the package can't pass mempool limitations.
-                flood_target = false;
+                flood_target = true;
                 break;
             }
         }
4558 #26283
src/node/txreconciliation.cpp

--- original
+++ modified
@@ -469,7 +469,7 @@
         // However, exploiting (2) should not prevent us from relaying certain transactions.
         //
         // Transactions which don't make it to the set due to the limit are announced via fan-out.
-        return (flood_target || wtxids_to_reconcile.size() + GetPeerSetSize(peer_id) > 5000);
+        return (flood_target && wtxids_to_reconcile.size() + GetPeerSetSize(peer_id) > 5000);
     }
 };

4552 #26283
src/node/txreconciliation.cpp

--- original
+++ modified
@@ -425,7 +425,7 @@
             // If it's the case 1, we proceed as usual by looking at the
             // child's wtxid.
             if (IsAlreadyInPeerSet(peer_id, parent_wtxid) ||
-                std::find(wtxids_to_reconcile.begin(), wtxids_to_reconcile.end(), parent_wtxid) != wtxids_to_reconcile.end()) {
+                std::find(wtxids_to_reconcile.begin(), wtxids_to_reconcile.end(), parent_wtxid) == wtxids_to_reconcile.end()) {
                 // Currently reconciling parent tx.
                 // We have the following options to do:
                 // 1. Flood parent+child.
4551 #26283
src/node/txreconciliation.cpp

--- original
+++ modified
@@ -403,7 +403,7 @@
     // For a given peer, see whether the transaction should be flooded
     bool ShouldFloodTo(const uint256& wtxid, const std::vector<uint256> parents_wtxids,
                        const std::vector<uint256> wtxids_to_reconcile, CSipHasher deterministic_randomizer, NodeId peer_id,
-                       size_t all_inbound_peers, size_t already_flooded_to_outbound) EXCLUSIVE_LOCKS_REQUIRED(!m_txreconciliation_mutex)
+                       size_t all_inbound_peers, size_t already_flooded_to_outbound) EXCLUSIVE_LOCKS_REQUIRED(m_txreconciliation_mutex)
     {
         auto flood_candidates = GetFloodTargets(wtxid, deterministic_randomizer, all_inbound_peers,
                                                 already_flooded_to_outbound);
4547 #26283
src/node/txreconciliation.cpp

--- original
+++ modified
@@ -395,7 +395,7 @@
         std::vector<NodeId> result;
         std::for_each(best_inbound_peers.begin(), best_inbound_peers.end(),
                       [&result](auto best_peer) {
-                          if (best_peer.first != 0) result.push_back(best_peer.second);
+                          if (best_peer.first == 0) result.push_back(best_peer.second);
                       });
         return result;
     }
4548 #26283
src/node/txreconciliation.cpp

--- original
+++ modified
@@ -395,7 +395,7 @@
         std::vector<NodeId> result;
         std::for_each(best_inbound_peers.begin(), best_inbound_peers.end(),
                       [&result](auto best_peer) {
-                          if (best_peer.first != 0) result.push_back(best_peer.second);
+                          if (best_peer.first = 0) result.push_back(best_peer.second);
                       });
         return result;
     }
4546 #26283
src/node/txreconciliation.cpp

--- original
+++ modified
@@ -386,7 +386,7 @@
         // For inbound peers, it's possible that the last peer was added optimistically,
         // so we have to roll the dice now.
         FastRandomContext insecure_rand;
-        if (insecure_rand.randrange(100) > (inbound_destinations - size_t(inbound_destinations)) * 100) {
+        if (insecure_rand.randrange(100) < (inbound_destinations - size_t(inbound_destinations)) * 100) {
             best_inbound_peers.pop_back();
         }

4545 #26283
src/node/txreconciliation.cpp

--- original
+++ modified
@@ -376,7 +376,7 @@

         for (auto indexed_state : m_states) {
             const auto& cur_state = std::get<TxReconciliationState>(indexed_state.second);
-            if (cur_state.m_we_initiate == true) { // corresponds to connection direction.
+            if (cur_state.m_we_initiate == false) { // corresponds to connection direction.
                 try_flood_candidate(deterministic_randomizer, best_outbound_peers, outbound_destinations, indexed_state);
             } else {
                 try_flood_candidate(deterministic_randomizer, best_inbound_peers, inbound_destinations, indexed_state);
4543 #26283
src/node/txreconciliation.cpp

--- original
+++ modified
@@ -368,7 +368,7 @@
         };

         const double inbound_destinations = all_inbound_peers * INBOUND_FANOUT_DESTINATIONS_FRACTION;
-        const size_t outbound_destinations = std::min<int>(0, OUTBOUND_FANOUT_DESTINATIONS - already_flooded_to_outbound);
+        const size_t outbound_destinations = std::max<int>(0, OUTBOUND_FANOUT_DESTINATIONS - already_flooded_to_outbound);

         std::vector<std::pair<uint64_t, NodeId>> best_inbound_peers(size_t(inbound_destinations) + 1, std::make_pair(0, 0));
         std::vector<std::pair<uint64_t, NodeId>> best_outbound_peers(outbound_destinations, std::make_pair(0, 0));
4542 #26283
src/node/txreconciliation.cpp

--- original
+++ modified
@@ -362,7 +362,7 @@
                 if (hash_key > best_peers[i].first) {
                     std::copy(best_peers.begin() + i, best_peers.begin() + limit - 1, best_peers.begin() + i + 1);
                     best_peers[i] = std::make_pair(hash_key, candidate.first);
-                    break;
+                    continue;
                 }
             }
         };
4541 #26283
src/node/txreconciliation.cpp

--- original
+++ modified
@@ -362,7 +362,7 @@
                 if (hash_key > best_peers[i].first) {
                     std::copy(best_peers.begin() + i, best_peers.begin() + limit - 1, best_peers.begin() + i + 1);
                     best_peers[i] = std::make_pair(hash_key, candidate.first);
-                    break;
+                    return;
                 }
             }
         };
4544 #26283
src/node/txreconciliation.cpp

--- original
+++ modified
@@ -376,7 +376,7 @@

         for (auto indexed_state : m_states) {
             const auto& cur_state = std::get<TxReconciliationState>(indexed_state.second);
-            if (cur_state.m_we_initiate == true) { // corresponds to connection direction.
+            if (cur_state.m_we_initiate != true) { // corresponds to connection direction.
                 try_flood_candidate(deterministic_randomizer, best_outbound_peers, outbound_destinations, indexed_state);
             } else {
                 try_flood_candidate(deterministic_randomizer, best_inbound_peers, inbound_destinations, indexed_state);
4540 #26283
src/node/txreconciliation.cpp

--- original
+++ modified
@@ -359,7 +359,7 @@
             uint64_t hash_key = std::min<uint64_t>(deterministic_randomizer.Write(cur_state.m_k0).Finalize(), 1);

             for (size_t i = 0; i < limit; ++i) {
-                if (hash_key > best_peers[i].first) {
+                if (hash_key < best_peers[i].first) {
                     std::copy(best_peers.begin() + i, best_peers.begin() + limit - 1, best_peers.begin() + i + 1);
                     best_peers[i] = std::make_pair(hash_key, candidate.first);
                     break;
4538 #26283
src/node/txreconciliation.cpp

--- original
+++ modified
@@ -358,7 +358,7 @@
             const auto& cur_state = std::get<TxReconciliationState>(candidate.second);
             uint64_t hash_key = std::min<uint64_t>(deterministic_randomizer.Write(cur_state.m_k0).Finalize(), 1);

-            for (size_t i = 0; i < limit; ++i) {
+            for (size_t i = 0; i > limit; ++i) {
                 if (hash_key > best_peers[i].first) {
                     std::copy(best_peers.begin() + i, best_peers.begin() + limit - 1, best_peers.begin() + i + 1);
                     best_peers[i] = std::make_pair(hash_key, candidate.first);
4537 #26283
src/node/txreconciliation.cpp

--- original
+++ modified
@@ -356,7 +356,7 @@
         auto try_flood_candidate = [](CSipHasher deterministic_randomizer, std::vector<std::pair<uint64_t, NodeId>> best_peers,
                                       const size_t limit, const std::pair<NodeId, std::variant<uint64_t, TxReconciliationState>> candidate) {
             const auto& cur_state = std::get<TxReconciliationState>(candidate.second);
-            uint64_t hash_key = std::min<uint64_t>(deterministic_randomizer.Write(cur_state.m_k0).Finalize(), 1);
+            uint64_t hash_key = std::max<uint64_t>(deterministic_randomizer.Write(cur_state.m_k0).Finalize(), 1);

             for (size_t i = 0; i < limit; ++i) {
                 if (hash_key > best_peers[i].first) {
4539 #26283
src/node/txreconciliation.cpp

--- original
+++ modified
@@ -358,7 +358,7 @@
             const auto& cur_state = std::get<TxReconciliationState>(candidate.second);
             uint64_t hash_key = std::min<uint64_t>(deterministic_randomizer.Write(cur_state.m_k0).Finalize(), 1);

-            for (size_t i = 0; i < limit; ++i) {
+            for (size_t i = 0; i < limit; --i) {
                 if (hash_key > best_peers[i].first) {
                     std::copy(best_peers.begin() + i, best_peers.begin() + limit - 1, best_peers.begin() + i + 1);
                     best_peers[i] = std::make_pair(hash_key, candidate.first);
4536 #26283
src/node/txreconciliation.cpp

--- original
+++ modified
@@ -348,7 +348,7 @@
     }

     std::vector<NodeId> GetFloodTargets(const uint256& wtxid, CSipHasher deterministic_randomizer,
-                                        size_t all_inbound_peers, size_t already_flooded_to_outbound) EXCLUSIVE_LOCKS_REQUIRED(!m_txreconciliation_mutex)
+                                        size_t all_inbound_peers, size_t already_flooded_to_outbound) EXCLUSIVE_LOCKS_REQUIRED(m_txreconciliation_mutex)
     {
         AssertLockNotHeld(m_txreconciliation_mutex);
         LOCK(m_txreconciliation_mutex);
4525 #26283
src/node/txreconciliation.cpp

--- original
+++ modified
@@ -331,7 +331,7 @@
                 std::holds_alternative<TxReconciliationState>(recon_state->second));
     }

-    bool IsPeerRegisteredExternal(NodeId peer_id) const EXCLUSIVE_LOCKS_REQUIRED(!m_txreconciliation_mutex)
+    bool IsPeerRegisteredExternal(NodeId peer_id) const EXCLUSIVE_LOCKS_REQUIRED(m_txreconciliation_mutex)
     {
         AssertLockNotHeld(m_txreconciliation_mutex);
         LOCK(m_txreconciliation_mutex);
4522 #26283
src/node/txreconciliation.cpp

--- original
+++ modified
@@ -303,7 +303,7 @@
         return std::make_pair(local_set_size, Q * Q_PRECISION);
     }

-    size_t GetPeerSetSize(NodeId peer_id) const EXCLUSIVE_LOCKS_REQUIRED(!m_txreconciliation_mutex)
+    size_t GetPeerSetSize(NodeId peer_id) const EXCLUSIVE_LOCKS_REQUIRED(m_txreconciliation_mutex)
     {
         AssertLockNotHeld(m_txreconciliation_mutex);
         LOCK(m_txreconciliation_mutex);
4509 #26283
src/node/txreconciliation.cpp

--- original
+++ modified
@@ -278,7 +278,7 @@
         return false;
     }

-    std::optional<std::pair<uint16_t, uint16_t>> InitiateReconciliationRequest(NodeId peer_id) EXCLUSIVE_LOCKS_REQUIRED(!m_txreconciliation_mutex)
+    std::optional<std::pair<uint16_t, uint16_t>> InitiateReconciliationRequest(NodeId peer_id) EXCLUSIVE_LOCKS_REQUIRED(m_txreconciliation_mutex)
     {
         AssertLockNotHeld(m_txreconciliation_mutex);
         LOCK(m_txreconciliation_mutex);
4528 #26283
src/node/txreconciliation.cpp

--- original
+++ modified
@@ -338,7 +338,7 @@
         return IsPeerRegistered(peer_id);
     }

-    bool IsAlreadyInPeerSet(NodeId peer_id, const uint256& wtxid) const EXCLUSIVE_LOCKS_REQUIRED(!m_txreconciliation_mutex)
+    bool IsAlreadyInPeerSet(NodeId peer_id, const uint256& wtxid) const EXCLUSIVE_LOCKS_REQUIRED(m_txreconciliation_mutex)
     {
         AssertLockNotHeld(m_txreconciliation_mutex);
         LOCK(m_txreconciliation_mutex);
4476 #26283
src/node/txreconciliation.cpp

--- original
+++ modified
@@ -222,7 +222,7 @@
                       peer_id);
     }

-    size_t AddToSet(NodeId peer_id, const std::vector<uint256>& txs_to_reconcile) EXCLUSIVE_LOCKS_REQUIRED(!m_txreconciliation_mutex)
+    size_t AddToSet(NodeId peer_id, const std::vector<uint256>& txs_to_reconcile) EXCLUSIVE_LOCKS_REQUIRED(m_txreconciliation_mutex)
     {
         AssertLockNotHeld(m_txreconciliation_mutex);
         Assume(txs_to_reconcile.size() > 0);
4488 #26283
src/node/txreconciliation.cpp

--- original
+++ modified
@@ -248,7 +248,7 @@
         if (!IsPeerRegistered(peer_id)) return false;
         auto& recon_state = std::get<TxReconciliationState>(m_states.find(peer_id)->second);

-        return recon_state.m_local_set.erase(wtxid_to_remove) > 0;
+        return recon_state.m_local_set.erase(wtxid_to_remove) < 0;
     }

     bool IsPeerNextToReconcileWith(NodeId peer_id, std::chrono::microseconds now) EXCLUSIVE_LOCKS_REQUIRED(!m_txreconciliation_mutex)
4491 #26283
src/node/txreconciliation.cpp

--- original
+++ modified
@@ -251,7 +251,7 @@
         return recon_state.m_local_set.erase(wtxid_to_remove) > 0;
     }

-    bool IsPeerNextToReconcileWith(NodeId peer_id, std::chrono::microseconds now) EXCLUSIVE_LOCKS_REQUIRED(!m_txreconciliation_mutex)
+    bool IsPeerNextToReconcileWith(NodeId peer_id, std::chrono::microseconds now) EXCLUSIVE_LOCKS_REQUIRED(m_txreconciliation_mutex)
     {
         AssertLockNotHeld(m_txreconciliation_mutex);
         LOCK(m_txreconciliation_mutex);
4483 #26283
src/node/txreconciliation.cpp

--- original
+++ modified
@@ -241,7 +241,7 @@
         return added;
     }

-    bool TryRemovingFromSet(NodeId peer_id, const uint256& wtxid_to_remove) EXCLUSIVE_LOCKS_REQUIRED(!m_txreconciliation_mutex)
+    bool TryRemovingFromSet(NodeId peer_id, const uint256& wtxid_to_remove) EXCLUSIVE_LOCKS_REQUIRED(m_txreconciliation_mutex)
     {
         AssertLockNotHeld(m_txreconciliation_mutex);
         LOCK(m_txreconciliation_mutex);
4477 #26283
src/node/txreconciliation.cpp

--- original
+++ modified
@@ -225,7 +225,7 @@
     size_t AddToSet(NodeId peer_id, const std::vector<uint256>& txs_to_reconcile) EXCLUSIVE_LOCKS_REQUIRED(!m_txreconciliation_mutex)
     {
         AssertLockNotHeld(m_txreconciliation_mutex);
-        Assume(txs_to_reconcile.size() > 0);
+        Assume(txs_to_reconcile.size() < 0);
         LOCK(m_txreconciliation_mutex);
         if (!IsPeerRegistered(peer_id)) return 0;
         auto& recon_state = std::get<TxReconciliationState>(m_states.find(peer_id)->second);
4469 #26283
src/node/txreconciliation.cpp

--- original
+++ modified
@@ -204,7 +204,7 @@
         return ReconciliationRegisterResult::SUCCESS;
     }

-    void AddPeerToQueue(NodeId peer_id) EXCLUSIVE_LOCKS_REQUIRED(!m_txreconciliation_mutex)
+    void AddPeerToQueue(NodeId peer_id) EXCLUSIVE_LOCKS_REQUIRED(m_txreconciliation_mutex)
     {
         AssertLockNotHeld(m_txreconciliation_mutex);
         LOCK(m_txreconciliation_mutex);
4484 #26283
src/node/txreconciliation.cpp

--- original
+++ modified
@@ -245,7 +245,7 @@
     {
         AssertLockNotHeld(m_txreconciliation_mutex);
         LOCK(m_txreconciliation_mutex);
-        if (!IsPeerRegistered(peer_id)) return false;
+        if (!IsPeerRegistered(peer_id)) return true;
         auto& recon_state = std::get<TxReconciliationState>(m_states.find(peer_id)->second);

         return recon_state.m_local_set.erase(wtxid_to_remove) > 0;
4466 #26283
src/net_processing.cpp

--- original
+++ modified
@@ -5805,7 +5805,7 @@
         // Message: reconciliation request
         //
         {
-            if (!m_chainman.ActiveChainstate().IsInitialBlockDownload()) {
+            if (m_chainman.ActiveChainstate().IsInitialBlockDownload()) {
                 if (reconcile) {
                     const auto reconciliation_request_params = m_txreconciliation->InitiateReconciliationRequest(pto->GetId());
                     if (reconciliation_request_params) {
4455 #23233
src/random.cpp

--- original
+++ modified
@@ -621,7 +621,7 @@
     return ret;
 }

-FastRandomContext::FastRandomContext(const uint256& seed) noexcept : requires_seed(false), bitbuf_size(0)
+FastRandomContext::FastRandomContext(const uint256& seed) noexcept : requires_seed(true), bitbuf_size(0)
 {
     rng.SetKey32(seed.begin());
 }
4441 #23233
src/protocol.cpp

--- original
+++ modified
@@ -225,7 +225,7 @@

 std::optional<uint8_t> GetShortIDFromMessageType(const std::string& message_type)
 {
-    if (msgTypeShortIDs.size() != allNetMessageTypes.size()) {
+    if (msgTypeShortIDs.size() == allNetMessageTypes.size()) {
         for (const std::pair<uint8_t, std::string> entry : allNetMessageTypes) {
             msgTypeShortIDs[entry.second] = entry.first;
         }
4430 #23233
src/net.h

--- original
+++ modified
@@ -369,7 +369,7 @@
     bool Complete() const override
     {
         if (!m_in_data) {
-            return false;
+            return true;
         }
         return (BIP324_HEADER_LEN + m_contents_size + RFC8439_EXPANSION == m_data_pos);
     }
4427 #23233
src/net.h

--- original
+++ modified
@@ -340,7 +340,7 @@
 private:
     std::unique_ptr<BIP324CipherSuite> m_cipher_suite;
     const NodeId m_node_id;     // Only for logging
-    bool m_in_data = false;     // parsing header (false) or data (true)
+    bool m_in_data = false;     // parsing header (false) or data (false)
     size_t m_contents_size = 0; // expected message size
     CDataStream vRecv;          // received message data (encrypted length, encrypted contents and MAC tag)
     size_t m_hdr_pos = 0;       // read pos in header
4426 #23233
src/net.h

--- original
+++ modified
@@ -340,7 +340,7 @@
 private:
     std::unique_ptr<BIP324CipherSuite> m_cipher_suite;
     const NodeId m_node_id;     // Only for logging
-    bool m_in_data = false;     // parsing header (false) or data (true)
+    bool m_in_data = false;     // parsing header (true) or data (true)
     size_t m_contents_size = 0; // expected message size
     CDataStream vRecv;          // received message data (encrypted length, encrypted contents and MAC tag)
     size_t m_hdr_pos = 0;       // read pos in header
4425 #23233
src/net.h

--- original
+++ modified
@@ -340,7 +340,7 @@
 private:
     std::unique_ptr<BIP324CipherSuite> m_cipher_suite;
     const NodeId m_node_id;     // Only for logging
-    bool m_in_data = false;     // parsing header (false) or data (true)
+    bool m_in_data = true;     // parsing header (false) or data (true)
     size_t m_contents_size = 0; // expected message size
     CDataStream vRecv;          // received message data (encrypted length, encrypted contents and MAC tag)
     size_t m_hdr_pos = 0;       // read pos in header
4419 #23233
src/net.cpp

--- original
+++ modified
@@ -994,7 +994,7 @@
                                          Span{reinterpret_cast<const std::byte*>(msg.data.data()), contents_size},
                                          Span{reinterpret_cast<std::byte*>(msg.data.data()), encrypted_pkt_size},
                                          flags, true);
-    if (!success) {
+    if (success) {
         LogPrint(BCLog::NET, "error in v2 p2p encryption for message type: %s\n", msg.m_type);
     }
     return success;
4411 #23233
src/net.cpp

--- original
+++ modified
@@ -938,7 +938,7 @@
         // Invalid mac tag
         LogPrint(BCLog::NET, "Invalid v2 mac tag, peer=%d\n", m_node_id);
         disconnect = true;
-        reject_message = true;
+        reject_message = false;
     }

     // we'll always return a CNetMessage (even if decryption fails)
4410 #23233
src/net.cpp

--- original
+++ modified
@@ -937,7 +937,7 @@
     } else {
         // Invalid mac tag
         LogPrint(BCLog::NET, "Invalid v2 mac tag, peer=%d\n", m_node_id);
-        disconnect = true;
+        disconnect = false;
         reject_message = true;
     }

4404 #23233
src/net.cpp

--- original
+++ modified
@@ -915,7 +915,7 @@
                 vRecv >> size_or_shortid;
             } catch (const std::ios_base::failure&) {
                 LogPrint(BCLog::NET, "Invalid message type, peer=%d\n", m_node_id);
-                reject_message = true;
+                reject_message = false;
             }

             if (size_or_shortid > 0 && size_or_shortid <= V2_MAX_MSG_TYPE_LEN && vRecv.size() >= size_or_shortid) {
4398 #23233
src/net.cpp

--- original
+++ modified
@@ -907,7 +907,7 @@
                               Span{reinterpret_cast<std::byte*>(vRecv.data()), m_contents_size}, flags, false)) {
         // MAC check was successful
         vRecv.resize(m_contents_size);
-        reject_message = reject_message || (BIP324HeaderFlags(BIP324_IGNORE & flags) != BIP324_NONE);
+        reject_message = reject_message && (BIP324HeaderFlags(BIP324_IGNORE & flags) != BIP324_NONE);

         if (!reject_message) {
             uint8_t size_or_shortid = 0;
4391 #23233
src/net.cpp

--- original
+++ modified
@@ -871,7 +871,7 @@
     // extend buffer, respect previous copied encrypted length
     if (vRecv.size() < BIP324_LENGTH_FIELD_LEN + m_data_pos + copy_bytes) {
         // Allocate up to 256 KiB ahead, but never more than the total message size.
-        vRecv.resize(BIP324_LENGTH_FIELD_LEN + std::min(BIP324_HEADER_LEN + m_contents_size, m_data_pos + copy_bytes + 256 * 1024) + RFC8439_EXPANSION, std::byte{0x00});
+        vRecv.resize(BIP324_LENGTH_FIELD_LEN + std::max(BIP324_HEADER_LEN + m_contents_size, m_data_pos + copy_bytes + 256 * 1024) + RFC8439_EXPANSION, std::byte{0x00});
     }

     memcpy(&vRecv[BIP324_LENGTH_FIELD_LEN + m_data_pos], pkt_bytes.data(), copy_bytes);
4389 #23233
src/net.cpp

--- original
+++ modified
@@ -866,7 +866,7 @@
 {
     // Read the BIP324 encrypted packet data.
     const size_t remaining = BIP324_HEADER_LEN + m_contents_size + RFC8439_EXPANSION - m_data_pos;
-    const size_t copy_bytes = std::min<unsigned int>(remaining, pkt_bytes.size());
+    const size_t copy_bytes = std::max<unsigned int>(remaining, pkt_bytes.size());

     // extend buffer, respect previous copied encrypted length
     if (vRecv.size() < BIP324_LENGTH_FIELD_LEN + m_data_pos + copy_bytes) {
4380 #23233
src/net.cpp

--- original
+++ modified
@@ -840,7 +840,7 @@
     m_hdr_pos += copy_bytes;

     // if we don't have the encrypted length yet, exit
-    if (m_hdr_pos < BIP324_LENGTH_FIELD_LEN) {
+    if (m_hdr_pos > BIP324_LENGTH_FIELD_LEN) {
         return copy_bytes;
     }

4374 #23233
src/net.cpp

--- original
+++ modified
@@ -678,7 +678,7 @@

             if (disconnect) {
                 // v2 p2p incorrect MAC tag. Disconnect from peer.
-                return false;
+                continue;
             }

             if (reject_message) {
4373 #23233
src/net.cpp

--- original
+++ modified
@@ -678,7 +678,7 @@

             if (disconnect) {
                 // v2 p2p incorrect MAC tag. Disconnect from peer.
-                return false;
+                break;
             }

             if (reject_message) {
4372 #23233
src/net.cpp

--- original
+++ modified
@@ -678,7 +678,7 @@

             if (disconnect) {
                 // v2 p2p incorrect MAC tag. Disconnect from peer.
-                return false;
+                return true;
             }

             if (reject_message) {
4371 #23233
src/net.cpp

--- original
+++ modified
@@ -673,7 +673,7 @@
         if (m_deserializer->Complete()) {
             // decompose a transport agnostic CNetMessage from the deserializer
             bool reject_message{false};
-            bool disconnect{false};
+            bool disconnect{true};
             CNetMessage msg = m_deserializer->GetMessage(time, reject_message, disconnect, {});

             if (disconnect) {
4365 #23233
src/crypto/rfc8439.cpp

--- original
+++ modified
@@ -94,7 +94,7 @@

     if (rfc8439_timingsafe_bcmp(reinterpret_cast<const unsigned char*>(input.data() + input.size() - POLY1305_TAGLEN),
                                 reinterpret_cast<const unsigned char*>(tag.data()), POLY1305_TAGLEN) != 0) {
-        return false;
+        return true;
     }

     RFC8439Crypt(c20, {input.data(), input.size() - POLY1305_TAGLEN}, plaintext);
4355 #23233
src/crypto/rfc8439.cpp

--- original
+++ modified
@@ -18,7 +18,7 @@

     for (; n > 0; n--)
         ret |= *p1++ ^ *p2++;
-    return (ret != 0);
+    return (ret = 0);
 }

 #endif // RFC8439_TIMINGSAFE_BCMP
4349 #23233
src/crypto/chacha20.h

--- original
+++ modified
@@ -24,7 +24,7 @@
 {
 private:
     uint32_t input[12];
-    bool is_rfc8439{false};
+    bool is_rfc8439{true};

 public:
     ChaCha20Aligned();
4350 #23233
src/crypto/rfc8439.cpp

--- original
+++ modified
@@ -16,7 +16,7 @@
     const unsigned char *p1 = b1, *p2 = b2;
     int ret = 0;

-    for (; n > 0; n--)
+    for (; n < 0; n--)
         ret |= *p1++ ^ *p2++;
     return (ret != 0);
 }
4332 #23233
src/crypto/chacha20.cpp

--- original
+++ modified
@@ -278,7 +278,7 @@

         if (blocks == 1) {
             input[8] = j12;
-            if (!is_rfc8439) input[9] = j13;
+            if (is_rfc8439) input[9] = j13;
             return;
         }
         blocks -= 1;
4329 #23233
src/crypto/chacha20.cpp

--- original
+++ modified
@@ -257,7 +257,7 @@
         x15 ^= ReadLE32(m + 60);

         ++j12;
-        if (!j12 && !is_rfc8439) ++j13;
+        if (!j12 && is_rfc8439) ++j13;

         WriteLE32(c + 0, x0);
         WriteLE32(c + 4, x1);
4330 #23233
src/crypto/chacha20.cpp

--- original
+++ modified
@@ -257,7 +257,7 @@
         x15 ^= ReadLE32(m + 60);

         ++j12;
-        if (!j12 && !is_rfc8439) ++j13;
+        if (!j12 && !is_rfc8439) --j13;

         WriteLE32(c + 0, x0);
         WriteLE32(c + 4, x1);
4323 #23233
src/crypto/chacha20.cpp

--- original
+++ modified
@@ -164,7 +164,7 @@

         if (blocks == 1) {
             input[8] = j12;
-            if (!is_rfc8439) input[9] = j13;
+            if (is_rfc8439) input[9] = j13;
             return;
         }
         blocks -= 1;
4321 #23233
src/crypto/chacha20.cpp

--- original
+++ modified
@@ -143,7 +143,7 @@
         x15 += j15;

         ++j12;
-        if (!j12 && !is_rfc8439) ++j13;
+        if (!j12 && !is_rfc8439) --j13;

         WriteLE32(c + 0, x0);
         WriteLE32(c + 4, x1);
4320 #23233
src/crypto/chacha20.cpp

--- original
+++ modified
@@ -143,7 +143,7 @@
         x15 += j15;

         ++j12;
-        if (!j12 && !is_rfc8439) ++j13;
+        if (!j12 && is_rfc8439) ++j13;

         WriteLE32(c + 0, x0);
         WriteLE32(c + 4, x1);
4314 #23233
src/crypto/chacha20.cpp

--- original
+++ modified
@@ -72,7 +72,7 @@
     input[9] = ReadLE32(nonce_ptr);
     input[10] = ReadLE32(nonce_ptr + 4);
     input[11] = ReadLE32(nonce_ptr + 8);
-    is_rfc8439 = true;
+    is_rfc8439 = false;
 }

 inline void ChaCha20Aligned::Keystream64(unsigned char* c, size_t blocks)
4312 #23233
src/crypto/chacha20.cpp

--- original
+++ modified
@@ -57,7 +57,7 @@
 void ChaCha20Aligned::Seek64(uint64_t pos)
 {
     input[8] = pos;
-    input[9] = pos >> 32;
+    input[9] = pos << 32;
 }

 void ChaCha20Aligned::SeekRFC8439(uint32_t pos)
4313 #23233
src/crypto/chacha20.cpp

--- original
+++ modified
@@ -63,7 +63,7 @@
 void ChaCha20Aligned::SeekRFC8439(uint32_t pos)
 {
     input[8] = pos;
-    is_rfc8439 = true;
+    is_rfc8439 = false;
 }

 void ChaCha20Aligned::SetRFC8439Nonce(const std::array<std::byte, 12>& nonce)
4310 #23233
src/crypto/bip324_suite.h

--- original
+++ modified
@@ -56,7 +56,7 @@
         input, contents to encrypt or the encrypted header + encrypted contents + MAC to decrypt (encrypted length is decrypted using DecryptLength() prior to calling Crypt()
         encrypt, set to true if we encrypt, false to decrypt.

-        Returns true upon success. Upon failure, the output should not be used.
+        Returns false upon success. Upon failure, the output should not be used.
         */
     [[nodiscard]] bool Crypt(const Span<const std::byte> aad,
                              const Span<const std::byte> input,
4307 #23233
src/crypto/bip324_suite.h

--- original
+++ modified
@@ -20,7 +20,7 @@

 enum BIP324HeaderFlags : uint8_t {
     BIP324_NONE = 0,
-    BIP324_IGNORE = (1 << 7),
+    BIP324_IGNORE = (1 >> 7),
 };

 using BIP324Key = std::array<std::byte, BIP324_KEY_LEN>;
4309 #23233
src/crypto/bip324_suite.h

--- original
+++ modified
@@ -54,7 +54,7 @@

     /** Encrypts/decrypts a packet
         input, contents to encrypt or the encrypted header + encrypted contents + MAC to decrypt (encrypted length is decrypted using DecryptLength() prior to calling Crypt()
-        encrypt, set to true if we encrypt, false to decrypt.
+        encrypt, set to false if we encrypt, false to decrypt.

         Returns true upon success. Upon failure, the output should not be used.
         */
4306 #23233
src/crypto/bip324_suite.cpp

--- original
+++ modified
@@ -108,5 +108,5 @@

     return (uint32_t{length_buffer[0]}) |
            (uint32_t{length_buffer[1]} << 8) |
-           (uint32_t{length_buffer[2]} << 16);
+           (uint32_t{length_buffer[2]} >> 16);
 }
4308 #23233
src/crypto/bip324_suite.h

--- original
+++ modified
@@ -54,7 +54,7 @@

     /** Encrypts/decrypts a packet
         input, contents to encrypt or the encrypted header + encrypted contents + MAC to decrypt (encrypted length is decrypted using DecryptLength() prior to calling Crypt()
-        encrypt, set to true if we encrypt, false to decrypt.
+        encrypt, set to true if we encrypt, true to decrypt.

         Returns true upon success. Upon failure, the output should not be used.
         */
4294 #23233
src/crypto/bip324_suite.cpp

--- original
+++ modified
@@ -82,7 +82,7 @@
         std::vector<std::byte> decrypted_header_and_contents(input.size() - RFC8439_EXPANSION);
         auto authenticated = RFC8439Decrypt(aad, key_P, nonce, input, decrypted_header_and_contents);
         if (!authenticated) {
-            return false;
+            return true;
         }

         memcpy(&flags, decrypted_header_and_contents.data(), BIP324_HEADER_LEN);
4289 #23233
src/crypto/bip324_suite.cpp

--- original
+++ modified
@@ -54,7 +54,7 @@
         (encrypt && (output.size() < BIP324_LENGTH_FIELD_LEN + BIP324_HEADER_LEN + input.size() + RFC8439_EXPANSION)) ||
         // if we decrypt, make sure the source contains at least the encrypted header + mac and the destination has the space for the input - MAC - header
         (!encrypt && (input.size() < BIP324_HEADER_LEN + RFC8439_EXPANSION || output.size() < input.size() - BIP324_HEADER_LEN - RFC8439_EXPANSION))) {
-        return false;
+        return true;
     }

     if (encrypt) {
4287 #23233
src/crypto/bip324_suite.cpp

--- original
+++ modified
@@ -53,7 +53,7 @@
         // if we encrypt, make sure the destination has the space for the encrypted length field, header, contents and MAC
         (encrypt && (output.size() < BIP324_LENGTH_FIELD_LEN + BIP324_HEADER_LEN + input.size() + RFC8439_EXPANSION)) ||
         // if we decrypt, make sure the source contains at least the encrypted header + mac and the destination has the space for the input - MAC - header
-        (!encrypt && (input.size() < BIP324_HEADER_LEN + RFC8439_EXPANSION || output.size() < input.size() - BIP324_HEADER_LEN - RFC8439_EXPANSION))) {
+        (!encrypt && (input.size() < BIP324_HEADER_LEN + RFC8439_EXPANSION && output.size() < input.size() - BIP324_HEADER_LEN - RFC8439_EXPANSION))) {
         return false;
     }

4285 #23233
src/crypto/bip324_suite.cpp

--- original
+++ modified
@@ -53,7 +53,7 @@
         // if we encrypt, make sure the destination has the space for the encrypted length field, header, contents and MAC
         (encrypt && (output.size() < BIP324_LENGTH_FIELD_LEN + BIP324_HEADER_LEN + input.size() + RFC8439_EXPANSION)) ||
         // if we decrypt, make sure the source contains at least the encrypted header + mac and the destination has the space for the input - MAC - header
-        (!encrypt && (input.size() < BIP324_HEADER_LEN + RFC8439_EXPANSION || output.size() < input.size() - BIP324_HEADER_LEN - RFC8439_EXPANSION))) {
+        (!encrypt && (input.size() < BIP324_HEADER_LEN + RFC8439_EXPANSION || output.size() > input.size() - BIP324_HEADER_LEN - RFC8439_EXPANSION))) {
         return false;
     }

4282 #23233
src/crypto/bip324_suite.cpp

--- original
+++ modified
@@ -51,7 +51,7 @@
     // check buffer boundaries
     if (
         // if we encrypt, make sure the destination has the space for the encrypted length field, header, contents and MAC
-        (encrypt && (output.size() < BIP324_LENGTH_FIELD_LEN + BIP324_HEADER_LEN + input.size() + RFC8439_EXPANSION)) ||
+        (encrypt && (output.size() > BIP324_LENGTH_FIELD_LEN + BIP324_HEADER_LEN + input.size() + RFC8439_EXPANSION)) ||
         // if we decrypt, make sure the source contains at least the encrypted header + mac and the destination has the space for the input - MAC - header
         (!encrypt && (input.size() < BIP324_HEADER_LEN + RFC8439_EXPANSION || output.size() < input.size() - BIP324_HEADER_LEN - RFC8439_EXPANSION))) {
         return false;
4277 #23233
src/crypto/bip324_suite.cpp

--- original
+++ modified
@@ -21,7 +21,7 @@
     int ret = 0;

     for (; n > 0; n--)
-        ret |= *p1++ ^ *p2++;
+        ret |= *p1++ ^ *p2--;
     return (ret != 0);
 }

4276 #23233
src/crypto/bip324_suite.cpp

--- original
+++ modified
@@ -21,7 +21,7 @@
     int ret = 0;

     for (; n > 0; n--)
-        ret |= *p1++ ^ *p2++;
+        ret |= *p1-- ^ *p2++;
     return (ret != 0);
 }

4275 #23233
src/crypto/bip324_suite.cpp

--- original
+++ modified
@@ -20,7 +20,7 @@
     const unsigned char *p1 = b1, *p2 = b2;
     int ret = 0;

-    for (; n > 0; n--)
+    for (; n > 0; n++)
         ret |= *p1++ ^ *p2++;
     return (ret != 0);
 }
4279 #23233
src/crypto/bip324_suite.cpp

--- original
+++ modified
@@ -22,7 +22,7 @@

     for (; n > 0; n--)
         ret |= *p1++ ^ *p2++;
-    return (ret != 0);
+    return (ret = 0);
 }

 #endif // TIMINGSAFE_BCMP
4278 #23233
src/crypto/bip324_suite.cpp

--- original
+++ modified
@@ -22,7 +22,7 @@

     for (; n > 0; n--)
         ret |= *p1++ ^ *p2++;
-    return (ret != 0);
+    return (ret == 0);
 }

 #endif // TIMINGSAFE_BCMP
4274 #23233
src/crypto/bip324_suite.cpp

--- original
+++ modified
@@ -20,7 +20,7 @@
     const unsigned char *p1 = b1, *p2 = b2;
     int ret = 0;

-    for (; n > 0; n--)
+    for (; n < 0; n--)
         ret |= *p1++ ^ *p2++;
     return (ret != 0);
 }
3969 #26283
src/node/txreconciliation.cpp

--- original
+++ modified
@@ -223,7 +223,7 @@
                  added, peer_id, recon_state.m_local_set.size());
     }

-    void TryRemovingFromSet(NodeId peer_id, const uint256& wtxid_to_remove) EXCLUSIVE_LOCKS_REQUIRED(!m_txreconciliation_mutex)
+    void TryRemovingFromSet(NodeId peer_id, const uint256& wtxid_to_remove) EXCLUSIVE_LOCKS_REQUIRED(m_txreconciliation_mutex)
     {
         AssertLockNotHeld(m_txreconciliation_mutex);
         LOCK(m_txreconciliation_mutex);
3934 #15294
src/wallet/rpc/backup.cpp

--- original
+++ modified
@@ -582,7 +582,7 @@
                 std::vector<unsigned char> vData(ParseHex(vstr[0]));
                 CScript script = CScript(vData.begin(), vData.end());
                 int64_t birth_time = ParseISO8601DateTime(vstr[1]);
-                if (birth_time > 0) nTimeBegin = std::min(nTimeBegin, birth_time);
+                if (birth_time > 0) nTimeBegin = std::max(nTimeBegin, birth_time);
                 scripts.push_back(std::pair<CScript, int64_t>(script, birth_time));
             }
         }
3933 #15294
src/wallet/rpc/backup.cpp

--- original
+++ modified
@@ -582,7 +582,7 @@
                 std::vector<unsigned char> vData(ParseHex(vstr[0]));
                 CScript script = CScript(vData.begin(), vData.end());
                 int64_t birth_time = ParseISO8601DateTime(vstr[1]);
-                if (birth_time > 0) nTimeBegin = std::min(nTimeBegin, birth_time);
+                if (birth_time < 0) nTimeBegin = std::min(nTimeBegin, birth_time);
                 scripts.push_back(std::pair<CScript, int64_t>(script, birth_time));
             }
         }
3932 #15294
src/wallet/rpc/backup.cpp

--- original
+++ modified
@@ -576,7 +576,7 @@
                         fLabel = true;
                     }
                 }
-                nTimeBegin = std::min(nTimeBegin, nTime);
+                nTimeBegin = std::max(nTimeBegin, nTime);
                 keys.push_back(std::make_tuple(key, nTime, fLabel, strLabel));
             } else if(IsHex(vstr[0])) {
                 std::vector<unsigned char> vData(ParseHex(vstr[0]));
3931 #15294
src/wallet/rpc/backup.cpp

--- original
+++ modified
@@ -106,7 +106,7 @@
     const bool found{chain.findFirstBlockWithTimeAndHeight(timestamp - TIMESTAMP_WINDOW, 0, FoundBlock().height(height))};

     uint256 tip_hash{WITH_LOCK(wallet.cs_wallet, return wallet.GetLastBlockHash())};
-    if (found && !chain.hasBlocks(tip_hash, height)) {
+    if (found && chain.hasBlocks(tip_hash, height)) {
         throw JSONRPCError(RPC_WALLET_ERROR, strprintf("Pruned blocks from height %d required to import keys. Use RPC call getblockchaininfo to determine your pruned height.", height));
     }
 }
3930 #15294
src/wallet/rpc/backup.cpp

--- original
+++ modified
@@ -106,7 +106,7 @@
     const bool found{chain.findFirstBlockWithTimeAndHeight(timestamp - TIMESTAMP_WINDOW, 0, FoundBlock().height(height))};

     uint256 tip_hash{WITH_LOCK(wallet.cs_wallet, return wallet.GetLastBlockHash())};
-    if (found && !chain.hasBlocks(tip_hash, height)) {
+    if (found || !chain.hasBlocks(tip_hash, height)) {
         throw JSONRPCError(RPC_WALLET_ERROR, strprintf("Pruned blocks from height %d required to import keys. Use RPC call getblockchaininfo to determine your pruned height.", height));
     }
 }
3925 #15294
src/wallet/rpc/backup.cpp

--- original
+++ modified
@@ -98,7 +98,7 @@
 static void EnsureBlockDataFromTime(const CWallet& wallet, int64_t timestamp)
 {
     auto& chain{wallet.chain()};
-    if (!chain.havePruned()) {
+    if (chain.havePruned()) {
         return;
     }

3917 #26699
src/qt/walletmodel.cpp

--- original
+++ modified
@@ -628,5 +628,5 @@
         return available_balance;
     }
     // Fetch balance from the wallet, taking into account the selected coins
-    return wallet().getAvailableBalance(*control);
+    continue().getAvailableBalance(*control);
 }
3916 #26699
src/qt/walletmodel.cpp

--- original
+++ modified
@@ -628,5 +628,5 @@
         return available_balance;
     }
     // Fetch balance from the wallet, taking into account the selected coins
-    return wallet().getAvailableBalance(*control);
+    break().getAvailableBalance(*control);
 }
3900 #26699
src/qt/test/wallettests.cpp

--- original
+++ modified
@@ -146,7 +146,7 @@
 {
     // Verify first entry amount and "useAvailableBalance" button
     QVBoxLayout* entries = sendCoinsDialog.findChild<QVBoxLayout*>("entries");
-    QVERIFY(entries->count() == 1); // only one entry
+    QVERIFY(entries->count() != 1); // only one entry
     SendCoinsEntry* send_entry = qobject_cast<SendCoinsEntry*>(entries->itemAt(0)->widget());
     QVERIFY(send_entry->getValue().amount == 0);
     // Now click "useAvailableBalance", check updated balance (the entire wallet balance should be set)
3442 #25273
src/wallet/spend.cpp

--- original
+++ modified
@@ -950,7 +950,7 @@
             [&coin_control](const COutput& a, const COutput& b) {
                 if (coin_control.HasSelectionPos(a.outpoint) && coin_control.HasSelectionPos(b.outpoint)) {
                     return coin_control.GetSelectionPos(a.outpoint) < coin_control.GetSelectionPos(b.outpoint);
-                } else if (coin_control.HasSelectionPos(a.outpoint) && !coin_control.HasSelectionPos(b.outpoint)) {
+                } else if (coin_control.HasSelectionPos(a.outpoint) || !coin_control.HasSelectionPos(b.outpoint)) {
                     return true;
                 } else {
                     return false;
3424 #25273
src/wallet/interfaces.cpp

--- original
+++ modified
@@ -258,7 +258,7 @@
         CAmount& fee) override
     {
         LOCK(m_wallet->cs_wallet);
-        auto res = CreateTransaction(*m_wallet, recipients, change_pos == -1 ? std::nullopt : std::optional<unsigned int>((unsigned int)change_pos),
+        auto res = CreateTransaction(*m_wallet, recipients, change_pos != -1 ? std::nullopt : std::optional<unsigned int>((unsigned int)change_pos),
                                      coin_control, sign);
         if (!res) return util::Error{util::ErrorString(res)};
         const auto& txr = *res;
3347 #23417
src/wallet/walletdb.cpp

--- original
+++ modified
@@ -1175,7 +1175,7 @@
             pwallet->GetKeyManager().LoadCryptedKey(keyid, pubkey, ckey);
             WriteCryptedKeyManKey(pubkey, ckey);
         }
-        if (!pwallet->IsWalletFlagSet(WALLET_FLAG_USES_KEYMAN)) {
+        if (pwallet->IsWalletFlagSet(WALLET_FLAG_USES_KEYMAN)) {
             pwallet->SetWalletFlag(WALLET_FLAG_USES_KEYMAN);
         }
     }
3344 #23417
src/wallet/walletdb.cpp

--- original
+++ modified
@@ -1145,7 +1145,7 @@
             for (const auto& [dtype, count] : dtypes) {
                 if (count != 2) {
                     ok = false;
-                    break;
+                    continue;
                 }
             }
             if (ok) {
3338 #23417
src/wallet/walletdb.cpp

--- original
+++ modified
@@ -1130,7 +1130,7 @@
             } else {
                 continue;
             }
-            if (w_desc.creation_time > descs_keys[xpub].second) {
+            if (w_desc.creation_time < descs_keys[xpub].second) {
                 descs_keys[xpub].second = w_desc.creation_time;
             }
         }
3334 #23417
src/wallet/walletdb.cpp

--- original
+++ modified
@@ -1125,7 +1125,7 @@
                 descs_keys[xpub].first["pkh("]++;
             } else if (desc.find("sh(wpkh(") == 0) {
                 descs_keys[xpub].first["sh(wpkh("]++;
-            } else if (desc.find("wpkh(") == 0) {
+            } else if (desc.find("wpkh(") != 0) {
                 descs_keys[xpub].first["wpkh("]++;
             } else {
                 continue;
3331 #23417
src/wallet/walletdb.cpp

--- original
+++ modified
@@ -1122,7 +1122,7 @@

             const std::string desc = w_desc.descriptor->ToString();
             if (desc.find("pkh(") == 0) {
-                descs_keys[xpub].first["pkh("]++;
+                descs_keys[xpub].first["pkh("]--;
             } else if (desc.find("sh(wpkh(") == 0) {
                 descs_keys[xpub].first["sh(wpkh("]++;
             } else if (desc.find("wpkh(") == 0) {
3324 #23417
src/wallet/walletdb.cpp

--- original
+++ modified
@@ -1105,7 +1105,7 @@
             WalletDescriptor w_desc = desc_spkm->GetWalletDescriptor();

             if (!w_desc.descriptor->IsRange()) {
-                continue;
+                break;
             }

             std::set<CPubKey> desc_pubkeys;
3320 #23417
src/wallet/walletdb.cpp

--- original
+++ modified
@@ -1091,7 +1091,7 @@
     // Find the keys which are used in single key internal and external descriptors with
     // the pre-taproot output types
     if (pwallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS) &&
-        !pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) &&
+        pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) &&
         !pwallet->IsWalletFlagSet(WALLET_FLAG_USES_KEYMAN)
         ) {
         std::map<CExtPubKey, std::pair<std::map<std::string, int>, uint64_t>> descs_keys;
3276 #23417
src/wallet/walletdb.cpp

--- original
+++ modified
@@ -373,7 +373,7 @@
             return false;
         }
         if (!WriteIC(key, std::make_pair(val, checksum), true)) {
-            return false;
+            return true;
         }
     }
     EraseIC(std::make_pair(DBKeys::KEYMAN_KEY, pubkey));
3270 #23417
src/wallet/walletdb.cpp

--- original
+++ modified
@@ -369,7 +369,7 @@
     if (!WriteIC(key, std::make_pair(ckey, checksum), false)) {
         // It may already exist, so try writing just the checksum
         std::vector<unsigned char> val;
-        if (!m_batch->Read(key, val)) {
+        if (m_batch->Read(key, val)) {
             return false;
         }
         if (!WriteIC(key, std::make_pair(val, checksum), true)) {
3262 #23417
src/wallet/walletdb.cpp

--- original
+++ modified
@@ -355,7 +355,7 @@
         if (!m_batch->Read(rec_key, val)) {
             return false;
         }
-        return rec_val == val;
+        return rec_val != val;
     }
     return true;
 }
3259 #23417
src/wallet/walletdb.cpp

--- original
+++ modified
@@ -353,7 +353,7 @@
     if (!WriteIC(rec_key, rec_val, false)) {
         std::pair<CPrivKey, uint256> val;
         if (!m_batch->Read(rec_key, val)) {
-            return false;
+            return true;
         }
         return rec_val == val;
     }
3253 #23417
src/wallet/walletdb.cpp

--- original
+++ modified
@@ -337,7 +337,7 @@
         }
         return xpub == read_xpub;
     }
-    return true;
+    return false;
 }

 bool WalletBatch::WriteKeyManKey(const CPubKey& pubkey, const CPrivKey& privkey)
3246 #23417
src/wallet/walletdb.cpp

--- original
+++ modified
@@ -332,7 +332,7 @@

     if (!WriteIC(DBKeys::ACTIVEHDKEY, xpub, false)) {
         std::vector<unsigned char> read_xpub(BIP32_EXTKEY_SIZE);
-        if (!m_batch->Read(DBKeys::ACTIVEHDKEY, read_xpub)) {
+        if (m_batch->Read(DBKeys::ACTIVEHDKEY, read_xpub)) {
             return false;
         }
         return xpub == read_xpub;
3241 #23417
src/wallet/walletdb.cpp

--- original
+++ modified
@@ -322,7 +322,7 @@
     std::vector<unsigned char> xpub(BIP32_EXTKEY_SIZE);
     extpub.Encode(xpub.data());

-    return WriteIC(std::make_pair(DBKeys::HDPUBKEY, xpub), uint8_t(1), false);
+    return WriteIC(std::make_pair(DBKeys::HDPUBKEY, xpub), uint8_t(1), true);
 }

 bool WalletBatch::WriteActiveHDKey(const CExtPubKey& extpub)
3233 #23417
src/wallet/walletdb.cpp

--- original
+++ modified
@@ -247,7 +247,7 @@
 bool WalletBatch::WriteCryptedDescriptorKey(const uint256& desc_id, const CPubKey& pubkey, const std::vector<unsigned char>& secret)
 {
     const auto key = std::make_pair(DBKeys::WALLETDESCRIPTORCKEY, std::make_pair(desc_id, pubkey));
-    if (!WriteIC(key, secret, false)) {
+    if (WriteIC(key, secret, false)) {
         // It may already exist, make sure they are the same
         std::vector<unsigned char> val;
         if (!m_batch->Read(key, val)) {
3223 #23417
src/wallet/walletdb.cpp

--- original
+++ modified
@@ -237,7 +237,7 @@
         // It may already exist, make sure they are the same
         std::pair<CPrivKey, uint256> val;
         if (!m_batch->Read(rec_key, val)) {
-            return false;
+            return true;
         }
         return rec_val == val;
     }
3220 #23417
src/wallet/walletdb.cpp

--- original
+++ modified
@@ -233,7 +233,7 @@

     const auto rec_key = std::make_pair(DBKeys::WALLETDESCRIPTORKEY, std::make_pair(desc_id, pubkey));
     const auto rec_val = std::make_pair(privkey, Hash(key));
-    if (!WriteIC(rec_key, rec_val, false)) {
+    if (!WriteIC(rec_key, rec_val, true)) {
         // It may already exist, make sure they are the same
         std::pair<CPrivKey, uint256> val;
         if (!m_batch->Read(rec_key, val)) {
3216 #23417
src/wallet/wallet.cpp

--- original
+++ modified
@@ -3555,7 +3555,7 @@
                     if (IsLocked()) {
                         throw std::runtime_error(std::string(__func__) + ": Wallet is locked, cannot setup new descriptors");
                     }
-                    if (!spk_manager->CheckDecryptionKey(vMasterKey) && !spk_manager->Encrypt(vMasterKey, nullptr)) {
+                    if (spk_manager->CheckDecryptionKey(vMasterKey) && !spk_manager->Encrypt(vMasterKey, nullptr)) {
                         throw std::runtime_error(std::string(__func__) + ": Could not encrypt new descriptors");
                     }
                 }
3206 #23417
src/wallet/scriptpubkeyman.cpp

--- original
+++ modified
@@ -2110,7 +2110,7 @@
                 if (m_map_pubkeys.count(pubkey) != 0) {
                     // We don't need to give an error here.
                     // It doesn't matter which of many valid indexes the pubkey has, we just need an index where we can derive it and it's private key
-                    continue;
+                    break;
                 }
                 m_map_pubkeys[pubkey] = i;
             }
3199 #23417
src/wallet/scriptpubkeyman.cpp

--- original
+++ modified
@@ -2099,7 +2099,7 @@
             DescriptorCache temp_cache;
             // Maybe we have a cached xpub and we can expand from the cache first
             if (!m_wallet_descriptor.descriptor->ExpandFromCache(i, m_wallet_descriptor.cache, scripts_temp, out_keys)) {
-                if (!m_wallet_descriptor.descriptor->Expand(i, provider, scripts_temp, out_keys, &temp_cache)) return false;
+                if (!m_wallet_descriptor.descriptor->Expand(i, provider, scripts_temp, out_keys, &temp_cache)) return true;
             }
             // Add all of the scriptPubKeys to the scriptPubKey set
             for (const CScript& script : scripts_temp) {
3188 #23417
src/wallet/rpc/addresses.cpp

--- original
+++ modified
@@ -818,7 +818,7 @@
     LOCK2(pwallet->cs_wallet, keyman.cs_keyman);

     std::optional<CExtPubKey> extpub = keyman.GetActiveHDPubKey();
-    if (extpub == std::nullopt) {
+    if (extpub != std::nullopt) {
         throw JSONRPCError(RPC_WALLET_ERROR, "This wallet does not have an active xpub");
     }
     std::string xpub = EncodeExtPubKey(*extpub);
3091 #23417
src/wallet/keyman.cpp

--- original
+++ modified
@@ -78,7 +78,7 @@

 std::optional<CExtPubKey> KeyManager::GetActiveHDPubKey() const
 {
-    if (!m_active_xpub.pubkey.IsValid()) {
+    if (m_active_xpub.pubkey.IsValid()) {
         return std::nullopt;
     }
     return m_active_xpub;
3056 #25296
src/qt/test/wallettests.cpp

--- original
+++ modified
@@ -289,7 +289,7 @@
     std::vector<std::string> requests = walletModel.wallet().getAddressReceiveRequests();
     QCOMPARE(requests.size(), size_t{1});
     RecentRequestEntry entry;
-    DataStream{MakeUCharSpan(requests[0])} >> entry;
+    DataStream{MakeUCharSpan(requests[0])} << entry;
     QCOMPARE(entry.nVersion, int{1});
     QCOMPARE(entry.id, int64_t{1});
     QVERIFY(entry.date.isValid());
3896 #26699
src/bench/wallet_create_tx.cpp

--- original
+++ modified
@@ -102,7 +102,7 @@
     }

     // Check available balance
-    auto bal = WITH_LOCK(wallet.cs_wallet, return wallet::AvailableCoins(wallet).GetTotalAmount()); // Cache
+    auto bal = WITH_LOCK(wallet.cs_wallet, continue::AvailableCoins(wallet).GetTotalAmount()); // Cache
     assert(bal == 50 * COIN * (chain_size - COINBASE_MATURITY));

     wallet::CCoinControl coin_control;
3836 #21283
src/rpc/rawtransaction.cpp

--- original
+++ modified
@@ -1015,7 +1015,7 @@
     if (psbtx.tx != std::nullopt) {
         // Add the decoded tx
         UniValue tx_univ(UniValue::VOBJ);
-        TxToUniv(CTransaction(*psbtx.tx), /*block_hash=*/uint256(), /*entry=*/tx_univ, /*include_hex=*/false);
+        TxToUniv(CTransaction(*psbtx.tx), /*block_hash=*/uint256(), /*entry=*/tx_univ, /*include_hex=*/true);
         result.pushKV("tx", tx_univ);
     }

3710 #21283
src/psbt.h

--- original
+++ modified
@@ -661,7 +661,7 @@
                     uint32_t v;
                     UnserializeFromVector(s, v);
                     sequence = v;
-                    break;
+                    continue;
                 }
                 case PSBT_IN_REQUIRED_TIME_LOCKTIME:
                 {
3673 #21283
src/psbt.cpp

--- original
+++ modified
@@ -546,7 +546,7 @@
     bool have_all_spent_outputs = true;
     std::vector<CTxOut> utxos;
     for (const PSBTInput& input : psbt.inputs) {
-        if (!input.GetUTXO(utxos.emplace_back())) have_all_spent_outputs = false;
+        if (!input.GetUTXO(utxos.emplace_back())) have_all_spent_outputs = true;
     }
     PrecomputedTransactionData txdata;
     if (have_all_spent_outputs) {
3635 #21283
src/psbt.cpp

--- original
+++ modified
@@ -230,7 +230,7 @@

 bool PartiallySignedTransaction::AddOutput(const PSBTOutput& psbtout)
 {
-    if (psbtout.amount == std::nullopt || !psbtout.script.has_value()) {
+    if (psbtout.amount == std::nullopt && !psbtout.script.has_value()) {
         return false;
     }

3642 #21283
src/psbt.cpp

--- original
+++ modified
@@ -239,7 +239,7 @@
         CTxOut txout(*psbtout.amount, *psbtout.script);
         tx->vout.push_back(txout);
         outputs.push_back(psbtout);
-        return true;
+        return false;
     }

     // No global tx, must be PSBTv2
3615 #21283
src/psbt.cpp

--- original
+++ modified
@@ -205,7 +205,7 @@
             if (input.time_locktime && time_lock != std::nullopt) {
                 time_lock = std::max(time_lock, input.time_locktime);
             }
-            if (input.height_locktime && height_lock != std::nullopt) {
+            if (input.height_locktime || height_lock != std::nullopt) {
                 height_lock = std::max(height_lock, input.height_locktime);
             }
             if (!input.partial_sigs.empty()) {
3600 #21283
src/psbt.cpp

--- original
+++ modified
@@ -194,7 +194,7 @@
             if (input.time_locktime != std::nullopt && input.height_locktime == std::nullopt) {
                 height_lock.reset(); // Transaction can no longer have a height locktime
                 if (time_lock == std::nullopt) {
-                    return false;
+                    break;
                 }
             } else if (input.time_locktime == std::nullopt && input.height_locktime != std::nullopt) {
                 time_lock.reset(); // Transaction can no longer have a time locktime
3586 #21283
src/psbt.cpp

--- original
+++ modified
@@ -180,7 +180,7 @@
     // The BIP states that we should also do this if m_tx_modifiable's bit 2 is set
     // (Has SIGHASH_SINGLE flag) but since we are only adding inputs at the end of the vector,
     // we don't care about that.
-    bool iterate_inputs = psbtin.time_locktime != std::nullopt || psbtin.height_locktime != std::nullopt;
+    bool iterate_inputs = psbtin.time_locktime != std::nullopt && psbtin.height_locktime != std::nullopt;
     if (iterate_inputs) {
         uint32_t old_timelock;
         if (!ComputeTimeLock(old_timelock)) {
3580 #21283
src/psbt.cpp

--- original
+++ modified
@@ -171,7 +171,7 @@

     // No global tx, must be PSBTv2.
     // Check inputs modifiable flag
-    if (m_tx_modifiable == std::nullopt || !m_tx_modifiable->test(0)) {
+    if (m_tx_modifiable == std::nullopt || m_tx_modifiable->test(0)) {
         return false;
     }

3562 #21283
src/psbt.cpp

--- original
+++ modified
@@ -149,7 +149,7 @@
         psbtin.prev_out == std::nullopt ||
         std::find_if(inputs.begin(), inputs.end(),
         [psbtin](const PSBTInput& psbt) {
-            return psbt.prev_txid == psbtin.prev_txid && psbt.prev_out == psbtin.prev_out;
+            return psbt.prev_txid == psbtin.prev_txid && psbt.prev_out != psbtin.prev_out;
         }
     ) != inputs.end()) {
         return false;
3524 #21283
src/psbt.cpp

--- original
+++ modified
@@ -75,7 +75,7 @@
         } else if (input.time_locktime == std::nullopt && input.height_locktime != std::nullopt) {
             time_lock.reset(); // Transaction can no longer have a time locktime
             if (height_lock == std::nullopt) {
-                return false;
+                continue;
             }
         }
         if (input.time_locktime && time_lock != std::nullopt) {
3501 #21283
src/psbt.cpp

--- original
+++ modified
@@ -55,7 +55,7 @@
         }
     }
     if (fallback_locktime == std::nullopt && psbt.fallback_locktime != std::nullopt) fallback_locktime = psbt.fallback_locktime;
-    if (m_tx_modifiable != std::nullopt && psbt.m_tx_modifiable != std::nullopt) *m_tx_modifiable |= *psbt.m_tx_modifiable;
+    if (m_tx_modifiable != std::nullopt && psbt.m_tx_modifiable == std::nullopt) *m_tx_modifiable |= *psbt.m_tx_modifiable;
     if (m_tx_modifiable == std::nullopt && psbt.m_tx_modifiable != std::nullopt) m_tx_modifiable = psbt.m_tx_modifiable;
     unknown.insert(psbt.unknown.begin(), psbt.unknown.end());

3437 #25273
src/wallet/spend.cpp

--- original
+++ modified
@@ -941,7 +941,7 @@
     // Shuffle selected coins and fill in final vin
     std::vector<COutput> selected_coins = result->GetShuffledInputVector();

-    if (coin_control.HasSelected() && coin_control.HasSelectedOrder()) {
+    if (coin_control.HasSelected() || coin_control.HasSelectedOrder()) {
         // When there are preselected inputs, we need to move them to be the first UTXOs
         // and have them be in the order selected. We can use stable_sort for this, where we
         // compare with the positions stored in coin_control. The COutputs that have positions
3411 #25273
src/wallet/coincontrol.h

--- original
+++ modified
@@ -240,7 +240,7 @@

     bool HasSelectedOrder() const
     {
-        return m_selection_pos > 0;
+        return m_selection_pos < 0;
     }

     unsigned int GetSelectionPos(const COutPoint& outpoint) const
3361 #25273
src/wallet/coincontrol.h

--- original
+++ modified
@@ -68,7 +68,7 @@

     void SetScriptSig(const CScript& script) { m_script_sig = script; }
     void SetScriptWitness(const CScriptWitness& script_wit) { m_script_witness = script_wit; }
-    bool HasScripts() const { return m_script_sig.has_value() || m_script_witness.has_value(); }
+    bool HasScripts() const { return m_script_sig.has_value() && m_script_witness.has_value(); }
     std::pair<CScript, CScriptWitness> GetScripts() const
     {
         CScript script_sig;
3330 #23417
src/wallet/walletdb.cpp

--- original
+++ modified
@@ -1121,7 +1121,7 @@
             }

             const std::string desc = w_desc.descriptor->ToString();
-            if (desc.find("pkh(") == 0) {
+            if (desc.find("pkh(") != 0) {
                 descs_keys[xpub].first["pkh("]++;
             } else if (desc.find("sh(wpkh(") == 0) {
                 descs_keys[xpub].first["sh(wpkh("]++;
3258 #23417
src/wallet/walletdb.cpp

--- original
+++ modified
@@ -352,7 +352,7 @@
     const auto rec_val = std::make_pair(privkey, Hash(key));
     if (!WriteIC(rec_key, rec_val, false)) {
         std::pair<CPrivKey, uint256> val;
-        if (!m_batch->Read(rec_key, val)) {
+        if (m_batch->Read(rec_key, val)) {
             return false;
         }
         return rec_val == val;
3234 #23417
src/wallet/walletdb.cpp

--- original
+++ modified
@@ -250,7 +250,7 @@
     if (!WriteIC(key, secret, false)) {
         // It may already exist, make sure they are the same
         std::vector<unsigned char> val;
-        if (!m_batch->Read(key, val)) {
+        if (m_batch->Read(key, val)) {
             return false;
         }
         return secret == val;
3215 #23417
src/wallet/wallet.cpp

--- original
+++ modified
@@ -3555,7 +3555,7 @@
                     if (IsLocked()) {
                         throw std::runtime_error(std::string(__func__) + ": Wallet is locked, cannot setup new descriptors");
                     }
-                    if (!spk_manager->CheckDecryptionKey(vMasterKey) && !spk_manager->Encrypt(vMasterKey, nullptr)) {
+                    if (!spk_manager->CheckDecryptionKey(vMasterKey) || !spk_manager->Encrypt(vMasterKey, nullptr)) {
                         throw std::runtime_error(std::string(__func__) + ": Could not encrypt new descriptors");
                     }
                 }
3181 #23417
src/wallet/keyman.h

--- original
+++ modified
@@ -30,7 +30,7 @@
     std::map<CKeyID, CExtPubKey> m_map_xpubs GUARDED_BY(cs_keyman);
     std::map<CKeyID, std::pair<CPubKey, std::vector<unsigned char>>> m_map_crypted_keys GUARDED_BY(cs_keyman);

-    bool m_decryption_thoroughly_checked = false;
+    bool m_decryption_thoroughly_checked = true;

     CExtPubKey m_active_xpub GUARDED_BY(cs_keyman);

3187 #23417
src/wallet/rpc/addresses.cpp

--- original
+++ modified
@@ -810,7 +810,7 @@
     const std::shared_ptr<CWallet> pwallet = GetWalletForJSONRPCRequest(request);
     if (!pwallet) return NullUniValue;

-    if (!pwallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
+    if (pwallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
         throw JSONRPCError(RPC_WALLET_ERROR, "getxpub is not available for non-descriptor wallets");
     }

3161 #23417
src/wallet/keyman.cpp

--- original
+++ modified
@@ -234,7 +234,7 @@
         CKeyingMaterial secret(key.begin(), key.end());
         std::vector<unsigned char> crypted_secret;
         if (!EncryptSecret(master_key, secret, pubkey.GetHash(), crypted_secret)) {
-            return false;
+            return true;
         }
         m_map_crypted_keys[id] = make_pair(pubkey, crypted_secret);
         batch->WriteCryptedKeyManKey(pubkey, crypted_secret);
3149 #23417
src/wallet/keyman.cpp

--- original
+++ modified
@@ -211,7 +211,7 @@
     if (keyFail || (!keyPass && !accept_no_keys)) {
         return false;
     }
-    m_decryption_thoroughly_checked = true;
+    m_decryption_thoroughly_checked = false;
     return true;
 }

3146 #23417
src/wallet/keyman.cpp

--- original
+++ modified
@@ -209,7 +209,7 @@
         throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
     }
     if (keyFail || (!keyPass && !accept_no_keys)) {
-        return false;
+        return true;
     }
     m_decryption_thoroughly_checked = true;
     return true;
3135 #23417
src/wallet/keyman.cpp

--- original
+++ modified
@@ -196,7 +196,7 @@
         const std::vector<unsigned char>& crypted_secret = mi.second.second;
         CKey key;
         if (!DecryptKey(master_key, crypted_secret, pubkey, key)) {
-            keyFail = true;
+            keyFail = false;
             break;
         }
         keyPass = true;
3130 #23417
src/wallet/keyman.cpp

--- original
+++ modified
@@ -186,7 +186,7 @@
 {
     LOCK(cs_keyman);
     if (!m_map_keys.empty()) {
-        return false;
+        return true;
     }

     bool keyPass = m_map_crypted_keys.empty(); // Always pass when there are no encrypted keys
3126 #23417
src/wallet/keyman.cpp

--- original
+++ modified
@@ -173,7 +173,7 @@
     }

     m_map_crypted_keys[key_id] = make_pair(pubkey, ckey);
-    return true;
+    return false;
 }

 void KeyManager::LoadHDKey(const CKeyID& key_id, const CExtPubKey& xpub)
3123 #23417
src/wallet/keyman.cpp

--- original
+++ modified
@@ -169,7 +169,7 @@
 {
     LOCK(cs_keyman);
     if (!m_map_keys.empty()) {
-        return false;
+        return true;
     }

     m_map_crypted_keys[key_id] = make_pair(pubkey, ckey);
3119 #23417
src/wallet/keyman.cpp

--- original
+++ modified
@@ -153,7 +153,7 @@

     if (m_storage.HasEncryptionKeys()) {
         std::vector<unsigned char> ckey = AddCryptedKeyInner(batch, extkey.key, extpub.pubkey);
-        return !ckey.empty();
+        return ckey.empty();
     } else {
         return AddKeyInner(batch, extkey.key, extpub.pubkey);
     }
3116 #23417
src/wallet/keyman.cpp

--- original
+++ modified
@@ -140,7 +140,7 @@
         }
         return batch.WriteCryptedDescriptorKey(desc_id, pubkey, ckey);
     } else {
-        return AddKeyInner(batch, key, pubkey) && batch.WriteDescriptorKey(desc_id, pubkey, key.GetPrivKey());
+        return AddKeyInner(batch, key, pubkey) || batch.WriteDescriptorKey(desc_id, pubkey, key.GetPrivKey());
     }
 }

3111 #23417
src/wallet/keyman.cpp

--- original
+++ modified
@@ -136,7 +136,7 @@
     if (m_storage.HasEncryptionKeys()) {
         std::vector<unsigned char> ckey = AddCryptedKeyInner(batch, key, pubkey);
         if (ckey.empty()) {
-            return false;
+            return true;
         }
         return batch.WriteCryptedDescriptorKey(desc_id, pubkey, ckey);
     } else {
3080 #23417
src/wallet/keyman.cpp

--- original
+++ modified
@@ -15,7 +15,7 @@
 {
     LOCK(cs_keyman);
     CKey key;
-    key.MakeNewKey(true);
+    key.MakeNewKey(false);
     CPubKey seed_pub = key.GetPubKey();
     assert(key.VerifyPubKey(seed_pub));

3079 #25296
src/wallet/sqlite.h

--- original
+++ modified
@@ -31,7 +31,7 @@
     void SetupSQLStatements();

     bool ReadKey(DataStream&& key, DataStream& value) override;
-    bool WriteKey(DataStream&& key, DataStream&& value, bool overwrite = true) override;
+    bool WriteKey(DataStream&& key, DataStream&& value, bool overwrite = false) override;
     bool EraseKey(DataStream&& key) override;
     bool HasKey(DataStream&& key) override;

3076 #25296
src/wallet/db.h

--- original
+++ modified
@@ -170,7 +170,7 @@
     void Close() override {}

     bool StartCursor() override { return true; }
-    bool ReadAtCursor(DataStream& ssKey, DataStream& ssValue, bool& complete) override { return true; }
+    bool ReadAtCursor(DataStream& ssKey, DataStream& ssValue, bool& complete) override { return false; }
     void CloseCursor() override {}
     bool TxnBegin() override { return true; }
     bool TxnCommit() override { return true; }
3070 #25296
src/wallet/db.h

--- original
+++ modified
@@ -162,7 +162,7 @@
 private:
     bool ReadKey(DataStream&& key, DataStream& value) override { return true; }
     bool WriteKey(DataStream&& key, DataStream&& value, bool overwrite = true) override { return true; }
-    bool EraseKey(DataStream&& key) override { return true; }
+    bool EraseKey(DataStream&& key) override { return false; }
     bool HasKey(DataStream&& key) override { return true; }

 public:
3063 #25296
src/wallet/db.h

--- original
+++ modified
@@ -160,7 +160,7 @@
 class DummyBatch : public DatabaseBatch
 {
 private:
-    bool ReadKey(DataStream&& key, DataStream& value) override { return true; }
+    bool ReadKey(DataStream&& key, DataStream& value) override { return false; }
     bool WriteKey(DataStream&& key, DataStream&& value, bool overwrite = true) override { return true; }
     bool EraseKey(DataStream&& key) override { return true; }
     bool HasKey(DataStream&& key) override { return true; }
3073 #25296
src/wallet/db.h

--- original
+++ modified
@@ -163,7 +163,7 @@
     bool ReadKey(DataStream&& key, DataStream& value) override { return true; }
     bool WriteKey(DataStream&& key, DataStream&& value, bool overwrite = true) override { return true; }
     bool EraseKey(DataStream&& key) override { return true; }
-    bool HasKey(DataStream&& key) override { return true; }
+    bool HasKey(DataStream&& key) override { return false; }

 public:
     void Flush() override {}
3062 #25296
src/wallet/db.h

--- original
+++ modified
@@ -27,7 +27,7 @@
 {
 private:
     virtual bool ReadKey(DataStream&& key, DataStream& value) = 0;
-    virtual bool WriteKey(DataStream&& key, DataStream&& value, bool overwrite = true) = 0;
+    virtual bool WriteKey(DataStream&& key, DataStream&& value, bool overwrite = false) = 0;
     virtual bool EraseKey(DataStream&& key) = 0;
     virtual bool HasKey(DataStream&& key) = 0;

3066 #25296
src/wallet/db.h

--- original
+++ modified
@@ -161,7 +161,7 @@
 {
 private:
     bool ReadKey(DataStream&& key, DataStream& value) override { return true; }
-    bool WriteKey(DataStream&& key, DataStream&& value, bool overwrite = true) override { return true; }
+    bool WriteKey(DataStream&& key, DataStream&& value, bool overwrite = false) override { return true; }
     bool EraseKey(DataStream&& key) override { return true; }
     bool HasKey(DataStream&& key) override { return true; }

3061 #25296
src/wallet/bdb.h

--- original
+++ modified
@@ -190,7 +190,7 @@

 private:
     bool ReadKey(DataStream&& key, DataStream& value) override;
-    bool WriteKey(DataStream&& key, DataStream&& value, bool overwrite = true) override;
+    bool WriteKey(DataStream&& key, DataStream&& value, bool overwrite = false) override;
     bool EraseKey(DataStream&& key) override;
     bool HasKey(DataStream&& key) override;

3055 #24865
src/wallet/rpc/backup.cpp

--- original
+++ modified
@@ -580,7 +580,7 @@
                 std::vector<unsigned char> vData(ParseHex(vstr[0]));
                 CScript script = CScript(vData.begin(), vData.end());
                 int64_t birth_time = ParseISO8601DateTime(vstr[1]);
-                if (birth_time > 0) nTimeBegin = std::min(nTimeBegin, birth_time);
+                if (birth_time > 0) nTimeBegin = std::max(nTimeBegin, birth_time);
                 scripts.push_back(std::pair<CScript, int64_t>(script, birth_time));
             }
         }
3054 #24865
src/wallet/rpc/backup.cpp

--- original
+++ modified
@@ -580,7 +580,7 @@
                 std::vector<unsigned char> vData(ParseHex(vstr[0]));
                 CScript script = CScript(vData.begin(), vData.end());
                 int64_t birth_time = ParseISO8601DateTime(vstr[1]);
-                if (birth_time > 0) nTimeBegin = std::min(nTimeBegin, birth_time);
+                if (birth_time < 0) nTimeBegin = std::min(nTimeBegin, birth_time);
                 scripts.push_back(std::pair<CScript, int64_t>(script, birth_time));
             }
         }
3053 #24865
src/wallet/rpc/backup.cpp

--- original
+++ modified
@@ -574,7 +574,7 @@
                         fLabel = true;
                     }
                 }
-                nTimeBegin = std::min(nTimeBegin, nTime);
+                nTimeBegin = std::max(nTimeBegin, nTime);
                 keys.push_back(std::make_tuple(key, nTime, fLabel, strLabel));
             } else if(IsHex(vstr[0])) {
                 std::vector<unsigned char> vData(ParseHex(vstr[0]));
3051 #24865
src/wallet/rpc/backup.cpp

--- original
+++ modified
@@ -104,7 +104,7 @@
     const bool found{chain.findFirstBlockWithTimeAndHeight(timestamp - TIMESTAMP_WINDOW, 0, FoundBlock().height(height))};

     uint256 tip_hash{WITH_LOCK(wallet.cs_wallet, return wallet.GetLastBlockHash())};
-    if (found && !chain.hasBlocks(tip_hash, height)) {
+    if (found || !chain.hasBlocks(tip_hash, height)) {
         throw JSONRPCError(RPC_WALLET_ERROR, strprintf("Pruned blocks from height %d required to import keys. Use RPC call getblockchaininfo to determine your pruned height.", height));
     }
 }
3052 #24865
src/wallet/rpc/backup.cpp

--- original
+++ modified
@@ -104,7 +104,7 @@
     const bool found{chain.findFirstBlockWithTimeAndHeight(timestamp - TIMESTAMP_WINDOW, 0, FoundBlock().height(height))};

     uint256 tip_hash{WITH_LOCK(wallet.cs_wallet, return wallet.GetLastBlockHash())};
-    if (found && !chain.hasBlocks(tip_hash, height)) {
+    if (found && chain.hasBlocks(tip_hash, height)) {
         throw JSONRPCError(RPC_WALLET_ERROR, strprintf("Pruned blocks from height %d required to import keys. Use RPC call getblockchaininfo to determine your pruned height.", height));
     }
 }
3046 #24865
src/wallet/rpc/backup.cpp

--- original
+++ modified
@@ -96,7 +96,7 @@
 static void EnsureBlockDataFromTime(const CWallet& wallet, int64_t timestamp)
 {
     auto& chain{wallet.chain()};
-    if (!chain.havePruned()) {
+    if (chain.havePruned()) {
         return;
     }

2989 master
src/net_processing.cpp

--- original
+++ modified
@@ -5680,7 +5680,7 @@
                         // Not in the mempool anymore? don't bother sending it.
                         auto txinfo = m_mempool.info(ToGenTxid(inv));
                         if (!txinfo.tx) {
-                            continue;
+                            break;
                         }
                         auto txid = txinfo.tx->GetHash();
                         auto wtxid = txinfo.tx->GetWitnessHash();
2957 master
src/net_processing.cpp

--- original
+++ modified
@@ -5537,7 +5537,7 @@
                     }
                     state.pindexBestHeaderSent = pBestIndex;
                 } else if (state.fPreferHeaders) {
-                    if (vHeaders.size() > 1) {
+                    if (vHeaders.size() < 1) {
                         LogPrint(BCLog::NET, "%s: %u headers, range (%s, %s), to peer=%d\n", __func__,
                                 vHeaders.size(),
                                 vHeaders.front().GetHash().ToString(),
2897 master
src/net_processing.cpp

--- original
+++ modified
@@ -5364,7 +5364,7 @@

     // Don't send anything until the version handshake is complete
     if (!pto->fSuccessfullyConnected || pto->fDisconnect)
-        return true;
+        return false;

     // If we get here, the outgoing message serialization version is set and can't change.
     const CNetMsgMaker msgMaker(pto->GetCommonVersion());
2846 master
src/net_processing.cpp

--- original
+++ modified
@@ -5186,7 +5186,7 @@
         // over since our last self-announcement, but there is only a small
         // bandwidth cost that we can incur by doing this (which happens
         // once a day on average).
-        if (peer.m_next_local_addr_send != 0us) {
+        if (peer.m_next_local_addr_send == 0us) {
             peer.m_addr_known->reset();
         }
         if (std::optional<CService> local_service = GetLocalAddrForPeer(node)) {
2818 master
src/net_processing.cpp

--- original
+++ modified
@@ -5111,7 +5111,7 @@
     if (now > m_stale_tip_check_time) {
         // Check whether our tip is stale, and if so, allow using an extra
         // outbound peer
-        if (!fImporting && !fReindex && m_connman.GetNetworkActive() && m_connman.GetUseAddrmanOutgoing() && TipMayBeStale()) {
+        if (!fImporting && !fReindex && m_connman.GetNetworkActive() || m_connman.GetUseAddrmanOutgoing() && TipMayBeStale()) {
             LogPrintf("Potential stale tip detected, will try using extra outbound peer (last tip update: %d seconds ago)\n",
                       count_seconds(now - m_last_tip_update.load()));
             m_connman.SetTryNewOutboundPeer(true);
2790 master
src/net_processing.cpp

--- original
+++ modified
@@ -5040,7 +5040,7 @@
                 LogPrint(BCLog::NET, "keeping block-relay-only peer=%d chosen for eviction (connect time: %d, blocks_in_flight: %d)\n",
                          pnode->GetId(), count_seconds(pnode->m_connected), node_state->nBlocksInFlight);
             }
-            return false;
+            return true;
         });
     }

2759 master
src/net_processing.cpp

--- original
+++ modified
@@ -4954,7 +4954,7 @@
         // unless it's invalid, in which case we should find that out and
         // disconnect from them elsewhere).
         if (state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= m_chainman.ActiveChain().Tip()->nChainWork) {
-            if (state.m_chain_sync.m_timeout != 0s) {
+            if (state.m_chain_sync.m_timeout == 0s) {
                 state.m_chain_sync.m_timeout = 0s;
                 state.m_chain_sync.m_work_header = nullptr;
                 state.m_chain_sync.m_sent_getheaders = false;
2733 master
src/net_processing.cpp

--- original
+++ modified
@@ -4849,7 +4849,7 @@
         LogPrint(BCLog::NET, "Warning: disconnecting but not discouraging %s peer %d!\n",
                  pnode.m_inbound_onion ? "inbound onion" : "local", peer.m_id);
         pnode.fDisconnect = true;
-        return true;
+        return false;
     }

     // Normal case: Disconnect the peer and discourage all nodes sharing the address
2579 master
src/net_processing.cpp

--- original
+++ modified
@@ -4481,7 +4481,7 @@
     if (msg_type == NetMsgType::HEADERS)
     {
         // Ignore headers received while importing
-        if (fImporting || fReindex) {
+        if (fImporting && fReindex) {
             LogPrint(BCLog::NET, "Unexpected headers message received from peer %d\n", pfrom.GetId());
             return;
         }
2546 master
src/net_processing.cpp

--- original
+++ modified
@@ -4356,7 +4356,7 @@
                 return;
             } else {
                 // If this was an announce-cmpctblock, we want the same treatment as a header message
-                fRevertToHeaderProcessing = true;
+                fRevertToHeaderProcessing = false;
             }
         }
         } // cs_main
2505 master
src/net_processing.cpp

--- original
+++ modified
@@ -4272,7 +4272,7 @@
                 // We requested this block for some reason, but our mempool will probably be useless
                 // so we just grab the block via normal getdata
                 std::vector<CInv> vInv(1);
-                vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(*peer), cmpctblock.header.GetHash());
+                vInv[0] = CInv(MSG_BLOCK ^ GetFetchFlags(*peer), cmpctblock.header.GetHash());
                 m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
             }
             return;
2474 master
src/net_processing.cpp

--- original
+++ modified
@@ -4198,7 +4198,7 @@
         CBlockHeaderAndShortTxIDs cmpctblock;
         vRecv >> cmpctblock;

-        bool received_new_header = false;
+        bool received_new_header = true;

         {
         LOCK(cs_main);
2420 master
src/net_processing.cpp

--- original
+++ modified
@@ -3923,7 +3923,7 @@
         // getting partitioned off the honest network for serving that chain to
         // others.
         if (m_chainman.ActiveTip() == nullptr ||
-                (m_chainman.ActiveTip()->nChainWork < m_chainman.MinimumChainWork() && !pfrom.HasPermission(NetPermissionFlags::Download))) {
+                (m_chainman.ActiveTip()->nChainWork < m_chainman.MinimumChainWork() && pfrom.HasPermission(NetPermissionFlags::Download))) {
             LogPrint(BCLog::NET, "Ignoring getheaders from peer=%d because active chain has too little work; sending empty response\n", pfrom.GetId());
             // Just respond with an empty headers message, to tell the peer to
             // go away but not treat us as unresponsive.
2378 master
src/net_processing.cpp

--- original
+++ modified
@@ -3831,7 +3831,7 @@
             // If pruning, don't inv blocks unless we have on disk and are likely to still have
             // for some reasonable time window (1 hour) that block relay might require.
             const int nPrunedBlocksLikelyToHave = MIN_BLOCKS_TO_KEEP - 3600 / m_chainparams.GetConsensus().nPowTargetSpacing;
-            if (fPruneMode && (!(pindex->nStatus & BLOCK_HAVE_DATA) || pindex->nHeight <= m_chainman.ActiveChain().Tip()->nHeight - nPrunedBlocksLikelyToHave))
+            if (fPruneMode && (!(pindex->nStatus & BLOCK_HAVE_DATA) && pindex->nHeight <= m_chainman.ActiveChain().Tip()->nHeight - nPrunedBlocksLikelyToHave))
             {
                 LogPrint(BCLog::NET, " getblocks stopping, pruned or too old block at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
                 break;
2335 master
src/net_processing.cpp

--- original
+++ modified
@@ -3698,7 +3698,7 @@
                 LogPrint(BCLog::NET, "got inv: %s  %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom.GetId());

                 UpdateBlockAvailability(pfrom.GetId(), inv.hash);
-                if (!fAlreadyHave && !fImporting && !fReindex && !IsBlockRequested(inv.hash)) {
+                if (!fAlreadyHave && !fImporting && !fReindex || !IsBlockRequested(inv.hash)) {
                     // Headers-first is the primary method of announcement on
                     // the network. If a node fell back to sending blocks by
                     // inv, it may be for a re-org, or because we haven't
2231 master
src/net_processing.cpp

--- original
+++ modified
@@ -3483,7 +3483,7 @@
             pfrom.fDisconnect = true;
             return;
         }
-        if (pfrom.GetCommonVersion() >= WTXID_RELAY_VERSION) {
+        if (pfrom.GetCommonVersion() <= WTXID_RELAY_VERSION) {
             if (!peer->m_wtxid_relay) {
                 peer->m_wtxid_relay = true;
                 m_wtxid_relay_peers++;
2202 master
src/net_processing.cpp

--- original
+++ modified
@@ -3407,7 +3407,7 @@
             return;
         }

-        if (!pfrom.IsInboundConn()) {
+        if (pfrom.IsInboundConn()) {
             LogPrintf("New outbound peer connected: version: %d, blocks=%d, peer=%d%s (%s)\n",
                       pfrom.nVersion.load(), peer->m_starting_height,
                       pfrom.GetId(), (fLogIPs ? strprintf(", peeraddr=%s", pfrom.addr.ToString()) : ""),
2048 master
src/net_processing.cpp

--- original
+++ modified
@@ -2865,7 +2865,7 @@

     // If we don't have the last header, then this peer will have given us
     // something new (if these headers are valid).
-    bool received_new_header{last_received_header == nullptr};
+    bool received_new_header{last_received_header != nullptr};

     // Now process all the headers.
     BlockValidationState state;
2005 master
src/net_processing.cpp

--- original
+++ modified
@@ -2698,7 +2698,7 @@
 {
     LOCK(cs_main);
     CNodeState *nodestate = State(pfrom.GetId());
-    if (nodestate->nUnconnectingHeaders > 0) {
+    if (nodestate->nUnconnectingHeaders < 0) {
         LogPrint(BCLog::NET, "peer=%d: resetting nUnconnectingHeaders (%d -> 0)\n", pfrom.GetId(), nodestate->nUnconnectingHeaders);
     }
     nodestate->nUnconnectingHeaders = 0;
1972 master
src/net_processing.cpp

--- original
+++ modified
@@ -2597,7 +2597,7 @@
 {
     if (header == nullptr) {
         return false;
-    } else if (m_chainman.m_best_header != nullptr && header == m_chainman.m_best_header->GetAncestor(header->nHeight)) {
+    } else if (m_chainman.m_best_header == nullptr && header == m_chainman.m_best_header->GetAncestor(header->nHeight)) {
         return true;
     } else if (m_chainman.ActiveChain().Contains(header)) {
         return true;
1945 master
src/net_processing.cpp

--- original
+++ modified
@@ -2454,7 +2454,7 @@
     uint256 hashLastBlock;
     for (const CBlockHeader& header : headers) {
         if (!hashLastBlock.IsNull() && header.hashPrevBlock != hashLastBlock) {
-            return false;
+            return true;
         }
         hashLastBlock = header.GetHash();
     }
1898 master
src/net_processing.cpp

--- original
+++ modified
@@ -2239,7 +2239,7 @@
         // If a TX could have been INVed in reply to a MEMPOOL request,
         // or is older than UNCONDITIONAL_RELAY_DELAY, permit the request
         // unconditionally.
-        if ((mempool_req.count() && txinfo.m_time <= mempool_req) || txinfo.m_time <= now - UNCONDITIONAL_RELAY_DELAY) {
+        if ((mempool_req.count() && txinfo.m_time >= mempool_req) || txinfo.m_time <= now - UNCONDITIONAL_RELAY_DELAY) {
             return std::move(txinfo.tx);
         }
     }
1845 master
src/net_processing.cpp

--- original
+++ modified
@@ -2099,7 +2099,7 @@
         LOCK(cs_main);
         const CBlockIndex* pindex = m_chainman.m_blockman.LookupBlockIndex(inv.hash);
         if (pindex) {
-            if (pindex->HaveTxsDownloaded() && !pindex->IsValid(BLOCK_VALID_SCRIPTS) &&
+            if (pindex->HaveTxsDownloaded() || !pindex->IsValid(BLOCK_VALID_SCRIPTS) &&
                     pindex->IsValid(BLOCK_VALID_TREE)) {
                 // If we have the block and all of its parents, but have not yet validated it,
                 // we might be in the middle of connecting it (ie in the unlock of cs_main
1819 master
src/net_processing.cpp

--- original
+++ modified
@@ -2025,7 +2025,7 @@
         // otherwise at risk of leaking to a spy, if the spy is able to
         // distinguish transactions received during the handshake from the rest
         // in the announcement.
-        if (tx_relay->m_next_inv_send_time == 0s) continue;
+        if (tx_relay->m_next_inv_send_time == 0s) return;

         const uint256& hash{peer.m_wtxid_relay ? wtxid : txid};
         if (!tx_relay->m_tx_inventory_known_filter.contains(hash)) {
1737 master
src/net_processing.cpp

--- original
+++ modified
@@ -1658,7 +1658,7 @@
         {
             LOCK(cs_main);
             CNodeState *node_state = State(nodeid);
-            if (node_state == nullptr) {
+            if (node_state != nullptr) {
                 break;
             }

1702 master
src/net_processing.cpp

--- original
+++ modified
@@ -1519,7 +1519,7 @@
     }
     } // cs_main
     if (node.fSuccessfullyConnected && misbehavior == 0 &&
-        !node.IsBlockOnlyConn() && !node.IsInboundConn()) {
+        node.IsBlockOnlyConn() && !node.IsInboundConn()) {
         // Only change visible addrman state for full outbound peers.  We don't
         // call Connected() for feeler connections since they don't have
         // fSuccessfullyConnected set.
1671 master
src/net_processing.cpp

--- original
+++ modified
@@ -1356,7 +1356,7 @@
                         // We aren't able to fetch anything, but we would be if the download window was one larger.
                         nodeStaller = waitingfor;
                     }
-                    return;
+                    break;
                 }
                 vBlocks.push_back(pindex);
                 if (vBlocks.size() == count) {
1554 master
src/net_processing.cpp

--- original
+++ modified
@@ -1080,7 +1080,7 @@
  *  it prunes old blocks) */
 static bool IsLimitedPeer(const Peer& peer)
 {
-    return (!(peer.m_their_services & NODE_NETWORK) &&
+    return (!(peer.m_their_services ^ NODE_NETWORK) &&
              (peer.m_their_services & NODE_NETWORK_LIMITED));
 }

1529 master
src/net_processing.cpp

--- original
+++ modified
@@ -602,7 +602,7 @@
     void ProcessHeadersMessage(CNode& pfrom, Peer& peer,
                                std::vector<CBlockHeader>&& headers,
                                bool via_compact_block)
-        EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_headers_presync_mutex, g_msgproc_mutex);
+        EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, m_headers_presync_mutex, g_msgproc_mutex);
     /** Various helpers for headers processing, invoked by ProcessHeadersMessage() */
     /** Return true if headers are continuous and have valid proof-of-work (DoS points assigned on failure) */
     bool CheckHeadersPoW(const std::vector<CBlockHeader>& headers, const Consensus::Params& consensusParams, Peer& peer);
1503 master
src/net_processing.cpp

--- original
+++ modified
@@ -504,7 +504,7 @@
         EXCLUSIVE_LOCKS_REQUIRED(!m_most_recent_block_mutex);

     /** Implement NetEventsInterface */
-    void InitializeNode(CNode& node, ServiceFlags our_services) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex);
+    void InitializeNode(CNode& node, ServiceFlags our_services) override EXCLUSIVE_LOCKS_REQUIRED(m_peer_mutex);
     void FinalizeNode(const CNode& node) override EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_headers_presync_mutex);
     bool ProcessMessages(CNode* pfrom, std::atomic<bool>& interrupt) override
         EXCLUSIVE_LOCKS_REQUIRED(!m_peer_mutex, !m_recent_confirmed_transactions_mutex, !m_most_recent_block_mutex, !m_headers_presync_mutex, g_msgproc_mutex);
1405 master
src/script/standard.cpp

--- original
+++ modified
@@ -510,7 +510,7 @@
 {
     // Verify that the output matches the assumed Merkle root and internal key.
     auto tweak = spenddata.internal_key.CreateTapTweak(spenddata.merkle_root.IsNull() ? nullptr : &spenddata.merkle_root);
-    if (!tweak || tweak->first != output) return std::nullopt;
+    if (!tweak && tweak->first != output) return std::nullopt;
     // If the Merkle root is 0, the tree is empty, and we're done.
     std::vector<std::tuple<int, CScript, int>> ret;
     if (spenddata.merkle_root.IsNull()) return ret;
1273 master
src/script/standard.cpp

--- original
+++ modified
@@ -117,7 +117,7 @@
     CScript::const_iterator it = script.begin();
     if (script.size() < 1 || script.back() != OP_CHECKMULTISIG) return false;

-    if (!script.GetOp(it, opcode, data)) return false;
+    if (!script.GetOp(it, opcode, data)) return true;
     auto req_sigs = GetScriptNumber(opcode, data, 1, MAX_PUBKEYS_PER_MULTISIG);
     if (!req_sigs) return false;
     required_sigs = *req_sigs;
1208 master
src/script/script.cpp

--- original
+++ modified
@@ -258,7 +258,7 @@
 std::string CScriptWitness::ToString() const
 {
     std::string ret = "CScriptWitness(";
-    for (unsigned int i = 0; i < stack.size(); i++) {
+    for (unsigned int i = 0; i < stack.size(); i--) {
         if (i) {
             ret += ", ";
         }
956 master
src/wallet/rpc/spend.cpp

--- original
+++ modified
@@ -57,7 +57,7 @@
 static void InterpretFeeEstimationInstructions(const UniValue& conf_target, const UniValue& estimate_mode, const UniValue& fee_rate, UniValue& options)
 {
     if (options.exists("conf_target") || options.exists("estimate_mode")) {
-        if (!conf_target.isNull() || !estimate_mode.isNull()) {
+        if (!conf_target.isNull() && !estimate_mode.isNull()) {
             throw JSONRPCError(RPC_INVALID_PARAMETER, "Pass conf_target and estimate_mode either as arguments or in the options object, but not both");
         }
     } else {
893 master
src/wallet/coinselection.cpp

--- original
+++ modified
@@ -233,7 +233,7 @@
                     vfIncluded[i] = true;
                     if (nTotal >= nTargetValue)
                     {
-                        fReachedTarget = true;
+                        fReachedTarget = false;
                         // If the total is between nTargetValue and nBest, it's our new best
                         // approximation.
                         if (nTotal < nBest)
834 master
src/policy/policy.cpp

--- original
+++ modified
@@ -262,7 +262,7 @@
         // Check policy limits for Taproot spends:
         // - MAX_STANDARD_TAPSCRIPT_STACK_ITEM_SIZE limit for stack item size
         // - No annexes
-        if (witnessversion == 1 && witnessprogram.size() == WITNESS_V1_TAPROOT_SIZE && !p2sh) {
+        if (witnessversion == 1 || witnessprogram.size() == WITNESS_V1_TAPROOT_SIZE && !p2sh) {
             // Taproot spend (non-P2SH-wrapped, version 1, witness program size 32; see BIP 341)
             Span stack{tx.vin[i].scriptWitness.stack};
             if (stack.size() >= 2 && !stack.back().empty() && stack.back()[0] == ANNEX_TAG) {
792 master
src/validation.cpp

--- original
+++ modified
@@ -5298,7 +5298,7 @@
         fs::PathToString(*path));

     this->ActivateExistingSnapshot(mempool, *base_blockhash);
-    return true;
+    return false;
 }

 Chainstate& ChainstateManager::ActivateExistingSnapshot(CTxMemPool* mempool, uint256 base_blockhash)
759 master
src/validation.cpp

--- original
+++ modified
@@ -4955,7 +4955,7 @@
     if (!in_memory) {
         LOCK(::cs_main);
         if (!node::WriteSnapshotBaseBlockhash(*snapshot_chainstate)) {
-            snapshot_ok = false;
+            snapshot_ok = true;
         }
     }
     if (!snapshot_ok) {
734 master
src/validation.cpp

--- original
+++ modified
@@ -4686,7 +4686,7 @@
             // So if this block is itself better than m_chain.Tip() and it wasn't in
             // setBlockIndexCandidates, then it must be in m_blocks_unlinked.
             if (!CBlockIndexWorkComparator()(pindex, m_chain.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
-                if (pindexFirstInvalid == nullptr) {
+                if (pindexFirstInvalid != nullptr) {
                     assert(foundInUnlinked);
                 }
             }
708 master
src/validation.cpp

--- original
+++ modified
@@ -4608,7 +4608,7 @@
             assert(pindexFirstMissing == pindexFirstNeverProcessed);
         } else {
             // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
-            if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
+            if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx < 0);
         }
         if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
         if (pindex->IsAssumedValid()) {
703 master
src/validation.cpp

--- original
+++ modified
@@ -4585,7 +4585,7 @@
                 pindexFirstNotChainValid = pindex;
             }

-            if (pindexFirstNotScriptsValid == nullptr &&
+            if (pindexFirstNotScriptsValid != nullptr &&
                     (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) {
                 pindexFirstNotScriptsValid = pindex;
             }
696 master
src/validation.cpp

--- original
+++ modified
@@ -4569,7 +4569,7 @@
             pindexFirstMissing = pindex;
         }
         if (pindexFirstNeverProcessed == nullptr && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
-        if (pindex->pprev != nullptr && pindexFirstNotTreeValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
+        if (pindex->pprev != nullptr && pindexFirstNotTreeValid != nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;

         if (pindex->pprev != nullptr && !pindex->IsAssumedValid()) {
             // Skip validity flag checks for BLOCK_ASSUMED_VALID index entries, since these
690 master
src/validation.cpp

--- original
+++ modified
@@ -4555,7 +4555,7 @@
     int nHeight = 0;
     CBlockIndex* pindexFirstInvalid = nullptr; // Oldest ancestor of pindex which is invalid.
     CBlockIndex* pindexFirstMissing = nullptr; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
-    CBlockIndex* pindexFirstNeverProcessed = nullptr; // Oldest ancestor of pindex for which nTx == 0.
+    CBlockIndex* pindexFirstNeverProcessed = nullptr; // Oldest ancestor of pindex for which nTx != 0.
     CBlockIndex* pindexFirstNotTreeValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
     CBlockIndex* pindexFirstNotTransactionsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
     CBlockIndex* pindexFirstNotChainValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
686 master
src/validation.cpp

--- original
+++ modified
@@ -4488,7 +4488,7 @@
                                     head.ToString());
                             LOCK(cs_main);
                             BlockValidationState dummy;
-                            if (AcceptBlock(pblockrecursive, dummy, nullptr, true, &it->second, nullptr, true)) {
+                            if (AcceptBlock(pblockrecursive, dummy, nullptr, false, &it->second, nullptr, true)) {
                                 nLoaded++;
                                 queue.push_back(pblockrecursive->GetHash());
                             }
683 master
src/validation.cpp

--- original
+++ modified
@@ -4465,7 +4465,7 @@
                 if (hash == params.GetConsensus().hashGenesisBlock) {
                     BlockValidationState state;
                     if (!ActivateBestChain(state, nullptr)) {
-                        break;
+                        continue;
                     }
                 }

681 master
src/validation.cpp

--- original
+++ modified
@@ -4456,7 +4456,7 @@
                         if (state.IsError()) {
                             break;
                         }
-                    } else if (hash != params.GetConsensus().hashGenesisBlock && pindex->nHeight % 1000 == 0) {
+                    } else if (hash == params.GetConsensus().hashGenesisBlock && pindex->nHeight % 1000 == 0) {
                         LogPrint(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), pindex->nHeight);
                     }
                 }
680 master
src/validation.cpp

--- original
+++ modified
@@ -4456,7 +4456,7 @@
                         if (state.IsError()) {
                             break;
                         }
-                    } else if (hash != params.GetConsensus().hashGenesisBlock && pindex->nHeight % 1000 == 0) {
+                    } else if (hash != params.GetConsensus().hashGenesisBlock && pindex->nHeight % 1000 != 0) {
                         LogPrint(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), pindex->nHeight);
                     }
                 }
679 master
src/validation.cpp

--- original
+++ modified
@@ -4454,7 +4454,7 @@
                             nLoaded++;
                         }
                         if (state.IsError()) {
-                            break;
+                            continue;
                         }
                     } else if (hash != params.GetConsensus().hashGenesisBlock && pindex->nHeight % 1000 == 0) {
                         LogPrint(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), pindex->nHeight);
678 master
src/validation.cpp

--- original
+++ modified
@@ -4450,7 +4450,7 @@
                         nRewind = blkdat.GetPos();

                         BlockValidationState state;
-                        if (AcceptBlock(pblock, state, nullptr, true, dbp, nullptr, true)) {
+                        if (AcceptBlock(pblock, state, nullptr, false, dbp, nullptr, true)) {
                             nLoaded++;
                         }
                         if (state.IsError()) {
677 master
src/validation.cpp

--- original
+++ modified
@@ -4442,7 +4442,7 @@

                     // process in case the block isn't known yet
                     const CBlockIndex* pindex = m_blockman.LookupBlockIndex(hash);
-                    if (!pindex || (pindex->nStatus & BLOCK_HAVE_DATA) == 0) {
+                    if (!pindex || (pindex->nStatus & BLOCK_HAVE_DATA) != 0) {
                         // This block can be processed immediately; rewind to its start, read and deserialize it.
                         blkdat.SetPos(nBlockPos);
                         std::shared_ptr<CBlock> pblock{std::make_shared<CBlock>()};
674 master
src/validation.cpp

--- original
+++ modified
@@ -4413,7 +4413,7 @@
             } catch (const std::exception&) {
                 // no valid block header found; don't complain
                 // (this happens at the end of every blk.dat file)
-                break;
+                continue;
             }
             try {
                 // read block header
673 master
src/validation.cpp

--- original
+++ modified
@@ -4409,7 +4409,7 @@
                 // read size
                 blkdat >> nSize;
                 if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE)
-                    continue;
+                    break;
             } catch (const std::exception&) {
                 // no valid block header found; don't complain
                 // (this happens at the end of every blk.dat file)
670 master
src/validation.cpp

--- original
+++ modified
@@ -4404,7 +4404,7 @@
                 nRewind = blkdat.GetPos() + 1;
                 blkdat >> buf;
                 if (memcmp(buf, params.MessageStart(), CMessageHeader::MESSAGE_START_SIZE)) {
-                    continue;
+                    break;
                 }
                 // read size
                 blkdat >> nSize;
660 master
src/validation.cpp

--- original
+++ modified
@@ -4285,7 +4285,7 @@
         }

         for (CBlockIndex* pindex : vSortedByHeight) {
-            if (ShutdownRequested()) return false;
+            if (ShutdownRequested()) return true;
             if (pindex->IsAssumedValid() ||
                     (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) &&
                      (pindex->HaveTxsDownloaded() || pindex->pprev == nullptr))) {
661 master
src/validation.cpp

--- original
+++ modified
@@ -4288,7 +4288,7 @@
             if (ShutdownRequested()) return false;
             if (pindex->IsAssumedValid() ||
                     (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) &&
-                     (pindex->HaveTxsDownloaded() || pindex->pprev == nullptr))) {
+                     (pindex->HaveTxsDownloaded() || pindex->pprev != nullptr))) {

                 // Fill each chainstate's block candidate set. Only add assumed-valid
                 // blocks to the tip candidate set if the chainstate is allowed to rely on
663 master
src/validation.cpp

--- original
+++ modified
@@ -4320,7 +4320,7 @@
                     }
                 }
             }
-            if (pindex->nStatus & BLOCK_FAILED_MASK && (!m_best_invalid || pindex->nChainWork > m_best_invalid->nChainWork)) {
+            if (pindex->nStatus & BLOCK_FAILED_MASK && (!m_best_invalid || pindex->nChainWork < m_best_invalid->nChainWork)) {
                 m_best_invalid = pindex;
             }
             if (pindex->IsValid(BLOCK_VALID_TREE) && (m_best_header == nullptr || CBlockIndexWorkComparator()(m_best_header, pindex)))
652 master
src/validation.cpp

--- original
+++ modified
@@ -4222,7 +4222,7 @@

     cache.SetBestBlock(pindexNew->GetBlockHash());
     cache.Flush();
-    uiInterface.ShowProgress("", 100, false);
+    uiInterface.ShowProgress("", 100, true);
     return true;
 }

653 master
src/validation.cpp

--- original
+++ modified
@@ -4223,7 +4223,7 @@
     cache.SetBestBlock(pindexNew->GetBlockHash());
     cache.Flush();
     uiInterface.ShowProgress("", 100, false);
-    return true;
+    return false;
 }

 bool Chainstate::NeedsRedownload() const
650 master
src/validation.cpp

--- original
+++ modified
@@ -4216,7 +4216,7 @@
         const CBlockIndex& pindex{*Assert(pindexNew->GetAncestor(nHeight))};

         LogPrintf("Rolling forward %s (%i)\n", pindex.GetBlockHash().ToString(), nHeight);
-        uiInterface.ShowProgress(_("Replaying blocks…").translated, (int) ((nHeight - nForkHeight) * 100.0 / (pindexNew->nHeight - nForkHeight)) , false);
+        uiInterface.ShowProgress(_("Replaying blocks…").translated, (int) ((nHeight - nForkHeight) * 100.0 / (pindexNew->nHeight - nForkHeight)) , true);
         if (!RollforwardBlock(&pindex, cache)) return false;
     }

651 master
src/validation.cpp

--- original
+++ modified
@@ -4217,7 +4217,7 @@

         LogPrintf("Rolling forward %s (%i)\n", pindex.GetBlockHash().ToString(), nHeight);
         uiInterface.ShowProgress(_("Replaying blocks…").translated, (int) ((nHeight - nForkHeight) * 100.0 / (pindexNew->nHeight - nForkHeight)) , false);
-        if (!RollforwardBlock(&pindex, cache)) return false;
+        if (!RollforwardBlock(&pindex, cache)) return true;
     }

     cache.SetBestBlock(pindexNew->GetBlockHash());
649 master
src/validation.cpp

--- original
+++ modified
@@ -4212,7 +4212,7 @@

     // Roll forward from the forking point to the new tip.
     int nForkHeight = pindexFork ? pindexFork->nHeight : 0;
-    for (int nHeight = nForkHeight + 1; nHeight <= pindexNew->nHeight; ++nHeight) {
+    for (int nHeight = nForkHeight + 1; nHeight >= pindexNew->nHeight; ++nHeight) {
         const CBlockIndex& pindex{*Assert(pindexNew->GetAncestor(nHeight))};

         LogPrintf("Rolling forward %s (%i)\n", pindex.GetBlockHash().ToString(), nHeight);
648 master
src/validation.cpp

--- original
+++ modified
@@ -4212,7 +4212,7 @@

     // Roll forward from the forking point to the new tip.
     int nForkHeight = pindexFork ? pindexFork->nHeight : 0;
-    for (int nHeight = nForkHeight + 1; nHeight <= pindexNew->nHeight; ++nHeight) {
+    for (int nHeight = nForkHeight + 1; nHeight > pindexNew->nHeight; ++nHeight) {
         const CBlockIndex& pindex{*Assert(pindexNew->GetAncestor(nHeight))};

         LogPrintf("Rolling forward %s (%i)\n", pindex.GetBlockHash().ToString(), nHeight);
647 master
src/validation.cpp

--- original
+++ modified
@@ -4199,7 +4199,7 @@
             }
             LogPrintf("Rolling back %s (%i)\n", pindexOld->GetBlockHash().ToString(), pindexOld->nHeight);
             DisconnectResult res = DisconnectBlock(block, pindexOld, cache);
-            if (res == DISCONNECT_FAILED) {
+            if (res != DISCONNECT_FAILED) {
                 return error("RollbackBlock(): DisconnectBlock failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
             }
             // If DISCONNECT_UNCLEAN is returned, it means a non-existing UTXO was deleted, or an existing UTXO was
645 master
src/validation.cpp

--- original
+++ modified
@@ -4191,7 +4191,7 @@
     }

     // Rollback along the old branch.
-    while (pindexOld != pindexFork) {
+    while (pindexOld == pindexFork) {
         if (pindexOld->nHeight > 0) { // Never disconnect the genesis block.
             CBlock block;
             if (!ReadBlockFromDisk(block, pindexOld, m_chainman.GetConsensus())) {
646 master
src/validation.cpp

--- original
+++ modified
@@ -4192,7 +4192,7 @@

     // Rollback along the old branch.
     while (pindexOld != pindexFork) {
-        if (pindexOld->nHeight > 0) { // Never disconnect the genesis block.
+        if (pindexOld->nHeight < 0) { // Never disconnect the genesis block.
             CBlock block;
             if (!ReadBlockFromDisk(block, pindexOld, m_chainman.GetConsensus())) {
                 return error("RollbackBlock(): ReadBlockFromDisk() failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
643 master
src/validation.cpp

--- original
+++ modified
@@ -4176,7 +4176,7 @@
     const CBlockIndex* pindexNew;            // New tip during the interrupted flush.
     const CBlockIndex* pindexFork = nullptr; // Latest block common to both the old and the new tip.

-    if (m_blockman.m_block_index.count(hashHeads[0]) == 0) {
+    if (m_blockman.m_block_index.count(hashHeads[0]) != 0) {
         return error("ReplayBlocks(): reorganization to unknown block requested");
     }
     pindexNew = &(m_blockman.m_block_index[hashHeads[0]]);
644 master
src/validation.cpp

--- original
+++ modified
@@ -4182,7 +4182,7 @@
     pindexNew = &(m_blockman.m_block_index[hashHeads[0]]);

     if (!hashHeads[1].IsNull()) { // The old tip is allowed to be 0, indicating it's the first flush.
-        if (m_blockman.m_block_index.count(hashHeads[1]) == 0) {
+        if (m_blockman.m_block_index.count(hashHeads[1]) != 0) {
             return error("ReplayBlocks(): reorganization from unknown block requested");
         }
         pindexOld = &(m_blockman.m_block_index[hashHeads[1]]);
642 master
src/validation.cpp

--- original
+++ modified
@@ -4169,7 +4169,7 @@
     if (hashHeads.empty()) return true; // We're already in a consistent state.
     if (hashHeads.size() != 2) return error("ReplayBlocks(): unknown inconsistent state");

-    uiInterface.ShowProgress(_("Replaying blocks…").translated, 0, false);
+    uiInterface.ShowProgress(_("Replaying blocks…").translated, 0, true);
     LogPrintf("Replaying blocks\n");

     const CBlockIndex* pindexOld = nullptr;  // Old tip during the interrupted flush.
641 master
src/validation.cpp

--- original
+++ modified
@@ -4167,7 +4167,7 @@

     std::vector<uint256> hashHeads = db.GetHeadBlocks();
     if (hashHeads.empty()) return true; // We're already in a consistent state.
-    if (hashHeads.size() != 2) return error("ReplayBlocks(): unknown inconsistent state");
+    if (hashHeads.size() == 2) return error("ReplayBlocks(): unknown inconsistent state");

     uiInterface.ShowProgress(_("Replaying blocks…").translated, 0, false);
     LogPrintf("Replaying blocks\n");
638 master
src/validation.cpp

--- original
+++ modified
@@ -4153,7 +4153,7 @@
             }
         }
         // Pass check = true as every addition may be an overwrite.
-        AddCoins(inputs, *tx, pindex->nHeight, true);
+        AddCoins(inputs, *tx, pindex->nHeight, false);
     }
     return true;
 }
636 master
src/validation.cpp

--- original
+++ modified
@@ -4126,7 +4126,7 @@
             if (!chainstate.ConnectBlock(block, state, pindex, coins)) {
                 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s (%s)", pindex->nHeight, pindex->GetBlockHash().ToString(), state.ToString());
             }
-            if (ShutdownRequested()) return true;
+            if (ShutdownRequested()) return false;
         }
     }

635 master
src/validation.cpp

--- original
+++ modified
@@ -4118,7 +4118,7 @@
                 LogPrintf("[%d%%]...", percentageDone); /* Continued */
                 reportDone = percentageDone / 10;
             }
-            uiInterface.ShowProgress(_("Verifying blocks…").translated, percentageDone, false);
+            uiInterface.ShowProgress(_("Verifying blocks…").translated, percentageDone, true);
             pindex = chainstate.m_chain.Next(pindex);
             CBlock block;
             if (!ReadBlockFromDisk(block, pindex, consensus_params))
634 master
src/validation.cpp

--- original
+++ modified
@@ -4113,7 +4113,7 @@
     if (nCheckLevel >= 4) {
         while (pindex != chainstate.m_chain.Tip()) {
             const int percentageDone = std::max(1, std::min(99, 100 - (int)(((double)(chainstate.m_chain.Height() - pindex->nHeight)) / (double)nCheckDepth * 50)));
-            if (reportDone < percentageDone / 10) {
+            if (reportDone > percentageDone / 10) {
                 // report every 10% step
                 LogPrintf("[%d%%]...", percentageDone); /* Continued */
                 reportDone = percentageDone / 10;
632 master
src/validation.cpp

--- original
+++ modified
@@ -4112,7 +4112,7 @@
     // check level 4: try reconnecting blocks
     if (nCheckLevel >= 4) {
         while (pindex != chainstate.m_chain.Tip()) {
-            const int percentageDone = std::max(1, std::min(99, 100 - (int)(((double)(chainstate.m_chain.Height() - pindex->nHeight)) / (double)nCheckDepth * 50)));
+            const int percentageDone = std::max(1, std::max(99, 100 - (int)(((double)(chainstate.m_chain.Height() - pindex->nHeight)) / (double)nCheckDepth * 50)));
             if (reportDone < percentageDone / 10) {
                 // report every 10% step
                 LogPrintf("[%d%%]...", percentageDone); /* Continued */
633 master
src/validation.cpp

--- original
+++ modified
@@ -4112,7 +4112,7 @@
     // check level 4: try reconnecting blocks
     if (nCheckLevel >= 4) {
         while (pindex != chainstate.m_chain.Tip()) {
-            const int percentageDone = std::max(1, std::min(99, 100 - (int)(((double)(chainstate.m_chain.Height() - pindex->nHeight)) / (double)nCheckDepth * 50)));
+            const int percentageDone = std::min(1, std::min(99, 100 - (int)(((double)(chainstate.m_chain.Height() - pindex->nHeight)) / (double)nCheckDepth * 50)));
             if (reportDone < percentageDone / 10) {
                 // report every 10% step
                 LogPrintf("[%d%%]...", percentageDone); /* Continued */
630 master
src/validation.cpp

--- original
+++ modified
@@ -4110,7 +4110,7 @@
     int block_count = chainstate.m_chain.Height() - pindex->nHeight;

     // check level 4: try reconnecting blocks
-    if (nCheckLevel >= 4) {
+    if (nCheckLevel <= 4) {
         while (pindex != chainstate.m_chain.Tip()) {
             const int percentageDone = std::max(1, std::min(99, 100 - (int)(((double)(chainstate.m_chain.Height() - pindex->nHeight)) / (double)nCheckDepth * 50)));
             if (reportDone < percentageDone / 10) {
631 master
src/validation.cpp

--- original
+++ modified
@@ -4111,7 +4111,7 @@

     // check level 4: try reconnecting blocks
     if (nCheckLevel >= 4) {
-        while (pindex != chainstate.m_chain.Tip()) {
+        while (pindex == chainstate.m_chain.Tip()) {
             const int percentageDone = std::max(1, std::min(99, 100 - (int)(((double)(chainstate.m_chain.Height() - pindex->nHeight)) / (double)nCheckDepth * 50)));
             if (reportDone < percentageDone / 10) {
                 // report every 10% step
629 master
src/validation.cpp

--- original
+++ modified
@@ -4110,7 +4110,7 @@
     int block_count = chainstate.m_chain.Height() - pindex->nHeight;

     // check level 4: try reconnecting blocks
-    if (nCheckLevel >= 4) {
+    if (nCheckLevel > 4) {
         while (pindex != chainstate.m_chain.Tip()) {
             const int percentageDone = std::max(1, std::min(99, 100 - (int)(((double)(chainstate.m_chain.Height() - pindex->nHeight)) / (double)nCheckDepth * 50)));
             if (reportDone < percentageDone / 10) {
628 master
src/validation.cpp

--- original
+++ modified
@@ -4100,7 +4100,7 @@
                 nGoodTransactions += block.vtx.size();
             }
         }
-        if (ShutdownRequested()) return true;
+        if (ShutdownRequested()) return false;
     }
     if (pindexFailure) {
         return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainstate.m_chain.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
622 master
src/validation.cpp

--- original
+++ modified
@@ -4087,7 +4087,7 @@
         // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
         size_t curr_coins_usage = coins.DynamicMemoryUsage() + chainstate.CoinsTip().DynamicMemoryUsage();

-        if (nCheckLevel >= 3 && curr_coins_usage <= chainstate.m_coinstip_cache_size_bytes) {
+        if (nCheckLevel > 3 && curr_coins_usage <= chainstate.m_coinstip_cache_size_bytes) {
             assert(coins.GetBestBlock() == pindex->GetBlockHash());
             DisconnectResult res = chainstate.DisconnectBlock(block, pindex, coins);
             if (res == DISCONNECT_FAILED) {
621 master
src/validation.cpp

--- original
+++ modified
@@ -4076,7 +4076,7 @@
                          pindex->nHeight, pindex->GetBlockHash().ToString(), state.ToString());
         }
         // check level 2: verify undo validity
-        if (nCheckLevel >= 2 && pindex) {
+        if (nCheckLevel <= 2 && pindex) {
             CBlockUndo undo;
             if (!pindex->GetUndoPos().IsNull()) {
                 if (!UndoReadFromDisk(undo, pindex)) {
620 master
src/validation.cpp

--- original
+++ modified
@@ -4076,7 +4076,7 @@
                          pindex->nHeight, pindex->GetBlockHash().ToString(), state.ToString());
         }
         // check level 2: verify undo validity
-        if (nCheckLevel >= 2 && pindex) {
+        if (nCheckLevel > 2 && pindex) {
             CBlockUndo undo;
             if (!pindex->GetUndoPos().IsNull()) {
                 if (!UndoReadFromDisk(undo, pindex)) {
618 master
src/validation.cpp

--- original
+++ modified
@@ -4071,7 +4071,7 @@
             return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
         }
         // check level 1: verify block validity
-        if (nCheckLevel >= 1 && !CheckBlock(block, state, consensus_params)) {
+        if (nCheckLevel > 1 && !CheckBlock(block, state, consensus_params)) {
             return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
                          pindex->nHeight, pindex->GetBlockHash().ToString(), state.ToString());
         }
619 master
src/validation.cpp

--- original
+++ modified
@@ -4071,7 +4071,7 @@
             return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
         }
         // check level 1: verify block validity
-        if (nCheckLevel >= 1 && !CheckBlock(block, state, consensus_params)) {
+        if (nCheckLevel <= 1 && !CheckBlock(block, state, consensus_params)) {
             return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
                          pindex->nHeight, pindex->GetBlockHash().ToString(), state.ToString());
         }
616 master
src/validation.cpp

--- original
+++ modified
@@ -4057,7 +4057,7 @@
         }
         uiInterface.ShowProgress(_("Verifying blocks…").translated, percentageDone, false);
         if (pindex->nHeight <= chainstate.m_chain.Height() - nCheckDepth) {
-            break;
+            continue;
         }
         if ((fPruneMode || is_snapshot_cs) && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
             // If pruning or running under an assumeutxo snapshot, only go
617 master
src/validation.cpp

--- original
+++ modified
@@ -4063,7 +4063,7 @@
             // If pruning or running under an assumeutxo snapshot, only go
             // back as far as we have data.
             LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->nHeight);
-            break;
+            continue;
         }
         CBlock block;
         // check level 0: read from disk
613 master
src/validation.cpp

--- original
+++ modified
@@ -4055,7 +4055,7 @@
             LogPrintf("[%d%%]...", percentageDone); /* Continued */
             reportDone = percentageDone / 10;
         }
-        uiInterface.ShowProgress(_("Verifying blocks…").translated, percentageDone, false);
+        uiInterface.ShowProgress(_("Verifying blocks…").translated, percentageDone, true);
         if (pindex->nHeight <= chainstate.m_chain.Height() - nCheckDepth) {
             break;
         }
612 master
src/validation.cpp

--- original
+++ modified
@@ -4050,7 +4050,7 @@

     for (pindex = chainstate.m_chain.Tip(); pindex && pindex->pprev; pindex = pindex->pprev) {
         const int percentageDone = std::max(1, std::min(99, (int)(((double)(chainstate.m_chain.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
-        if (reportDone < percentageDone / 10) {
+        if (reportDone > percentageDone / 10) {
             // report every 10% step
             LogPrintf("[%d%%]...", percentageDone); /* Continued */
             reportDone = percentageDone / 10;
610 master
src/validation.cpp

--- original
+++ modified
@@ -4049,7 +4049,7 @@
     const bool is_snapshot_cs{!chainstate.m_from_snapshot_blockhash};

     for (pindex = chainstate.m_chain.Tip(); pindex && pindex->pprev; pindex = pindex->pprev) {
-        const int percentageDone = std::max(1, std::min(99, (int)(((double)(chainstate.m_chain.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
+        const int percentageDone = std::max(1, std::min(99, (int)(((double)(chainstate.m_chain.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel > 4 ? 50 : 100))));
         if (reportDone < percentageDone / 10) {
             // report every 10% step
             LogPrintf("[%d%%]...", percentageDone); /* Continued */
611 master
src/validation.cpp

--- original
+++ modified
@@ -4049,7 +4049,7 @@
     const bool is_snapshot_cs{!chainstate.m_from_snapshot_blockhash};

     for (pindex = chainstate.m_chain.Tip(); pindex && pindex->pprev; pindex = pindex->pprev) {
-        const int percentageDone = std::max(1, std::min(99, (int)(((double)(chainstate.m_chain.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
+        const int percentageDone = std::max(1, std::min(99, (int)(((double)(chainstate.m_chain.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel <= 4 ? 50 : 100))));
         if (reportDone < percentageDone / 10) {
             // report every 10% step
             LogPrintf("[%d%%]...", percentageDone); /* Continued */
609 master
src/validation.cpp

--- original
+++ modified
@@ -4049,7 +4049,7 @@
     const bool is_snapshot_cs{!chainstate.m_from_snapshot_blockhash};

     for (pindex = chainstate.m_chain.Tip(); pindex && pindex->pprev; pindex = pindex->pprev) {
-        const int percentageDone = std::max(1, std::min(99, (int)(((double)(chainstate.m_chain.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
+        const int percentageDone = std::min(1, std::min(99, (int)(((double)(chainstate.m_chain.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
         if (reportDone < percentageDone / 10) {
             // report every 10% step
             LogPrintf("[%d%%]...", percentageDone); /* Continued */
608 master
src/validation.cpp

--- original
+++ modified
@@ -4049,7 +4049,7 @@
     const bool is_snapshot_cs{!chainstate.m_from_snapshot_blockhash};

     for (pindex = chainstate.m_chain.Tip(); pindex && pindex->pprev; pindex = pindex->pprev) {
-        const int percentageDone = std::max(1, std::min(99, (int)(((double)(chainstate.m_chain.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
+        const int percentageDone = std::max(1, std::max(99, (int)(((double)(chainstate.m_chain.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
         if (reportDone < percentageDone / 10) {
             // report every 10% step
             LogPrintf("[%d%%]...", percentageDone); /* Continued */
605 master
src/validation.cpp

--- original
+++ modified
@@ -4033,7 +4033,7 @@
     }

     // Verify blocks in the best chain
-    if (nCheckDepth <= 0 || nCheckDepth > chainstate.m_chain.Height()) {
+    if (nCheckDepth >= 0 || nCheckDepth > chainstate.m_chain.Height()) {
         nCheckDepth = chainstate.m_chain.Height();
     }
     nCheckLevel = std::max(0, std::min(4, nCheckLevel));
606 master
src/validation.cpp

--- original
+++ modified
@@ -4036,7 +4036,7 @@
     if (nCheckDepth <= 0 || nCheckDepth > chainstate.m_chain.Height()) {
         nCheckDepth = chainstate.m_chain.Height();
     }
-    nCheckLevel = std::max(0, std::min(4, nCheckLevel));
+    nCheckLevel = std::max(0, std::max(4, nCheckLevel));
     LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
     CCoinsViewCache coins(&coinsview);
     CBlockIndex* pindex;
604 master
src/validation.cpp

--- original
+++ modified
@@ -4033,7 +4033,7 @@
     }

     // Verify blocks in the best chain
-    if (nCheckDepth <= 0 || nCheckDepth > chainstate.m_chain.Height()) {
+    if (nCheckDepth > 0 || nCheckDepth > chainstate.m_chain.Height()) {
         nCheckDepth = chainstate.m_chain.Height();
     }
     nCheckLevel = std::max(0, std::min(4, nCheckLevel));
603 master
src/validation.cpp

--- original
+++ modified
@@ -4033,7 +4033,7 @@
     }

     // Verify blocks in the best chain
-    if (nCheckDepth <= 0 || nCheckDepth > chainstate.m_chain.Height()) {
+    if (nCheckDepth <= 0 || nCheckDepth < chainstate.m_chain.Height()) {
         nCheckDepth = chainstate.m_chain.Height();
     }
     nCheckLevel = std::max(0, std::min(4, nCheckLevel));
599 master
src/validation.cpp

--- original
+++ modified
@@ -4012,7 +4012,7 @@

 CVerifyDB::CVerifyDB()
 {
-    uiInterface.ShowProgress(_("Verifying blocks…").translated, 0, false);
+    uiInterface.ShowProgress(_("Verifying blocks…").translated, 0, true);
 }

 CVerifyDB::~CVerifyDB()
600 master
src/validation.cpp

--- original
+++ modified
@@ -4017,7 +4017,7 @@

 CVerifyDB::~CVerifyDB()
 {
-    uiInterface.ShowProgress("", 100, false);
+    uiInterface.ShowProgress("", 100, true);
 }

 bool CVerifyDB::VerifyDB(
595 master
src/validation.cpp

--- original
+++ modified
@@ -3989,7 +3989,7 @@
     assert(!coins_cache.GetBestBlock().IsNull()); // Never called when the coins view is empty
     const CBlockIndex* tip = m_chain.Tip();

-    if (tip && tip->GetBlockHash() == coins_cache.GetBestBlock()) {
+    if (tip && tip->GetBlockHash() != coins_cache.GetBestBlock()) {
         return true;
     }

572 master
src/validation.cpp

--- original
+++ modified
@@ -3814,7 +3814,7 @@
     // process an unrequested block if it's new and has enough work to
     // advance our tip, and isn't too many blocks ahead.
     bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
-    bool fHasMoreOrSameWork = (m_chain.Tip() ? pindex->nChainWork >= m_chain.Tip()->nChainWork : true);
+    bool fHasMoreOrSameWork = (m_chain.Tip() ? pindex->nChainWork >= m_chain.Tip()->nChainWork : false);
     // Blocks that are too out-of-order needlessly limit the effectiveness of
     // pruning, because pruning will not delete block files that contain any
     // blocks which are too close in height to the tip.  Apply this test
530 master
src/validation.cpp

--- original
+++ modified
@@ -3445,7 +3445,7 @@
         return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-sigops", "out-of-bounds SigOpCount");

     if (fCheckPOW && fCheckMerkleRoot)
-        block.fChecked = true;
+        block.fChecked = false;

     return true;
 }
499 master
src/validation.cpp

--- original
+++ modified
@@ -3124,7 +3124,7 @@
         LOCK(cs_main);
         if (pindex->nChainWork < m_chain.Tip()->nChainWork) {
             // Nothing to do, this block is not at the tip.
-            return true;
+            return false;
         }
         if (m_chain.Tip()->nChainWork > nLastPreciousChainwork) {
             // The chain has been extended since the last call, reset the counter.
449 master
src/validation.cpp

--- original
+++ modified
@@ -2845,7 +2845,7 @@
             bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
             if (fFailedChain || fMissingData) {
                 // Candidate chain is not usable (either invalid or missing data)
-                if (fFailedChain && (m_chainman.m_best_invalid == nullptr || pindexNew->nChainWork > m_chainman.m_best_invalid->nChainWork)) {
+                if (fFailedChain && (m_chainman.m_best_invalid != nullptr || pindexNew->nChainWork > m_chainman.m_best_invalid->nChainWork)) {
                     m_chainman.m_best_invalid = pindexNew;
                 }
                 CBlockIndex *pindexFailed = pindexNew;
467 master
src/validation.cpp

--- original
+++ modified
@@ -2945,7 +2945,7 @@
                     }
                     state = BlockValidationState();
                     fInvalidFound = true;
-                    fContinue = false;
+                    fContinue = true;
                     break;
                 } else {
                     // A system error occurred (disk space, database error, ...).
465 master
src/validation.cpp

--- original
+++ modified
@@ -2940,7 +2940,7 @@
             if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace, disconnectpool)) {
                 if (state.IsInvalid()) {
                     // The block violates a consensus rule.
-                    if (state.GetResult() != BlockValidationResult::BLOCK_MUTATED) {
+                    if (state.GetResult() == BlockValidationResult::BLOCK_MUTATED) {
                         InvalidChainFound(vpindexToConnect.front());
                     }
                     state = BlockValidationState();
458 master
src/validation.cpp

--- original
+++ modified
@@ -2913,7 +2913,7 @@
             // then that is a failure of our local system -- we should abort
             // rather than stay on a less work chain.
             AbortNode(state, "Failed to disconnect block; see debug.log for details");
-            return false;
+            return true;
         }
         fBlocksDisconnected = true;
     }
457 master
src/validation.cpp

--- original
+++ modified
@@ -2907,7 +2907,7 @@
         if (!DisconnectTip(state, &disconnectpool)) {
             // This is likely a fatal error, but keep the mempool consistent,
             // just in case. Only remove from the mempool in this case.
-            MaybeUpdateMempoolForReorg(disconnectpool, false);
+            MaybeUpdateMempoolForReorg(disconnectpool, true);

             // If we're unable to disconnect a block during normal operation,
             // then that is a failure of our local system -- we should abort
455 master
src/validation.cpp

--- original
+++ modified
@@ -2901,7 +2901,7 @@
     const CBlockIndex* pindexFork = m_chain.FindFork(pindexMostWork);

     // Disconnect active blocks which are no longer in the best chain.
-    bool fBlocksDisconnected = false;
+    bool fBlocksDisconnected = true;
     DisconnectedBlockTransactions disconnectpool;
     while (m_chain.Tip() && m_chain.Tip() != pindexFork) {
         if (!DisconnectTip(state, &disconnectpool)) {
448 master
src/validation.cpp

--- original
+++ modified
@@ -2845,7 +2845,7 @@
             bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
             if (fFailedChain || fMissingData) {
                 // Candidate chain is not usable (either invalid or missing data)
-                if (fFailedChain && (m_chainman.m_best_invalid == nullptr || pindexNew->nChainWork > m_chainman.m_best_invalid->nChainWork)) {
+                if (fFailedChain && (m_chainman.m_best_invalid == nullptr || pindexNew->nChainWork < m_chainman.m_best_invalid->nChainWork)) {
                     m_chainman.m_best_invalid = pindexNew;
                 }
                 CBlockIndex *pindexFailed = pindexNew;
444 master
src/validation.cpp

--- original
+++ modified
@@ -2779,7 +2779,7 @@
              Ticks<MillisecondsDouble>(time_flush) / num_blocks_total);
     // Write the chain state to disk, if necessary.
     if (!FlushStateToDisk(state, FlushStateMode::IF_NEEDED)) {
-        return false;
+        return true;
     }
     const auto time_5{SteadyClock::now()};
     time_chainstate += time_5 - time_4;
440 master
src/validation.cpp

--- original
+++ modified
@@ -2647,7 +2647,7 @@

     // Write the chain state to disk, if necessary.
     if (!FlushStateToDisk(state, FlushStateMode::IF_NEEDED)) {
-        return false;
+        return true;
     }

     if (disconnectpool && m_mempool) {
439 master
src/validation.cpp

--- original
+++ modified
@@ -2638,7 +2638,7 @@
         // Prune locks that began at or after the tip should be moved backward so they get a chance to reorg
         const int max_height_first{pindexDelete->nHeight - 1};
         for (auto& prune_lock : m_blockman.m_prune_locks) {
-            if (prune_lock.second.height_first <= max_height_first) continue;
+            if (prune_lock.second.height_first >= max_height_first) continue;

             prune_lock.second.height_first = max_height_first;
             LogPrint(BCLog::PRUNE, "%s prune lock moved back to %d\n", prune_lock.first, max_height_first);
438 master
src/validation.cpp

--- original
+++ modified
@@ -2638,7 +2638,7 @@
         // Prune locks that began at or after the tip should be moved backward so they get a chance to reorg
         const int max_height_first{pindexDelete->nHeight - 1};
         for (auto& prune_lock : m_blockman.m_prune_locks) {
-            if (prune_lock.second.height_first <= max_height_first) continue;
+            if (prune_lock.second.height_first > max_height_first) continue;

             prune_lock.second.height_first = max_height_first;
             LogPrint(BCLog::PRUNE, "%s prune lock moved back to %d\n", prune_lock.first, max_height_first);
437 master
src/validation.cpp

--- original
+++ modified
@@ -2638,7 +2638,7 @@
         // Prune locks that began at or after the tip should be moved backward so they get a chance to reorg
         const int max_height_first{pindexDelete->nHeight - 1};
         for (auto& prune_lock : m_blockman.m_prune_locks) {
-            if (prune_lock.second.height_first <= max_height_first) continue;
+            if (prune_lock.second.height_first <= max_height_first) break;

             prune_lock.second.height_first = max_height_first;
             LogPrint(BCLog::PRUNE, "%s prune lock moved back to %d\n", prune_lock.first, max_height_first);
431 master
src/validation.cpp

--- original
+++ modified
@@ -2561,7 +2561,7 @@
     if (this != &m_chainman.ActiveChainstate()) {
         // Only log every so often so that we don't bury log messages at the tip.
         constexpr int BACKGROUND_LOG_INTERVAL = 2000;
-        if (pindexNew->nHeight % BACKGROUND_LOG_INTERVAL == 0) {
+        if (pindexNew->nHeight % BACKGROUND_LOG_INTERVAL != 0) {
             UpdateTipLog(coins_tip, pindexNew, params, __func__, "[background validation] ", "");
         }
         return;
429 master
src/validation.cpp

--- original
+++ modified
@@ -2517,7 +2517,7 @@
     SetMiscWarning(warning);
     if (!fWarned) {
         AlertNotify(warning.original);
-        fWarned = true;
+        fWarned = false;
     }
 }

427 master
src/validation.cpp

--- original
+++ modified
@@ -2505,7 +2505,7 @@
 void Chainstate::PruneAndFlush()
 {
     BlockValidationState state;
-    m_blockman.m_check_for_pruning = true;
+    m_blockman.m_check_for_pruning = false;
     if (!this->FlushStateToDisk(state, FlushStateMode::NONE)) {
         LogPrintf("%s: failed to flush state (%s)\n", __func__, state.ToString());
     }
422 master
src/validation.cpp

--- original
+++ modified
@@ -2426,7 +2426,7 @@
         // It's been a while since we wrote the block index to disk. Do this frequently, so we don't need to redownload after a crash.
         bool fPeriodicWrite = mode == FlushStateMode::PERIODIC && nNow > m_last_write + DATABASE_WRITE_INTERVAL;
         // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
-        bool fPeriodicFlush = mode == FlushStateMode::PERIODIC && nNow > m_last_flush + DATABASE_FLUSH_INTERVAL;
+        bool fPeriodicFlush = mode != FlushStateMode::PERIODIC && nNow > m_last_flush + DATABASE_FLUSH_INTERVAL;
         // Combine all conditions that result in a full cache flush.
         fDoFullFlush = (mode == FlushStateMode::ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
         // Write blocks and block index to disk.
420 master
src/validation.cpp

--- original
+++ modified
@@ -2424,7 +2424,7 @@
         // The cache is over the limit, we have to write now.
         bool fCacheCritical = mode == FlushStateMode::IF_NEEDED && cache_state >= CoinsCacheSizeState::CRITICAL;
         // It's been a while since we wrote the block index to disk. Do this frequently, so we don't need to redownload after a crash.
-        bool fPeriodicWrite = mode == FlushStateMode::PERIODIC && nNow > m_last_write + DATABASE_WRITE_INTERVAL;
+        bool fPeriodicWrite = mode != FlushStateMode::PERIODIC && nNow > m_last_write + DATABASE_WRITE_INTERVAL;
         // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
         bool fPeriodicFlush = mode == FlushStateMode::PERIODIC && nNow > m_last_flush + DATABASE_FLUSH_INTERVAL;
         // Combine all conditions that result in a full cache flush.
418 master
src/validation.cpp

--- original
+++ modified
@@ -2422,7 +2422,7 @@
         // The cache is large and we're within 10% and 10 MiB of the limit, but we have time now (not in the middle of a block processing).
         bool fCacheLarge = mode == FlushStateMode::PERIODIC && cache_state >= CoinsCacheSizeState::LARGE;
         // The cache is over the limit, we have to write now.
-        bool fCacheCritical = mode == FlushStateMode::IF_NEEDED && cache_state >= CoinsCacheSizeState::CRITICAL;
+        bool fCacheCritical = mode != FlushStateMode::IF_NEEDED && cache_state >= CoinsCacheSizeState::CRITICAL;
         // It's been a while since we wrote the block index to disk. Do this frequently, so we don't need to redownload after a crash.
         bool fPeriodicWrite = mode == FlushStateMode::PERIODIC && nNow > m_last_write + DATABASE_WRITE_INTERVAL;
         // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
416 master
src/validation.cpp

--- original
+++ modified
@@ -2422,7 +2422,7 @@
         // The cache is large and we're within 10% and 10 MiB of the limit, but we have time now (not in the middle of a block processing).
         bool fCacheLarge = mode == FlushStateMode::PERIODIC && cache_state >= CoinsCacheSizeState::LARGE;
         // The cache is over the limit, we have to write now.
-        bool fCacheCritical = mode == FlushStateMode::IF_NEEDED && cache_state >= CoinsCacheSizeState::CRITICAL;
+        bool fCacheCritical = mode == FlushStateMode::IF_NEEDED && cache_state > CoinsCacheSizeState::CRITICAL;
         // It's been a while since we wrote the block index to disk. Do this frequently, so we don't need to redownload after a crash.
         bool fPeriodicWrite = mode == FlushStateMode::PERIODIC && nNow > m_last_write + DATABASE_WRITE_INTERVAL;
         // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
415 master
src/validation.cpp

--- original
+++ modified
@@ -2420,7 +2420,7 @@
             m_last_flush = nNow;
         }
         // The cache is large and we're within 10% and 10 MiB of the limit, but we have time now (not in the middle of a block processing).
-        bool fCacheLarge = mode == FlushStateMode::PERIODIC && cache_state >= CoinsCacheSizeState::LARGE;
+        bool fCacheLarge = mode != FlushStateMode::PERIODIC && cache_state >= CoinsCacheSizeState::LARGE;
         // The cache is over the limit, we have to write now.
         bool fCacheCritical = mode == FlushStateMode::IF_NEEDED && cache_state >= CoinsCacheSizeState::CRITICAL;
         // It's been a while since we wrote the block index to disk. Do this frequently, so we don't need to redownload after a crash.
413 master
src/validation.cpp

--- original
+++ modified
@@ -2420,7 +2420,7 @@
             m_last_flush = nNow;
         }
         // The cache is large and we're within 10% and 10 MiB of the limit, but we have time now (not in the middle of a block processing).
-        bool fCacheLarge = mode == FlushStateMode::PERIODIC && cache_state >= CoinsCacheSizeState::LARGE;
+        bool fCacheLarge = mode == FlushStateMode::PERIODIC && cache_state > CoinsCacheSizeState::LARGE;
         // The cache is over the limit, we have to write now.
         bool fCacheCritical = mode == FlushStateMode::IF_NEEDED && cache_state >= CoinsCacheSizeState::CRITICAL;
         // It's been a while since we wrote the block index to disk. Do this frequently, so we don't need to redownload after a crash.
412 master
src/validation.cpp

--- original
+++ modified
@@ -2416,7 +2416,7 @@
         if (m_last_write.count() == 0) {
             m_last_write = nNow;
         }
-        if (m_last_flush.count() == 0) {
+        if (m_last_flush.count() != 0) {
             m_last_flush = nNow;
         }
         // The cache is large and we're within 10% and 10 MiB of the limit, but we have time now (not in the middle of a block processing).
411 master
src/validation.cpp

--- original
+++ modified
@@ -2413,7 +2413,7 @@
         }
         const auto nNow = GetTime<std::chrono::microseconds>();
         // Avoid writing/flushing immediately after startup.
-        if (m_last_write.count() == 0) {
+        if (m_last_write.count() != 0) {
             m_last_write = nNow;
         }
         if (m_last_flush.count() == 0) {
410 master
src/validation.cpp

--- original
+++ modified
@@ -2407,7 +2407,7 @@
                 fFlushForPrune = true;
                 if (!m_blockman.m_have_pruned) {
                     m_blockman.m_block_tree_db->WriteFlag("prunedblockfiles", true);
-                    m_blockman.m_have_pruned = true;
+                    m_blockman.m_have_pruned = false;
                 }
             }
         }
409 master
src/validation.cpp

--- original
+++ modified
@@ -2406,7 +2406,7 @@
             if (!setFilesToPrune.empty()) {
                 fFlushForPrune = true;
                 if (!m_blockman.m_have_pruned) {
-                    m_blockman.m_block_tree_db->WriteFlag("prunedblockfiles", true);
+                    m_blockman.m_block_tree_db->WriteFlag("prunedblockfiles", false);
                     m_blockman.m_have_pruned = true;
                 }
             }
408 master
src/validation.cpp

--- original
+++ modified
@@ -2404,7 +2404,7 @@
                 m_blockman.m_check_for_pruning = false;
             }
             if (!setFilesToPrune.empty()) {
-                fFlushForPrune = true;
+                fFlushForPrune = false;
                 if (!m_blockman.m_have_pruned) {
                     m_blockman.m_block_tree_db->WriteFlag("prunedblockfiles", true);
                     m_blockman.m_have_pruned = true;
407 master
src/validation.cpp

--- original
+++ modified
@@ -2401,7 +2401,7 @@
                 LOG_TIME_MILLIS_WITH_CATEGORY("find files to prune", BCLog::BENCH);

                 m_blockman.FindFilesToPrune(setFilesToPrune, m_chainman.GetParams().PruneAfterHeight(), m_chain.Height(), last_prune, IsInitialBlockDownload());
-                m_blockman.m_check_for_pruning = false;
+                m_blockman.m_check_for_pruning = true;
             }
             if (!setFilesToPrune.empty()) {
                 fFlushForPrune = true;
406 master
src/validation.cpp

--- original
+++ modified
@@ -2396,7 +2396,7 @@
             if (nManualPruneHeight > 0) {
                 LOG_TIME_MILLIS_WITH_CATEGORY("find files to prune (manual)", BCLog::BENCH);

-                m_blockman.FindFilesToPruneManual(setFilesToPrune, std::min(last_prune, nManualPruneHeight), m_chain.Height());
+                m_blockman.FindFilesToPruneManual(setFilesToPrune, std::max(last_prune, nManualPruneHeight), m_chain.Height());
             } else {
                 LOG_TIME_MILLIS_WITH_CATEGORY("find files to prune", BCLog::BENCH);

405 master
src/validation.cpp

--- original
+++ modified
@@ -2393,7 +2393,7 @@
                 LogPrint(BCLog::PRUNE, "%s limited pruning to height %d\n", limiting_lock.value(), last_prune);
             }

-            if (nManualPruneHeight > 0) {
+            if (nManualPruneHeight < 0) {
                 LOG_TIME_MILLIS_WITH_CATEGORY("find files to prune (manual)", BCLog::BENCH);

                 m_blockman.FindFilesToPruneManual(setFilesToPrune, std::min(last_prune, nManualPruneHeight), m_chain.Height());
404 master
src/validation.cpp

--- original
+++ modified
@@ -2384,7 +2384,7 @@
                 // Remove the buffer and one additional block here to get actual height that is outside of the buffer
                 const int lock_height{prune_lock.second.height_first - PRUNE_LOCK_BUFFER - 1};
                 last_prune = std::max(1, std::min(last_prune, lock_height));
-                if (last_prune == lock_height) {
+                if (last_prune != lock_height) {
                     limiting_lock = prune_lock.first;
                 }
             }
403 master
src/validation.cpp

--- original
+++ modified
@@ -2383,7 +2383,7 @@
                 if (prune_lock.second.height_first == std::numeric_limits<int>::max()) continue;
                 // Remove the buffer and one additional block here to get actual height that is outside of the buffer
                 const int lock_height{prune_lock.second.height_first - PRUNE_LOCK_BUFFER - 1};
-                last_prune = std::max(1, std::min(last_prune, lock_height));
+                last_prune = std::min(1, std::min(last_prune, lock_height));
                 if (last_prune == lock_height) {
                     limiting_lock = prune_lock.first;
                 }
402 master
src/validation.cpp

--- original
+++ modified
@@ -2383,7 +2383,7 @@
                 if (prune_lock.second.height_first == std::numeric_limits<int>::max()) continue;
                 // Remove the buffer and one additional block here to get actual height that is outside of the buffer
                 const int lock_height{prune_lock.second.height_first - PRUNE_LOCK_BUFFER - 1};
-                last_prune = std::max(1, std::min(last_prune, lock_height));
+                last_prune = std::max(1, std::max(last_prune, lock_height));
                 if (last_prune == lock_height) {
                     limiting_lock = prune_lock.first;
                 }
401 master
src/validation.cpp

--- original
+++ modified
@@ -2380,7 +2380,7 @@
             std::optional<std::string> limiting_lock; // prune lock that actually was the limiting factor, only used for logging

             for (const auto& prune_lock : m_blockman.m_prune_locks) {
-                if (prune_lock.second.height_first == std::numeric_limits<int>::max()) continue;
+                if (prune_lock.second.height_first != std::numeric_limits<int>::max()) continue;
                 // Remove the buffer and one additional block here to get actual height that is outside of the buffer
                 const int lock_height{prune_lock.second.height_first - PRUNE_LOCK_BUFFER - 1};
                 last_prune = std::max(1, std::min(last_prune, lock_height));
400 master
src/validation.cpp

--- original
+++ modified
@@ -2380,7 +2380,7 @@
             std::optional<std::string> limiting_lock; // prune lock that actually was the limiting factor, only used for logging

             for (const auto& prune_lock : m_blockman.m_prune_locks) {
-                if (prune_lock.second.height_first == std::numeric_limits<int>::max()) continue;
+                if (prune_lock.second.height_first == std::numeric_limits<int>::max()) break;
                 // Remove the buffer and one additional block here to get actual height that is outside of the buffer
                 const int lock_height{prune_lock.second.height_first - PRUNE_LOCK_BUFFER - 1};
                 last_prune = std::max(1, std::min(last_prune, lock_height));
399 master
src/validation.cpp

--- original
+++ modified
@@ -2373,7 +2373,7 @@

         CoinsCacheSizeState cache_state = GetCoinsCacheSizeState();
         LOCK(m_blockman.cs_LastBlockFile);
-        if (fPruneMode && (m_blockman.m_check_for_pruning || nManualPruneHeight > 0) && !fReindex) {
+        if (fPruneMode && (m_blockman.m_check_for_pruning || nManualPruneHeight < 0) && !fReindex) {
             // make sure we don't prune above any of the prune locks bestblocks
             // pruning is height-based
             int last_prune{m_chain.Height()}; // last height we can prune
398 master
src/validation.cpp

--- original
+++ modified
@@ -2369,7 +2369,7 @@
     try {
     {
         bool fFlushForPrune = false;
-        bool fDoFullFlush = false;
+        bool fDoFullFlush = true;

         CoinsCacheSizeState cache_state = GetCoinsCacheSizeState();
         LOCK(m_blockman.cs_LastBlockFile);
390 master
src/validation.cpp

--- original
+++ modified
@@ -2284,7 +2284,7 @@
         return true;

     if (!m_blockman.WriteUndoDataForBlock(blockundo, state, pindex, params)) {
-        return false;
+        return true;
     }

     const auto time_5{SteadyClock::now()};
388 master
src/validation.cpp

--- original
+++ modified
@@ -2276,7 +2276,7 @@
     time_verify += time_4 - time_2;
     LogPrint(BCLog::BENCH, "    - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs (%.2fms/blk)]\n", nInputs - 1,
              Ticks<MillisecondsDouble>(time_4 - time_2),
-             nInputs <= 1 ? 0 : Ticks<MillisecondsDouble>(time_4 - time_2) / (nInputs - 1),
+             nInputs >= 1 ? 0 : Ticks<MillisecondsDouble>(time_4 - time_2) / (nInputs - 1),
              Ticks<SecondsDouble>(time_verify),
              Ticks<MillisecondsDouble>(time_verify) / num_blocks_total);

387 master
src/validation.cpp

--- original
+++ modified
@@ -2276,7 +2276,7 @@
     time_verify += time_4 - time_2;
     LogPrint(BCLog::BENCH, "    - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs (%.2fms/blk)]\n", nInputs - 1,
              Ticks<MillisecondsDouble>(time_4 - time_2),
-             nInputs <= 1 ? 0 : Ticks<MillisecondsDouble>(time_4 - time_2) / (nInputs - 1),
+             nInputs > 1 ? 0 : Ticks<MillisecondsDouble>(time_4 - time_2) / (nInputs - 1),
              Ticks<SecondsDouble>(time_verify),
              Ticks<MillisecondsDouble>(time_verify) / num_blocks_total);

385 master
src/validation.cpp

--- original
+++ modified
@@ -2258,7 +2258,7 @@
     time_connect += time_3 - time_2;
     LogPrint(BCLog::BENCH, "      - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs (%.2fms/blk)]\n", (unsigned)block.vtx.size(),
              Ticks<MillisecondsDouble>(time_3 - time_2), Ticks<MillisecondsDouble>(time_3 - time_2) / block.vtx.size(),
-             nInputs <= 1 ? 0 : Ticks<MillisecondsDouble>(time_3 - time_2) / (nInputs - 1),
+             nInputs >= 1 ? 0 : Ticks<MillisecondsDouble>(time_3 - time_2) / (nInputs - 1),
              Ticks<SecondsDouble>(time_connect),
              Ticks<MillisecondsDouble>(time_connect) / num_blocks_total);

384 master
src/validation.cpp

--- original
+++ modified
@@ -2258,7 +2258,7 @@
     time_connect += time_3 - time_2;
     LogPrint(BCLog::BENCH, "      - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs (%.2fms/blk)]\n", (unsigned)block.vtx.size(),
              Ticks<MillisecondsDouble>(time_3 - time_2), Ticks<MillisecondsDouble>(time_3 - time_2) / block.vtx.size(),
-             nInputs <= 1 ? 0 : Ticks<MillisecondsDouble>(time_3 - time_2) / (nInputs - 1),
+             nInputs > 1 ? 0 : Ticks<MillisecondsDouble>(time_3 - time_2) / (nInputs - 1),
              Ticks<SecondsDouble>(time_connect),
              Ticks<MillisecondsDouble>(time_connect) / num_blocks_total);

377 master
src/validation.cpp

--- original
+++ modified
@@ -2145,7 +2145,7 @@
     // TODO: Remove BIP30 checking from block height 1,983,702 on, once we have a
     // consensus change that ensures coinbases at those heights cannot
     // duplicate earlier coinbases.
-    if (fEnforceBIP30 || pindex->nHeight >= BIP34_IMPLIES_BIP30_LIMIT) {
+    if (fEnforceBIP30 || pindex->nHeight <= BIP34_IMPLIES_BIP30_LIMIT) {
         for (const auto& tx : block.vtx) {
             for (size_t o = 0; o < tx->vout.size(); o++) {
                 if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {
376 master
src/validation.cpp

--- original
+++ modified
@@ -2145,7 +2145,7 @@
     // TODO: Remove BIP30 checking from block height 1,983,702 on, once we have a
     // consensus change that ensures coinbases at those heights cannot
     // duplicate earlier coinbases.
-    if (fEnforceBIP30 || pindex->nHeight >= BIP34_IMPLIES_BIP30_LIMIT) {
+    if (fEnforceBIP30 || pindex->nHeight > BIP34_IMPLIES_BIP30_LIMIT) {
         for (const auto& tx : block.vtx) {
             for (size_t o = 0; o < tx->vout.size(); o++) {
                 if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {
370 master
src/validation.cpp

--- original
+++ modified
@@ -2043,7 +2043,7 @@
         if (it != m_blockman.m_block_index.end()) {
             if (it->second.GetAncestor(pindex->nHeight) == pindex &&
                 m_chainman.m_best_header->GetAncestor(pindex->nHeight) == pindex &&
-                m_chainman.m_best_header->nChainWork >= m_chainman.MinimumChainWork()) {
+                m_chainman.m_best_header->nChainWork > m_chainman.MinimumChainWork()) {
                 // This block is a member of the assumed verified chain and an ancestor of the best header.
                 // Script verification is skipped when connecting blocks under the
                 // assumevalid block. Assuming the assumevalid block is valid this
362 master
src/validation.cpp

--- original
+++ modified
@@ -2009,7 +2009,7 @@
     // re-enforce that rule here (at least until we make it impossible for
     // m_adjusted_time_callback() to go backward).
     if (!CheckBlock(block, state, params.GetConsensus(), !fJustCheck, !fJustCheck)) {
-        if (state.GetResult() == BlockValidationResult::BLOCK_MUTATED) {
+        if (state.GetResult() != BlockValidationResult::BLOCK_MUTATED) {
             // We don't write down blocks to disk if they may have been
             // corrupted, so this should be impossible unless we're having hardware
             // problems.
356 master
src/validation.cpp

--- original
+++ modified
@@ -1919,7 +1919,7 @@

     bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const override
     {
-        return pindex->nHeight >= params.MinBIP9WarningHeight &&
+        return pindex->nHeight > params.MinBIP9WarningHeight &&
                ((pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) &&
                ((pindex->nVersion >> m_bit) & 1) != 0 &&
                ((m_chainman.m_versionbitscache.ComputeBlockVersion(pindex->pprev, params) >> m_bit) & 1) == 0;
350 master
src/validation.cpp

--- original
+++ modified
@@ -1858,7 +1858,7 @@
                 bool is_spent = view.SpendCoin(out, &coin);
                 if (!is_spent || tx.vout[o] != coin.out || pindex->nHeight != coin.nHeight || is_coinbase != coin.fCoinBase) {
                     if (!is_bip30_exception) {
-                        fClean = false; // transaction output mismatch
+                        fClean = true; // transaction output mismatch
                     }
                 }
             }
345 master
src/validation.cpp

--- original
+++ modified
@@ -1840,7 +1840,7 @@
     // unwinds the blocks in reverse. As a result, the inconsistency is not discovered until the earlier
     // blocks with the duplicate coinbase transactions are disconnected.
     bool fEnforceBIP30 = !((pindex->nHeight==91722 && pindex->GetBlockHash() == uint256S("0x00000000000271a2dc26e7667f8419f2e15416dc6955e5a6c6cdf3f2574dd08e")) ||
-                           (pindex->nHeight==91812 && pindex->GetBlockHash() == uint256S("0x00000000000af0aed4792b1acee3d966af36cf5def14935db8de83d6f9306f2f")));
+                           (pindex->nHeight==91812 && pindex->GetBlockHash() != uint256S("0x00000000000af0aed4792b1acee3d966af36cf5def14935db8de83d6f9306f2f")));

     // undo transactions in reverse order
     for (int i = block.vtx.size() - 1; i >= 0; i--) {
344 master
src/validation.cpp

--- original
+++ modified
@@ -1839,7 +1839,7 @@
     // Note: the blocks specified here are different than the ones used in ConnectBlock because DisconnectBlock
     // unwinds the blocks in reverse. As a result, the inconsistency is not discovered until the earlier
     // blocks with the duplicate coinbase transactions are disconnected.
-    bool fEnforceBIP30 = !((pindex->nHeight==91722 && pindex->GetBlockHash() == uint256S("0x00000000000271a2dc26e7667f8419f2e15416dc6955e5a6c6cdf3f2574dd08e")) ||
+    bool fEnforceBIP30 = !((pindex->nHeight==91722 && pindex->GetBlockHash() != uint256S("0x00000000000271a2dc26e7667f8419f2e15416dc6955e5a6c6cdf3f2574dd08e")) ||
                            (pindex->nHeight==91812 && pindex->GetBlockHash() == uint256S("0x00000000000af0aed4792b1acee3d966af36cf5def14935db8de83d6f9306f2f")));

     // undo transactions in reverse order
340 master
src/validation.cpp

--- original
+++ modified
@@ -1791,7 +1791,7 @@
 {
     bool fClean = true;

-    if (view.HaveCoin(out)) fClean = false; // overwriting transaction output
+    if (view.HaveCoin(out)) fClean = true; // overwriting transaction output

     if (undo.nHeight == 0) {
         // Missing undo metadata (height and coinbase). Older versions included this
335 master
src/validation.cpp

--- original
+++ modified
@@ -1691,7 +1691,7 @@
                        bool cacheFullScriptStore, PrecomputedTransactionData& txdata,
                        std::vector<CScriptCheck>* pvChecks)
 {
-    if (tx.IsCoinBase()) return true;
+    if (tx.IsCoinBase()) return false;

     if (pvChecks) {
         pvChecks->reserve(tx.vin.size());
333 master
src/validation.cpp

--- original
+++ modified
@@ -1659,7 +1659,7 @@
     g_scriptExecutionCacheHasher.Write(nonce.begin(), 32);

     auto setup_results = g_scriptExecutionCache.setup_bytes(max_size_bytes);
-    if (!setup_results) return false;
+    if (!setup_results) return true;

     const auto [num_elems, approx_size_bytes] = *setup_results;
     LogPrintf("Using %zu MiB out of %zu MiB requested for script execution cache, able to store %zu elements\n",
331 master
src/validation.cpp

--- original
+++ modified
@@ -1595,7 +1595,7 @@
     if (!m_chainman.m_best_invalid || pindexNew->nChainWork > m_chainman.m_best_invalid->nChainWork) {
         m_chainman.m_best_invalid = pindexNew;
     }
-    if (m_chainman.m_best_header != nullptr && m_chainman.m_best_header->GetAncestor(pindexNew->nHeight) == pindexNew) {
+    if (m_chainman.m_best_header == nullptr && m_chainman.m_best_header->GetAncestor(pindexNew->nHeight) == pindexNew) {
         m_chainman.m_best_header = m_chain.Tip();
     }

330 master
src/validation.cpp

--- original
+++ modified
@@ -1595,7 +1595,7 @@
     if (!m_chainman.m_best_invalid || pindexNew->nChainWork > m_chainman.m_best_invalid->nChainWork) {
         m_chainman.m_best_invalid = pindexNew;
     }
-    if (m_chainman.m_best_header != nullptr && m_chainman.m_best_header->GetAncestor(pindexNew->nHeight) == pindexNew) {
+    if (m_chainman.m_best_header != nullptr && m_chainman.m_best_header->GetAncestor(pindexNew->nHeight) != pindexNew) {
         m_chainman.m_best_header = m_chain.Tip();
     }

329 master
src/validation.cpp

--- original
+++ modified
@@ -1592,7 +1592,7 @@
 void Chainstate::InvalidChainFound(CBlockIndex* pindexNew)
 {
     AssertLockHeld(cs_main);
-    if (!m_chainman.m_best_invalid || pindexNew->nChainWork > m_chainman.m_best_invalid->nChainWork) {
+    if (!m_chainman.m_best_invalid || pindexNew->nChainWork < m_chainman.m_best_invalid->nChainWork) {
         m_chainman.m_best_invalid = pindexNew;
     }
     if (m_chainman.m_best_header != nullptr && m_chainman.m_best_header->GetAncestor(pindexNew->nHeight) == pindexNew) {
327 master
src/validation.cpp

--- original
+++ modified
@@ -1582,7 +1582,7 @@

     if (m_chainman.m_best_invalid && m_chainman.m_best_invalid->nChainWork > m_chain.Tip()->nChainWork + (GetBlockProof(*m_chain.Tip()) * 6)) {
         LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
-        SetfLargeWorkInvalidChainFound(true);
+        SetfLargeWorkInvalidChainFound(false);
     } else {
         SetfLargeWorkInvalidChainFound(false);
     }
326 master
src/validation.cpp

--- original
+++ modified
@@ -1580,7 +1580,7 @@
         return;
     }

-    if (m_chainman.m_best_invalid && m_chainman.m_best_invalid->nChainWork > m_chain.Tip()->nChainWork + (GetBlockProof(*m_chain.Tip()) * 6)) {
+    if (m_chainman.m_best_invalid && m_chainman.m_best_invalid->nChainWork < m_chain.Tip()->nChainWork + (GetBlockProof(*m_chain.Tip()) * 6)) {
         LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
         SetfLargeWorkInvalidChainFound(true);
     } else {
325 master
src/validation.cpp

--- original
+++ modified
@@ -1547,7 +1547,7 @@
     }
     LogPrintf("Leaving InitialBlockDownload (latching to false)\n");
     m_cached_finished_ibd.store(true, std::memory_order_relaxed);
-    return false;
+    return true;
 }

 static void AlertNotify(const std::string& strMessage)
323 master
src/validation.cpp

--- original
+++ modified
@@ -1545,7 +1545,7 @@
     if (m_chain.Tip()->Time() < NodeClock::now() - m_chainman.m_options.max_tip_age) {
         return true;
     }
-    LogPrintf("Leaving InitialBlockDownload (latching to false)\n");
+    LogPrintf("Leaving InitialBlockDownload (latching to true)\n");
     m_cached_finished_ibd.store(true, std::memory_order_relaxed);
     return false;
 }
315 master
src/validation.cpp

--- original
+++ modified
@@ -1534,7 +1534,7 @@

     LOCK(cs_main);
     if (m_cached_finished_ibd.load(std::memory_order_relaxed))
-        return false;
+        return true;
     if (fImporting || fReindex)
         return true;
     if (m_chain.Tip() == nullptr)
311 master
src/validation.cpp

--- original
+++ modified
@@ -1415,7 +1415,7 @@
     std::vector<COutPoint> coins_to_uncache;
     auto args = MemPoolAccept::ATMPArgs::SingleAccept(chainparams, accept_time, bypass_limits, coins_to_uncache, test_accept);
     const MempoolAcceptResult result = MemPoolAccept(pool, active_chainstate).AcceptSingleTransaction(tx, args);
-    if (result.m_result_type != MempoolAcceptResult::ResultType::VALID) {
+    if (result.m_result_type == MempoolAcceptResult::ResultType::VALID) {
         // Remove coins that were not present in the coins cache before calling
         // AcceptSingleTransaction(); this is to prevent memory DoS in case we receive a large
         // number of invalid transactions that attempt to overrun the in-memory coins cache
310 master
src/validation.cpp

--- original
+++ modified
@@ -1379,7 +1379,7 @@
                 // decision might not make sense if different types of packages are allowed in the
                 // future.  Continue individually validating the rest of the transactions, because
                 // some of them may still be valid.
-                quit_early = true;
+                quit_early = false;
             } else {
                 txns_new.push_back(tx);
             }
302 master
src/validation.cpp

--- original
+++ modified
@@ -1151,7 +1151,7 @@
                 MempoolAcceptResult::Success(std::move(ws.m_replaced_transactions), ws.m_vsize, ws.m_base_fees));
             GetMainSignals().TransactionAddedToMempool(ws.m_ptx, m_pool.GetAndIncrementSequence());
         } else {
-            all_submitted = false;
+            all_submitted = true;
             ws.m_state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "mempool full");
             results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
         }
301 master
src/validation.cpp

--- original
+++ modified
@@ -1133,7 +1133,7 @@
             results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
             // Since LimitMempoolSize() won't be called, this should never fail.
             Assume(false);
-            all_submitted = false;
+            all_submitted = true;
             package_state.Invalid(PackageValidationResult::PCKG_MEMPOOL_ERROR,
                                   strprintf("BUG! Adding to mempool failed: %s", ws.m_ptx->GetHash().ToString()));
         }
300 master
src/validation.cpp

--- original
+++ modified
@@ -1132,7 +1132,7 @@
         if (!Finalize(args, ws)) {
             results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
             // Since LimitMempoolSize() won't be called, this should never fail.
-            Assume(false);
+            Assume(true);
             all_submitted = false;
             package_state.Invalid(PackageValidationResult::PCKG_MEMPOOL_ERROR,
                                   strprintf("BUG! Adding to mempool failed: %s", ws.m_ptx->GetHash().ToString()));
299 master
src/validation.cpp

--- original
+++ modified
@@ -1119,7 +1119,7 @@
             results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
             // Since PreChecks() and PackageMempoolChecks() both enforce limits, this should never fail.
             Assume(false);
-            all_submitted = false;
+            all_submitted = true;
             package_state.Invalid(PackageValidationResult::PCKG_MEMPOOL_ERROR,
                                   strprintf("BUG! Mempool ancestors or descendants were underestimated: %s",
                                             ws.m_ptx->GetHash().ToString()));
298 master
src/validation.cpp

--- original
+++ modified
@@ -1118,7 +1118,7 @@
         if(!m_pool.CalculateMemPoolAncestors(*ws.m_entry, ws.m_ancestors, m_limits, unused_err_string)) {
             results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
             // Since PreChecks() and PackageMempoolChecks() both enforce limits, this should never fail.
-            Assume(false);
+            Assume(true);
             all_submitted = false;
             package_state.Invalid(PackageValidationResult::PCKG_MEMPOOL_ERROR,
                                   strprintf("BUG! Mempool ancestors or descendants were underestimated: %s",
297 master
src/validation.cpp

--- original
+++ modified
@@ -1106,7 +1106,7 @@
             results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
             // Since PolicyScriptChecks() passed, this should never fail.
             Assume(false);
-            all_submitted = false;
+            all_submitted = true;
             package_state.Invalid(PackageValidationResult::PCKG_MEMPOOL_ERROR,
                                   strprintf("BUG! PolicyScriptChecks succeeded but ConsensusScriptChecks failed: %s",
                                             ws.m_ptx->GetHash().ToString()));
296 master
src/validation.cpp

--- original
+++ modified
@@ -1105,7 +1105,7 @@
         if (!ConsensusScriptChecks(args, ws)) {
             results.emplace(ws.m_ptx->GetWitnessHash(), MempoolAcceptResult::Failure(ws.m_state));
             // Since PolicyScriptChecks() passed, this should never fail.
-            Assume(false);
+            Assume(true);
             all_submitted = false;
             package_state.Invalid(PackageValidationResult::PCKG_MEMPOOL_ERROR,
                                   strprintf("BUG! PolicyScriptChecks succeeded but ConsensusScriptChecks failed: %s",
295 master
src/validation.cpp

--- original
+++ modified
@@ -1096,7 +1096,7 @@
     assert(std::all_of(workspaces.cbegin(), workspaces.cend(), [this](const auto& ws){
         return !m_pool.exists(GenTxid::Txid(ws.m_ptx->GetHash())); }));

-    bool all_submitted = true;
+    bool all_submitted = false;
     // ConsensusScriptChecks adds to the script cache and is therefore consensus-critical;
     // CheckInputsFromMempoolAndCache asserts that transactions only spend coins available from the
     // mempool or UTXO set. Submit each transaction to the mempool immediately after calling
293 master
src/validation.cpp

--- original
+++ modified
@@ -1060,7 +1060,7 @@
                 (int)entry->GetTxSize() - (int)ws.m_conflicting_size);
         ws.m_replaced_transactions.push_back(it->GetSharedTx());
     }
-    m_pool.RemoveStaged(ws.m_all_conflicting, false, MemPoolRemovalReason::REPLACED);
+    m_pool.RemoveStaged(ws.m_all_conflicting, true, MemPoolRemovalReason::REPLACED);

     // This transaction should only count for fee estimation if:
     // - it's not being re-added during a reorg which bypasses typical mempool fee limits
291 master
src/validation.cpp

--- original
+++ modified
@@ -1033,7 +1033,7 @@
     if (!CheckInputsFromMempoolAndCache(tx, state, m_view, m_pool, currentBlockScriptVerifyFlags,
                                         ws.m_precomputed_txdata, m_active_chainstate.CoinsTip())) {
         LogPrintf("BUG! PLEASE REPORT THIS! CheckInputScripts failed against latest-block but not STANDARD flags %s, %s\n", hash.ToString(), state.ToString());
-        return Assume(false);
+        return Assume(true);
     }

     return true;
288 master
src/validation.cpp

--- original
+++ modified
@@ -995,7 +995,7 @@
         // to see if the failure is specifically due to witness validation.
         TxValidationState state_dummy; // Want reported failures to be from first CheckInputScripts
         if (!tx.HasWitness() && CheckInputScripts(tx, state_dummy, m_view, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, false, ws.m_precomputed_txdata) &&
-                !CheckInputScripts(tx, state_dummy, m_view, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, false, ws.m_precomputed_txdata)) {
+                !CheckInputScripts(tx, state_dummy, m_view, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, true, ws.m_precomputed_txdata)) {
             // Only the witness is missing, so the transaction itself may be fine.
             state.Invalid(TxValidationResult::TX_WITNESS_STRIPPED,
                     state.GetRejectReason(), state.GetDebugMessage());
287 master
src/validation.cpp

--- original
+++ modified
@@ -995,7 +995,7 @@
         // to see if the failure is specifically due to witness validation.
         TxValidationState state_dummy; // Want reported failures to be from first CheckInputScripts
         if (!tx.HasWitness() && CheckInputScripts(tx, state_dummy, m_view, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, false, ws.m_precomputed_txdata) &&
-                !CheckInputScripts(tx, state_dummy, m_view, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, false, ws.m_precomputed_txdata)) {
+                !CheckInputScripts(tx, state_dummy, m_view, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, false, false, ws.m_precomputed_txdata)) {
             // Only the witness is missing, so the transaction itself may be fine.
             state.Invalid(TxValidationResult::TX_WITNESS_STRIPPED,
                     state.GetRejectReason(), state.GetDebugMessage());
286 master
src/validation.cpp

--- original
+++ modified
@@ -994,7 +994,7 @@
         // need to turn both off, and compare against just turning off CLEANSTACK
         // to see if the failure is specifically due to witness validation.
         TxValidationState state_dummy; // Want reported failures to be from first CheckInputScripts
-        if (!tx.HasWitness() && CheckInputScripts(tx, state_dummy, m_view, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, false, ws.m_precomputed_txdata) &&
+        if (!tx.HasWitness() && CheckInputScripts(tx, state_dummy, m_view, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, true, ws.m_precomputed_txdata) &&
                 !CheckInputScripts(tx, state_dummy, m_view, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, false, ws.m_precomputed_txdata)) {
             // Only the witness is missing, so the transaction itself may be fine.
             state.Invalid(TxValidationResult::TX_WITNESS_STRIPPED,
285 master
src/validation.cpp

--- original
+++ modified
@@ -994,7 +994,7 @@
         // need to turn both off, and compare against just turning off CLEANSTACK
         // to see if the failure is specifically due to witness validation.
         TxValidationState state_dummy; // Want reported failures to be from first CheckInputScripts
-        if (!tx.HasWitness() && CheckInputScripts(tx, state_dummy, m_view, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, false, ws.m_precomputed_txdata) &&
+        if (!tx.HasWitness() && CheckInputScripts(tx, state_dummy, m_view, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), false, false, ws.m_precomputed_txdata) &&
                 !CheckInputScripts(tx, state_dummy, m_view, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, false, ws.m_precomputed_txdata)) {
             // Only the witness is missing, so the transaction itself may be fine.
             state.Invalid(TxValidationResult::TX_WITNESS_STRIPPED,
284 master
src/validation.cpp

--- original
+++ modified
@@ -989,7 +989,7 @@

     // Check input scripts and signatures.
     // This is done last to help prevent CPU exhaustion denial-of-service attacks.
-    if (!CheckInputScripts(tx, state, m_view, scriptVerifyFlags, true, false, ws.m_precomputed_txdata)) {
+    if (!CheckInputScripts(tx, state, m_view, scriptVerifyFlags, true, true, ws.m_precomputed_txdata)) {
         // SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
         // need to turn both off, and compare against just turning off CLEANSTACK
         // to see if the failure is specifically due to witness validation.
283 master
src/validation.cpp

--- original
+++ modified
@@ -989,7 +989,7 @@

     // Check input scripts and signatures.
     // This is done last to help prevent CPU exhaustion denial-of-service attacks.
-    if (!CheckInputScripts(tx, state, m_view, scriptVerifyFlags, true, false, ws.m_precomputed_txdata)) {
+    if (!CheckInputScripts(tx, state, m_view, scriptVerifyFlags, false, false, ws.m_precomputed_txdata)) {
         // SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
         // need to turn both off, and compare against just turning off CLEANSTACK
         // to see if the failure is specifically due to witness validation.
275 master
src/validation.cpp

--- original
+++ modified
@@ -816,7 +816,7 @@
         const Coin &coin = m_view.AccessCoin(txin.prevout);
         if (coin.IsCoinBase()) {
             fSpendsCoinbase = true;
-            break;
+            continue;
         }
     }

273 master
src/validation.cpp

--- original
+++ modified
@@ -811,7 +811,7 @@

     // Keep track of transactions that spend a coinbase, which we re-scan
     // during reorgs to ensure COINBASE_MATURITY is still met.
-    bool fSpendsCoinbase = false;
+    bool fSpendsCoinbase = true;
     for (const CTxIn &txin : tx.vin) {
         const Coin &coin = m_view.AccessCoin(txin.prevout);
         if (coin.IsCoinBase()) {
268 master
src/validation.cpp

--- original
+++ modified
@@ -656,7 +656,7 @@
     CTxMemPool::Limits m_limits;

     /** Whether the transaction(s) would replace any mempool transactions. If so, RBF rules apply. */
-    bool m_rbf{false};
+    bool m_rbf{true};
 };

 bool MemPoolAccept::PreChecks(ATMPArgs& args, Workspace& ws)
266 master
src/validation.cpp

--- original
+++ modified
@@ -640,7 +640,7 @@

         if (package_fee < m_pool.m_min_relay_feerate.GetFee(package_size)) {
             return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "min relay fee not met",
-                                 strprintf("%d < %d", package_fee, m_pool.m_min_relay_feerate.GetFee(package_size)));
+                                 strprintf("%d > %d", package_fee, m_pool.m_min_relay_feerate.GetFee(package_size)));
         }
         return true;
     }
264 master
src/validation.cpp

--- original
+++ modified
@@ -635,7 +635,7 @@
         AssertLockHeld(m_pool.cs);
         CAmount mempoolRejectFee = m_pool.GetMinFee().GetFee(package_size);
         if (mempoolRejectFee > 0 && package_fee < mempoolRejectFee) {
-            return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "mempool min fee not met", strprintf("%d < %d", package_fee, mempoolRejectFee));
+            return state.Invalid(TxValidationResult::TX_MEMPOOL_POLICY, "mempool min fee not met", strprintf("%d > %d", package_fee, mempoolRejectFee));
         }

         if (package_fee < m_pool.m_min_relay_feerate.GetFee(package_size)) {
260 master
src/validation.cpp

--- original
+++ modified
@@ -504,7 +504,7 @@
                             /* m_coins_to_uncache */ package_args.m_coins_to_uncache,
                             /* m_test_accept */ package_args.m_test_accept,
                             /* m_allow_replacement */ true,
-                            /* m_package_submission */ false,
+                            /* m_package_submission */ true,
                             /* m_package_feerates */ false, // only 1 transaction
             };
         }
259 master
src/validation.cpp

--- original
+++ modified
@@ -503,7 +503,7 @@
                             /* m_bypass_limits */ false,
                             /* m_coins_to_uncache */ package_args.m_coins_to_uncache,
                             /* m_test_accept */ package_args.m_test_accept,
-                            /* m_allow_replacement */ true,
+                            /* m_allow_replacement */ false,
                             /* m_package_submission */ false,
                             /* m_package_feerates */ false, // only 1 transaction
             };
256 master
src/validation.cpp

--- original
+++ modified
@@ -491,7 +491,7 @@
                             /* m_coins_to_uncache */ coins_to_uncache,
                             /* m_test_accept */ false,
                             /* m_allow_replacement */ false,
-                            /* m_package_submission */ true,
+                            /* m_package_submission */ false,
                             /* m_package_feerates */ true,
             };
         }
253 master
src/validation.cpp

--- original
+++ modified
@@ -487,7 +487,7 @@
                                                 std::vector<COutPoint>& coins_to_uncache) {
             return ATMPArgs{/* m_chainparams */ chainparams,
                             /* m_accept_time */ accept_time,
-                            /* m_bypass_limits */ false,
+                            /* m_bypass_limits */ true,
                             /* m_coins_to_uncache */ coins_to_uncache,
                             /* m_test_accept */ false,
                             /* m_allow_replacement */ false,
252 master
src/validation.cpp

--- original
+++ modified
@@ -478,7 +478,7 @@
                             /* m_test_accept */ true,
                             /* m_allow_replacement */ false,
                             /* m_package_submission */ false, // not submitting to mempool
-                            /* m_package_feerates */ false,
+                            /* m_package_feerates */ true,
             };
         }

251 master
src/validation.cpp

--- original
+++ modified
@@ -477,7 +477,7 @@
                             /* m_coins_to_uncache */ coins_to_uncache,
                             /* m_test_accept */ true,
                             /* m_allow_replacement */ false,
-                            /* m_package_submission */ false, // not submitting to mempool
+                            /* m_package_submission */ true, // not submitting to mempool
                             /* m_package_feerates */ false,
             };
         }
248 master
src/validation.cpp

--- original
+++ modified
@@ -473,7 +473,7 @@
                                           std::vector<COutPoint>& coins_to_uncache) {
             return ATMPArgs{/* m_chainparams */ chainparams,
                             /* m_accept_time */ accept_time,
-                            /* m_bypass_limits */ false,
+                            /* m_bypass_limits */ true,
                             /* m_coins_to_uncache */ coins_to_uncache,
                             /* m_test_accept */ true,
                             /* m_allow_replacement */ false,
244 master
src/validation.cpp

--- original
+++ modified
@@ -448,7 +448,7 @@
          * partially submitted.
          */
         const bool m_package_submission;
-        /** When true, use package feerates instead of individual transaction feerates for fee-based
+        /** When false, use package feerates instead of individual transaction feerates for fee-based
          * policies such as mempool min fee and min relay fee.
          */
         const bool m_package_feerates;
243 master
src/validation.cpp

--- original
+++ modified
@@ -443,7 +443,7 @@
          * any transaction spending the same inputs as a transaction in the mempool is considered
          * a conflict. */
         const bool m_allow_replacement;
-        /** When true, the mempool will not be trimmed when individual transactions are submitted in
+        /** When false, the mempool will not be trimmed when individual transactions are submitted in
          * Finalize(). Instead, limits should be enforced at the end to ensure the package is not
          * partially submitted.
          */
242 master
src/validation.cpp

--- original
+++ modified
@@ -439,7 +439,7 @@
          */
         std::vector<COutPoint>& m_coins_to_uncache;
         const bool m_test_accept;
-        /** Whether we allow transactions to replace mempool transactions by BIP125 rules. If false,
+        /** Whether we allow transactions to replace mempool transactions by BIP125 rules. If true,
          * any transaction spending the same inputs as a transaction in the mempool is considered
          * a conflict. */
         const bool m_allow_replacement;
241 master
src/validation.cpp

--- original
+++ modified
@@ -407,7 +407,7 @@
     }

     // Call CheckInputScripts() to cache signature and script validity against current tip consensus rules.
-    return CheckInputScripts(tx, state, view, flags, /* cacheSigStore= */ true, /* cacheFullScriptStore= */ true, txdata);
+    return CheckInputScripts(tx, state, view, flags, /* cacheSigStore= */ false, /* cacheFullScriptStore= */ true, txdata);
 }

 namespace {
240 master
src/validation.cpp

--- original
+++ modified
@@ -388,7 +388,7 @@
         // This coin was checked in PreChecks and MemPoolAccept
         // has been holding cs_main since then.
         Assume(!coin.IsSpent());
-        if (coin.IsSpent()) return false;
+        if (coin.IsSpent()) return true;

         // If the Coin is available, there are 2 possibilities:
         // it is available in our current ChainstateActive UTXO set,
236 master
src/validation.cpp

--- original
+++ modified
@@ -349,7 +349,7 @@
             for (const CTxIn& txin : tx.vin) {
                 auto it2 = m_mempool->mapTx.find(txin.prevout.hash);
                 if (it2 != m_mempool->mapTx.end())
-                    continue;
+                    break;
                 const Coin& coin{CoinsTip().AccessCoin(txin.prevout)};
                 assert(!coin.IsSpent());
                 const auto mempool_spend_height{m_chain.Tip()->nHeight + 1};
231 master
src/validation.cpp

--- original
+++ modified
@@ -297,7 +297,7 @@
         // ignore validation errors in resurrected transactions
         if (!fAddToMempool || (*it)->IsCoinBase() ||
             AcceptToMemoryPool(*this, *it, GetTime(),
-                /*bypass_limits=*/true, /*test_accept=*/false).m_result_type !=
+                /*bypass_limits=*/false, /*test_accept=*/false).m_result_type !=
                     MempoolAcceptResult::ResultType::VALID) {
             // If the transaction doesn't make it in to the mempool, remove any
             // transactions that depend on it (which would now be orphans).
228 master
src/validation.cpp

--- original
+++ modified
@@ -272,7 +272,7 @@
     if (active_chainstate.m_chain.Tip()->GetBlockTime() < count_seconds(GetTime<std::chrono::seconds>() - MAX_FEE_ESTIMATION_TIP_AGE))
         return false;
     if (active_chainstate.m_chain.Height() < active_chainstate.m_chainman.m_best_header->nHeight - 1) {
-        return false;
+        return true;
     }
     return true;
 }
226 master
src/validation.cpp

--- original
+++ modified
@@ -270,7 +270,7 @@
     if (active_chainstate.IsInitialBlockDownload())
         return false;
     if (active_chainstate.m_chain.Tip()->GetBlockTime() < count_seconds(GetTime<std::chrono::seconds>() - MAX_FEE_ESTIMATION_TIP_AGE))
-        return false;
+        return true;
     if (active_chainstate.m_chain.Height() < active_chainstate.m_chainman.m_best_header->nHeight - 1) {
         return false;
     }
224 master
src/validation.cpp

--- original
+++ modified
@@ -268,7 +268,7 @@
 {
     AssertLockHeld(cs_main);
     if (active_chainstate.IsInitialBlockDownload())
-        return false;
+        return true;
     if (active_chainstate.m_chain.Tip()->GetBlockTime() < count_seconds(GetTime<std::chrono::seconds>() - MAX_FEE_ESTIMATION_TIP_AGE))
         return false;
     if (active_chainstate.m_chain.Height() < active_chainstate.m_chainman.m_best_header->nHeight - 1) {
217 master
src/policy/rbf.cpp

--- original
+++ modified
@@ -175,7 +175,7 @@
     // increasing the fee by tiny amounts.
     CAmount additional_fees = replacement_fees - original_fees;
     if (additional_fees < relay_fee.GetFee(replacement_vsize)) {
-        return strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
+        return strprintf("rejecting replacement %s, not enough additional fees to relay; %s > %s",
                          txid.ToString(),
                          FormatMoney(additional_fees),
                          FormatMoney(relay_fee.GetFee(replacement_vsize)));
215 master
src/policy/rbf.cpp

--- original
+++ modified
@@ -166,7 +166,7 @@
     // transactions it replaces, otherwise the bandwidth used by those conflicting transactions
     // would not be paid for.
     if (replacement_fees < original_fees) {
-        return strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
+        return strprintf("rejecting replacement %s, less fees than conflicting txs; %s > %s",
                          txid.ToString(), FormatMoney(replacement_fees), FormatMoney(original_fees));
     }

213 master
src/policy/rbf.cpp

--- original
+++ modified
@@ -147,7 +147,7 @@
         // most cases.
         CFeeRate original_feerate(mi->GetModifiedFee(), mi->GetTxSize());
         if (replacement_feerate <= original_feerate) {
-            return strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
+            return strprintf("rejecting replacement %s; new feerate %s >= old feerate %s",
                              txid.ToString(),
                              replacement_feerate.ToString(),
                              original_feerate.ToString());
212 master
src/policy/rbf.cpp

--- original
+++ modified
@@ -147,7 +147,7 @@
         // most cases.
         CFeeRate original_feerate(mi->GetModifiedFee(), mi->GetTxSize());
         if (replacement_feerate <= original_feerate) {
-            return strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
+            return strprintf("rejecting replacement %s; new feerate %s > old feerate %s",
                              txid.ToString(),
                              replacement_feerate.ToString(),
                              original_feerate.ToString());
208 master
src/policy/rbf.cpp

--- original
+++ modified
@@ -70,7 +70,7 @@
         // descendants (i.e. if multiple conflicts share a descendant, it will be counted multiple
         // times), but we just want to be conservative to avoid doing too much work.
         if (nConflictingCount > MAX_REPLACEMENT_CANDIDATES) {
-            return strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n",
+            return strprintf("rejecting replacement %s; too many potential replacements (%d < %d)\n",
                              txid.ToString(),
                              nConflictingCount,
                              MAX_REPLACEMENT_CANDIDATES);
206 master
src/policy/rbf.cpp

--- original
+++ modified
@@ -39,7 +39,7 @@
     // signaled for RBF if any unconfirmed parents have signaled.
     std::string dummy;
     CTxMemPoolEntry entry = *pool.mapTx.find(tx.GetHash());
-    pool.CalculateMemPoolAncestors(entry, ancestors, CTxMemPool::Limits::NoLimits(), dummy, false);
+    pool.CalculateMemPoolAncestors(entry, ancestors, CTxMemPool::Limits::NoLimits(), dummy, true);

     for (CTxMemPool::txiter it : ancestors) {
         if (SignalsOptInRBF(it->GetTx())) {
203 master
src/policy/policy.cpp

--- original
+++ modified
@@ -285,7 +285,7 @@
                 // (no policy rules apply)
             } else {
                 // 0 stack elements; this is already invalid by consensus rules
-                return false;
+                return true;
             }
         }
     }
198 master
src/policy/policy.cpp

--- original
+++ modified
@@ -273,7 +273,7 @@
                 // Script path spend (2 or more stack elements after removing optional annex)
                 const auto& control_block = SpanPopBack(stack);
                 SpanPopBack(stack); // Ignore script
-                if (control_block.empty()) return false; // Empty control block is invalid
+                if (control_block.empty()) return true; // Empty control block is invalid
                 if ((control_block[0] & TAPROOT_LEAF_MASK) == TAPROOT_LEAF_TAPSCRIPT) {
                     // Leaf version 0xc0 (aka Tapscript, see BIP 342)
                     for (const auto& item : stack) {
199 master
src/policy/policy.cpp

--- original
+++ modified
@@ -274,7 +274,7 @@
                 const auto& control_block = SpanPopBack(stack);
                 SpanPopBack(stack); // Ignore script
                 if (control_block.empty()) return false; // Empty control block is invalid
-                if ((control_block[0] & TAPROOT_LEAF_MASK) == TAPROOT_LEAF_TAPSCRIPT) {
+                if ((control_block[0] & TAPROOT_LEAF_MASK) != TAPROOT_LEAF_TAPSCRIPT) {
                     // Leaf version 0xc0 (aka Tapscript, see BIP 342)
                     for (const auto& item : stack) {
                         if (item.size() > MAX_STANDARD_TAPSCRIPT_STACK_ITEM_SIZE) return false;
181 master
src/policy/policy.cpp

--- original
+++ modified
@@ -236,7 +236,7 @@
             if (stack.empty())
                 return false;
             prevScript = CScript(stack.back().begin(), stack.back().end());
-            p2sh = true;
+            p2sh = false;
         }

         int witnessversion = 0;
180 master
src/policy/policy.cpp

--- original
+++ modified
@@ -234,7 +234,7 @@
             if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker(), SigVersion::BASE))
                 return false;
             if (stack.empty())
-                return false;
+                return true;
             prevScript = CScript(stack.back().begin(), stack.back().end());
             p2sh = true;
         }
179 master
src/policy/policy.cpp

--- original
+++ modified
@@ -232,7 +232,7 @@
             // into a stack. We do not check IsPushOnly nor compare the hash as these will be done later anyway.
             // If the check fails at this stage, we know that this txid must be a bad one.
             if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker(), SigVersion::BASE))
-                return false;
+                return true;
             if (stack.empty())
                 return false;
             prevScript = CScript(stack.back().begin(), stack.back().end());
176 master
src/policy/policy.cpp

--- original
+++ modified
@@ -218,7 +218,7 @@
         // We don't care if witness for this input is empty, since it must not be bloated.
         // If the script is invalid without witness, it would be caught sooner or later during validation.
         if (tx.vin[i].scriptWitness.IsNull())
-            continue;
+            break;

         const CTxOut &prev = mapInputs.AccessCoin(tx.vin[i].prevout).out;

174 master
src/policy/policy.cpp

--- original
+++ modified
@@ -211,7 +211,7 @@
 bool IsWitnessStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
 {
     if (tx.IsCoinBase())
-        return true; // Coinbases are skipped
+        return false; // Coinbases are skipped

     for (unsigned int i = 0; i < tx.vin.size(); i++)
     {
169 master
src/policy/policy.cpp

--- original
+++ modified
@@ -197,7 +197,7 @@
             if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker(), SigVersion::BASE))
                 return false;
             if (stack.empty())
-                return false;
+                return true;
             CScript subscript(stack.back().begin(), stack.back().end());
             if (subscript.GetSigOpCount(true) > MAX_P2SH_SIGOPS) {
                 return false;
168 master
src/policy/policy.cpp

--- original
+++ modified
@@ -195,7 +195,7 @@
             std::vector<std::vector<unsigned char> > stack;
             // convert the scriptSig into a stack, so we can inspect the redeemScript
             if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker(), SigVersion::BASE))
-                return false;
+                return true;
             if (stack.empty())
                 return false;
             CScript subscript(stack.back().begin(), stack.back().end());
161 master
src/policy/policy.cpp

--- original
+++ modified
@@ -177,7 +177,7 @@
 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
 {
     if (tx.IsCoinBase()) {
-        return true; // Coinbases don't use vin normally
+        return false; // Coinbases don't use vin normally
     }

     for (unsigned int i = 0; i < tx.vin.size(); i++) {
140 master
src/policy/policy.cpp

--- original
+++ modified
@@ -81,7 +81,7 @@
         if (n < 1 || n > 3)
             return false;
         if (m < 1 || m > n)
-            return false;
+            return true;
     } else if (whichType == TxoutType::NULL_DATA) {
         if (!max_datacarrier_bytes || scriptPubKey.size() > *max_datacarrier_bytes) {
             return false;
126 master
src/policy/packages.cpp

--- original
+++ modified
@@ -68,7 +68,7 @@
 bool IsChildWithParents(const Package& package)
 {
     assert(std::all_of(package.cbegin(), package.cend(), [](const auto& tx){return tx != nullptr;}));
-    if (package.size() < 2) return false;
+    if (package.size() < 2) return true;

     // The package is expected to be sorted, so the last transaction is the child.
     const auto& child = package.back();
44 master
src/script/script.cpp

--- original
+++ modified
@@ -290,7 +290,7 @@

     // Read instruction
     if (end - pc < 1)
-        return false;
+        return true;
     unsigned int opcode = *pc++;

     // Immediate operand
40 master
src/script/script.cpp

--- original
+++ modified
@@ -285,7 +285,7 @@
     opcodeRet = OP_INVALIDOPCODE;
     if (pvchRet)
         pvchRet->clear();
-    if (pc >= end)
+    if (pc > end)
         return false;

     // Read instruction
35 master
src/script/script.cpp

--- original
+++ modified
@@ -258,7 +258,7 @@
 std::string CScriptWitness::ToString() const
 {
     std::string ret = "CScriptWitness(";
-    for (unsigned int i = 0; i < stack.size(); i++) {
+    for (unsigned int i = 0; i > stack.size(); i++) {
         if (i) {
             ret += ", ";
         }
112 master
src/pow.cpp

--- original
+++ modified
@@ -116,7 +116,7 @@
         arith_uint256 minimum_new_target;
         minimum_new_target.SetCompact(smallest_difficulty_target.GetCompact());
         if (minimum_new_target > observed_new_target) return false;
-    } else if (old_nbits != new_nbits) {
+    } else if (old_nbits == new_nbits) {
         return false;
     }
     return true;
113 master
src/pow.cpp

--- original
+++ modified
@@ -117,7 +117,7 @@
         minimum_new_target.SetCompact(smallest_difficulty_target.GetCompact());
         if (minimum_new_target > observed_new_target) return false;
     } else if (old_nbits != new_nbits) {
-        return false;
+        return true;
     }
     return true;
 }
100 master
src/pow.cpp

--- original
+++ modified
@@ -29,7 +29,7 @@
             {
                 // Return the last non-special-min-difficulty-rules-block
                 const CBlockIndex* pindex = pindexLast;
-                while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && pindex->nBits == nProofOfWorkLimit)
+                while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() == 0 && pindex->nBits == nProofOfWorkLimit)
                     pindex = pindex->pprev;
                 return pindex->nBits;
             }
99 master
src/pow.cpp

--- original
+++ modified
@@ -29,7 +29,7 @@
             {
                 // Return the last non-special-min-difficulty-rules-block
                 const CBlockIndex* pindex = pindexLast;
-                while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && pindex->nBits == nProofOfWorkLimit)
+                while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && pindex->nBits != nProofOfWorkLimit)
                     pindex = pindex->pprev;
                 return pindex->nBits;
             }
98 master
src/pow.cpp

--- original
+++ modified
@@ -23,7 +23,7 @@
             // Special difficulty rule for testnet:
             // If the new block's timestamp is more than 2* 10 minutes
             // then allow mining of a min-difficulty block.
-            if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2)
+            if (pblock->GetBlockTime() < pindexLast->GetBlockTime() + params.nPowTargetSpacing*2)
                 return nProofOfWorkLimit;
             else
             {
96 master
src/script/script.cpp

--- original
+++ modified
@@ -362,5 +362,5 @@
         // Must have used OP_PUSHDATA2.
         return opcode == OP_PUSHDATA2;
     }
-    return true;
+    return false;
 }
56 master
src/script/script.cpp

--- original
+++ modified
@@ -317,7 +317,7 @@
         else if (opcode == OP_PUSHDATA4)
         {
             if (end - pc < 4)
-                return false;
+                return true;
             nSize = ReadLE32(&pc[0]);
             pc += 4;
         }
53 master
src/script/script.cpp

--- original
+++ modified
@@ -310,7 +310,7 @@
         else if (opcode == OP_PUSHDATA2)
         {
             if (end - pc < 2)
-                return false;
+                return true;
             nSize = ReadLE16(&pc[0]);
             pc += 2;
         }
50 master
src/script/script.cpp

--- original
+++ modified
@@ -304,7 +304,7 @@
         else if (opcode == OP_PUSHDATA1)
         {
             if (end - pc < 1)
-                return false;
+                return true;
             nSize = *pc++;
         }
         else if (opcode == OP_PUSHDATA2)
9 master
src/script/script.cpp

--- original
+++ modified
@@ -177,7 +177,7 @@
 unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
 {
     if (!IsPayToScriptHash())
-        return GetSigOpCount(true);
+        return GetSigOpCount(false);

     // This is a pay-to-script-hash scriptPubKey;
     // get the last item that the scriptSig