Merge bitcoin/bitcoin#36890: Update secp256k1 subtree to latest master
What changed, and why it matters
This is a routine subtree update for the secp256k1 cryptographic library inside Bitcoin Core. It pulls in several upstream fixes, most of which are build-system cleanups, test improvements, and API hardening. The most user-visible changes make the Silent Payments module behave better when a transaction has no relevant inputs or outputs, and make ECDH/MuSig code more careful about clearing secret intermediate values from memory. There is no evidence in the commit message or diff of an active security vulnerability being patched.
Treat as a normal dependency update. Reviewers should verify that Bitcoin Core's own build still links the new INTERFACE targets correctly and that downstream projects using the secp256k1 subtree are not relying on the old global compile definitions. No urgent security patch is indicated by the supplied materials.
Security signals we found
Silent Payments API no longer aborts on empty input/output arrays; returns 0 per documented behavior
Silent Payments label-tweak overflow now rejected with ARG_CHECK instead of being silently handled
ecmult_const gains a _ge variant that clears intermediate Jacobian coordinates to reduce secret leakage
ECDH and silentpayments shared-secret paths updated to use the new clearing variant
CMake compile definitions moved from global add_compile_definitions to target-specific INTERFACE targets
modinv32/modinv64 volatile-variable usage adjusted to avoid unsequenced-read UB
Public-key parsing split into size-specific helpers (parse33, parse65, parse_with_hybrid65)
Evidence from the diff
The commit merges bitcoin/bitcoin#36890, updating the src/secp256k1 subtree from a7f264373e to 659f03b076. The upstream delta includes: CMake build hygiene (moving global compile definitions/options onto INTERFACE targets secp256k1_common/secp256k1_modules), CI matrix simplification, fixes for Clang 24 and CMake >=4.5 warnings, documentation corrections, API hardening in the silentpayments module (return 0 instead of aborting on empty inputs, allowing NULL arrays when size is 0, and rejecting label tweaks that overflow the group order), memory-clearing improvements in ecmult_const and ECDH, and new tests. The diff does not contain an explicit CVE or vendor security advisory.
Changed components
src/secp256k1 (libsecp256k1 subtree)Silent Payments moduleECDH moduleMuSig moduleCMake build configurationsecp256k1 public-key parsingInspect captured patch +902 / −491
### src/secp256k1/.github/workflows/ci.yml
@@ -33,13 +33,13 @@ env:
EXTRAFLAGS:
### secp256k1 modules
EXPERIMENTAL: 'no'
- ECDH: 'no'
- RECOVERY: 'no'
- EXTRAKEYS: 'no'
- SCHNORRSIG: 'no'
- MUSIG: 'no'
- ELLSWIFT: 'no'
- SILENTPAYMENTS: 'no'
+ ECDH: 'yes'
+ RECOVERY: 'yes'
+ EXTRAKEYS: 'yes'
+ SCHNORRSIG: 'yes'
+ MUSIG: 'yes'
+ ELLSWIFT: 'yes'
+ SILENTPAYMENTS: 'yes'
### test options
SECP256K1_TEST_ITERS: 64
BENCH: 'yes'
@@ -48,6 +48,9 @@ env:
SYMBOL_CHECK: 'yes'
# Compile and run the examples.
EXAMPLES: 'yes'
+ # Also run exhaustive_tests for this group order, with these command line arguments.
+ EXHAUSTIVE_TEST_ORDER:
+ EXHAUSTIVE_TEST_ARGS:
# Disable Docker build summary generation.
# See https://github.com/docker/build-push-action/blob/master/README.md#environment-variables.
DOCKER_BUILD_SUMMARY: false
@@ -96,21 +99,24 @@ jobs:
fail-fast: false
matrix:
configuration:
- - env_vars: { WIDEMUL: 'int64', RECOVERY: 'yes' }
- - env_vars: { WIDEMUL: 'int64', ECDH: 'yes', EXTRAKEYS: 'yes', SCHNORRSIG: 'yes', MUSIG: 'yes', ELLSWIFT: 'yes', SILENTPAYMENTS: 'yes' }
+ - env_vars: { WIDEMUL: 'int64' }
- env_vars: { WIDEMUL: 'int128' }
- - env_vars: { WIDEMUL: 'int128_struct', ELLSWIFT: 'yes' }
- - env_vars: { WIDEMUL: 'int128', RECOVERY: 'yes', EXTRAKEYS: 'yes', SCHNORRSIG: 'yes', MUSIG: 'yes', ELLSWIFT: 'yes' }
- - env_vars: { WIDEMUL: 'int128', ECDH: 'yes', EXTRAKEYS: 'yes', SCHNORRSIG: 'yes', MUSIG: 'yes', SILENTPAYMENTS: 'yes' }
- - env_vars: { WIDEMUL: 'int128', ASM: 'x86_64', ELLSWIFT: 'yes' }
- - env_vars: { RECOVERY: 'yes', EXTRAKEYS: 'yes', SCHNORRSIG: 'yes', MUSIG: 'yes' }
- - env_vars: { CTIMETESTS: 'no', RECOVERY: 'yes', ECDH: 'yes', EXTRAKEYS: 'yes', SCHNORRSIG: 'yes', MUSIG: 'yes', SILENTPAYMENTS: 'yes', CPPFLAGS: '-DVERIFY' }
+ - env_vars: { WIDEMUL: 'int128_struct' }
+ - env_vars: { WIDEMUL: 'int128', ASM: 'x86_64' }
+ - env_vars: { CTIMETESTS: 'no', CPPFLAGS: '-DVERIFY' }
- env_vars: { BUILD: 'distcheck', WITH_VALGRIND: 'no', CTIMETESTS: 'no', BENCH: 'no' }
- env_vars: { CPPFLAGS: '-DDETERMINISTIC' }
- env_vars: { CFLAGS: '-O0', CTIMETESTS: 'no' }
- - env_vars: { CFLAGS: '-O1', RECOVERY: 'yes', ECDH: 'yes', EXTRAKEYS: 'yes', SCHNORRSIG: 'yes', MUSIG: 'yes', ELLSWIFT: 'yes', SILENTPAYMENTS: 'yes' }
+ - env_vars: { CFLAGS: '-O1' }
- env_vars: { ECMULTGENKB: 2, ECMULTWINDOW: 2 }
- env_vars: { ECMULTGENKB: 86, ECMULTWINDOW: 4 }
+ - env_vars: { ECDH: 'no' }
+ - env_vars: { RECOVERY: 'no' }
+ - env_vars: { EXTRAKEYS: 'no', SCHNORRSIG: 'no', MUSIG: 'no', SILENTPAYMENTS: 'no' }
+ - env_vars: { SCHNORRSIG: 'no', MUSIG: 'no' }
+ - env_vars: { MUSIG: 'no' }
+ - env_vars: { ELLSWIFT: 'no' }
+ - env_vars: { SILENTPAYMENTS: 'no' }
cc:
- 'gcc'
- 'clang'
@@ -155,13 +161,6 @@ jobs:
env:
HOST: 'i686-linux-gnu'
- ECDH: 'yes'
- RECOVERY: 'yes'
- EXTRAKEYS: 'yes'
- SCHNORRSIG: 'yes'
- MUSIG: 'yes'
- ELLSWIFT: 'yes'
- SILENTPAYMENTS: 'yes'
CC: ${{ matrix.cc }}
steps:
@@ -184,13 +183,6 @@ jobs:
SECP256K1_TEST_ITERS: 16
HOST: 's390x-linux-gnu'
WITH_VALGRIND: 'no'
- ECDH: 'yes'
- RECOVERY: 'yes'
- EXTRAKEYS: 'yes'
- SCHNORRSIG: 'yes'
- MUSIG: 'yes'
- ELLSWIFT: 'yes'
- SILENTPAYMENTS: 'yes'
CTIMETESTS: 'no'
steps:
@@ -215,13 +207,6 @@ jobs:
SECP256K1_TEST_ITERS: 16
HOST: 'arm-linux-gnueabihf'
WITH_VALGRIND: 'no'
- ECDH: 'yes'
- RECOVERY: 'yes'
- EXTRAKEYS: 'yes'
- SCHNORRSIG: 'yes'
- MUSIG: 'yes'
- ELLSWIFT: 'yes'
- SILENTPAYMENTS: 'yes'
CTIMETESTS: 'no'
steps:
@@ -236,15 +221,6 @@ jobs:
env:
SECP256K1_TEST_ITERS: 16
- WITH_VALGRIND: 'no'
- ECDH: 'yes'
- RECOVERY: 'yes'
- EXTRAKEYS: 'yes'
- SCHNORRSIG: 'yes'
- MUSIG: 'yes'
- ELLSWIFT: 'yes'
- SILENTPAYMENTS: 'yes'
- CTIMETESTS: 'no'
CC: ${{ matrix.cc }}
strategy:
@@ -278,13 +254,6 @@ jobs:
SECP256K1_TEST_ITERS: 16
HOST: 'powerpc64le-linux-gnu'
WITH_VALGRIND: 'no'
- ECDH: 'yes'
- RECOVERY: 'yes'
- EXTRAKEYS: 'yes'
- SCHNORRSIG: 'yes'
- MUSIG: 'yes'
- ELLSWIFT: 'yes'
- SILENTPAYMENTS: 'yes'
CTIMETESTS: 'no'
steps:
@@ -309,7 +278,7 @@ jobs:
env_vars: { CC: 'i686-linux-gnu-gcc', HOST: 'i686-linux-gnu', ASM: 'auto' }
- runner: ubuntu-24.04-arm
binary_arch: arm64
- env_vars: { CC: 'clang', ASM: 'auto' }
+ env_vars: { CC: 'clang', ASM: 'auto', CTIMETESTS: 'yes' }
- runner: ubuntu-latest
binary_arch: x64
env_vars: { CC: 'clang', ASM: 'no', ECMULTGENKB: 2, ECMULTWINDOW: 2 }
@@ -318,19 +287,12 @@ jobs:
env_vars: { CC: 'i686-linux-gnu-gcc', HOST: 'i686-linux-gnu', ASM: 'no', ECMULTGENKB: 2, ECMULTWINDOW: 2 }
- runner: ubuntu-24.04-arm
binary_arch: arm64
- env_vars: { CC: 'clang', ASM: 'no', ECMULTGENKB: 2, ECMULTWINDOW: 2 }
+ env_vars: { CC: 'clang', ASM: 'no', ECMULTGENKB: 2, ECMULTWINDOW: 2, CTIMETESTS: 'yes' }
env:
# The `--error-exitcode` is required to make the test fail if valgrind found errors,
# otherwise it will return 0 (https://www.valgrind.org/docs/manual/manual-core.html).
WRAPPER_CMD: 'valgrind --error-exitcode=42'
- ECDH: 'yes'
- RECOVERY: 'yes'
- EXTRAKEYS: 'yes'
- SCHNORRSIG: 'yes'
- MUSIG: 'yes'
- ELLSWIFT: 'yes'
- SILENTPAYMENTS: 'yes'
CTIMETESTS: 'no'
SECP256K1_TEST_ITERS: 2
@@ -354,13 +316,6 @@ jobs:
- env_vars: { CC: 'i686-linux-gnu-gcc', HOST: 'i686-linux-gnu', ASM: 'no', ECMULTGENKB: 2, ECMULTWINDOW: 2 }
env:
- ECDH: 'yes'
- RECOVERY: 'yes'
- EXTRAKEYS: 'yes'
- SCHNORRSIG: 'yes'
- MUSIG: 'yes'
- ELLSWIFT: 'yes'
- SILENTPAYMENTS: 'yes'
CTIMETESTS: 'no'
CFLAGS: '-fsanitize=undefined,address -g'
UBSAN_OPTIONS: 'print_stacktrace=1:halt_on_error=1'
@@ -374,6 +329,33 @@ jobs:
- *CI_SCRIPT_IN_DOCKER
- *PRINT_LOGS
+ exhaustive_debian:
+ name: "Exhaustive tests, group order ${{ matrix.configuration.env_vars.EXHAUSTIVE_TEST_ORDER }}"
+ runs-on: ubuntu-latest
+ needs: docker_cache
+
+ strategy:
+ fail-fast: false
+ matrix:
+ configuration:
+ - env_vars: { EXHAUSTIVE_TEST_ORDER: 7 }
+ # A full run takes weeks: run one part in 20000.
+ - env_vars: { EXHAUSTIVE_TEST_ORDER: 199, EXHAUSTIVE_TEST_ARGS: '2 00000000000000000000000000000000 20000 0' }
+
+ env:
+ CC: 'gcc'
+ BUILD: 'exhaustive_tests'
+ WITH_VALGRIND: 'no'
+ CTIMETESTS: 'no'
+ BENCH: 'no'
+ EXAMPLES: 'no'
+ SYMBOL_CHECK: 'no'
+
+ steps:
+ - *CHECKOUT
+ - *CI_SCRIPT_IN_DOCKER
+ - *PRINT_LOGS
+
msan_debian:
name: "MSan"
runs-on: ubuntu-latest
@@ -401,13 +383,6 @@ jobs:
- 'clang-snapshot'
env:
- ECDH: 'yes'
- RECOVERY: 'yes'
- EXTRAKEYS: 'yes'
- SCHNORRSIG: 'yes'
- MUSIG: 'yes'
- ELLSWIFT: 'yes'
- SILENTPAYMENTS: 'yes'
CC: ${{ matrix.cc }}
SECP256K1_TEST_ITERS: 32
ASM: 'no'
@@ -421,19 +396,13 @@ jobs:
mingw_debian:
name: ${{ matrix.configuration.job_name }}
- runs-on: ubuntu-latest
+ # Wine fails on ubuntu-26.04 until https://github.com/actions/runner-images/issues/14790 is fixed.
+ runs-on: ubuntu-24.04
needs: docker_cache
env:
WRAPPER_CMD: 'wine'
WITH_VALGRIND: 'no'
- ECDH: 'yes'
- RECOVERY: 'yes'
- EXTRAKEYS: 'yes'
- SCHNORRSIG: 'yes'
- MUSIG: 'yes'
- ELLSWIFT: 'yes'
- SILENTPAYMENTS: 'yes'
CTIMETESTS: 'no'
strategy:
@@ -466,15 +435,13 @@ jobs:
fail-fast: false
matrix:
env_vars:
- - { WIDEMUL: 'int64', RECOVERY: 'yes', ECDH: 'yes', EXTRAKEYS: 'yes', SCHNORRSIG: 'yes', MUSIG: 'yes', ELLSWIFT: 'yes', SILENTPAYMENTS: 'yes' }
+ - { WIDEMUL: 'int64' }
- { WIDEMUL: 'int128_struct', ECMULTGENKB: 2, ECMULTWINDOW: 4 }
- - { WIDEMUL: 'int128', ECDH: 'yes', EXTRAKEYS: 'yes', SCHNORRSIG: 'yes', MUSIG: 'yes', ELLSWIFT: 'yes', SILENTPAYMENTS: 'yes' }
- - { WIDEMUL: 'int128', RECOVERY: 'yes' }
- - { WIDEMUL: 'int128', RECOVERY: 'yes', ECDH: 'yes', EXTRAKEYS: 'yes', SCHNORRSIG: 'yes', MUSIG: 'yes', ELLSWIFT: 'yes', SILENTPAYMENTS: 'yes' }
- - { WIDEMUL: 'int128', RECOVERY: 'yes', ECDH: 'yes', EXTRAKEYS: 'yes', SCHNORRSIG: 'yes', MUSIG: 'yes', ELLSWIFT: 'yes', SILENTPAYMENTS: 'yes', CC: 'gcc' }
- - { WIDEMUL: 'int128', RECOVERY: 'yes', ECDH: 'yes', EXTRAKEYS: 'yes', SCHNORRSIG: 'yes', MUSIG: 'yes', ELLSWIFT: 'yes', SILENTPAYMENTS: 'yes', WRAPPER_CMD: 'valgrind --error-exitcode=42', SECP256K1_TEST_ITERS: 2 }
- - { WIDEMUL: 'int128', RECOVERY: 'yes', ECDH: 'yes', EXTRAKEYS: 'yes', SCHNORRSIG: 'yes', MUSIG: 'yes', ELLSWIFT: 'yes', SILENTPAYMENTS: 'yes', CC: 'gcc', WRAPPER_CMD: 'valgrind --error-exitcode=42', SECP256K1_TEST_ITERS: 2 }
- - { WIDEMUL: 'int128', RECOVERY: 'yes', ECDH: 'yes', EXTRAKEYS: 'yes', SCHNORRSIG: 'yes', MUSIG: 'yes', ELLSWIFT: 'yes', CPPFLAGS: '-DVERIFY', CTIMETESTS: 'no' }
+ - { WIDEMUL: 'int128' }
+ - { WIDEMUL: 'int128', CC: 'gcc' }
+ - { WIDEMUL: 'int128', WRAPPER_CMD: 'valgrind --error-exitcode=42', SECP256K1_TEST_ITERS: 2 }
+ - { WIDEMUL: 'int128', CC: 'gcc', WRAPPER_CMD: 'valgrind --error-exitcode=42', SECP256K1_TEST_ITERS: 2 }
+ - { WIDEMUL: 'int128', CPPFLAGS: '-DVERIFY', CTIMETESTS: 'no' }
- BUILD: 'distcheck'
steps:
@@ -507,9 +474,9 @@ jobs:
- *PRINT_LOGS
arm64-macos-native:
- name: "ARM64: macOS Sonoma"
+ name: "ARM64: macOS Sequoia"
# See: https://github.com/actions/runner-images#available-images.
- runs-on: macos-14
+ runs-on: macos-15
env:
CC: 'clang'
@@ -523,13 +490,11 @@ jobs:
fail-fast: false
matrix:
env_vars:
- - { WIDEMUL: 'int64', RECOVERY: 'yes', ECDH: 'yes', EXTRAKEYS: 'yes', SCHNORRSIG: 'yes', MUSIG: 'yes', ELLSWIFT: 'yes', SILENTPAYMENTS: 'yes' }
+ - { WIDEMUL: 'int64' }
- { WIDEMUL: 'int128_struct', ECMULTGENKB: 2, ECMULTWINDOW: 4 }
- - { WIDEMUL: 'int128', ECDH: 'yes', EXTRAKEYS: 'yes', SCHNORRSIG: 'yes', MUSIG: 'yes', ELLSWIFT: 'yes', SILENTPAYMENTS: 'yes' }
- - { WIDEMUL: 'int128', RECOVERY: 'yes' }
- - { WIDEMUL: 'int128', RECOVERY: 'yes', ECDH: 'yes', EXTRAKEYS: 'yes', SCHNORRSIG: 'yes', MUSIG: 'yes', ELLSWIFT: 'yes', SILENTPAYMENTS: 'yes' }
- - { WIDEMUL: 'int128', RECOVERY: 'yes', ECDH: 'yes', EXTRAKEYS: 'yes', SCHNORRSIG: 'yes', MUSIG: 'yes', ELLSWIFT: 'yes', SILENTPAYMENTS: 'yes', CC: 'gcc' }
- - { WIDEMUL: 'int128', RECOVERY: 'yes', ECDH: 'yes', EXTRAKEYS: 'yes', SCHNORRSIG: 'yes', MUSIG: 'yes', ELLSWIFT: 'yes', SILENTPAYMENTS: 'yes', CPPFLAGS: '-DVERIFY' }
+ - { WIDEMUL: 'int128' }
+ - { WIDEMUL: 'int128', CC: 'gcc' }
+ - { WIDEMUL: 'int128', CPPFLAGS: '-DVERIFY' }
- BUILD: 'distcheck'
steps:
@@ -635,13 +600,6 @@ jobs:
CFLAGS: '-fpermissive -g'
CPPFLAGS: '-DSECP256K1_CPLUSPLUS_TEST_OVERRIDE'
WERROR_CFLAGS:
- ECDH: 'yes'
- RECOVERY: 'yes'
- EXTRAKEYS: 'yes'
- SCHNORRSIG: 'yes'
- MUSIG: 'yes'
- ELLSWIFT: 'yes'
- SILENTPAYMENTS: 'yes'
steps:
- *CHECKOUT
### src/secp256k1/CHANGELOG.md
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
#### Fixed
- Module `silentpayments`: `secp256k1_silentpayments_sender_create_outputs` and `secp256k1_silentpayments_recipient_prevouts_summary_create` no longer require empty key arrays to be passed as `NULL`. If the corresponding size argument is 0, the array pointer is ignored. This matches the API documentation, which only states that unused arrays *can* be `NULL`, and spares callers from special-casing empty arrays.
+ - Module `silentpayments`: `secp256k1_silentpayments_recipient_prevouts_summary_create` and `secp256k1_silentpayments_recipient_scan_outputs` now return 0 when called with no input public keys or no taproot outputs, respectively, instead of treating this as an illegal argument (which by default calls `abort()`). In addition, `secp256k1_silentpayments_recipient_scan_outputs` no longer requires `tx_outputs` and `found_outputs` to be non-`NULL` if `n_tx_outputs` is 0. This matches the API documentation, which states that 0 is returned if the transaction is not a Silent Payments transaction, and allows callers to pass transactions without eligible inputs or without taproot outputs as is.
## [0.8.0] - 2026-08-03
### src/secp256k1/CMakeLists.txt
@@ -31,6 +31,10 @@ set(${PROJECT_NAME}_LIB_VERSION_AGE 0)
set(CMAKE_C_STANDARD 90)
set(CMAKE_C_EXTENSIONS OFF)
+# Usage requirements shared by all targets of this project. Every
+# target that compiles sources of this project links to it.
+add_library(secp256k1_common INTERFACE)
+
#=============================
# Configurable options
#=============================
@@ -56,35 +60,47 @@ option(SECP256K1_ENABLE_MODULE_SILENTPAYMENTS "Enable Silent Payments module." O
option(SECP256K1_USE_EXTERNAL_DEFAULT_CALLBACKS "Enable external default callback functions." OFF)
if(SECP256K1_USE_EXTERNAL_DEFAULT_CALLBACKS)
- add_compile_definitions(USE_EXTERNAL_DEFAULT_CALLBACKS=1)
+ target_compile_definitions(secp256k1_common INTERFACE
+ USE_EXTERNAL_DEFAULT_CALLBACKS=1
+ )
endif()
set(SECP256K1_ECMULT_WINDOW_SIZE 15 CACHE STRING "Window size for ecmult precomputation for verification, specified as integer in range [2..24]. The default value is a reasonable setting for desktop machines (currently 15). [default=15]")
set_property(CACHE SECP256K1_ECMULT_WINDOW_SIZE PROPERTY STRINGS 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24)
include(CheckStringOptionValue)
check_string_option_value(SECP256K1_ECMULT_WINDOW_SIZE)
-add_compile_definitions(ECMULT_WINDOW_SIZE=${SECP256K1_ECMULT_WINDOW_SIZE})
+target_compile_definitions(secp256k1_common INTERFACE
+ ECMULT_WINDOW_SIZE=${SECP256K1_ECMULT_WINDOW_SIZE}
+)
set(SECP256K1_ECMULT_GEN_KB 86 CACHE STRING "The size of the precomputed table for signing in multiples of 1024 bytes (on typical platforms). Larger values result in possibly better signing or key generation performance at the cost of a larger table. Valid choices are 2, 22, 86. The default value is a reasonable setting for desktop machines (currently 86). [default=86]")
set_property(CACHE SECP256K1_ECMULT_GEN_KB PROPERTY STRINGS 2 22 86)
check_string_option_value(SECP256K1_ECMULT_GEN_KB)
if(SECP256K1_ECMULT_GEN_KB EQUAL 2)
- add_compile_definitions(COMB_BLOCKS=2)
- add_compile_definitions(COMB_TEETH=5)
+ target_compile_definitions(secp256k1_common INTERFACE
+ COMB_BLOCKS=2
+ COMB_TEETH=5
+ )
elseif(SECP256K1_ECMULT_GEN_KB EQUAL 22)
- add_compile_definitions(COMB_BLOCKS=11)
- add_compile_definitions(COMB_TEETH=6)
+ target_compile_definitions(secp256k1_common INTERFACE
+ COMB_BLOCKS=11
+ COMB_TEETH=6
+ )
elseif(SECP256K1_ECMULT_GEN_KB EQUAL 86)
- add_compile_definitions(COMB_BLOCKS=43)
- add_compile_definitions(COMB_TEETH=6)
+ target_compile_definitions(secp256k1_common INTERFACE
+ COMB_BLOCKS=43
+ COMB_TEETH=6
+ )
endif()
set(SECP256K1_TEST_OVERRIDE_WIDE_MULTIPLY "OFF" CACHE STRING "Test-only override of the (autodetected by the C code) \"widemul\" setting. Legal values are: \"OFF\", \"int128_struct\", \"int128\" or \"int64\". [default=OFF]")
set_property(CACHE SECP256K1_TEST_OVERRIDE_WIDE_MULTIPLY PROPERTY STRINGS "OFF" "int128_struct" "int128" "int64")
check_string_option_value(SECP256K1_TEST_OVERRIDE_WIDE_MULTIPLY)
if(SECP256K1_TEST_OVERRIDE_WIDE_MULTIPLY)
string(TOUPPER "${SECP256K1_TEST_OVERRIDE_WIDE_MULTIPLY}" widemul_upper_value)
- add_compile_definitions(USE_FORCE_WIDEMUL_${widemul_upper_value}=1)
+ target_compile_definitions(secp256k1_common INTERFACE
+ USE_FORCE_WIDEMUL_${widemul_upper_value}=1
+ )
endif()
mark_as_advanced(FORCE SECP256K1_TEST_OVERRIDE_WIDE_MULTIPLY)
@@ -96,7 +112,9 @@ if(SECP256K1_ASM STREQUAL "arm32")
include(CheckArm32Assembly)
check_arm32_assembly()
if(HAVE_ARM32_ASM)
- add_compile_definitions(USE_EXTERNAL_ASM=1)
+ target_compile_definitions(secp256k1_common INTERFACE
+ USE_EXTERNAL_ASM=1
+ )
else()
message(FATAL_ERROR "ARM32 assembly requested but not available.")
endif()
@@ -105,7 +123,9 @@ elseif(SECP256K1_ASM)
check_x86_64_assembly()
if(HAVE_X86_64_ASM)
set(SECP256K1_ASM "x86_64")
- add_compile_definitions(USE_ASM_X86_64=1)
+ target_compile_definitions(secp256k1_common INTERFACE
+ USE_ASM_X86_64=1
+ )
elseif(SECP256K1_ASM STREQUAL "AUTO")
set(SECP256K1_ASM "OFF")
else()
@@ -127,8 +147,12 @@ if(SECP256K1_VALGRIND)
find_package(Valgrind MODULE)
if(Valgrind_FOUND)
set(SECP256K1_VALGRIND ON)
- include_directories(${Valgrind_INCLUDE_DIR})
- add_compile_definitions(VALGRIND)
+ target_compile_definitions(secp256k1_common INTERFACE
+ VALGRIND
+ )
+ target_include_directories(secp256k1_common INTERFACE
+ ${Valgrind_INCLUDE_DIR}
+ )
elseif(SECP256K1_VALGRIND STREQUAL "AUTO")
set(SECP256K1_VALGRIND OFF)
else()
@@ -149,7 +173,9 @@ if(MSVC)
string(REGEX REPLACE "/DNDEBUG[ \t\r\n]*" "" CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE}")
string(REGEX REPLACE "/DNDEBUG[ \t\r\n]*" "" CMAKE_C_FLAGS_MINSIZEREL "${CMAKE_C_FLAGS_MINSIZEREL}")
# Match GCC/Clang's size-optimization macro for the inline guard
- add_compile_definitions($<$<CONFIG:MinSizeRel>:__OPTIMIZE_SIZE__=1>)
+ target_compile_definitions(secp256k1_common INTERFACE
+ $<$<CONFIG:MinSizeRel>:__OPTIMIZE_SIZE__=1>
+ )
else()
string(REGEX REPLACE "-DNDEBUG[ \t\r\n]*" "" CMAKE_C_FLAGS_RELWITHDEBINFO "${CMAKE_C_FLAGS_RELWITHDEBINFO}")
string(REGEX REPLACE "-DNDEBUG[ \t\r\n]*" "" CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE}")
@@ -202,42 +228,44 @@ endif()
include(TryAppendCFlags)
if(MSVC)
# For both cl and clang-cl compilers.
- try_append_c_flags(/W3) # Production quality warning level.
+ try_append_c_flags(/W3 TARGET secp256k1_common) # Production quality warning level.
# Eliminate deprecation warnings for the older, less secure functions.
- add_compile_definitions(_CRT_SECURE_NO_WARNINGS)
+ target_compile_definitions(secp256k1_common INTERFACE
+ _CRT_SECURE_NO_WARNINGS
+ )
else()
- try_append_c_flags(-Wall) # GCC >= 2.95 and probably many other compilers.
-endif()
+ try_append_c_flags(-Wall TARGET secp256k1_common) # GCC >= 2.95 and probably many other compilers.
+endif()
if(CMAKE_C_COMPILER_ID STREQUAL "MSVC")
# Keep the following commands ordered lexicographically.
- try_append_c_flags(/wd4146) # Disable warning C4146 "unary minus operator applied to unsigned type, result still unsigned".
- try_append_c_flags(/wd4244) # Disable warning C4244 "'conversion' conversion from 'type1' to 'type2', possible loss of data".
- try_append_c_flags(/wd4267) # Disable warning C4267 "'var' : conversion from 'size_t' to 'type', possible loss of data".
+ try_append_c_flags(/wd4146 TARGET secp256k1_common) # Disable warning C4146 "unary minus operator applied to unsigned type, result still unsigned".
+ try_append_c_flags(/wd4244 TARGET secp256k1_common) # Disable warning C4244 "'conversion' conversion from 'type1' to 'type2', possible loss of data".
+ try_append_c_flags(/wd4267 TARGET secp256k1_common) # Disable warning C4267 "'var' : conversion from 'size_t' to 'type', possible loss of data".
else()
# Keep the following commands ordered lexicographically.
- try_append_c_flags(-pedantic)
- try_append_c_flags(-Wcast-align) # GCC >= 2.95.
- try_append_c_flags(-Wcast-align=strict) # GCC >= 8.0.
- try_append_c_flags(-Wconditional-uninitialized) # Clang >= 3.0 only.
- try_append_c_flags(-Wextra) # GCC >= 3.4, this is the newer name of -W, which we don't use because older GCCs will warn about unused functions.
- try_append_c_flags(-Wleading-whitespace=spaces) # GCC >= 15.0
- try_append_c_flags(-Wnested-externs)
- try_append_c_flags(-Wno-long-long) # GCC >= 3.0, -Wlong-long is implied by -pedantic.
- try_append_c_flags(-Wno-overlength-strings) # GCC >= 4.2, -Woverlength-strings is implied by -pedantic.
- try_append_c_flags(-Wno-unused-function) # GCC >= 3.0, -Wunused-function is implied by -Wall.
- try_append_c_flags(-Wreserved-identifier) # Clang >= 13.0 only.
- try_append_c_flags(-Wshadow)
- try_append_c_flags(-Wstrict-prototypes)
- try_append_c_flags(-Wtrailing-whitespace=any) # GCC >= 15.0
- try_append_c_flags(-Wundef)
+ try_append_c_flags(-pedantic TARGET secp256k1_common)
+ try_append_c_flags(-Wcast-align TARGET secp256k1_common) # GCC >= 2.95.
+ try_append_c_flags(-Wcast-align=strict TARGET secp256k1_common) # GCC >= 8.0.
+ try_append_c_flags(-Wconditional-uninitialized TARGET secp256k1_common) # Clang >= 3.0 only.
+ try_append_c_flags(-Wextra TARGET secp256k1_common) # GCC >= 3.4, this is the newer name of -W, which we don't use because older GCCs will warn about unused functions.
+ try_append_c_flags(-Wleading-whitespace=spaces TARGET secp256k1_common) # GCC >= 15.0
+ try_append_c_flags(-Wnested-externs TARGET secp256k1_common)
+ try_append_c_flags(-Wno-long-long TARGET secp256k1_common) # GCC >= 3.0, -Wlong-long is implied by -pedantic.
+ try_append_c_flags(-Wno-overlength-strings TARGET secp256k1_common) # GCC >= 4.2, -Woverlength-strings is implied by -pedantic.
+ try_append_c_flags(-Wno-unused-function TARGET secp256k1_common) # GCC >= 3.0, -Wunused-function is implied by -Wall.
+ try_append_c_flags(-Wreserved-identifier TARGET secp256k1_common) # Clang >= 13.0 only.
+ try_append_c_flags(-Wshadow TARGET secp256k1_common)
+ try_append_c_flags(-Wstrict-prototypes TARGET secp256k1_common)
+ try_append_c_flags(-Wtrailing-whitespace=any TARGET secp256k1_common) # GCC >= 15.0
+ try_append_c_flags(-Wundef TARGET secp256k1_common)
endif()
set(print_msan_notice)
if(SECP256K1_BUILD_CTIME_TESTS)
include(CheckMemorySanitizer)
check_memory_sanitizer(msan_enabled)
if(msan_enabled)
- try_append_c_flags(-fno-sanitize-memory-param-retval)
+ try_append_c_flags(-fno-sanitize-memory-param-retval TARGET secp256k1_common)
set(print_msan_notice YES)
endif()
unset(msan_enabled)
@@ -320,14 +348,14 @@ endif()
message("Cross compiling ....................... ${cross_status}")
message("API visibility attributes ............. ${SECP256K1_ENABLE_API_VISIBILITY_ATTRIBUTES}")
message("Valgrind .............................. ${SECP256K1_VALGRIND}")
-get_directory_property(definitions COMPILE_DEFINITIONS)
-string(REPLACE ";" " " definitions "${definitions}")
+get_property(definitions TARGET secp256k1_common PROPERTY INTERFACE_COMPILE_DEFINITIONS)
+list(JOIN definitions " " definitions)
message("Preprocessor defined macros ........... ${definitions}")
message("C compiler ............................ ${CMAKE_C_COMPILER_ID} ${CMAKE_C_COMPILER_VERSION}, ${CMAKE_C_COMPILER}")
message("CFLAGS ................................ ${CMAKE_C_FLAGS}")
-get_directory_property(compile_options COMPILE_OPTIONS)
-string(REPLACE ";" " " compile_options "${compile_options}")
-message("Compile options ....................... " ${compile_options})
+get_property(compile_options TARGET secp256k1_common PROPERTY INTERFACE_COMPILE_OPTIONS)
+list(JOIN compile_options " " compile_options)
+message("Compile options ....................... ${compile_options}")
if(NOT is_multi_config)
message("Build type:")
message(" - CMAKE_BUILD_TYPE ................... ${CMAKE_BUILD_TYPE}")
### src/secp256k1/ci/ci.sh
@@ -15,7 +15,7 @@ print_environment() {
ECMULTWINDOW ECMULTGENKB ASM WIDEMUL WITH_VALGRIND EXTRAFLAGS \
EXPERIMENTAL ECDH RECOVERY EXTRAKEYS MUSIG SCHNORRSIG ELLSWIFT SILENTPAYMENTS \
SECP256K1_TEST_ITERS BENCH SECP256K1_BENCH_ITERS CTIMETESTS SYMBOL_CHECK \
- EXAMPLES \
+ EXAMPLES EXHAUSTIVE_TEST_ORDER EXHAUSTIVE_TEST_ARGS \
HOST WRAPPER_CMD \
CC CFLAGS CPPFLAGS AR NM \
UBSAN_OPTIONS ASAN_OPTIONS LSAN_OPTIONS
@@ -118,6 +118,15 @@ then
EXEC="$EXEC $WRAPPER_CMD"
fi
+if [ -n "$EXHAUSTIVE_TEST_ORDER" ]
+then
+ # The group order is a compile-time constant, so rebuild for it.
+ rm -f exhaustive_tests src/exhaustive_tests-tests_exhaustive.o
+ make exhaustive_tests CPPFLAGS="${CPPFLAGS:-} -DEXHAUSTIVE_TEST_ORDER=$EXHAUSTIVE_TEST_ORDER"
+ $EXEC ./exhaustive_tests $EXHAUSTIVE_TEST_ARGS
+ rm -f exhaustive_tests src/exhaustive_tests-tests_exhaustive.o
+fi
+
if [ "$BENCH" = "yes" ]
then
{
### src/secp256k1/cmake/TryAppendCFlags.cmake
@@ -1,6 +1,15 @@
include(CheckCCompilerFlag)
-function(secp256k1_check_c_flags_internal flags output)
+# try_append_c_flags(<flags> TARGET <target>)
+#
+# Append <flags> to the INTERFACE_COMPILE_OPTIONS of <target>
+# if the C compiler accepts them.
+function(try_append_c_flags flags)
+ cmake_parse_arguments(PARSE_ARGV 1 arg "" "TARGET" "")
+ if(NOT DEFINED arg_TARGET OR arg_UNPARSED_ARGUMENTS)
+ message(FATAL_ERROR "Usage: ${CMAKE_CURRENT_FUNCTION}(<flags> TARGET <target>)")
+ endif()
+
string(MAKE_C_IDENTIFIER "${flags}" result)
string(TOUPPER "${result}" result)
set(result "C_SUPPORTS_${result}")
@@ -11,14 +20,7 @@ function(secp256k1_check_c_flags_internal flags output)
# This avoids running a linker.
set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY)
check_c_compiler_flag("${flags}" ${result})
-
- set(${output} ${${result}} PARENT_SCOPE)
-endfunction()
-
-# Append flags to the COMPILE_OPTIONS directory property if CC accepts them.
-macro(try_append_c_flags)
- secp256k1_check_c_flags_internal("${ARGV}" result)
- if(result)
- add_compile_options(${ARGV})
+ if(${result})
+ target_compile_options(${arg_TARGET} INTERFACE ${flags})
endif()
-endmacro()
+endfunction()
### src/secp256k1/doc/safegcd_implementation.md
@@ -767,7 +767,7 @@ def modinv_var(M, Mi, x):
eta, t = divsteps_n_matrix_var(eta, f % 2**N, g % 2**N)
f, g = update_fg(f, g, t)
d, e = update_de(d, e, t, M, Mi)
- return normalize(f, d, Mi)
+ return normalize(f, d, M)
```
## 8. From GCDs to Jacobi symbol
### src/secp256k1/examples/CMakeLists.txt
@@ -5,6 +5,7 @@ function(add_example name)
${PROJECT_SOURCE_DIR}/include
)
target_link_libraries(${target_name}
+ secp256k1_common
secp256k1
$<$<PLATFORM_ID:Windows>:bcrypt>
)
### src/secp256k1/examples/ecdsa.c
@@ -134,5 +134,5 @@ int main(void) {
* will remove any writes that aren't used. */
secure_erase(seckey, sizeof(seckey));
- return EXIT_SUCCESS;
+ return is_signature_valid ? EXIT_SUCCESS : EXIT_FAILURE;
}
### src/secp256k1/examples/schnorr.c
@@ -150,5 +150,5 @@ int main(void) {
* Here we are preventing these writes from being optimized out, as any good compiler
* will remove any writes that aren't used. */
secure_erase(seckey, sizeof(seckey));
- return EXIT_SUCCESS;
+ return is_signature_valid ? EXIT_SUCCESS : EXIT_FAILURE;
}
### src/secp256k1/include/secp256k1.h
@@ -418,6 +418,9 @@ typedef void (*secp256k1_sha256_compression_function)(
* The provided callback must exactly implement the effect of n_blocks
* repeated applications of the SHA256 compression function.
*
+ * The callback processes secrets such as secret keys, so it must run in
+ * constant time with respect to its input and must not keep or log it.
+ *
* This API exists to support environments that wish to route the
* SHA256 compression step through a hardware-accelerated or otherwise
* specialized implementation. It is NOT meant for replacing SHA256
### src/secp256k1/include/secp256k1_silentpayments.h
@@ -261,7 +261,9 @@ typedef struct secp256k1_silentpayments_prevouts_summary {
* The resulting data can be used for scanning on the recipient side.
*
* Returns: 1 if prevouts summary creation was successful.
- * 0 if the transaction is not a Silent Payments transaction.
+ * 0 if the transaction is not a Silent Payments transaction, e.g.,
+ * if no public keys are passed (the transaction has no eligible
+ * inputs) or if the public keys sum to the point at infinity.
*
* Args: ctx: pointer to a context object
* Out: prevouts_summary: pointer to prevouts_summary object containing the
@@ -347,20 +349,23 @@ typedef struct secp256k1_silentpayments_found_output {
* key group than this limit.
*
* Returns: 1 if output scanning was successful.
- * 0 if the transaction is not a Silent Payments transaction,
+ * 0 if the transaction is not a Silent Payments transaction (e.g.,
+ * if it has no taproot outputs, i.e., n_tx_outputs is 0),
* or if the arguments are invalid.
*
* Args: ctx: pointer to a context object
* Out: found_outputs: pointer to an array of pointers to found
* output objects. The found outputs array MUST
- * have the same length as the tx_outputs array.
+ * have the same length as the tx_outputs array
+ * (can be NULL if n_tx_outputs is 0).
* n_found_outputs: pointer to an integer indicating the final
* size of the found outputs array. This number
* represents the number of outputs found while
* scanning (0 if none are found). Can't be larger than
* SECP256K1_SILENTPAYMENTS_RECIPIENT_GROUP_LIMIT.
* In: tx_outputs: pointer to the transaction's x-only public key outputs,
- * in their original transaction (vout) order
+ * in their original transaction (vout) order (can be
+ * NULL if n_tx_outputs is 0)
* n_tx_outputs: the size of the tx_outputs array.
* scan_key32: pointer to the recipient's 32 byte scan key. The scan
* key is valid if it passes secp256k1_ec_seckey_verify
@@ -387,7 +392,7 @@ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_silentpayments_recipien
const secp256k1_pubkey *unlabeled_spend_pubkey,
secp256k1_silentpayments_label_lookup label_lookup,
const void *label_context
-) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4) SECP256K1_ARG_NONNULL(6) SECP256K1_ARG_NONNULL(7) SECP256K1_ARG_NONNULL(8);
+) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(6) SECP256K1_ARG_NONNULL(7) SECP256K1_ARG_NONNULL(8);
#ifdef __cplusplus
}
### src/secp256k1/src/CMakeLists.txt
@@ -1,4 +1,11 @@
add_library(secp256k1)
+add_library(secp256k1_modules INTERFACE)
+# Keep secp256k1_common and secp256k1_modules out of the export set.
+target_link_libraries(secp256k1
+ PRIVATE
+ $<BUILD_INTERFACE:secp256k1_common>
+ $<BUILD_INTERFACE:secp256k1_modules>
+)
set_property(TARGET secp256k1 PROPERTY PUBLIC_HEADER
${PROJECT_SOURCE_DIR}/include/secp256k1.h
@@ -8,7 +15,9 @@ set_property(TARGET secp256k1 PROPERTY PUBLIC_HEADER
# Processing must be done in a topological sorting of the dependency graph
# (dependent module first).
if(SECP256K1_ENABLE_MODULE_ELLSWIFT)
- add_compile_definitions(ENABLE_MODULE_ELLSWIFT=1)
+ target_compile_definitions(secp256k1_modules INTERFACE
+ ENABLE_MODULE_ELLSWIFT=1
+ )
set_property(TARGET secp256k1 APPEND PROPERTY PUBLIC_HEADER ${PROJECT_SOURCE_DIR}/include/secp256k1_ellswift.h)
endif()
@@ -17,7 +26,9 @@ if(SECP256K1_ENABLE_MODULE_MUSIG)
message(FATAL_ERROR "Module dependency error: You have disabled the schnorrsig module explicitly, but it is required by the musig module.")
endif()
set(SECP256K1_ENABLE_MODULE_SCHNORRSIG ON)
- add_compile_definitions(ENABLE_MODULE_MUSIG=1)
+ target_compile_definitions(secp256k1_modules INTERFACE
+ ENABLE_MODULE_MUSIG=1
+ )
set_property(TARGET secp256k1 APPEND PROPERTY PUBLIC_HEADER ${PROJECT_SOURCE_DIR}/include/secp256k1_musig.h)
endif()
@@ -26,7 +37,9 @@ if(SECP256K1_ENABLE_MODULE_SILENTPAYMENTS)
message(FATAL_ERROR "Module dependency error: You have disabled the extrakeys module explicitly, but it is required by the silent payments module.")
endif()
set(SECP256K1_ENABLE_MODULE_EXTRAKEYS ON)
- add_compile_definitions(ENABLE_MODULE_SILENTPAYMENTS=1)
+ target_compile_definitions(secp256k1_modules INTERFACE
+ ENABLE_MODULE_SILENTPAYMENTS=1
+ )
set_property(TARGET secp256k1 APPEND PROPERTY PUBLIC_HEADER ${PROJECT_SOURCE_DIR}/include/secp256k1_silentpayments.h)
endif()
@@ -35,29 +48,38 @@ if(SECP256K1_ENABLE_MODULE_SCHNORRSIG)
message(FATAL_ERROR "Module dependency error: You have disabled the extrakeys module explicitly, but it is required by the schnorrsig module.")
endif()
set(SECP256K1_ENABLE_MODULE_EXTRAKEYS ON)
- add_compile_definitions(ENABLE_MODULE_SCHNORRSIG=1)
+ target_compile_definitions(secp256k1_modules INTERFACE
+ ENABLE_MODULE_SCHNORRSIG=1
+ )
set_property(TARGET secp256k1 APPEND PROPERTY PUBLIC_HEADER ${PROJECT_SOURCE_DIR}/include/secp256k1_schnorrsig.h)
endif()
if(SECP256K1_ENABLE_MODULE_EXTRAKEYS)
- add_compile_definitions(ENABLE_MODULE_EXTRAKEYS=1)
+ target_compile_definitions(secp256k1_modules INTERFACE
+ ENABLE_MODULE_EXTRAKEYS=1
+ )
set_property(TARGET secp256k1 APPEND PROPERTY PUBLIC_HEADER ${PROJECT_SOURCE_DIR}/include/secp256k1_extrakeys.h)
endif()
if(SECP256K1_ENABLE_MODULE_RECOVERY)
- add_compile_definitions(ENABLE_MODULE_RECOVERY=1)
+ target_compile_definitions(secp256k1_modules INTERFACE
+ ENABLE_MODULE_RECOVERY=1
+ )
set_property(TARGET secp256k1 APPEND PROPERTY PUBLIC_HEADER ${PROJECT_SOURCE_DIR}/include/secp256k1_recovery.h)
endif()
if(SECP256K1_ENABLE_MODULE_ECDH)
- add_compile_definitions(ENABLE_MODULE_ECDH=1)
+ target_compile_definitions(secp256k1_modules INTERFACE
+ ENABLE_MODULE_ECDH=1
+ )
set_property(TARGET secp256k1 APPEND PROPERTY PUBLIC_HEADER ${PROJECT_SOURCE_DIR}/include/secp256k1_ecdh.h)
endif()
add_library(secp256k1_precomputed OBJECT EXCLUDE_FROM_ALL
precomputed_ecmult.c
precomputed_ecmult_gen.c
)
+target_link_libraries(secp256k1_precomputed PRIVATE secp256k1_common secp256k1_modules)
# Add objects explicitly rather than linking to the object libs to keep them
# from being exported.
@@ -78,6 +100,7 @@ if(SECP256K1_ASM STREQUAL "arm32")
target_sources(secp256k1_asm_arm PUBLIC
asm/field_10x26_arm.s
)
+ target_link_libraries(secp256k1_asm_arm PRIVATE secp256k1_common)
target_sources(secp256k1 PRIVATE $<TARGET_OBJECTS:secp256k1_asm_arm>)
target_sources(secp256k1_objs INTERFACE $<TARGET_OBJECTS:secp256k1_asm_arm>)
target_link_libraries(secp256k1_asm INTERFACE secp256k1_asm_arm)
@@ -112,11 +135,11 @@ set_libtool_abi_version(secp256k1
if(SECP256K1_BUILD_BENCHMARK)
add_executable(bench bench.c)
- target_link_libraries(bench secp256k1)
+ target_link_libraries(bench secp256k1_common secp256k1_modules secp256k1)
add_executable(bench_internal bench_internal.c)
- target_link_libraries(bench_internal secp256k1_precomputed secp256k1_asm)
+ target_link_libraries(bench_internal secp256k1_common secp256k1_modules secp256k1_precomputed secp256k1_asm)
add_executable(bench_ecmult bench_ecmult.c)
- target_link_libraries(bench_ecmult secp256k1_precomputed secp256k1_asm)
+ target_link_libraries(bench_ecmult secp256k1_common secp256k1_modules secp256k1_precomputed secp256k1_asm)
endif()
if(SECP256K1_BUILD_TESTS)
@@ -132,7 +155,7 @@ if(SECP256K1_BUILD_TESTS)
function(add_executable_and_tests exe_name verify_definition)
add_executable(${exe_name} tests.c)
- target_link_libraries(${exe_name} secp256k1_precomputed secp256k1_asm)
+ target_link_libraries(${exe_name} secp256k1_common secp256k1_modules secp256k1_precomputed secp256k1_asm)
target_compile_definitions(${exe_name} PRIVATE ${verify_definition} ${TEST_DEFINITIONS})
include(DiscoverTests)
discover_tests(${exe_name}
@@ -155,7 +178,7 @@ endif()
if(SECP256K1_BUILD_EXHAUSTIVE_TESTS)
# Note: do not include secp256k1_precomputed in exhaustive_tests (it uses runtime-generated tables).
add_executable(exhaustive_tests tests_exhaustive.c)
- target_link_libraries(exhaustive_tests secp256k1_asm)
+ target_link_libraries(exhaustive_tests secp256k1_common secp256k1_modules secp256k1_asm)
target_compile_definitions(exhaustive_tests PRIVATE $<$<NOT:$<CONFIG:Coverage>>:VERIFY>)
add_test(NAME secp256k1.exhaustive_tests COMMAND exhaustive_tests)
set_tests_properties(secp256k1.exhaustive_tests PROPERTIES
@@ -165,7 +188,7 @@ endif()
if(SECP256K1_BUILD_CTIME_TESTS)
add_executable(ctime_tests ctime_tests.c)
- target_link_libraries(ctime_tests secp256k1)
+ target_link_libraries(ctime_tests secp256k1_common secp256k1_modules secp256k1)
endif()
if(SECP256K1_INSTALL)
### src/secp256k1/src/assumptions.h
@@ -19,69 +19,59 @@
reduce the odds of experiencing an unwelcome surprise.
*/
-#if defined(__has_attribute)
-# if __has_attribute(__unavailable__)
-__attribute__((__unavailable__("Don't call this function. It only exists because STATIC_ASSERT cannot be used outside a function.")))
-# endif
-#endif
-static void secp256k1_assumption_checker(void) {
- /* Bytes are 8 bits. */
- STATIC_ASSERT(CHAR_BIT == 8);
+/* Bytes are 8 bits. */
+STATIC_ASSERT(CHAR_BIT == 8);
- /* No integer promotion for uint32_t. This ensures that we can multiply uintXX_t values where XX >= 32
- without signed overflow, which would be undefined behaviour. */
- STATIC_ASSERT(UINT_MAX <= UINT32_MAX);
+/* No integer promotion for uint32_t. This ensures that we can multiply uintXX_t values where XX >= 32
+ without signed overflow, which would be undefined behaviour. */
+STATIC_ASSERT(UINT_MAX <= UINT32_MAX);
- /* Conversions from unsigned to signed outside of the bounds of the signed type are
- implementation-defined. Verify that they function as reinterpreting the lower
- bits of the input in two's complement notation. Do this for conversions:
- - from uint(N)_t to int(N)_t with negative result
- - from uint(2N)_t to int(N)_t with negative result
- - from int(2N)_t to int(N)_t with negative result
- - from int(2N)_t to int(N)_t with positive result */
+/* Conversions from unsigned to signed outside of the bounds of the signed type are
+ implementation-defined. Verify that they function as reinterpreting the lower
+ bits of the input in two's complement notation. Do this for conversions:
+ - from uint(N)_t to int(N)_t with negative result
+ - from uint(2N)_t to int(N)_t with negative result
+ - from int(2N)_t to int(N)_t with negative result
+ - from int(2N)_t to int(N)_t with positive result */
- /* To int8_t. */
- STATIC_ASSERT(((int8_t)(uint8_t)0xAB == (int8_t)-(int8_t)0x55));
- STATIC_ASSERT((int8_t)(uint16_t)0xABCD == (int8_t)-(int8_t)0x33);
- STATIC_ASSERT((int8_t)(int16_t)(uint16_t)0xCDEF == (int8_t)(uint8_t)0xEF);
- STATIC_ASSERT((int8_t)(int16_t)(uint16_t)0x9234 == (int8_t)(uint8_t)0x34);
+/* To int8_t. */
+STATIC_ASSERT(((int8_t)(uint8_t)0xAB == (int8_t)-(int8_t)0x55));
+STATIC_ASSERT((int8_t)(uint16_t)0xABCD == (int8_t)-(int8_t)0x33);
+STATIC_ASSERT((int8_t)(int16_t)(uint16_t)0xCDEF == (int8_t)(uint8_t)0xEF);
+STATIC_ASSERT((int8_t)(int16_t)(uint16_t)0x9234 == (int8_t)(uint8_t)0x34);
- /* To int16_t. */
- STATIC_ASSERT((int16_t)(uint16_t)0xBCDE == (int16_t)-(int16_t)0x4322);
- STATIC_ASSERT((int16_t)(uint32_t)0xA1B2C3D4 == (int16_t)-(int16_t)0x3C2C);
- STATIC_ASSERT((int16_t)(int32_t)(uint32_t)0xC1D2E3F4 == (int16_t)(uint16_t)0xE3F4);
- STATIC_ASSERT((int16_t)(int32_t)(uint32_t)0x92345678 == (int16_t)(uint16_t)0x5678);
+/* To int16_t. */
+STATIC_ASSERT((int16_t)(uint16_t)0xBCDE == (int16_t)-(int16_t)0x4322);
+STATIC_ASSERT((int16_t)(uint32_t)0xA1B2C3D4 == (int16_t)-(int16_t)0x3C2C);
+STATIC_ASSERT((int16_t)(int32_t)(uint32_t)0xC1D2E3F4 == (int16_t)(uint16_t)0xE3F4);
+STATIC_ASSERT((int16_t)(int32_t)(uint32_t)0x92345678 == (int16_t)(uint16_t)0x5678);
- /* To int32_t. */
- STATIC_ASSERT((int32_t)(uint32_t)0xB2C3D4E5 == (int32_t)-(int32_t)0x4D3C2B1B);
- STATIC_ASSERT((int32_t)(uint64_t)0xA123B456C789D012ULL == (int32_t)-(int32_t)0x38762FEE);
- STATIC_ASSERT((int32_t)(int64_t)(uint64_t)0xC1D2E3F4A5B6C7D8ULL == (int32_t)(uint32_t)0xA5B6C7D8);
- STATIC_ASSERT((int32_t)(int64_t)(uint64_t)0xABCDEF0123456789ULL == (int32_t)(uint32_t)0x23456789);
+/* To int32_t. */
+STATIC_ASSERT((int32_t)(uint32_t)0xB2C3D4E5 == (int32_t)-(int32_t)0x4D3C2B1B);
+STATIC_ASSERT((int32_t)(uint64_t)0xA123B456C789D012ULL == (int32_t)-(int32_t)0x38762FEE);
+STATIC_ASSERT((int32_t)(int64_t)(uint64_t)0xC1D2E3F4A5B6C7D8ULL == (int32_t)(uint32_t)0xA5B6C7D8);
+STATIC_ASSERT((int32_t)(int64_t)(uint64_t)0xABCDEF0123456789ULL == (int32_t)(uint32_t)0x23456789);
- /* To int64_t. */
- STATIC_ASSERT((int64_t)(uint64_t)0xB123C456D789E012ULL == (int64_t)-(int64_t)0x4EDC3BA928761FEEULL);
+/* To int64_t. */
+STATIC_ASSERT((int64_t)(uint64_t)0xB123C456D789E012ULL == (int64_t)-(int64_t)0x4EDC3BA928761FEEULL);
#if defined(SECP256K1_INT128_NATIVE)
- STATIC_ASSERT((int64_t)(((uint128_t)0xA1234567B8901234ULL << 64) + 0xC5678901D2345678ULL) == (int64_t)-(int64_t)0x3A9876FE2DCBA988ULL);
- STATIC_ASSERT(((int64_t)(int128_t)(((uint128_t)0xB1C2D3E4F5A6B7C8ULL << 64) + 0xD9E0F1A2B3C4D5E6ULL)) == (int64_t)(uint64_t)0xD9E0F1A2B3C4D5E6ULL);
- STATIC_ASSERT(((int64_t)(int128_t)(((uint128_t)0xABCDEF0123456789ULL << 64) + 0x0123456789ABCDEFULL)) == (int64_t)(uint64_t)0x0123456789ABCDEFULL);
+STATIC_ASSERT((int64_t)(((uint128_t)0xA1234567B8901234ULL << 64) + 0xC5678901D2345678ULL) == (int64_t)-(int64_t)0x3A9876FE2DCBA988ULL);
+STATIC_ASSERT(((int64_t)(int128_t)(((uint128_t)0xB1C2D3E4F5A6B7C8ULL << 64) + 0xD9E0F1A2B3C4D5E6ULL)) == (int64_t)(uint64_t)0xD9E0F1A2B3C4D5E6ULL);
+STATIC_ASSERT(((int64_t)(int128_t)(((uint128_t)0xABCDEF0123456789ULL << 64) + 0x0123456789ABCDEFULL)) == (int64_t)(uint64_t)0x0123456789ABCDEFULL);
- /* To int128_t. */
- STATIC_ASSERT((int128_t)(((uint128_t)0xB1234567C8901234ULL << 64) + 0xD5678901E2345678ULL) == (int128_t)(-(int128_t)0x8E1648B3F50E80DCULL * 0x8E1648B3F50E80DDULL + 0x5EA688D5482F9464ULL));
+/* To int128_t. */
+STATIC_ASSERT((int128_t)(((uint128_t)0xB1234567C8901234ULL << 64) + 0xD5678901E2345678ULL) == (int128_t)(-(int128_t)0x8E1648B3F50E80DCULL * 0x8E1648B3F50E80DDULL + 0x5EA688D5482F9464ULL));
#endif
- /* Right shift on negative signed values is implementation defined. Verify that it
- acts as a right shift in two's complement with sign extension (i.e duplicating
- the top bit into newly added bits). */
- STATIC_ASSERT((((int8_t)0xE8) >> 2) == (int8_t)(uint8_t)0xFA);
- STATIC_ASSERT((((int16_t)0xE9AC) >> 4) == (int16_t)(uint16_t)0xFE9A);
- STATIC_ASSERT((((int32_t)0x937C918A) >> 9) == (int32_t)(uint32_t)0xFFC9BE48);
- STATIC_ASSERT((((int64_t)0xA8B72231DF9CF4B9ULL) >> 19) == (int64_t)(uint64_t)0xFFFFF516E4463BF3ULL);
+/* Right shift on negative signed values is implementation defined. Verify that it
+ acts as a right shift in two's complement with sign extension (i.e duplicating
+ the top bit into newly added bits). */
+STATIC_ASSERT((((int8_t)0xE8) >> 2) == (int8_t)(uint8_t)0xFA);
+STATIC_ASSERT((((int16_t)0xE9AC) >> 4) == (int16_t)(uint16_t)0xFE9A);
+STATIC_ASSERT((((int32_t)0x937C918A) >> 9) == (int32_t)(uint32_t)0xFFC9BE48);
+STATIC_ASSERT((((int64_t)0xA8B72231DF9CF4B9ULL) >> 19) == (int64_t)(uint64_t)0xFFFFF516E4463BF3ULL);
#if defined(SECP256K1_INT128_NATIVE)
- STATIC_ASSERT((((int128_t)(((uint128_t)0xCD833A65684A0DBCULL << 64) + 0xB349312F71EA7637ULL)) >> 39) == (int128_t)(((uint128_t)0xFFFFFFFFFF9B0674ULL << 64) + 0xCAD0941B79669262ULL));
+STATIC_ASSERT((((int128_t)(((uint128_t)0xCD833A65684A0DBCULL << 64) + 0xB349312F71EA7637ULL)) >> 39) == (int128_t)(((uint128_t)0xFFFFFFFFFF9B0674ULL << 64) + 0xCAD0941B79669262ULL));
#endif
- /* This function is not supposed to be called. */
- VERIFY_CHECK(0);
-}
-
#endif /* SECP256K1_ASSUMPTIONS_H */
### src/secp256k1/src/bench_ecmult.c
@@ -118,7 +118,7 @@ static void bench_ecmult_const(void* arg, int iters) {
int i;
for (i = 0; i < iters; ++i) {
- secp256k1_ecmult_const(&data->output[i], &data->pubkeys[(data->offset1+i) % POINTS], &data->scalars[(data->offset2+i) % POINTS]);
+ secp256k1_ecmult_const_gej(&data->output[i], &data->pubkeys[(data->offset1+i) % POINTS], &data->scalars[(data->offset2+i) % POINTS]);
}
}
### src/secp256k1/src/ctime_tests.c
@@ -42,13 +42,28 @@
#ifdef ENABLE_MODULE_SILENTPAYMENTS
#include "../include/secp256k1_silentpayments.h"
+
+static int label_lookups;
+
+static const unsigned char *label_lookup_none(const unsigned char *label33, const void *label_context) {
+ (void)label_context;
+ SECP256K1_CHECKMEM_CHECK(label33, 33);
+ label_lookups++;
+ return NULL;
+}
#endif
#if defined(__GNUC__)
# pragma GCC diagnostic push
# pragma GCC diagnostic warning "-Wunused-function"
#endif
+#ifdef ENABLE_MODULE_SCHNORRSIG
+static int nonce_function_custom(unsigned char *nonce32, const unsigned char *msg, size_t msglen, const unsigned char *key32, const unsigned char *xonly_pk32, const unsigned char *algo, size_t algolen, void *data) {
+ return secp256k1_nonce_function_bip340(nonce32, msg, msglen, key32, xonly_pk32, algo, algolen, data);
+}
+#endif
+
static void run_tests(secp256k1_context *ctx, unsigned char *key);
int main(void) {
@@ -99,6 +114,10 @@ static void run_tests(secp256k1_context *ctx, unsigned char *key) {
#ifdef ENABLE_MODULE_EXTRAKEYS
secp256k1_keypair keypair;
#endif
+#ifdef ENABLE_MODULE_SCHNORRSIG
+ secp256k1_schnorrsig_extraparams extraparams = SECP256K1_SCHNORRSIG_EXTRAPARAMS_INIT;
+ unsigned char aux_rand[32] = { 0 };
+#endif
#ifdef ENABLE_MODULE_ELLSWIFT
unsigned char ellswift[64];
static const unsigned char prefix[64] = {'t', 'e', 's', 't'};
@@ -113,10 +132,10 @@ static void run_tests(secp256k1_context *ctx, unsigned char *key) {
secp256k1_keypair sp_keypair;
const secp256k1_keypair *sp_keypairs[1];
const unsigned char *sp_seckeys[1];
- secp256k1_silentpayments_found_output found_outputs[1];
- secp256k1_silentpayments_found_output *found_outputs_ptrs[1];
+ secp256k1_silentpayments_found_output found_outputs[2];
+ secp256k1_silentpayments_found_output *found_outputs_ptrs[2];
uint32_t n_found_outputs;
- const secp256k1_xonly_pubkey *tx_outputs[1];
+ const secp256k1_xonly_pubkey *tx_outputs[2];
secp256k1_silentpayments_prevouts_summary prevouts_summary;
unsigned char label_tweak[32] = { 0 };
secp256k1_xonly_pubkey sp_xonly_pubkey;
@@ -214,6 +233,37 @@ static void run_tests(secp256k1_context *ctx, unsigned char *key) {
ret = secp256k1_schnorrsig_sign32(ctx, sig, msg, &keypair, NULL);
SECP256K1_CHECKMEM_DEFINE(&ret, sizeof(ret));
CHECK(ret == 1);
+
+ SECP256K1_CHECKMEM_UNDEFINE(key, 32);
+ ret = secp256k1_keypair_create(ctx, &keypair, key);
+ SECP256K1_CHECKMEM_DEFINE(&ret, sizeof(ret));
+ CHECK(ret == 1);
+ SECP256K1_CHECKMEM_UNDEFINE(&keypair, sizeof(keypair));
+ ret = secp256k1_schnorrsig_sign_custom(ctx, sig, msg, 32, &keypair, NULL);
+ SECP256K1_CHECKMEM_DEFINE(&ret, sizeof(ret));
+ CHECK(ret == 1);
+
+ extraparams.noncefp = NULL;
+ extraparams.ndata = aux_rand;
+ SECP256K1_CHECKMEM_UNDEFINE(key, 32);
+ ret = secp256k1_keypair_create(ctx, &keypair, key);
+ SECP256K1_CHECKMEM_DEFINE(&ret, sizeof(ret));
+ CHECK(ret == 1);
+ SECP256K1_CHECKMEM_UNDEFINE(&keypair, sizeof(keypair));
+ ret = secp256k1_schnorrsig_sign_custom(ctx, sig, msg, 32, &keypair, &extraparams);
+ SECP256K1_CHECKMEM_DEFINE(&ret, sizeof(ret));
+ CHECK(ret == 1);
+
+ extraparams.noncefp = nonce_function_custom;
+ extraparams.ndata = aux_rand;
+ SECP256K1_CHECKMEM_UNDEFINE(key, 32);
+ ret = secp256k1_keypair_create(ctx, &keypair, key);
+ SECP256K1_CHECKMEM_DEFINE(&ret, sizeof(ret));
+ CHECK(ret == 1);
+ SECP256K1_CHECKMEM_UNDEFINE(&keypair, sizeof(keypair));
+ ret = secp256k1_schnorrsig_sign_custom(ctx, sig, msg, sizeof(msg), &keypair, &extraparams);
+ SECP256K1_CHECKMEM_DEFINE(&ret, sizeof(ret));
+ CHECK(ret == 1);
#endif
#ifdef ENABLE_MODULE_MUSIG
@@ -301,7 +351,6 @@ static void run_tests(secp256k1_context *ctx, unsigned char *key) {
generated_outputs[0] = &generated_output;
/* Initialize recipient */
- CHECK(secp256k1_ec_pubkey_create(ctx, &recipient.scan_pubkey, key));
key[31] ^= 1;
CHECK(secp256k1_ec_pubkey_create(ctx, &recipient.spend_pubkey, key));
key[31] ^= (1 << 1);
@@ -317,9 +366,6 @@ static void run_tests(secp256k1_context *ctx, unsigned char *key) {
sp_keypairs[0] = &sp_keypair;
sp_seckeys[0] = key;
- ret = secp256k1_silentpayments_sender_create_outputs(ctx, generated_outputs, recipients, 1, outpoint_smallest, sp_keypairs, 1, sp_seckeys, 1);
- CHECK(ret == 1);
-
ret = secp256k1_silentpayments_recipient_label_create(ctx, &label, label_tweak, key, 0);
key[31] ^= (1 << 3);
SECP256K1_CHECKMEM_DEFINE(&ret, sizeof(ret));
@@ -337,14 +383,23 @@ static void run_tests(secp256k1_context *ctx, unsigned char *key) {
ret = secp256k1_silentpayments_recipient_prevouts_summary_create(ctx, &prevouts_summary, outpoint_smallest, sp_xonly_pubkeys, 1, sp_pubkeys, 1);
CHECK(ret == 1);
- tx_outputs[0] = generated_outputs[0];
+ /* key is also the scan seckey at scan time, so sp_pubkey doubles as the
+ * scan pubkey, making the generated output match during scanning. */
+ recipient.scan_pubkey = sp_pubkey;
+ CHECK(secp256k1_silentpayments_sender_create_outputs(ctx, generated_outputs, recipients, 1, outpoint_smallest, sp_keypairs, 1, sp_seckeys, 1));
+
found_outputs_ptrs[0] = &found_outputs[0];
- n_found_outputs = 1;
+ found_outputs_ptrs[1] = &found_outputs[1];
SECP256K1_CHECKMEM_DEFINE(&recipient.spend_pubkey, sizeof(recipient.spend_pubkey));
- /* It is sufficient to check _recipient_scan_outputs without a label lookup function, since the shared secret is created once (which is where the constant timeness matters)
- * and then reused for the rest of the scanning logic.
- */
- CHECK(secp256k1_silentpayments_recipient_scan_outputs(ctx, found_outputs_ptrs, &n_found_outputs, tx_outputs, 1, key, &prevouts_summary, &recipient.spend_pubkey, NULL, NULL));
+ tx_outputs[0] = &sp_xonly_pubkey;
+ tx_outputs[1] = &generated_output;
+ label_lookups = 0;
+ CHECK(secp256k1_silentpayments_recipient_scan_outputs(ctx, found_outputs_ptrs, &n_found_outputs, tx_outputs, 2, key, &prevouts_summary, &recipient.spend_pubkey, label_lookup_none, NULL));
+ CHECK(n_found_outputs == 1);
+ CHECK(found_outputs[0].found_with_label == 0);
+ /* Two candidates flush right before the direct k=0 match, four at the final k=1 miss.
+ * Both flush paths run as long as LABEL_BATCH_SIZE stays >= 2. */
+ CHECK(label_lookups == 2 + 4);
#endif
}
### src/secp256k1/src/ecdsa_impl.h
@@ -238,33 +238,39 @@ static int secp256k1_ecdsa_sig_verify(const secp256k1_scalar *sigr, const secp25
(void)range;
#endif
- /** We now have the recomputed R point in pr, and its claimed x coordinate (modulo n)
- * in xr. Naively, we would extract the x coordinate from pr (requiring a inversion modulo p),
- * compute the remainder modulo n, and compare it to xr. However:
+ /** We now have the recomputed R point in pr, and its claimed x coordinate (modulo n) in xr.
+ * Naively, we would extract pr's x-coordinate X(pr) (requiring an inversion modulo p), and
+ * check whether the congruence xr === X(pr) (mod n) holds. However, we can do better:
*
- * xr == X(pr) mod n
- * <=> exists h. (xr + h * n < p && xr + h * n == X(pr))
- * [Since 2 * n > p, h can only be 0 or 1]
- * <=> (xr == X(pr)) || (xr + n < p && xr + n == X(pr))
- * [In Jacobian coordinates, X(pr) is pr.x / pr.z^2 mod p]
- * <=> (xr == pr.x / pr.z^2 mod p) || (xr + n < p && xr + n == pr.x / pr.z^2 mod p)
- * [Multiplying both sides of the equations by pr.z^2 mod p]
- * <=> (xr * pr.z^2 mod p == pr.x) || (xr + n < p && (xr + n) * pr.z^2 mod p == pr.x)
+ * xr === X(pr) (mod n)
+ * <=> exists h. xr + h * n == X(pr)
+ * [Since 2 * n > p, h can only be 0 or 1:]
+ * <=> xr == X(pr) || xr + n == X(pr)
+ * [Since X(pr) < p, the second equality implies xr + n < p:]
+ * <=> xr == X(pr) || (xr + n < p && xr + n == X(pr))
+ * [Both sides of each equality are in [0, p), so it is equivalent to consider the
+ * congruences modulo p instead:]
+ * <=> xr === X(pr) (mod p) || (xr + n < p && xr + n === X(pr) (mod p))
+ * [In Jacobian coordinates, X(pr) is pr.x / pr.z^2:]
+ * <=> xr === pr.x / pr.z^2 (mod p)) || (xr + n < p && xr + n === pr.x / pr.z^2 (mod p))
+ * [Multiplying both sides of the congruences by pr.z^2 (which is nonzero modulo p because
+ * the point pr is not infinity) gives:]
+ * <=> xr * pr.z^2 === pr.x (mod p) || (xr + n < p && (xr + n) * pr.z^2 === pr.x (mod p))
*
* Thus, we can avoid the inversion, but we have to check both cases separately.
- * secp256k1_gej_eq_x implements the (xr * pr.z^2 mod p == pr.x) test.
+ * secp256k1_gej_eq_x implements the (xr * pr.z^2 === pr.x (mod p)) test.
*/
if (secp256k1_gej_eq_x_var(&xr, &pr)) {
- /* xr * pr.z^2 mod p == pr.x, so the signature is valid. */
+ /* xr * pr.z^2 === pr.x (mod p), so the signature is valid. */
return 1;
}
if (secp256k1_fe_cmp_var(&xr, &secp256k1_ecdsa_const_p_minus_order) >= 0) {
- /* xr + n >= p, so we can skip testing the second case. */
+ /* xr + n >= p, so the second case cannot hold. */
return 0;
}
secp256k1_fe_add(&xr, &secp256k1_ecdsa_const_order_as_fe);
if (secp256k1_gej_eq_x_var(&xr, &pr)) {
- /* (xr + n) * pr.z^2 mod p == pr.x, so the signature is valid. */
+ /* (xr + n) * pr.z^2 === pr.x (mod p), so the signature is valid. */
return 1;
}
return 0;
### src/secp256k1/src/ecmult.h
@@ -11,6 +11,14 @@
#include "scalar.h"
#include "scratch.h"
+/* See STATIC_ASSERT(sizeof(secp256k1_ge_storage) == 64) in group_impl.h. */
+/** Larger values for ECMULT_WINDOW_SIZE result in possibly better
+ * performance at the cost of an exponentially larger precomputed
+ * table. The exact table size is
+ * ECMULT_TABLE_SIZE(ECMULT_WINDOW_SIZE) * 64 bytes.
+ * Two tables of this size are used (due to the endomorphism
+ * optimization).
+ */
#ifndef ECMULT_WINDOW_SIZE
# define ECMULT_WINDOW_SIZE 15
# ifdef DEBUG_CONFIG
@@ -27,10 +35,10 @@
* tested.
*
* The following limitations are known, and there are probably more:
- * If WINDOW_G > 27 and size_t has 32 bits, then the code is incorrect
+ * If ECMULT_WINDOW_SIZE > 27 and size_t has 32 bits, then the code is incorrect
* because the size of the memory object that we allocate (in bytes)
* will not fit in a size_t.
- * If WINDOW_G > 31 and int has 32 bits, then the code is incorrect
+ * If ECMULT_WINDOW_SIZE > 31 and int has 32 bits, then the code is incorrect
* because certain expressions will overflow.
*/
#if ECMULT_WINDOW_SIZE < 2 || ECMULT_WINDOW_SIZE > 24
### src/secp256k1/src/ecmult_const.h
@@ -13,10 +13,11 @@
/**
* Multiply: R = q*A (in constant-time for q)
*/
-static void secp256k1_ecmult_const(secp256k1_gej *r, const secp256k1_ge *a, const secp256k1_scalar *q);
+static void secp256k1_ecmult_const_gej(secp256k1_gej *r, const secp256k1_ge *a, const secp256k1_scalar *q);
+static void secp256k1_ecmult_const_ge(secp256k1_ge *r, const secp256k1_ge *a, const secp256k1_scalar *q);
/**
- * Same as secp256k1_ecmult_const, but takes in an x coordinate of the base point
+ * Same as secp256k1_ecmult_const_gej, but takes in an x coordinate of the base point
* only, specified as fraction n/d (numerator/denominator). Only the x coordinate of the result is
* returned.
*
### src/secp256k1/src/ecmult_const_impl.h
@@ -119,7 +119,7 @@ static const secp256k1_scalar secp256k1_ecmult_const_K = SECP256K1_SCALAR_CONST(
# error "Unknown ECMULT_CONST_BITS"
#endif
-static void secp256k1_ecmult_const(secp256k1_gej *r, const secp256k1_ge *a, const secp256k1_scalar *q) {
+static void secp256k1_ecmult_const_gej(secp256k1_gej *r, const secp256k1_ge *a, const secp256k1_scalar *q) {
/* The approach below combines the signed-digit logic from Mike Hamburg's
* "Fast and compact elliptic-curve cryptography" (https://eprint.iacr.org/2012/309)
* Section 3.3, with the GLV endomorphism.
@@ -265,6 +265,15 @@ static void secp256k1_ecmult_const(secp256k1_gej *r, const secp256k1_ge *a, cons
secp256k1_fe_mul(&r->z, &r->z, &global_z);
}
+SECP256K1_INLINE static void secp256k1_ecmult_const_ge(secp256k1_ge *r, const secp256k1_ge *a, const secp256k1_scalar *q) {
+ secp256k1_gej rj;
+ secp256k1_ecmult_const_gej(&rj, a, q);
+ secp256k1_ge_set_gej(r, &rj);
+ /* Jacobian coordinates resulting from our multiplication algorithm could potentially leak
+ * information about the secret input scalar, so clear the memory out to be on the safe side. */
+ secp256k1_gej_clear(&rj);
+}
+
static int secp256k1_ecmult_const_xonly(secp256k1_fe* r, const secp256k1_fe *n, const secp256k1_fe *d, const secp256k1_scalar *q, int known_on_curve) {
/* This algorithm is a generalization of Peter Dettman's technique for
@@ -384,7 +393,7 @@ static int secp256k1_ecmult_const_xonly(secp256k1_fe* r, const secp256k1_fe *n,
/* Perform x-only EC multiplication of P with q. */
VERIFY_CHECK(!secp256k1_scalar_is_zero(q));
- secp256k1_ecmult_const(&rj, &p, q);
+ secp256k1_ecmult_const_gej(&rj, &p, q);
VERIFY_CHECK(!secp256k1_gej_is_infinity(&rj));
/* The resulting (X, Y, Z) point on the effective-affine isomorphic curve corresponds to
@@ -396,6 +405,10 @@ static int secp256k1_ecmult_const_xonly(secp256k1_fe* r, const secp256k1_fe *n,
secp256k1_fe_inv(&i, &i);
secp256k1_fe_mul(r, &rj.x, &i);
+ /* Clear local variables computed from secret scalar q */
+ secp256k1_gej_clear(&rj);
+ secp256k1_fe_clear(&i);
+
return 1;
}
### src/secp256k1/src/ecmult_impl.h
@@ -30,15 +30,6 @@
#else
/* optimal for 128-bit and 256-bit exponents. */
# define WINDOW_A 5
-/** Larger values for ECMULT_WINDOW_SIZE result in possibly better
- * performance at the cost of an exponentially larger precomputed
- * table. The exact table size is
- * (1 << (WINDOW_G - 2)) * sizeof(secp256k1_ge_storage) bytes,
- * where sizeof(secp256k1_ge_storage) is typically 64 bytes but can
- * be larger due to platform-specific padding and alignment.
- * Two tables of this size are used (due to the endomorphism
- * optimization).
- */
#endif
#define WNAF_BITS 128
### src/secp256k1/src/group.h
@@ -20,7 +20,6 @@ typedef struct {
} secp256k1_ge;
#define SECP256K1_GE_CONST(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) {SECP256K1_FE_CONST((a),(b),(c),(d),(e),(f),(g),(h)), SECP256K1_FE_CONST((i),(j),(k),(l),(m),(n),(o),(p)), 0}
-#define SECP256K1_GE_CONST_INFINITY {SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 0), SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 0), 1}
/** A group element of the secp256k1 curve, in jacobian coordinates.
* Note: For exhastive test mode, secp256k1 is replaced by a small subgroup of a different curve.
@@ -205,8 +204,15 @@ static void secp256k1_ge_to_bytes_ext(unsigned char *data, const secp256k1_ge *g
* provided buffer is the output of secp256k1_ge_to_bytes_ext. */
static void secp256k1_ge_from_bytes_ext(secp256k1_ge *ge, const unsigned char *data);
-/** Parse a group element from a 33-byte compressed or 65-byte uncompressed public key. */
-static int secp256k1_ge_parse(secp256k1_ge *elem, const unsigned char *pub, size_t size);
+/** Parse a group element from a 33-byte compressed public key (prefix byte is 0x02 or 0x03). */
+static int secp256k1_ge_parse33(secp256k1_ge *elem, const unsigned char *pub);
+
+/** Parse a group element from a 65-byte uncompressed public key (prefix byte is 0x04). */
+static int secp256k1_ge_parse65(secp256k1_ge *elem, const unsigned char *pub);
+
+/** Parse a group element from a 65-byte uncompressed or hybrid public key (prefix byte is 0x04, 0x06 or 0x07).
+ * Only intended for legacy public APIs that must accept hybrid keys. */
+static int secp256k1_ge_parse_with_hybrid65(secp256k1_ge *elem, const unsigned char *pub);
/** Serialize a group element (that is not allowed to be infinity) to a compressed public key (33 bytes). */
static void secp256k1_ge_serialize33(secp256k1_ge *elem, unsigned char *pub33);
### src/secp256k1/src/group_impl.h
@@ -1030,12 +1030,12 @@ static int secp256k1_ge_x_frac_on_curve_var(const secp256k1_fe *xn, const secp25
SECP256K1_INLINE static void secp256k1_ge_impl_to_bytes(unsigned char *buf, const secp256k1_ge *a) {
secp256k1_ge_storage s;
- VERIFY_CHECK(!a->infinity);
-
/* We require that the secp256k1_ge_storage type is exactly 64 bytes.
* This is formally not guaranteed by the C standard, but should hold on any
* sane compiler in the real world. */
STATIC_ASSERT(sizeof(secp256k1_ge_storage) == 64);
+
+ VERIFY_CHECK(!a->infinity);
secp256k1_ge_to_storage(&s, a);
memcpy(buf, &s, 64);
}
@@ -1081,11 +1081,24 @@ static void secp256k1_ge_from_bytes_ext(secp256k1_ge *ge, const unsigned char *d
SECP256K1_GE_VERIFY(ge);
}
-SECP256K1_INLINE static int secp256k1_ge_impl_parse(secp256k1_ge *elem, const unsigned char *pub, size_t size) {
- if (size == 33 && (pub[0] == SECP256K1_TAG_PUBKEY_EVEN || pub[0] == SECP256K1_TAG_PUBKEY_ODD)) {
+SECP256K1_INLINE static int secp256k1_ge_impl_parse33(secp256k1_ge *elem, const unsigned char *pub) {
+ if (pub[0] == SECP256K1_TAG_PUBKEY_EVEN || pub[0] == SECP256K1_TAG_PUBKEY_ODD) {
secp256k1_fe x;
return secp256k1_fe_set_b32_limit(&x, pub+1) && secp256k1_ge_set_xo_var(elem, &x, pub[0] == SECP256K1_TAG_PUBKEY_ODD);
- } else if (size == 65 && (pub[0] == SECP256K1_TAG_PUBKEY_UNCOMPRESSED || pub[0] == SECP256K1_TAG_PUBKEY_HYBRID_EVEN || pub[0] == SECP256K1_TAG_PUBKEY_HYBRID_ODD)) {
+ } else {
+ return 0;
+ }
+}
+static int secp256k1_ge_parse33(secp256k1_ge *elem, const unsigned char *pub) {
+ int ret = secp256k1_ge_impl_parse33(elem, pub);
+ if (ret) {
+ SECP256K1_GE_VERIFY(elem);
+ }
+ return ret;
+}
+
+SECP256K1_INLINE static int secp256k1_ge_impl_parse_with_hybrid65(secp256k1_ge *elem, const unsigned char *pub) {
+ if (pub[0] == SECP256K1_TAG_PUBKEY_UNCOMPRESSED || pub[0] == SECP256K1_TAG_PUBKEY_HYBRID_EVEN || pub[0] == SECP256K1_TAG_PUBKEY_HYBRID_ODD) {
secp256k1_fe x, y;
if (!secp256k1_fe_set_b32_limit(&x, pub+1) || !secp256k1_fe_set_b32_limit(&y, pub+33)) {
return 0;
@@ -1100,8 +1113,23 @@ SECP256K1_INLINE static int secp256k1_ge_impl_parse(secp256k1_ge *elem, const un
return 0;
}
}
-static int secp256k1_ge_parse(secp256k1_ge *elem, const unsigned char *pub, size_t size) {
- int ret = secp256k1_ge_impl_parse(elem, pub, size);
+static int secp256k1_ge_parse_with_hybrid65(secp256k1_ge *elem, const unsigned char *pub) {
+ int ret = secp256k1_ge_impl_parse_with_hybrid65(elem, pub);
+ if (ret) {
+ SECP256K1_GE_VERIFY(elem);
+ }
+ return ret;
+}
+
+SECP256K1_INLINE static int secp256k1_ge_impl_parse65(secp256k1_ge *elem, const unsigned char *pub) {
+ if (pub[0] == SECP256K1_TAG_PUBKEY_UNCOMPRESSED) {
+ return secp256k1_ge_impl_parse_with_hybrid65(elem, pub);
+ } else {
+ return 0;
+ }
+}
+static int secp256k1_ge_parse65(secp256k1_ge *elem, const unsigned char *pub) {
+ int ret = secp256k1_ge_impl_parse65(elem, pub);
if (ret) {
SECP256K1_GE_VERIFY(elem);
}
@@ -1158,7 +1186,7 @@ SECP256K1_INLINE static int secp256k1_ge_impl_parse_ext33(secp256k1_ge *ge, cons
secp256k1_ge_set_infinity(ge);
return 1;
}
- if (!secp256k1_ge_parse(ge, in33, 33)) {
+ if (!secp256k1_ge_parse33(ge, in33)) {
return 0;
}
return secp256k1_ge_is_in_correct_subgroup(ge);
### src/secp256k1/src/modinv32_impl.h
@@ -64,7 +64,8 @@ static void secp256k1_modinv32_normalize_30(secp256k1_modinv32_signed30 *r, int3
const int32_t M30 = (int32_t)(UINT32_MAX >> 2);
int32_t r0 = r->v[0], r1 = r->v[1], r2 = r->v[2], r3 = r->v[3], r4 = r->v[4],
r5 = r->v[5], r6 = r->v[6], r7 = r->v[7], r8 = r->v[8];
- volatile int32_t cond_add, cond_negate;
+ int32_t cond_negate;
+ volatile int32_t vcond_add, vcond_negate;
#ifdef VERIFY
/* Verify that all limbs are in range (-2^30,2^30). */
@@ -82,17 +83,19 @@ static void secp256k1_modinv32_normalize_30(secp256k1_modinv32_signed30 *r, int3
* limbs are in range (-2^30,2^30), this cannot overflow an int32_t. Note that the right
* shifts below are signed sign-extending shifts (see assumptions.h for tests that that is
* indeed the behavior of the right shift operator). */
- cond_add = r8 >> 31;
- r0 += modinfo->modulus.v[0] & cond_add;
- r1 += modinfo->modulus.v[1] & cond_add;
- r2 += modinfo->modulus.v[2] & cond_add;
- r3 += modinfo->modulus.v[3] & cond_add;
- r4 += modinfo->modulus.v[4] & cond_add;
- r5 += modinfo->modulus.v[5] & cond_add;
- r6 += modinfo->modulus.v[6] & cond_add;
- r7 += modinfo->modulus.v[7] & cond_add;
- r8 += modinfo->modulus.v[8] & cond_add;
- cond_negate = sign >> 31;
+ vcond_add = r8 >> 31;
+ r0 += modinfo->modulus.v[0] & vcond_add;
+ r1 += modinfo->modulus.v[1] & vcond_add;
+ r2 += modinfo->modulus.v[2] & vcond_add;
+ r3 += modinfo->modulus.v[3] & vcond_add;
+ r4 += modinfo->modulus.v[4] & vcond_add;
+ r5 += modinfo->modulus.v[5] & vcond_add;
+ r6 += modinfo->modulus.v[6] & vcond_add;
+ r7 += modinfo->modulus.v[7] & vcond_add;
+ r8 += modinfo->modulus.v[8] & vcond_add;
+ vcond_negate = sign >> 31;
+ /* Unsequenced reads to volatile variables are UB, so copy to a non-volatile variable first.*/
+ cond_negate = vcond_negate;
r0 = (r0 ^ cond_negate) - cond_negate;
r1 = (r1 ^ cond_negate) - cond_negate;
r2 = (r2 ^ cond_negate) - cond_negate;
@@ -114,16 +117,16 @@ static void secp256k1_modinv32_normalize_30(secp256k1_modinv32_signed30 *r, int3
/* In a second step add the modulus again if the result is still negative, bringing r to range
* [0,modulus). */
- cond_add = r8 >> 31;
- r0 += modinfo->modulus.v[0] & cond_add;
- r1 += modinfo->modulus.v[1] & cond_add;
- r2 += modinfo->modulus.v[2] & cond_add;
- r3 += modinfo->modulus.v[3] & cond_add;
- r4 += modinfo->modulus.v[4] & cond_add;
- r5 += modinfo->modulus.v[5] & cond_add;
- r6 += modinfo->modulus.v[6] & cond_add;
- r7 += modinfo->modulus.v[7] & cond_add;
- r8 += modinfo->modulus.v[8] & cond_add;
+ vcond_add = r8 >> 31;
+ r0 += modinfo->modulus.v[0] & vcond_add;
+ r1 += modinfo->modulus.v[1] & vcond_add;
+ r2 += modinfo->modulus.v[2] & vcond_add;
+ r3 += modinfo->modulus.v[3] & vcond_add;
+ r4 += modinfo->modulus.v[4] & vcond_add;
+ r5 += modinfo->modulus.v[5] & vcond_add;
+ r6 += modinfo->modulus.v[6] & vcond_add;
+ r7 += modinfo->modulus.v[7] & vcond_add;
+ r8 += modinfo->modulus.v[8] & vcond_add;
/* And propagate again. */
r1 += r0 >> 30; r0 &= M30;
r2 += r1 >> 30; r1 &= M30;
### src/secp256k1/src/modinv64_impl.h
@@ -88,7 +88,8 @@ static int secp256k1_modinv64_det_check_pow2(const secp256k1_modinv64_trans2x2 *
static void secp256k1_modinv64_normalize_62(secp256k1_modinv64_signed62 *r, int64_t sign, const secp256k1_modinv64_modinfo *modinfo) {
const int64_t M62 = (int64_t)(UINT64_MAX >> 2);
int64_t r0 = r->v[0], r1 = r->v[1], r2 = r->v[2], r3 = r->v[3], r4 = r->v[4];
- volatile int64_t cond_add, cond_negate;
+ int64_t cond_negate;
+ volatile int64_t vcond_add, vcond_negate;
#ifdef VERIFY
/* Verify that all limbs are in range (-2^62,2^62). */
@@ -106,13 +107,15 @@ static void secp256k1_modinv64_normalize_62(secp256k1_modinv64_signed62 *r, int6
* limbs are in range (-2^62,2^62), this cannot overflow an int64_t. Note that the right
* shifts below are signed sign-extending shifts (see assumptions.h for tests that that is
* indeed the behavior of the right shift operator). */
- cond_add = r4 >> 63;
- r0 += modinfo->modulus.v[0] & cond_add;
- r1 += modinfo->modulus.v[1] & cond_add;
- r2 += modinfo->modulus.v[2] & cond_add;
- r3 += modinfo->modulus.v[3] & cond_add;
- r4 += modinfo->modulus.v[4] & cond_add;
- cond_negate = sign >> 63;
+ vcond_add = r4 >> 63;
+ r0 += modinfo->modulus.v[0] & vcond_add;
+ r1 += modinfo->modulus.v[1] & vcond_add;
+ r2 += modinfo->modulus.v[2] & vcond_add;
+ r3 += modinfo->modulus.v[3] & vcond_add;
+ r4 += modinfo->modulus.v[4] & vcond_add;
+ vcond_negate = sign >> 63;
+ /* Unsequenced reads to volatile variables are UB, so copy to a non-volatile variable first.*/
+ cond_negate = vcond_negate;
r0 = (r0 ^ cond_negate) - cond_negate;
r1 = (r1 ^ cond_negate) - cond_negate;
r2 = (r2 ^ cond_negate) - cond_negate;
@@ -126,12 +129,12 @@ static void secp256k1_modinv64_normalize_62(secp256k1_modinv64_signed62 *r, int6
/* In a second step add the modulus again if the result is still negative, bringing
* r to range [0,modulus). */
- cond_add = r4 >> 63;
- r0 += modinfo->modulus.v[0] & cond_add;
- r1 += modinfo->modulus.v[1] & cond_add;
- r2 += modinfo->modulus.v[2] & cond_add;
- r3 += modinfo->modulus.v[3] & cond_add;
- r4 += modinfo->modulus.v[4] & cond_add;
+ vcond_add = r4 >> 63;
+ r0 += modinfo->modulus.v[0] & vcond_add;
+ r1 += modinfo->modulus.v[1] & vcond_add;
+ r2 += modinfo->modulus.v[2] & vcond_add;
+ r3 += modinfo->modulus.v[3] & vcond_add;
+ r4 += modinfo->modulus.v[4] & vcond_add;
/* And propagate again. */
r1 += r0 >> 62; r0 &= M62;
r2 += r1 >> 62; r1 &= M62;
@@ -194,7 +197,7 @@ static int64_t secp256k1_modinv64_divsteps_59(int64_t zeta, uint64_t f0, uint64_
g += x & mask2;
q += y & mask2;
r += z & mask2;
- /* In what follows, c1 is a condition mask for (zeta < 0) and (g & 1). */
+ /* In what follows, mask1 is a condition mask for (zeta < 0) and (g & 1). */
mask1 &= mask2;
/* Conditionally change zeta into -zeta-2 or zeta-1. */
zeta = (zeta ^ mask1) - 1;
### src/secp256k1/src/modules/ecdh/main_impl.h
@@ -34,7 +34,6 @@ const secp256k1_ecdh_hash_function secp256k1_ecdh_hash_function_default = ecdh_h
int secp256k1_ecdh(const secp256k1_context* ctx, unsigned char *output, const secp256k1_pubkey *point, const unsigned char *scalar, secp256k1_ecdh_hash_function hashfp, void *data) {
int ret = 0;
int is_sec_valid;
- secp256k1_gej res;
secp256k1_ge pt;
secp256k1_scalar s;
unsigned char x[32];
@@ -49,8 +48,7 @@ int secp256k1_ecdh(const secp256k1_context* ctx, unsigned char *output, const se
is_sec_valid = secp256k1_scalar_set_b32_seckey(&s, scalar);
secp256k1_scalar_cmov(&s, &secp256k1_scalar_one, !is_sec_valid);
- secp256k1_ecmult_const(&res, &pt, &s);
- secp256k1_ge_set_gej(&pt, &res);
+ secp256k1_ecmult_const_ge(&pt, &pt, &s);
/* Compute a hash of the point */
secp256k1_fe_normalize(&pt.x);
@@ -69,7 +67,6 @@ int secp256k1_ecdh(const secp256k1_context* ctx, unsigned char *output, const se
secp256k1_memclear_explicit(y, sizeof(y));
secp256k1_scalar_clear(&s);
secp256k1_ge_clear(&pt);
- secp256k1_gej_clear(&res);
return (!!ret) & is_sec_valid;
}
### src/secp256k1/src/modules/musig/session_impl.h
@@ -168,7 +168,7 @@ int secp256k1_musig_pubnonce_parse(const secp256k1_context* ctx, secp256k1_musig
ARG_CHECK(in66 != NULL);
for (i = 0; i < 2; i++) {
- if (!secp256k1_ge_parse(&ges[i], &in66[33*i], 33)) {
+ if (!secp256k1_ge_parse33(&ges[i], &in66[33*i])) {
return 0;
}
if (!secp256k1_ge_is_in_correct_subgroup(&ges[i])) {
### src/secp256k1/src/modules/musig/tests_impl.h
@@ -20,6 +20,7 @@
#include "../../group.h"
#include "../../hash.h"
#include "../../util.h"
+#include "../../testutil.h"
#include "../../unit_test.h"
#include "vectors.h"
@@ -608,6 +609,96 @@ static void sha256_tag_test(void) {
}
}
+DEFINE_SHA256_TRANSFORM_PROBE(sha256_musig_pubkey_agg)
+DEFINE_SHA256_TRANSFORM_PROBE(sha256_musig_nonce_gen)
+DEFINE_SHA256_TRANSFORM_PROBE(sha256_musig_nonce_gen_counter)
+DEFINE_SHA256_TRANSFORM_PROBE(sha256_musig_nonce_process)
+DEFINE_SHA256_TRANSFORM_PROBE(sha256_musig_partial_sign)
+DEFINE_SHA256_TRANSFORM_PROBE(sha256_musig_partial_sig_verify)
+/* Check that a ctx-provided SHA256 compression override takes effect in every musig
+ * API function that uses the hash context. These functions share the same signing
+ * session, so the setup is built only once with the default compression, then each
+ * function is re-run with its own override enabled. */
+static void musig_ctx_sha256(void) {
+ secp256k1_context *ctx = secp256k1_context_clone(CTX);
+ secp256k1_musig_keyagg_cache keyagg_cache, keyagg_cache_custom;
+ secp256k1_musig_secnonce secnonce, secnonce_tmp, secnonce_unused;
+ secp256k1_musig_pubnonce pubnonce, pubnonce_custom;
+ secp256k1_musig_pubnonce pubnonce_counter, pubnonce_counter_custom;
+ const secp256k1_musig_pubnonce *pubnonce_ptr[1];
+ secp256k1_musig_aggnonce aggnonce;
+ secp256k1_musig_session session, session_custom;
+ secp256k1_musig_partial_sig partial_sig, partial_sig_custom;
+ const unsigned char sk[32] = {1};
+ const unsigned char msg32[32] = {1};
+ unsigned char secrand[32] = {1};
+ secp256k1_keypair keypair;
+ secp256k1_pubkey pk;
+ const secp256k1_pubkey *pks[1];
+
+ CHECK(secp256k1_keypair_create(ctx, &keypair, sk) == 1);
+ CHECK(secp256k1_keypair_pub(ctx, &pk, &keypair) == 1);
+ pks[0] = &pk;
+ pubnonce_ptr[0] = &pubnonce;
+
+ /* Run a full signing session with the default compression. */
+ CHECK(secp256k1_musig_pubkey_agg(ctx, NULL, &keyagg_cache, pks, 1) == 1);
+ CHECK(secp256k1_musig_nonce_gen(ctx, &secnonce, &pubnonce, secrand, sk, &pk, NULL, NULL, NULL) == 1);
+ CHECK(secp256k1_musig_nonce_agg(ctx, &aggnonce, pubnonce_ptr, 1) == 1);
+ CHECK(secp256k1_musig_nonce_process(ctx, &session, &aggnonce, msg32, &keyagg_cache) == 1);
+ /* partial_sign zeroes the secnonce to prevent reuse, so keep a copy for the override run */
+ memcpy(&secnonce_tmp, &secnonce, sizeof(secnonce_tmp));
+ CHECK(secp256k1_musig_partial_sign(ctx, &partial_sig, &secnonce, &keypair, &keyagg_cache, &session) == 1);
+ CHECK(secp256k1_musig_partial_sig_verify(ctx, &partial_sig, &pubnonce, &pk, &keyagg_cache, &session) == 1);
+ /* nonce_gen_counter is an alternative to nonce_gen and not part of the session above,
+ * so run it separately with the default compression. */
+ CHECK(secp256k1_musig_nonce_gen_counter(ctx, &secnonce_unused, &pubnonce_counter, 0, &keypair, NULL, NULL, NULL) == 1);
+ CHECK(!sha256_musig_pubkey_agg_called);
+ CHECK(!sha256_musig_nonce_gen_called);
+ CHECK(!sha256_musig_nonce_gen_counter_called);
+ CHECK(!sha256_musig_nonce_process_called);
+ CHECK(!sha256_musig_partial_sign_called);
+ CHECK(!sha256_musig_partial_sig_verify_called);
+
+ /* Re-run each function with its SHA256 compression override, set directly to bypass
+ * the ctx setter sanity checks. Each override must change the output relative to the
+ * default run above. The override runs reuse the default inputs from above, so each
+ * function is exercised in isolation. */
+ ctx->hash_ctx.fn_sha256_compression = sha256_musig_pubkey_agg;
+ CHECK(secp256k1_musig_pubkey_agg(ctx, NULL, &keyagg_cache_custom, pks, 1) == 1);
+ CHECK(sha256_musig_pubkey_agg_called);
+ CHECK(secp256k1_memcmp_var(keyagg_cache.data, keyagg_cache_custom.data, sizeof(keyagg_cache.data)) != 0);
+
+ /* Restore secrand (nonce_gen zeroed it). */
+ secrand[0] = 1;
+ ctx->hash_ctx.fn_sha256_compression = sha256_musig_nonce_gen;
+ CHECK(secp256k1_musig_nonce_gen(ctx, &secnonce_unused, &pubnonce_custom, secrand, sk, &pk, NULL, NULL, NULL) == 1);
+ CHECK(sha256_musig_nonce_gen_called);
+ CHECK(secp256k1_memcmp_var(pubnonce.data, pubnonce_custom.data, sizeof(pubnonce.data)) != 0);
+
+ ctx->hash_ctx.fn_sha256_compression = sha256_musig_nonce_process;
+ CHECK(secp256k1_musig_nonce_process(ctx, &session_custom, &aggnonce, msg32, &keyagg_cache) == 1);
+ CHECK(sha256_musig_nonce_process_called);
+ CHECK(secp256k1_memcmp_var(session.data, session_custom.data, sizeof(session.data)) != 0);
+
+ ctx->hash_ctx.fn_sha256_compression = sha256_musig_partial_sign;
+ CHECK(secp256k1_musig_partial_sign(ctx, &partial_sig_custom, &secnonce_tmp, &keypair, &keyagg_cache, &session) == 1);
+ CHECK(sha256_musig_partial_sign_called);
+ CHECK(secp256k1_memcmp_var(partial_sig.data, partial_sig_custom.data, sizeof(partial_sig.data)) != 0);
+
+ /* The default partial sig no longer verifies once the override changes the KeyAgg coefficient. */
+ ctx->hash_ctx.fn_sha256_compression = sha256_musig_partial_sig_verify;
+ CHECK(secp256k1_musig_partial_sig_verify(ctx, &partial_sig, &pubnonce, &pk, &keyagg_cache, &session) == 0);
+ CHECK(sha256_musig_partial_sig_verify_called);
+
+ ctx->hash_ctx.fn_sha256_compression = sha256_musig_nonce_gen_counter;
+ CHECK(secp256k1_musig_nonce_gen_counter(ctx, &secnonce_unused, &pubnonce_counter_custom, 0, &keypair, NULL, NULL, NULL) == 1);
+ CHECK(sha256_musig_nonce_gen_counter_called);
+ CHECK(secp256k1_memcmp_var(pubnonce_counter.data, pubnonce_counter_custom.data, sizeof(pubnonce_counter.data)) != 0);
+
+ secp256k1_context_destroy(ctx);
+}
+
/* Attempts to create a signature for the aggregate public key using given secret
* keys and keyagg_cache. */
static void musig_tweak_test_helper(const secp256k1_xonly_pubkey* agg_pk, const unsigned char *sk0, const unsigned char *sk1, secp256k1_musig_keyagg_cache *keyagg_cache) {
@@ -1138,6 +1229,29 @@ static void musig_test_static_nonce_gen_counter(void) {
CHECK(secp256k1_memcmp_var(pubnonce66, expected_pubnonce, sizeof(pubnonce66)) == 0);
}
+/* Checks that nonce_gen_counter matches nonce_gen */
+static void musig_nonce_gen_counter_test(void) {
+ secp256k1_musig_secnonce secnonce;
+ secp256k1_musig_pubnonce pubnonce[2];
+ secp256k1_keypair keypair;
+ secp256k1_pubkey pk;
+ unsigned char sk[32];
+ int i;
+
+ testrand256(sk);
+ CHECK(create_keypair_and_pk(&keypair, &pk, sk));
+
+ for (i = 0; i < COUNT; i++) {
+ unsigned char session_secrand32[32] = { 0 };
+ uint64_t nonrepeating_cnt = testrand64();
+
+ secp256k1_write_be64(session_secrand32, nonrepeating_cnt);
+ CHECK(secp256k1_musig_nonce_gen_counter(CTX, &secnonce, &pubnonce[0], nonrepeating_cnt, &keypair, NULL, NULL, NULL) == 1);
+ CHECK(secp256k1_musig_nonce_gen(CTX, &secnonce, &pubnonce[1], session_secrand32, sk, &pk, NULL, NULL, NULL) == 1);
+ CHECK(secp256k1_memcmp_var(&pubnonce[0], &pubnonce[1], sizeof(pubnonce[0])) == 0);
+ }
+}
+
/* --- Test registry --- */
REPEAT_TEST(musig_simple_test)
/* Run multiple times to ensure that pk and nonce have different y parities */
@@ -1149,13 +1263,15 @@ static const struct tf_test_entry tests_musig[] = {
CASE1(musig_nonce_test),
CASE1(musig_tweak_test),
CASE1(sha256_tag_test),
+ CASE1(musig_ctx_sha256),
CASE1(musig_test_vectors_keyagg),
CASE1(musig_test_vectors_noncegen),
CASE1(musig_test_vectors_nonceagg),
CASE1(musig_test_vectors_signverify),
CASE1(musig_test_vectors_tweak),
CASE1(musig_test_vectors_sigagg),
CASE1(musig_test_static_nonce_gen_counter),
+ CASE1(musig_nonce_gen_counter_test),
};
#endif
### src/secp256k1/src/modules/silentpayments/main_impl.h
@@ -86,14 +86,12 @@ static int secp256k1_silentpayments_calculate_input_hash_scalar(const secp256k1_
}
static void secp256k1_silentpayments_create_shared_secret(unsigned char *shared_secret33, const secp256k1_ge *public_component, const secp256k1_scalar *secret_component) {
- secp256k1_gej ss_j;
secp256k1_ge ss;
VERIFY_CHECK(!secp256k1_ge_is_infinity(public_component));
VERIFY_CHECK(!secp256k1_scalar_is_zero(secret_component));
- secp256k1_ecmult_const(&ss_j, public_component, secret_component);
- secp256k1_ge_set_gej(&ss, &ss_j);
+ secp256k1_ecmult_const_ge(&ss, public_component, secret_component);
/* serialize shared secret in constant-time */
secp256k1_fe_normalize(&ss.x);
@@ -103,7 +101,6 @@ static void secp256k1_silentpayments_create_shared_secret(unsigned char *shared_
/* Leaking these values would break indistinguishability of the transaction, so clear them. */
secp256k1_ge_clear(&ss);
- secp256k1_gej_clear(&ss_j);
}
/** Set hash state to the BIP340 tagged hash midstate for "BIP0352/SharedSecret". */
@@ -363,7 +360,7 @@ int secp256k1_silentpayments_recipient_label_parse(const secp256k1_context* ctx,
memset(label, 0, sizeof(*label));
ARG_CHECK(in33 != NULL);
- if (!secp256k1_ge_parse(&ge, in33, 33)) {
+ if (!secp256k1_ge_parse33(&ge, in33)) {
return 0;
}
@@ -500,7 +497,6 @@ int secp256k1_silentpayments_recipient_prevouts_summary_create(
ARG_CHECK(prevouts_summary != NULL);
memset(prevouts_summary, 0, sizeof(*prevouts_summary));
ARG_CHECK(outpoint_smallest36 != NULL);
- ARG_CHECK((n_pubkeys > 0) || (n_xonly_pubkeys > 0));
if (n_xonly_pubkeys > 0) {
ARG_CHECK(xonly_pubkeys != NULL);
for (i = 0; i < n_xonly_pubkeys; i++) {
@@ -519,7 +515,8 @@ int secp256k1_silentpayments_recipient_prevouts_summary_create(
* Since an attacker can maliciously craft transactions where the public keys sum to zero, fail early here
* to avoid making the caller do extra work, e.g., when building an index or scanning a malicious transaction.
*
- * This will also fail if any of the provided prevout public keys are malformed.
+ * This will also fail if any of the provided prevout public keys are malformed, or if no public keys were
+ * provided at all (i.e., the transaction has no eligible inputs), as the sum is then the point at infinity.
*/
secp256k1_gej_set_infinity(&prevouts_pubkey_sum_gej);
for (i = 0; i < n_pubkeys; i++) {
@@ -614,17 +611,18 @@ int secp256k1_silentpayments_recipient_scan_outputs(
/* Sanity check inputs */
VERIFY_CHECK(ctx != NULL);
- ARG_CHECK(found_outputs != NULL);
ARG_CHECK(n_found_outputs != NULL);
*n_found_outputs = 0;
- ARG_CHECK(tx_outputs != NULL);
- ARG_CHECK(n_tx_outputs > 0);
- for (i = 0; i < n_tx_outputs; i++) {
- ARG_CHECK(found_outputs[i] != NULL);
- ARG_CHECK(tx_outputs[i] != NULL);
- /* Validate each tx output object early so malformed pubkeys are always rejected. */
- if (!secp256k1_xonly_pubkey_load(ctx, &tx_output_ge, tx_outputs[i])) {
- return 0;
+ if (n_tx_outputs > 0) {
+ ARG_CHECK(found_outputs != NULL);
+ ARG_CHECK(tx_outputs != NULL);
+ for (i = 0; i < n_tx_outputs; i++) {
+ ARG_CHECK(found_outputs[i] != NULL);
+ ARG_CHECK(tx_outputs[i] != NULL);
+ /* Validate each tx output object early so malformed pubkeys are always rejected. */
+ if (!secp256k1_xonly_pubkey_load(ctx, &tx_output_ge, tx_outputs[i])) {
+ return 0;
+ }
}
}
ARG_CHECK(scan_key32 != NULL);
@@ -635,6 +633,10 @@ int secp256k1_silentpayments_recipient_scan_outputs(
if (label_context != NULL) {
ARG_CHECK(label_lookup != NULL);
}
+ /* A transaction without any taproot outputs is not a Silent Payments transaction. */
+ if (n_tx_outputs == 0) {
+ return 0;
+ }
valid_scan_key = secp256k1_scalar_set_b32_seckey(&scan_key_scalar, scan_key32);
secp256k1_declassify(ctx, &valid_scan_key, sizeof(valid_scan_key));
if (!valid_scan_key) {
@@ -752,34 +754,33 @@ int secp256k1_silentpayments_recipient_scan_outputs(
}
}
if (found_idx != -1) {
- found_outputs[k]->output = *tx_outputs[found_idx];
- secp256k1_scalar_get_b32(found_outputs[k]->tweak, &t_k_scalar);
+ secp256k1_scalar final_tweak_scalar = t_k_scalar;
/* Clear the t_k_scalar since we no longer need it and leaking this value would
* break indistinguishability of the transaction. */
secp256k1_scalar_clear(&t_k_scalar);
if (label_tweak != NULL) {
- found_outputs[k]->found_with_label = 1;
- /* This is extremely unlikely to fail in that it can only really happen if label_tweak
- * is the negation of the shared secret tweak. But since both tweak and label_tweak are
- * created by hashing data, practically speaking this would only happen if an attacker
- * tricked us into using a particular label_tweak (deviating from the protocol).
- * Note that this call could also fail due to a malformed label_tweak data from the
- * label cache, but we generally assume the passed in data is created using the API
- * functions and thus have already been checked for correctness.
- *
- * Furthermore, although technically a failure for ec_seckey_tweak_add, this is not treated
- * as a failure for Silent Payments because the output is still spendable with just the
- * spend secret key. We set `tweak = 0` for this case.
- */
- if (!secp256k1_ec_seckey_tweak_add(ctx, found_outputs[k]->tweak, label_tweak)) {
- memset(found_outputs[k]->tweak, 0, 32);
+ int tweak_overflow;
+ secp256k1_scalar label_tweak_scalar;
+ secp256k1_scalar_set_b32(&label_tweak_scalar, label_tweak, &tweak_overflow);
+ if (tweak_overflow) {
+ /* Leaking these values would break indistinguishability of the transaction, so clear them. */
+ secp256k1_scalar_clear(&label_tweak_scalar);
+ secp256k1_scalar_clear(&final_tweak_scalar);
+ secp256k1_memclear_explicit(&shared_secret, sizeof(shared_secret));
}
+ ARG_CHECK(!tweak_overflow);
+ found_outputs[k]->found_with_label = 1;
+ secp256k1_scalar_add(&final_tweak_scalar, &final_tweak_scalar, &label_tweak_scalar);
+ secp256k1_scalar_clear(&label_tweak_scalar);
secp256k1_silentpayments_label_save(&found_outputs[k]->label, &label_ge);
} else {
found_outputs[k]->found_with_label = 0;
/* Set the label to an invalid value. */
memset(&found_outputs[k]->label, 0, sizeof(found_outputs[k]->label));
}
+ found_outputs[k]->output = *tx_outputs[found_idx];
+ secp256k1_scalar_get_b32(found_outputs[k]->tweak, &final_tweak_scalar);
+ secp256k1_scalar_clear(&final_tweak_scalar);
/* Reset everything for the next round of scanning. */
label_tweak = NULL;
} else {
### src/secp256k1/src/modules/silentpayments/tests_impl.h
@@ -19,6 +19,9 @@
* scan public keys
* Smallest Outpoint: smallest outpoint lexicographically from the transaction
* Seckey: secret key for Alice
+ * Output Tweak: output tweak (k = 0) when scanning with Alice's secret key
+ * as scan key, Bob's first address key as both input public
+ * keys, and the smallest outpoint
*
* The values themselves are not important.
*/
@@ -85,6 +88,12 @@ static unsigned char ALICE_SECKEY[32] = {
0x8a, 0x4c, 0x53, 0xf6, 0xe0, 0x50, 0x7b, 0x42,
0x15, 0x42, 0x01, 0xb8, 0xe5, 0xdf, 0xf3, 0xb1
};
+static unsigned char OUTPUT_TWEAK[32] = {
+ 0x96, 0x32, 0xb4, 0x06, 0xeb, 0x56, 0xcc, 0xb2,
+ 0x0f, 0xc6, 0xe5, 0x2c, 0x41, 0xd5, 0x73, 0xb2,
+ 0xae, 0xa0, 0x45, 0x07, 0x63, 0xf1, 0xf6, 0x22,
+ 0xfa, 0x87, 0xc2, 0x4c, 0x7d, 0x80, 0x58, 0x62
+};
struct label_cache_entry {
unsigned char label[33];
@@ -111,6 +120,30 @@ const unsigned char* label_lookup(const unsigned char* key, const void* cache_pt
return NULL;
}
+static void prevouts_summary_create_bob(secp256k1_silentpayments_prevouts_summary *ps, secp256k1_xonly_pubkey *t, secp256k1_pubkey *p) {
+ secp256k1_xonly_pubkey const *tp[1];
+ secp256k1_pubkey const *pp[1];
+
+ CHECK(secp256k1_ec_pubkey_parse(CTX, p, BOB_ADDRESS[0], 33));
+ CHECK(secp256k1_xonly_pubkey_parse(CTX, t, &BOB_ADDRESS[0][1]));
+ tp[0] = t;
+ pp[0] = p;
+ CHECK(secp256k1_silentpayments_recipient_prevouts_summary_create(CTX, ps, SMALLEST_OUTPOINT, tp, 1, pp, 1));
+}
+
+static void labels_cache_set_neg_output_tweak(struct labels_cache *cache) {
+ unsigned char neg_output_tweak[32];
+ secp256k1_pubkey label_pubkey;
+ size_t len = 33;
+
+ memcpy(neg_output_tweak, OUTPUT_TWEAK, 32);
+ CHECK(secp256k1_ec_seckey_negate(CTX, neg_output_tweak));
+ CHECK(secp256k1_ec_pubkey_create(CTX, &label_pubkey, neg_output_tweak));
+ CHECK(secp256k1_ec_pubkey_serialize(CTX, cache->entries[0].label, &len, &label_pubkey, SECP256K1_EC_COMPRESSED));
+ memcpy(cache->entries[0].label_tweak, neg_output_tweak, 32);
+ cache->entries_used = 1;
+}
+
static void test_recipient_sort_helper(unsigned char (*sp_addresses[3])[2][33], unsigned char (*sp_outputs[3])[32]) {
unsigned char const *seckey_ptrs[1];
secp256k1_silentpayments_recipient recipients[3];
@@ -295,6 +328,24 @@ static void test_send_api(void) {
p2[0] = secp256k1_group_order_bytes;
CHECK(secp256k1_silentpayments_sender_create_outputs(CTX, op, rp, 2, SMALLEST_OUTPOINT, NULL, 0, p2, 2) == 0);
}
+ /* Check that an invalid keypair is caught even when it is passed alongside a valid one.
+ * Putting the invalid keypair first ensures that a missing early return is not masked
+ * by the subsequent zero-sum check, since the valid keypair leaves a nonzero sum. */
+ {
+ secp256k1_keypair valid_keypair;
+ secp256k1_keypair invalid_keypair;
+ secp256k1_keypair const *t2[2];
+ CHECK(secp256k1_keypair_create(CTX, &valid_keypair, ALICE_SECKEY));
+ invalid_keypair = valid_keypair;
+ /* Zero the secret key while keeping the public key valid. */
+ memset(&invalid_keypair.data[0], 0, 32);
+ t2[0] = &valid_keypair;
+ t2[1] = &invalid_keypair;
+ CHECK_ILLEGAL(CTX, secp256k1_silentpayments_sender_create_outputs(CTX, op, rp, 2, SMALLEST_OUTPOINT, t2, 2, NULL, 0));
+ t2[0] = &invalid_keypair;
+ t2[1] = &valid_keypair;
+ CHECK_ILLEGAL(CTX, secp256k1_silentpayments_sender_create_outputs(CTX, op, rp, 2, SMALLEST_OUTPOINT, t2, 2, NULL, 0));
+ }
/* Create malformed recipients by setting all of the public key bytes to zero.
* Realistically, this would never happen since a bad public key would get caught when
* trying to parse the public key with _ec_pubkey_parse
@@ -482,14 +533,12 @@ static void test_recipient_api(void) {
secp256k1_pubkey const *pp[1]; /* array of pointers to plain pks */
uint32_t n_f; /* number of found outputs */
- CHECK(secp256k1_ec_pubkey_parse(CTX, &p, BOB_ADDRESS[0], 33));
memset(&malformed_p, 0, sizeof(malformed_p));
memset(&malformed_t, 0, sizeof(malformed_t));
- CHECK(secp256k1_xonly_pubkey_parse(CTX, &t, &BOB_ADDRESS[0][1]));
+ prevouts_summary_create_bob(&ps, &t, &p);
tp[0] = &t;
pp[0] = &p;
fp[0] = &f;
- CHECK(secp256k1_silentpayments_recipient_prevouts_summary_create(CTX, &ps, SMALLEST_OUTPOINT, tp, 1, pp, 1));
/* Reusing a prevouts_summary after a failure must not leave the old object valid. */
{
secp256k1_pubkey neg_p = p;
@@ -538,46 +587,31 @@ static void test_recipient_api(void) {
CHECK(secp256k1_silentpayments_recipient_prevouts_summary_create(CTX, &ps, SMALLEST_OUTPOINT, tp, 0, pp, 1));
CHECK(secp256k1_silentpayments_recipient_prevouts_summary_create(CTX, &ps, SMALLEST_OUTPOINT, tp, 1, NULL, 0));
CHECK(secp256k1_silentpayments_recipient_prevouts_summary_create(CTX, &ps, SMALLEST_OUTPOINT, tp, 1, pp, 0));
- CHECK_ILLEGAL(CTX, secp256k1_silentpayments_recipient_prevouts_summary_create(CTX, &ps, SMALLEST_OUTPOINT, NULL, 0, pp, 0));
- CHECK_ILLEGAL(CTX, secp256k1_silentpayments_recipient_prevouts_summary_create(CTX, &ps, SMALLEST_OUTPOINT, NULL, 0, NULL, 0));
+ /* A transaction without any eligible inputs is not a Silent Payments transaction (no illegal argument) */
+ CHECK(secp256k1_silentpayments_recipient_prevouts_summary_create(CTX, &ps, SMALLEST_OUTPOINT, NULL, 0, pp, 0) == 0);
+ CHECK(secp256k1_silentpayments_recipient_prevouts_summary_create(CTX, &ps, SMALLEST_OUTPOINT, tp, 0, pp, 0) == 0);
+ CHECK(secp256k1_silentpayments_recipient_prevouts_summary_create(CTX, &ps, SMALLEST_OUTPOINT, NULL, 0, NULL, 0) == 0);
CHECK(secp256k1_silentpayments_recipient_prevouts_summary_create(CTX, &ps, SMALLEST_OUTPOINT, tp, 1, pp, 1));
/* check the _recipient_scan_outputs cornercase where internal tweaking would fail;
this is the case if the recipient spend public key is P = -(create_output_tweak(shared_secret, k))*G */
{
- unsigned char output_tweak[32] = {
- 0x96, 0x32, 0xb4, 0x06, 0xeb, 0x56, 0xcc, 0xb2,
- 0x0f, 0xc6, 0xe5, 0x2c, 0x41, 0xd5, 0x73, 0xb2,
- 0xae, 0xa0, 0x45, 0x07, 0x63, 0xf1, 0xf6, 0x22,
- 0xfa, 0x87, 0xc2, 0x4c, 0x7d, 0x80, 0x58, 0x62,
- };
secp256k1_pubkey neg_spend_pubkey;
- CHECK(secp256k1_ec_pubkey_create(CTX, &neg_spend_pubkey, output_tweak));
+ CHECK(secp256k1_ec_pubkey_create(CTX, &neg_spend_pubkey, OUTPUT_TWEAK));
CHECK(secp256k1_ec_pubkey_negate(CTX, &neg_spend_pubkey));
CHECK(secp256k1_silentpayments_recipient_scan_outputs(CTX, fp, &n_f, tp, 1, ALICE_SECKEY, &ps, &neg_spend_pubkey, &label_lookup, &labels_cache) == 0);
}
/* check the _recipients_scan_outputs cornercase where the output_tweak is the negation of the label_tweak */
{
- unsigned char output_tweak[32] = {
- 0x96, 0x32, 0xb4, 0x06, 0xeb, 0x56, 0xcc, 0xb2,
- 0x0f, 0xc6, 0xe5, 0x2c, 0x41, 0xd5, 0x73, 0xb2,
- 0xae, 0xa0, 0x45, 0x07, 0x63, 0xf1, 0xf6, 0x22,
- 0xfa, 0x87, 0xc2, 0x4c, 0x7d, 0x80, 0x58, 0x62,
- };
static const unsigned char zero[32] = {0};
- secp256k1_pubkey spk, neg_label_pubkey;
+ secp256k1_pubkey spk;
secp256k1_xonly_pubkey output_xonly;
secp256k1_xonly_pubkey const *output_xonly_ptrs[1];
- size_t len = 33;
uint32_t found;
CHECK(secp256k1_ec_pubkey_parse(CTX, &spk, BOB_ADDRESS[0], 33));
CHECK(secp256k1_xonly_pubkey_from_pubkey(CTX, &output_xonly, NULL, &spk));
output_xonly_ptrs[0] = &output_xonly;
- CHECK(secp256k1_ec_seckey_negate(CTX, output_tweak));
- CHECK(secp256k1_ec_pubkey_create(CTX, &neg_label_pubkey, output_tweak));
- CHECK(secp256k1_ec_pubkey_serialize(CTX, labels_cache.entries[0].label, &len, &neg_label_pubkey, SECP256K1_EC_COMPRESSED));
- memcpy(labels_cache.entries[0].label_tweak, output_tweak, 32);
- labels_cache.entries_used = 1;
+ labels_cache_set_neg_output_tweak(&labels_cache);
found = 0;
CHECK(secp256k1_silentpayments_recipient_scan_outputs(CTX, fp, &found, output_xonly_ptrs, 1, ALICE_SECKEY, &ps, &spk, &label_lookup, &labels_cache));
CHECK(found == 1);
@@ -588,6 +622,9 @@ static void test_recipient_api(void) {
CHECK(secp256k1_silentpayments_recipient_label_serialize(CTX, found_label_ser, &fp[0]->label));
CHECK(secp256k1_memcmp_var(found_label_ser, labels_cache.entries[0].label, 33) == 0);
}
+ /* check that a label tweak overflowing the group order is rejected */
+ memcpy(labels_cache.entries[0].label_tweak, secp256k1_group_order_bytes, 32);
+ CHECK_ILLEGAL(CTX, secp256k1_silentpayments_recipient_scan_outputs(CTX, fp, &found, output_xonly_ptrs, 1, ALICE_SECKEY, &ps, &spk, &label_lookup, &labels_cache));
}
n_f = 0;
@@ -616,8 +653,14 @@ static void test_recipient_api(void) {
CHECK_ILLEGAL(CTX, secp256k1_silentpayments_recipient_scan_outputs(CTX, fp, &n_f, tp, 1, NULL, &ps, &p, &label_lookup, &labels_cache));
CHECK_ILLEGAL(CTX, secp256k1_silentpayments_recipient_scan_outputs(CTX, fp, &n_f, tp, 1, ALICE_SECKEY, NULL, &p, &label_lookup, &labels_cache));
CHECK_ILLEGAL(CTX, secp256k1_silentpayments_recipient_scan_outputs(CTX, fp, &n_f, tp, 1, ALICE_SECKEY, &ps, NULL, &label_lookup, &labels_cache));
- CHECK_ILLEGAL(CTX, secp256k1_silentpayments_recipient_scan_outputs(CTX, fp, &n_f, tp, 0, ALICE_SECKEY, &ps, &p, &label_lookup, &labels_cache));
CHECK_ILLEGAL(CTX, secp256k1_silentpayments_recipient_scan_outputs(CTX, fp, &n_f, tp, 1, ALICE_SECKEY, &ps, &p, NULL, &labels_cache));
+ /* A transaction without any taproot outputs is not a Silent Payments transaction (no illegal argument) */
+ n_f = 1;
+ CHECK(secp256k1_silentpayments_recipient_scan_outputs(CTX, fp, &n_f, tp, 0, ALICE_SECKEY, &ps, &p, &label_lookup, &labels_cache) == 0);
+ CHECK(n_f == 0);
+ n_f = 1;
+ CHECK(secp256k1_silentpayments_recipient_scan_outputs(CTX, NULL, &n_f, NULL, 0, ALICE_SECKEY, &ps, &p, &label_lookup, &labels_cache) == 0);
+ CHECK(n_f == 0);
/* Check that malformed secret key, public keys, and prevouts_summary arguments are handled */
CHECK_ILLEGAL(CTX, secp256k1_silentpayments_recipient_scan_outputs(CTX, fp, &n_f, tp, 1, ALICE_SECKEY, &ps, &malformed_p, NULL, NULL));
@@ -690,6 +733,50 @@ static void test_recipient_scan_label_precedes_direct_match(void) {
CHECK(secp256k1_memcmp_var(found_label, cache.entries[0].label, sizeof(found_label)) == 0);
}
+static void test_recipient_scan_label_batch_index(void) {
+ enum { N_OUTPUTS = 2 * LABEL_BATCH_SIZE + 1 };
+ secp256k1_silentpayments_prevouts_summary ps;
+ secp256k1_silentpayments_found_output f[N_OUTPUTS];
+ secp256k1_silentpayments_found_output *fp[N_OUTPUTS];
+ secp256k1_xonly_pubkey t, filler;
+ secp256k1_xonly_pubkey const *tp[N_OUTPUTS];
+ secp256k1_pubkey p, filler_p;
+ secp256k1_pubkey p_neg;
+ struct labels_cache cache;
+ uint32_t n_f;
+ size_t i, k;
+
+ prevouts_summary_create_bob(&ps, &t, &p);
+ /* Use a label whose tweak is the negation of the output tweak, so the
+ * labeled output for this prevouts summary equals the spend public key. */
+ labels_cache_set_neg_output_tweak(&cache);
+
+ /* Place the labeled output at every position among non-matching outputs spanning several label
+ * batches, so that the batch index and the tx output index differ. */
+ CHECK(secp256k1_ec_pubkey_create(CTX, &filler_p, ALICE_SECKEY));
+ CHECK(secp256k1_xonly_pubkey_from_pubkey(CTX, &filler, NULL, &filler_p));
+ p_neg = p;
+ CHECK(secp256k1_ec_pubkey_negate(CTX, &p_neg));
+ for (i = 0; i < N_OUTPUTS; i++) {
+ fp[i] = &f[i];
+ }
+ for (k = 0; k < N_OUTPUTS; k++) {
+ for (i = 0; i < N_OUTPUTS; i++) {
+ tp[i] = &filler;
+ }
+ tp[k] = &t;
+ /* Scan with p and -p as spend public key to test both even and odd candidates slots. */
+ CHECK(secp256k1_silentpayments_recipient_scan_outputs(CTX, fp, &n_f, tp, N_OUTPUTS, ALICE_SECKEY, &ps, &p, &label_lookup, &cache));
+ CHECK(n_f == 1);
+ CHECK(secp256k1_xonly_pubkey_cmp(CTX, &f[0].output, &t) == 0);
+ CHECK(f[0].found_with_label);
+ CHECK(secp256k1_silentpayments_recipient_scan_outputs(CTX, fp, &n_f, tp, N_OUTPUTS, ALICE_SECKEY, &ps, &p_neg, &label_lookup, &cache));
+ CHECK(n_f == 1);
+ CHECK(secp256k1_xonly_pubkey_cmp(CTX, &f[0].output, &t) == 0);
+ CHECK(f[0].found_with_label);
+ }
+}
+
void run_silentpayments_test_vector_send(const struct bip352_test_vector *test) {
static secp256k1_silentpayments_recipient recipients[MAX_OUTPUTS_PER_TEST_CASE];
static const secp256k1_silentpayments_recipient *recipient_ptrs[MAX_OUTPUTS_PER_TEST_CASE];
@@ -798,20 +885,14 @@ void run_silentpayments_test_vector_receive(const struct bip352_test_vector *tes
CHECK(secp256k1_xonly_pubkey_parse(CTX, &xonly_pubkeys_objs[i], test->xonly_pubkeys[i]));
xonly_pubkeys[i] = &xonly_pubkeys_objs[i];
}
- {
- int32_t ecount = 0;
- secp256k1_context_set_illegal_callback(CTX, counting_callback_fn, &ecount);
- ret = secp256k1_silentpayments_recipient_prevouts_summary_create(CTX, &prevouts_summary,
- test->outpoint_smallest,
- test->num_taproot_inputs > 0 ? xonly_pubkeys : NULL, test->num_taproot_inputs,
- test->num_plain_inputs > 0 ? pubkeys : NULL, test->num_plain_inputs
- );
- secp256k1_context_set_illegal_callback(CTX, NULL, NULL);
- /* We expect exactly one ARG_CHECK if the number of input keys was 0. */
- CHECK(ecount == ((test->num_taproot_inputs + test->num_plain_inputs) == 0));
- }
- /* If we are unable to create the prevouts_summary object, e.g., the input public keys sum to
- * zero, check that the expected number of recipient outputs for this test case is zero
+ ret = secp256k1_silentpayments_recipient_prevouts_summary_create(CTX, &prevouts_summary,
+ test->outpoint_smallest,
+ xonly_pubkeys, test->num_taproot_inputs,
+ pubkeys, test->num_plain_inputs
+ );
+ /* If we are unable to create the prevouts_summary object, e.g., there are no eligible inputs or
+ * the input public keys sum to zero, check that the expected number of recipient outputs for
+ * this test case is zero
*/
if (!ret) {
CHECK(subtest->num_found_output_pubkeys == 0);
@@ -905,6 +986,14 @@ void run_silentpayments_test_vector_receive(const struct bip352_test_vector *tes
CHECK(found_label_tweak != NULL);
}
}
+ } else {
+ /* Not performing a full check, so resort to a structural sanity check: */
+ /* All outputs must have distinct x-only pubkeys. */
+ for (i = 0; i < n_found; i++) {
+ for (j = i + 1; j < n_found; j++) {
+ CHECK(secp256k1_xonly_pubkey_cmp(CTX, &found_outputs[i]->output, &found_outputs[j]->output) != 0);
+ }
+ }
}
CHECK(n_found == subtest->num_found_output_pubkeys);
}
@@ -951,6 +1040,7 @@ static const struct tf_test_entry tests_silentpayments[] = {
CASE1(test_label_api),
CASE1(test_recipient_api),
CASE1(test_recipient_scan_label_precedes_direct_match),
+ CASE1(test_recipient_scan_label_batch_index),
CASE1(run_silentpayments_test_vectors),
CASE1(silentpayments_sha256_tag_test),
};
### src/secp256k1/src/secp256k1.c
@@ -263,12 +263,18 @@ static void secp256k1_pubkey_save(secp256k1_pubkey* pubkey, secp256k1_ge* ge) {
int secp256k1_ec_pubkey_parse(const secp256k1_context* ctx, secp256k1_pubkey* pubkey, const unsigned char *input, size_t inputlen) {
secp256k1_ge Q;
+ int is_pubkey_valid;
VERIFY_CHECK(ctx != NULL);
ARG_CHECK(pubkey != NULL);
memset(pubkey, 0, sizeof(*pubkey));
ARG_CHECK(input != NULL);
- if (!secp256k1_ge_parse(&Q, input, inputlen)) {
+ switch (inputlen) {
+ case 33: is_pubkey_valid = secp256k1_ge_parse33(&Q, input); break;
+ case 65: is_pubkey_valid = secp256k1_ge_parse_with_hybrid65(&Q, input); break;
+ default: is_pubkey_valid = 0;
+ }
+ if (!is_pubkey_valid) {
return 0;
}
if (!secp256k1_ge_is_in_correct_subgroup(&Q)) {
### src/secp256k1/src/tests.c
@@ -4645,28 +4645,27 @@ static void test_point_times_order(const secp256k1_gej *point) {
* - For b in [-3, -1, 1, 3]:
* - Output (a*LAMBDA + (ORDER+b)/2) % ORDER
*/
-static const secp256k1_scalar scalars_near_split_bounds[20] = {
- SECP256K1_SCALAR_CONST(0xd938a566, 0x7f479e3e, 0xb5b3c7fa, 0xefdb3749, 0x3aa0585c, 0xc5ea2367, 0xe1b660db, 0x0209e6fc),
- SECP256K1_SCALAR_CONST(0xd938a566, 0x7f479e3e, 0xb5b3c7fa, 0xefdb3749, 0x3aa0585c, 0xc5ea2367, 0xe1b660db, 0x0209e6fd),
- SECP256K1_SCALAR_CONST(0xd938a566, 0x7f479e3e, 0xb5b3c7fa, 0xefdb3749, 0x3aa0585c, 0xc5ea2367, 0xe1b660db, 0x0209e6fe),
- SECP256K1_SCALAR_CONST(0xd938a566, 0x7f479e3e, 0xb5b3c7fa, 0xefdb3749, 0x3aa0585c, 0xc5ea2367, 0xe1b660db, 0x0209e6ff),
- SECP256K1_SCALAR_CONST(0x2c9c52b3, 0x3fa3cf1f, 0x5ad9e3fd, 0x77ed9ba5, 0xb294b893, 0x3722e9a5, 0x00e698ca, 0x4cf7632d),
- SECP256K1_SCALAR_CONST(0x2c9c52b3, 0x3fa3cf1f, 0x5ad9e3fd, 0x77ed9ba5, 0xb294b893, 0x3722e9a5, 0x00e698ca, 0x4cf7632e),
- SECP256K1_SCALAR_CONST(0x2c9c52b3, 0x3fa3cf1f, 0x5ad9e3fd, 0x77ed9ba5, 0xb294b893, 0x3722e9a5, 0x00e698ca, 0x4cf7632f),
- SECP256K1_SCALAR_CONST(0x2c9c52b3, 0x3fa3cf1f, 0x5ad9e3fd, 0x77ed9ba5, 0xb294b893, 0x3722e9a5, 0x00e698ca, 0x4cf76330),
- SECP256K1_SCALAR_CONST(0x7fffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xd576e735, 0x57a4501d, 0xdfe92f46, 0x681b209f),
- SECP256K1_SCALAR_CONST(0x7fffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xd576e735, 0x57a4501d, 0xdfe92f46, 0x681b20a0),
- SECP256K1_SCALAR_CONST(0x7fffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xd576e735, 0x57a4501d, 0xdfe92f46, 0x681b20a1),
- SECP256K1_SCALAR_CONST(0x7fffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xd576e735, 0x57a4501d, 0xdfe92f46, 0x681b20a2),
- SECP256K1_SCALAR_CONST(0xd363ad4c, 0xc05c30e0, 0xa5261c02, 0x88126459, 0xf85915d7, 0x7825b696, 0xbeebc5c2, 0x833ede11),
- SECP256K1_SCALAR_CONST(0xd363ad4c, 0xc05c30e0, 0xa5261c02, 0x88126459, 0xf85915d7, 0x7825b696, 0xbeebc5c2, 0x833ede12),
- SECP256K1_SCALAR_CONST(0xd363ad4c, 0xc05c30e0, 0xa5261c02, 0x88126459, 0xf85915d7, 0x7825b696, 0xbeebc5c2, 0x833ede13),
- SECP256K1_SCALAR_CONST(0xd363ad4c, 0xc05c30e0, 0xa5261c02, 0x88126459, 0xf85915d7, 0x7825b696, 0xbeebc5c2, 0x833ede14),
- SECP256K1_SCALAR_CONST(0x26c75a99, 0x80b861c1, 0x4a4c3805, 0x1024c8b4, 0x704d760e, 0xe95e7cd3, 0xde1bfdb1, 0xce2c5a42),
- SECP256K1_SCALAR_CONST(0x26c75a99, 0x80b861c1, 0x4a4c3805, 0x1024c8b4, 0x704d760e, 0xe95e7cd3, 0xde1bfdb1, 0xce2c5a43),
- SECP256K1_SCALAR_CONST(0x26c75a99, 0x80b861c1, 0x4a4c3805, 0x1024c8b4, 0x704d760e, 0xe95e7cd3, 0xde1bfdb1, 0xce2c5a44),
- SECP256K1_SCALAR_CONST(0x26c75a99, 0x80b861c1, 0x4a4c3805, 0x1024c8b4, 0x704d760e, 0xe95e7cd3, 0xde1bfdb1, 0xce2c5a45)
-};
+static void fill_scalars_near_split_bounds(secp256k1_scalar scalars20[20]) {
+ static const int a_values[] = {-2, -1, 0, 1, 2};
+ static const int b_values[] = {-3, -1, 1, 3};
+ size_t i, j;
+ for (i = 0; i < ARRAY_SIZE(a_values); ++i) {
+ for (j = 0; j < ARRAY_SIZE(b_values); ++j) {
+ secp256k1_scalar a, b;
+ secp256k1_scalar_set_int(&a, a_values[i] < 0 ? -a_values[i] : a_values[i]);
+ if (a_values[i] < 0) {
+ secp256k1_scalar_negate(&a, &a);
+ }
+ secp256k1_scalar_mul(&a, &a, &secp256k1_const_lambda);
+ secp256k1_scalar_set_int(&b, b_values[j] < 0 ? -b_values[j] : b_values[j]);
+ if (b_values[j] < 0) {
+ secp256k1_scalar_negate(&b, &b);
+ }
+ secp256k1_scalar_half(&b, &b);
+ secp256k1_scalar_add(&scalars20[i * ARRAY_SIZE(b_values) + j], &a, &b);
+ }
+ }
+}
static void test_ecmult_target(const secp256k1_scalar* target, int mode) {
/* Mode: 0=ecmult_gen, 1=ecmult, 2=ecmult_const */
@@ -4695,9 +4694,9 @@ static void test_ecmult_target(const secp256k1_scalar* target, int mode) {
secp256k1_ecmult(&p2j, &pj, &n2, &secp256k1_scalar_zero);
secp256k1_ecmult(&ptj, &pj, target, &secp256k1_scalar_zero);
} else {
- secp256k1_ecmult_const(&p1j, &p, &n1);
- secp256k1_ecmult_const(&p2j, &p, &n2);
- secp256k1_ecmult_const(&ptj, &p, target);
+ secp256k1_ecmult_const_gej(&p1j, &p, &n1);
+ secp256k1_ecmult_const_gej(&p2j, &p, &n2);
+ secp256k1_ecmult_const_gej(&ptj, &p, target);
}
/* Add them all up: n1*P + n2*P + target*P = (n1+n2+target)*P = (n1+n1-n1-n2)*P = 0. */
@@ -4709,6 +4708,8 @@ static void test_ecmult_target(const secp256k1_scalar* target, int mode) {
static void run_ecmult_near_split_bound(void) {
int i;
unsigned j;
+ secp256k1_scalar scalars_near_split_bounds[20];
+ fill_scalars_near_split_bounds(scalars_near_split_bounds);
for (i = 0; i < 4*COUNT; ++i) {
for (j = 0; j < ARRAY_SIZE(scalars_near_split_bounds); ++j) {
test_ecmult_target(&scalars_near_split_bounds[j], 0);
@@ -4760,7 +4761,7 @@ static void ecmult_const_random_mult(void) {
0xb84e4e1b, 0xfb77e21f, 0x96baae2a, 0x63dec956
);
secp256k1_gej b;
- secp256k1_ecmult_const(&b, &a, &xn);
+ secp256k1_ecmult_const_gej(&b, &a, &xn);
CHECK(secp256k1_ge_is_valid_var(&a));
CHECK(secp256k1_gej_eq_ge_var(&b, &expected_b));
@@ -4769,21 +4770,15 @@ static void ecmult_const_random_mult(void) {
static void ecmult_const_commutativity(void) {
secp256k1_scalar a;
secp256k1_scalar b;
- secp256k1_gej res1;
- secp256k1_gej res2;
secp256k1_ge mid1;
secp256k1_ge mid2;
testutil_random_scalar_order_test(&a);
testutil_random_scalar_order_test(&b);
- secp256k1_ecmult_const(&res1, &secp256k1_ge_const_g, &a);
- secp256k1_ecmult_const(&res2, &secp256k1_ge_const_g, &b);
- secp256k1_ge_set_gej(&mid1, &res1);
- secp256k1_ge_set_gej(&mid2, &res2);
- secp256k1_ecmult_const(&res1, &mid1, &b);
- secp256k1_ecmult_const(&res2, &mid2, &a);
- secp256k1_ge_set_gej(&mid1, &res1);
- secp256k1_ge_set_gej(&mid2, &res2);
+ secp256k1_ecmult_const_ge(&mid1, &secp256k1_ge_const_g, &a);
+ secp256k1_ecmult_const_ge(&mid2, &secp256k1_ge_const_g, &b);
+ secp256k1_ecmult_const_ge(&mid1, &mid1, &b);
+ secp256k1_ecmult_const_ge(&mid2, &mid2, &a);
CHECK(secp256k1_ge_eq_var(&mid1, &mid2));
}
@@ -4801,20 +4796,20 @@ static void ecmult_const_mult_zero_one(void) {
secp256k1_ge_set_infinity(&inf);
/* 0*point */
- secp256k1_ecmult_const(&res1, &point, &secp256k1_scalar_zero);
+ secp256k1_ecmult_const_gej(&res1, &point, &secp256k1_scalar_zero);
CHECK(secp256k1_gej_is_infinity(&res1));
/* s*inf */
- secp256k1_ecmult_const(&res1, &inf, &s);
+ secp256k1_ecmult_const_gej(&res1, &inf, &s);
CHECK(secp256k1_gej_is_infinity(&res1));
/* 1*point */
- secp256k1_ecmult_const(&res1, &point, &secp256k1_scalar_one);
+ secp256k1_ecmult_const_gej(&res1, &point, &secp256k1_scalar_one);
secp256k1_ge_set_gej(&res2, &res1);
CHECK(secp256k1_ge_eq_var(&res2, &point));
/* -1*point */
- secp256k1_ecmult_const(&res1, &point, &negone);
+ secp256k1_ecmult_const_gej(&res1, &point, &negone);
secp256k1_gej_neg(&res1, &res1);
secp256k1_ge_set_gej(&res2, &res1);
CHECK(secp256k1_ge_eq_var(&res2, &point));
@@ -4834,7 +4829,10 @@ static void ecmult_const_edges(void) {
secp256k1_ge point;
secp256k1_gej res;
size_t i;
- size_t cases = 1 + ARRAY_SIZE(scalars_near_split_bounds);
+ size_t cases;
+ secp256k1_scalar scalars_near_split_bounds[20];
+ fill_scalars_near_split_bounds(scalars_near_split_bounds);
+ cases = 1 + ARRAY_SIZE(scalars_near_split_bounds);
/* We are trying to reach the following edge cases (variables are defined as
* in ecmult_const_impl.h):
@@ -4851,7 +4849,7 @@ static void ecmult_const_edges(void) {
secp256k1_scalar_add(&q, &q, &scalars_near_split_bounds[i - 1]);
}
testutil_random_ge_test(&point);
- secp256k1_ecmult_const(&res, &point, &q);
+ secp256k1_ecmult_const_gej(&res, &point, &q);
ecmult_const_check_result(&point, &q, &res);
}
}
@@ -4923,17 +4921,12 @@ static void ecmult_const_chain_multiply(void) {
0x5d195d20, 0xe191bf7f, 0x1be3e55f, 0x56a80196,
0x6071ad01, 0xf1462f66, 0xc997fa94, 0xdb858435
);
- secp256k1_gej point;
- secp256k1_ge res;
+ secp256k1_ge res = secp256k1_ge_const_g;
int i;
- secp256k1_gej_set_ge(&point, &secp256k1_ge_const_g);
for (i = 0; i < 100; ++i) {
- secp256k1_ge tmp;
- secp256k1_ge_set_gej(&tmp, &point);
- secp256k1_ecmult_const(&point, &tmp, &scalar);
+ secp256k1_ecmult_const_ge(&res, &res, &scalar);
}
- secp256k1_ge_set_gej(&res, &point);
CHECK(secp256k1_gej_eq_ge_var(&expected_point, &res));
}
@@ -5742,7 +5735,7 @@ static void test_ecmult_accumulate(secp256k1_sha256* acc, const secp256k1_scalar
secp256k1_ecmult(&rj[3], &infj, &secp256k1_scalar_zero, x);
CHECK(secp256k1_ecmult_multi_var(&CTX->error_callback, scratch, &rj[4], x, NULL, NULL, 0));
CHECK(secp256k1_ecmult_multi_var(&CTX->error_callback, scratch, &rj[5], &secp256k1_scalar_zero, test_ecmult_accumulate_cb, (void*)x, 1));
- secp256k1_ecmult_const(&rj[6], &secp256k1_ge_const_g, x);
+ secp256k1_ecmult_const_gej(&rj[6], &secp256k1_ge_const_g, x);
secp256k1_ge_set_gej_var(&r, &rj[0]);
for (i = 0; i < ARRAY_SIZE(rj); i++) {
CHECK(secp256k1_gej_eq_ge_var(&rj[i], &r));
@@ -5947,7 +5940,7 @@ static void test_ecmult_gen_edge_cases(void) {
/* Run test with gn = i - scalar_offset (so that the ecmult_gen recoded value represents i). */
secp256k1_ecmult_gen_gej(&CTX->ecmult_gen_ctx, &res1, &gn);
secp256k1_ecmult(&res2, NULL, &secp256k1_scalar_zero, &gn);
- secp256k1_ecmult_const(&res3, &secp256k1_ge_const_g, &gn);
+ secp256k1_ecmult_const_gej(&res3, &secp256k1_ge_const_g, &gn);
CHECK(secp256k1_gej_eq_var(&res1, &res2));
CHECK(secp256k1_gej_eq_var(&res1, &res3));
secp256k1_scalar_add(&gn, &gn, &secp256k1_scalar_one);
@@ -5994,6 +5987,8 @@ static void test_scalar_split(const secp256k1_scalar* full) {
static void run_endomorphism_tests(void) {
unsigned i;
static secp256k1_scalar s;
+ secp256k1_scalar scalars_near_split_bounds[20];
+ fill_scalars_near_split_bounds(scalars_near_split_bounds);
test_scalar_split(&secp256k1_scalar_zero);
test_scalar_split(&secp256k1_scalar_one);
secp256k1_scalar_negate(&s,&secp256k1_scalar_one);
@@ -6258,15 +6253,22 @@ static void run_ec_pubkey_parse_test(void) {
0xA8, 0xFD, 0x17, 0xB4, 0x48, 0xA6, 0x85, 0x54, 0x19, 0x9C, 0x47, 0xD0, 0x8F, 0xFB, 0x10, 0xD4,
0xB8, 0x00
};
+ const unsigned char pubkeyc_comp[34] = {
+ /* Compressed serialization of G (y is even, so prefix is 0x02). */
+ 0x02, 0x79, 0xBE, 0x66, 0x7E, 0xF9, 0xDC, 0xBB, 0xAC, 0x55, 0xA0, 0x62, 0x95, 0xCE, 0x87, 0x0B,
+ 0x07, 0x02, 0x9B, 0xFC, 0xDB, 0x2D, 0xCE, 0x28, 0xD9, 0x59, 0xF2, 0x81, 0x5B, 0x16, 0xF8, 0x17,
+ 0x98, 0x00
+ };
unsigned char sout[65];
unsigned char shortkey[2] = { 0 };
secp256k1_ge ge;
secp256k1_pubkey pubkey;
size_t len;
int32_t i;
- /* Nothing should be reading this far into pubkeyc. */
+ /* Nothing should be reading this far into pubkeyc and pubkeyc_comp. */
SECP256K1_CHECKMEM_UNDEFINE(&pubkeyc[65], 1);
+ SECP256K1_CHECKMEM_UNDEFINE(&pubkeyc_comp[33], 1);
/* Zero length claimed, fail, zeroize, no illegal arg error. */
memset(&pubkey, 0xfe, sizeof(pubkey));
SECP256K1_CHECKMEM_UNDEFINE(shortkey, 2);
@@ -6294,6 +6296,8 @@ static void run_ec_pubkey_parse_test(void) {
SECP256K1_CHECKMEM_CHECK(&pubkey, sizeof(pubkey));
CHECK_ILLEGAL(CTX, secp256k1_pubkey_load(CTX, &ge, &pubkey));
}
+
+ /* Uncompressed public key parsing and serialization. */
memset(&pubkey, 0xfe, sizeof(pubkey));
SECP256K1_CHECKMEM_UNDEFINE(&pubkey, sizeof(pubkey));
/* 33 bytes claimed on otherwise valid input starting with 0x04, fail, zeroize output, no illegal arg error. */
@@ -6352,6 +6356,44 @@ static void run_ec_pubkey_parse_test(void) {
CHECK(len == 65);
/* Multiple illegal args. Should still set arg error only once. */
CHECK_ILLEGAL(CTX, secp256k1_ec_pubkey_parse(CTX, NULL, NULL, 65));
+
+ /* Compressed public key parsing and serialization. */
+ /* 32 bytes claimed on otherwise valid compressed input starting with 0x02, fail, zeroize output, no illegal arg error. */
+ memset(&pubkey, 0xfe, sizeof(pubkey));
+ SECP256K1_CHECKMEM_UNDEFINE(&pubkey, sizeof(pubkey));
+ CHECK(secp256k1_ec_pubkey_parse(CTX, &pubkey, pubkeyc_comp, 32) == 0);
+ SECP256K1_CHECKMEM_CHECK(&pubkey, sizeof(pubkey));
+ CHECK_ILLEGAL(CTX, secp256k1_pubkey_load(CTX, &ge, &pubkey));
+ /* 34 bytes claimed on otherwise valid compressed input starting with 0x02, fail, zeroize output, no illegal arg error. */
+ memset(&pubkey, 0xfe, sizeof(pubkey));
+ SECP256K1_CHECKMEM_UNDEFINE(&pubkey, sizeof(pubkey));
+ CHECK(secp256k1_ec_pubkey_parse(CTX, &pubkey, pubkeyc_comp, 34) == 0);
+ SECP256K1_CHECKMEM_CHECK(&pubkey, sizeof(pubkey));
+ CHECK_ILLEGAL(CTX, secp256k1_pubkey_load(CTX, &ge, &pubkey));
+ /* Valid compressed parse at length 33. */
+ memset(&pubkey, 0, sizeof(pubkey));
+ SECP256K1_CHECKMEM_UNDEFINE(&pubkey, sizeof(pubkey));
+ CHECK(secp256k1_ec_pubkey_parse(CTX, &pubkey, pubkeyc_comp, 33) == 1);
+ CHECK(secp256k1_ec_pubkey_parse(secp256k1_context_static, &pubkey, pubkeyc_comp, 33) == 1);
+ SECP256K1_CHECKMEM_CHECK(&pubkey, sizeof(pubkey));
+ SECP256K1_CHECKMEM_UNDEFINE(&ge, sizeof(ge));
+ CHECK(secp256k1_pubkey_load(CTX, &ge, &pubkey) == 1);
+ SECP256K1_CHECKMEM_CHECK(&ge.x, sizeof(ge.x));
+ SECP256K1_CHECKMEM_CHECK(&ge.y, sizeof(ge.y));
+ SECP256K1_CHECKMEM_CHECK(&ge.infinity, sizeof(ge.infinity));
+ CHECK(secp256k1_ge_eq_var(&ge, &secp256k1_ge_const_g));
+ /* secp256k1_ec_pubkey_serialize with too small output buffer, illegal arg error. Length is left untouched. */
+ len = 32;
+ CHECK_ILLEGAL(CTX, secp256k1_ec_pubkey_serialize(CTX, sout, &len, &pubkey, SECP256K1_EC_COMPRESSED));
+ CHECK(len == 32);
+ /* Valid compressed serialization, must round-trip to the input. */
+ len = 33;
+ SECP256K1_CHECKMEM_UNDEFINE(sout, 65);
+ CHECK(secp256k1_ec_pubkey_serialize(CTX, sout, &len, &pubkey, SECP256K1_EC_COMPRESSED) == 1);
+ SECP256K1_CHECKMEM_CHECK(sout, 33);
+ CHECK(len == 33);
+ CHECK(secp256k1_memcmp_var(sout, pubkeyc_comp, 33) == 0);
+
/* Try a bunch of prefabbed points with all possible encodings. */
for (i = 0; i < SECP256K1_EC_PARSE_TEST_NVALID; i++) {
ec_pubkey_parse_pointtest(valid[i], 1, 1);
@@ -6852,11 +6894,9 @@ static void test_random_pubkeys(void) {
secp256k1_ge elem;
secp256k1_ge elem2;
unsigned char in[65];
- /* Generate some randomly sized pubkeys. */
- size_t len = testrand_bits(2) == 0 ? 65 : 33;
- if (testrand_bits(2) == 0) {
- len = testrand_bits(6);
- }
+ int res;
+ /* Generate some random pubkeys with the two supported serialization sizes. */
+ size_t len = testrand_bits(1) == 0 ? 65 : 33;
if (len == 65) {
in[0] = testrand_bits(1) ? 4 : (testrand_bits(1) ? 6 : 7);
} else {
@@ -6865,17 +6905,14 @@ static void test_random_pubkeys(void) {
if (testrand_bits(3) == 0) {
in[0] = testrand_bits(8);
}
- if (len > 1) {
- testrand256(&in[1]);
- }
- if (len > 33) {
+ testrand256(&in[1]);
+ if (len == 65) {
testrand256(&in[33]);
}
- if (secp256k1_ge_parse(&elem, in, len)) {
+ res = (len == 33) ? secp256k1_ge_parse33(&elem, in) : secp256k1_ge_parse_with_hybrid65(&elem, in);
+ if (res) {
unsigned char out[65];
unsigned char firstb;
- int res;
- size_t size = len;
firstb = in[0];
/* If the pubkey can be parsed, it should round-trip... */
if (len == 33) {
@@ -6888,13 +6925,13 @@ static void test_random_pubkeys(void) {
if ((in[0] != 6) && (in[0] != 7)) {
CHECK(in[0] == out[0]);
}
- size = 65;
secp256k1_ge_serialize65(&elem, in);
- CHECK(secp256k1_ge_parse(&elem2, in, size));
+ CHECK(secp256k1_ge_parse65(&elem2, in));
CHECK(secp256k1_ge_eq_var(&elem2, &elem));
/* Check that the X9.62 hybrid type is checked. */
in[0] = testrand_bits(1) ? 6 : 7;
- res = secp256k1_ge_parse(&elem2, in, size);
+ CHECK(secp256k1_ge_parse65(&elem2, in) == 0);
+ res = secp256k1_ge_parse_with_hybrid65(&elem2, in);
if (firstb == 2 || firstb == 3) {
if (in[0] == firstb + 4) {
CHECK(res);
@@ -7550,7 +7587,7 @@ static void run_ecdsa_edge_cases(void) {
secp256k1_scalar_set_int(&ss, 1);
secp256k1_scalar_set_int(&msg, 0);
secp256k1_scalar_set_int(&sr, 0);
- CHECK(secp256k1_ge_parse(&key, pubkey_mods_zero, 33));
+ CHECK(secp256k1_ge_parse33(&key, pubkey_mods_zero));
CHECK(secp256k1_ecdsa_sig_verify( &sr, &ss, &key, &msg) == 0);
}
@@ -7569,7 +7606,7 @@ static void run_ecdsa_edge_cases(void) {
secp256k1_scalar_set_int(&ss, 0);
secp256k1_scalar_set_int(&msg, 0);
secp256k1_scalar_set_int(&sr, 1);
- CHECK(secp256k1_ge_parse(&key, pubkey, 33));
+ CHECK(secp256k1_ge_parse33(&key, pubkey));
CHECK(secp256k1_ecdsa_sig_verify(&sr, &ss, &key, &msg) == 0);
}
@@ -7596,8 +7633,8 @@ static void run_ecdsa_edge_cases(void) {
secp256k1_scalar_set_int(&ss, 2);
secp256k1_scalar_set_int(&msg, 0);
secp256k1_scalar_set_int(&sr, 2);
- CHECK(secp256k1_ge_parse(&key, pubkey, 33));
- CHECK(secp256k1_ge_parse(&key2, pubkey2, 33));
+ CHECK(secp256k1_ge_parse33(&key, pubkey));
+ CHECK(secp256k1_ge_parse33(&key2, pubkey2));
CHECK(secp256k1_ecdsa_sig_verify(&sr, &ss, &key, &msg) == 1);
CHECK(secp256k1_ecdsa_sig_verify(&sr, &ss, &key2, &msg) == 1);
secp256k1_scalar_negate(&ss, &ss);
@@ -7637,8 +7674,8 @@ static void run_ecdsa_edge_cases(void) {
secp256k1_scalar_set_int(&ss, 1);
secp256k1_scalar_set_int(&msg, 1);
secp256k1_scalar_set_b32(&sr, csr, NULL);
- CHECK(secp256k1_ge_parse(&key, pubkey, 33));
- CHECK(secp256k1_ge_parse(&key2, pubkey2, 33));
+ CHECK(secp256k1_ge_parse33(&key, pubkey));
+ CHECK(secp256k1_ge_parse33(&key2, pubkey2));
CHECK(secp256k1_ecdsa_sig_verify(&sr, &ss, &key, &msg) == 1);
CHECK(secp256k1_ecdsa_sig_verify(&sr, &ss, &key2, &msg) == 1);
secp256k1_scalar_negate(&ss, &ss);
@@ -7672,7 +7709,7 @@ static void run_ecdsa_edge_cases(void) {
secp256k1_scalar_set_int(&msg, 1);
secp256k1_scalar_negate(&msg, &msg);
secp256k1_scalar_set_b32(&sr, csr, NULL);
- CHECK(secp256k1_ge_parse(&key, pubkey, 33));
+ CHECK(secp256k1_ge_parse33(&key, pubkey));
CHECK(secp256k1_ecdsa_sig_verify(&sr, &ss, &key, &msg) == 1);
secp256k1_scalar_negate(&ss, &ss);
CHECK(secp256k1_ecdsa_sig_verify(&sr, &ss, &key, &msg) == 1);
@@ -7681,6 +7718,34 @@ static void run_ecdsa_edge_cases(void) {
CHECK(secp256k1_ecdsa_sig_verify(&sr, &ss, &key, &msg) == 0);
}
+ /* Verify signature where r + n overflows p fails. */
+ {
+ /* Scalar r as chars: r = p - n + 1, so that (r + n) mod p = 1 */
+ const unsigned char csr[32] = {
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
+ 0x45, 0x51, 0x23, 0x19, 0x50, 0xb7, 0x5f, 0xc4,
+ 0x40, 0x2d, 0xa1, 0x72, 0x2f, 0xc9, 0xba, 0xef
+ };
+ /* With s = 1 and msg = 0, verification computes R = r * pubkey.
+ * pubkey = r^-1 * (1, y), so x(R) = 1. */
+ const unsigned char pubkey[33] = {
+ 0x02, 0x57, 0xad, 0x61, 0xc8, 0x68, 0x3f, 0xcf,
+ 0x06, 0x99, 0x19, 0x11, 0x8c, 0x0f, 0x99, 0xb9,
+ 0x38, 0x9f, 0x65, 0x05, 0x9b, 0xa0, 0x71, 0xba,
+ 0xbe, 0xa6, 0x32, 0x05, 0x34, 0x14, 0x45, 0xda,
+ 0xe8
+ };
+ secp256k1_ge key;
+ secp256k1_scalar msg;
+ secp256k1_scalar sr, ss;
+ secp256k1_scalar_set_int(&ss, 1);
+ secp256k1_scalar_set_int(&msg, 0);
+ secp256k1_scalar_set_b32(&sr, csr, NULL);
+ CHECK(secp256k1_ge_parse33(&key, pubkey));
+ CHECK(secp256k1_ecdsa_sig_verify(&sr, &ss, &key, &msg) == 0);
+ }
+
/* Signature where s would be zero. */
{
secp256k1_pubkey pubkey;
### src/secp256k1/src/tests_exhaustive.c
@@ -168,7 +168,7 @@ static void test_exhaustive_ecmult(const secp256k1_ge *group, const secp256k1_ge
secp256k1_scalar_set_int(&ng, j);
/* Test secp256k1_ecmult_const. */
- secp256k1_ecmult_const(&tmp, &group[i], &ng);
+ secp256k1_ecmult_const_gej(&tmp, &group[i], &ng);
CHECK(secp256k1_gej_eq_ge_var(&tmp, &group[(i * j) % EXHAUSTIVE_TEST_ORDER]));
if (i != 0 && j != 0) {
@@ -358,7 +358,7 @@ static void test_exhaustive_sign(const secp256k1_context *ctx, const secp256k1_g
#include "modules/schnorrsig/tests_exhaustive_impl.h"
#endif
-#ifdef ENABLE_MODULE_ELLSWIFT
+#if defined(ENABLE_MODULE_ELLSWIFT) && !EXHAUSTIVE_TEST_CURVE_HAS_EVEN_ORDER
#include "modules/ellswift/tests_exhaustive_impl.h"
#endif
### src/secp256k1/src/unit_test.c
@@ -99,7 +99,7 @@ static void help(void) {
printf("Notes:\n");
printf(" - All arguments must be provided in the form '--key=value', '-key=value' or '-k=value'.\n");
printf(" - Single or double dashes are allowed for multi character options.\n");
- printf(" - Unknown arguments are reported but ignored.\n");
+ printf(" - Unknown arguments are reported and cause the program to exit with an error.\n");
printf(" - Sequential execution occurs if -jobs=0 or unspecified.\n");
printf(" - Iterations and seed can also be passed as positional arguments before any other argument for backward compatibility.\n");
}
### src/secp256k1/src/util.h
@@ -69,16 +69,18 @@ static void print_buf_plain(const unsigned char *buf, size_t len) {
/** Assert statically that expr is true.
*
- * This is a statement-like macro and can only be used inside functions.
+ * This is a declaration-like macro that can be used at file scope and before
+ * any statements in a block.
*/
-#define STATIC_ASSERT(expr) do { \
- switch(0) { \
- case 0: \
- /* If expr evaluates to 0, we have two case labels "0", which is illegal. */ \
- case /* ERROR: static assertion failed */ (expr): \
- ; \
- } \
-} while(0)
+#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
+# define STATIC_ASSERT(expr) _Static_assert(expr, #expr)
+#elif !defined(__cplusplus) && (defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))))
+/* GCC >= 4.6 and Clang support _Static_assert as an extension in pre-C11 modes,
+ * but g++ does not support it in C++. */
+# define STATIC_ASSERT(expr) __extension__ _Static_assert(expr, #expr)
+#else
+# define STATIC_ASSERT(expr) extern int secp256k1_static_assert_dummy[(expr) ? 1 : -1]
+#endif
/** Assert statically that expr is an integer constant expression, and run stmt.
*Why this scored 35/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.