Compare commits

...

26 Commits

Author SHA1 Message Date
Laan Tungir
56f37e092d v0.0.50 - Clean up README: rename 4c.1 to 'Verbs' (no past-tense references), remove section 11 (Implemented adjuncts and future work) and section 12 (Document map) 2026-07-19 14:07:04 -04:00
Laan Tungir
a017dc40e0 v0.0.49 - Added general encrypt/decrypt verbs with curve-based routing (otp, secp256k1 NIP-04/44, x25519, ml-kem-768) and updated README documentation 2026-07-19 11:38:44 -04:00
Laan Tungir
05c055503d v0.0.48 - Added OTP one-time pad encryption (otp_encrypt/otp_decrypt verbs), HTTP listener mode (--listen http:HOST:PORT), interactive OTP pad auto-scan on USB drives, raised SERVER_MAX_MSG_SIZE to 16MB, updated README with curl examples and current API documentation 2026-07-19 11:07:07 -04:00
Laan Tungir
a7c6de2dcd v0.0.47 - Clean up main menu layout and hotkeys 2026-07-16 17:59:58 -04:00
Laan Tungir
16a6da817c Auto-fix Gitea release timestamp via SSH after release creation (workaround for Gitea created_unix=0 bug) 2026-07-16 16:30:15 -04:00
Laan Tungir
1cf541b02d Fix install script: use git tags API with version sorting instead of releases API (works around Gitea epoch-zero timestamp bug) 2026-07-16 16:13:11 -04:00
Laan Tungir
8015742e29 v0.0.46 - Post-quantum crypto expansion: ML-DSA-65, SLH-DSA-128s, ML-KEM-768, ed25519, x25519, algorithm-based API 2026-07-16 16:11:46 -04:00
Laan Tungir
09f3ec2f7c Fix Gitea release creation: include created_at timestamp to work around Gitea bug where releases get epoch zero timestamp 2026-07-16 16:10:00 -04:00
Laan Tungir
5744b83288 v0.0.47 - Fix increment_and_push.sh build output visibility 2026-07-16 15:38:52 -04:00
Laan Tungir
21892c108e Fix increment_and_push.sh hanging by showing build output instead of suppressing it 2026-07-16 15:37:10 -04:00
Laan Tungir
344add841c v0.0.48 - . 2026-07-16 15:35:20 -04:00
Laan Tungir
3e3013dde1 v0.0.47 - . 2026-07-16 15:33:25 -04:00
Laan Tungir
11d3760d7b v0.0.46 - Fix release tagging for post-quantum crypto expansion 2026-07-16 15:27:34 -04:00
Laan Tungir
c5f1a70658 v0.0.47 - Added post-quantum cryptography (ML-DSA-65, SLH-DSA-128s, ML-KEM-768) and standard ECC (ed25519, x25519) support with algorithm-based API 2026-07-16 15:14:57 -04:00
Laan Tungir
6fd7b8ce1f v0.0.45 - Display qrexec service name (qubes.NsignerRpc) in signer connection info; use human-readable timestamps in activity log; fix static release build by adding miner.c to Dockerfile.alpine-musl 2026-07-11 19:12:34 -04:00
Laan Tungir
1b5af2fd33 v0.0.44 - Add JavaScript and Python demo programs (client/demo_javascript.js, client/demo_python.py) demonstrating get_public_key, sign_event, and nip44 encrypt/decrypt via qrexec 2026-07-11 15:01:48 -04:00
Laan Tungir
9b47883330 v0.0.43 - Add C99 demo program (client/demo_c99.c) demonstrating get_public_key, sign_event, and nip44 encrypt/decrypt via qrexec; sync nostr_core_lib with reconnect fix 2026-07-11 14:55:16 -04:00
Laan Tungir
9a8657f663 v0.0.42 - Add C qrexec client example using high-level nostr_signer API with nostr_index selector; sync nostr_core_lib with qrexec transport and index support 2026-07-11 14:28:09 -04:00
Laan Tungir
478c3a569e v0.0.41 - Fix activity log label for index whitelist denials — shows 'DENIED:index-not-approved' instead of 'DENIED:no-match' 2026-07-11 13:57:13 -04:00
Laan Tungir
10208e5fac v0.0.40 - Add interactive index whitelist prompt after transport selection — users can restrict nostr_index values without CLI flags 2026-07-11 13:46:23 -04:00
Laan Tungir
922a45ce3a v0.0.39 - Remove qrexec one-shot (option 4) from interactive transport menu — only persistent listeners remain 2026-07-11 13:42:59 -04:00
Laan Tungir
d28f691aae v0.0.38 - Add --allow-index whitelist for nostr_index restriction — supports list (1,3,4), range (0-3), mixed (0,2-3), or 'all' 2026-07-11 13:11:36 -04:00
Laan Tungir
2e8ce777d8 v0.0.37 - Add interactive multi-transport selection menu at startup — users can select one or more transports (unix, qrexec bridge, TCP) from a menu instead of memorizing CLI flags 2026-07-11 11:31:21 -04:00
Laan Tungir
8ebdb50789 v0.0.36 - Update README with qrexec bridge docs, update start_nsigner.sh to support qrexec mode and extra args, add setup scripts 2026-07-11 11:09:41 -04:00
Laan Tungir
a39baed82b v0.0.35 - Update README with qrexec bridge docs, update start_nsigner.sh to support qrexec mode and extra args 2026-07-11 11:08:04 -04:00
Laan Tungir
d15eebb80f v0.0.34 - Add qrexec bridge subcommand and --bridge-source-trusted flag for persistent-signer qrexec transport 2026-07-11 09:37:51 -04:00
244 changed files with 98317 additions and 966 deletions

3
.gitignore vendored
View File

@@ -6,4 +6,7 @@ build/
resources/
.test_mnemonic
Trash/
node_modules/
package.json
package-lock.json

View File

@@ -0,0 +1,13 @@
alarm impact educate burden vague honey horn buyer sight vocal age render
index 0
{
"index": 0,
"nsec": "nsec1z2lrfamae2dzax7dmnlhv497uuxe4mw0m3w694upx5x54q6dgttqvzrrwl",
"npub": "npub1j7d7yf47w8k2kseknqjr3045jvm00u0wnt3433kk6vu67d2zamcs8ynuw4",
"npubHex": "979be226be71ecab4336982438beb49336f7f1ee9ae358c6d6d339af3542eef1",
"nsecHex": "12be34f77dca9a2e9bcddcff7654bee70d9aedcfdc5da2d781350d4a834d42d6",
"fipsIpv6": "fd55:b7c6:536e:26ee:a79:6e25:6f05:a85f",
"strDerivationPath": "m/44'/1237'/0'/0/0"
}

View File

@@ -55,7 +55,9 @@ RUN if [ "$(uname -m)" = "aarch64" ] && ! command -v aarch64-linux-gnu-gcc >/dev
# Copy source files
COPY src/ /build/src/
COPY libotppad/ /build/libotppad/
COPY resources/tui_continuous/ /build/resources/tui_continuous/
COPY resources/pqclean/ /build/resources/pqclean/
# Build nsigner as a fully static binary
RUN ARCH="$(uname -m)"; \
@@ -70,6 +72,12 @@ RUN ARCH="$(uname -m)"; \
-I/build/nostr_core_lib/nostr_core \
-I/build/nostr_core_lib/cjson \
-I/build/resources/tui_continuous \
-I/build/resources/pqclean \
-I/build/resources/pqclean/common \
-I/build/resources/pqclean/crypto_sign/ml-dsa-65 \
-I/build/resources/pqclean/crypto_sign/slh-dsa-128s \
-I/build/resources/pqclean/crypto_kem/ml-kem-768 \
-I/build/libotppad \
/build/src/main.c \
/build/src/secure_mem.c \
/build/src/mnemonic.c \
@@ -83,6 +91,33 @@ RUN ARCH="$(uname -m)"; \
/build/src/key_store.c \
/build/src/socket_name.c \
/build/src/auth_envelope.c \
/build/src/miner.c \
/build/src/pq_crypto.c \
/build/src/pq_drbg.c \
/build/src/otp_pad.c \
/build/src/http_listener.c \
/build/libotppad/libotppad.c \
/build/resources/pqclean/crypto_sign/ml-dsa-65/sign.c \
/build/resources/pqclean/crypto_sign/ml-dsa-65/poly.c \
/build/resources/pqclean/crypto_sign/ml-dsa-65/ntt.c \
/build/resources/pqclean/crypto_sign/slh-dsa-128s/sign.c \
/build/resources/pqclean/crypto_sign/slh-dsa-128s/hash.c \
/build/resources/pqclean/crypto_sign/slh-dsa-128s/thash.c \
/build/resources/pqclean/crypto_sign/slh-dsa-128s/utils.c \
/build/resources/pqclean/crypto_sign/slh-dsa-128s/wots.c \
/build/resources/pqclean/crypto_sign/slh-dsa-128s/fors.c \
/build/resources/pqclean/crypto_sign/slh-dsa-128s/address.c \
/build/resources/pqclean/common/fips202.c \
/build/resources/pqclean/common/sha2.c \
/build/resources/pqclean/common/crypto_backend_openssl.c \
/build/resources/pqclean/crypto_kem/ml-kem-768/reduce.c \
/build/resources/pqclean/crypto_kem/ml-kem-768/ntt.c \
/build/resources/pqclean/crypto_kem/ml-kem-768/cbd.c \
/build/resources/pqclean/crypto_kem/ml-kem-768/verify.c \
/build/resources/pqclean/crypto_kem/ml-kem-768/symmetric.c \
/build/resources/pqclean/crypto_kem/ml-kem-768/poly.c \
/build/resources/pqclean/crypto_kem/ml-kem-768/indcpa.c \
/build/resources/pqclean/crypto_kem/ml-kem-768/kem.c \
/build/resources/tui_continuous/tui_continuous.c \
"$NOSTR_LIB" \
-o /build/nsigner_static \

156
Makefile
View File

@@ -1,5 +1,5 @@
CC := gcc
CFLAGS := -Wall -Wextra -std=c99 -Os -ffunction-sections -fdata-sections -Isrc -Iresources/nostr_core_lib -Iresources/nostr_core_lib/nostr_core -Iresources/nostr_core_lib/cjson -Iresources/tui_continuous
CFLAGS := -Wall -Wextra -std=c99 -Os -ffunction-sections -fdata-sections -DNOSTR_ENABLE_NSIGNER_CLIENT=1 -D_GNU_SOURCE -Isrc -Ilibotppad -Iresources/nostr_core_lib -Iresources/nostr_core_lib/nostr_core -Iresources/nostr_core_lib/cjson -Iresources/tui_continuous -Iresources/pqclean -Iresources/pqclean/crypto_sign/ml-dsa-65 -Iresources/pqclean/crypto_sign/slh-dsa-128s -Iresources/pqclean/crypto_kem/ml-kem-768 -Iresources/pqclean/common
LDFLAGS := -Wl,--gc-sections resources/nostr_core_lib/libnostr_core_x64.a -lz -ldl -lpthread -lm -lssl -lcrypto -lcurl -lsecp256k1
SRC_DIR := src
@@ -10,6 +10,31 @@ EXAMPLES_DIR := examples
TARGET_DEV := $(BUILD_DIR)/nsigner
# PQClean ML-DSA-65 sources (Phase 3)
PQCLEAN_DIR := resources/pqclean
PQCLEAN_SOURCES := \
$(PQCLEAN_DIR)/crypto_sign/ml-dsa-65/sign.c \
$(PQCLEAN_DIR)/crypto_sign/ml-dsa-65/poly.c \
$(PQCLEAN_DIR)/crypto_sign/ml-dsa-65/ntt.c \
$(PQCLEAN_DIR)/crypto_sign/slh-dsa-128s/sign.c \
$(PQCLEAN_DIR)/crypto_sign/slh-dsa-128s/hash.c \
$(PQCLEAN_DIR)/crypto_sign/slh-dsa-128s/thash.c \
$(PQCLEAN_DIR)/crypto_sign/slh-dsa-128s/utils.c \
$(PQCLEAN_DIR)/crypto_sign/slh-dsa-128s/wots.c \
$(PQCLEAN_DIR)/crypto_sign/slh-dsa-128s/fors.c \
$(PQCLEAN_DIR)/crypto_sign/slh-dsa-128s/address.c \
$(PQCLEAN_DIR)/common/fips202.c \
$(PQCLEAN_DIR)/common/sha2.c \
$(PQCLEAN_DIR)/common/crypto_backend_openssl.c \
$(PQCLEAN_DIR)/crypto_kem/ml-kem-768/reduce.c \
$(PQCLEAN_DIR)/crypto_kem/ml-kem-768/ntt.c \
$(PQCLEAN_DIR)/crypto_kem/ml-kem-768/cbd.c \
$(PQCLEAN_DIR)/crypto_kem/ml-kem-768/verify.c \
$(PQCLEAN_DIR)/crypto_kem/ml-kem-768/symmetric.c \
$(PQCLEAN_DIR)/crypto_kem/ml-kem-768/poly.c \
$(PQCLEAN_DIR)/crypto_kem/ml-kem-768/indcpa.c \
$(PQCLEAN_DIR)/crypto_kem/ml-kem-768/kem.c
SOURCES := \
$(SRC_DIR)/main.c \
$(SRC_DIR)/secure_mem.c \
@@ -24,6 +49,13 @@ SOURCES := \
$(SRC_DIR)/key_store.c \
$(SRC_DIR)/socket_name.c \
$(SRC_DIR)/auth_envelope.c \
$(SRC_DIR)/miner.c \
$(SRC_DIR)/pq_crypto.c \
$(SRC_DIR)/pq_drbg.c \
$(SRC_DIR)/otp_pad.c \
$(SRC_DIR)/http_listener.c \
libotppad/libotppad.c \
$(PQCLEAN_SOURCES) \
resources/tui_continuous/tui_continuous.c
HEADERS :=
@@ -40,15 +72,29 @@ TEST_SOCKET_NAME_TARGET := $(BUILD_DIR)/test_socket_name
TEST_AUTH_ENVELOPE_TARGET := $(BUILD_DIR)/test_auth_envelope
TEST_QREXEC_AUTH_TARGET := $(BUILD_DIR)/test_qrexec_auth
TEST_MNEMONIC_INPUT_TARGET := $(BUILD_DIR)/test_mnemonic_input
TEST_MINE_EVENT_TARGET := $(BUILD_DIR)/test_mine_event
TEST_PQ_CRYPTO_TARGET := $(BUILD_DIR)/test_pq_crypto
TEST_ED25519_X25519_TARGET := $(BUILD_DIR)/test_ed25519_x25519
TEST_ML_DSA_65_TARGET := $(BUILD_DIR)/test_ml_dsa_65
TEST_SLH_DSA_128S_TARGET := $(BUILD_DIR)/test_slh_dsa_128s
TEST_ML_KEM_768_TARGET := $(BUILD_DIR)/test_ml_kem_768
TEST_PUBKEY_FORMAT_TARGET := $(BUILD_DIR)/test_pubkey_format
TEST_ALGORITHM_API_TARGET := $(BUILD_DIR)/test_algorithm_api
EXAMPLE_GET_PUBLIC_KEY_TARGET := $(BUILD_DIR)/example_get_public_key_client
EXAMPLE_SIGN_EVENT_TARGET := $(BUILD_DIR)/example_sign_event_client
EXAMPLE_GET_PUBKEY_TCP_TARGET := $(BUILD_DIR)/example_get_pubkey_tcp
EXAMPLE_GET_PUBKEY_QREXEC_TARGET := $(BUILD_DIR)/example_get_pubkey_qrexec
EXAMPLE_PQ_SIGN_TARGET := $(BUILD_DIR)/example_pq_sign
EXAMPLE_PQ_KEM_TARGET := $(BUILD_DIR)/example_pq_kem
EXAMPLE_SSH_SIGN_TARGET := $(BUILD_DIR)/example_ssh_sign
DEMO_C99_TARGET := $(BUILD_DIR)/demo_c99
.PHONY: all lib dev static static-debug static-arm64 firmware-feather test test-integration test-mnemonic test-mnemonic-input test-role test-selector test-enforcement test-dispatcher test-policy test-socket-name test-auth-envelope test-qrexec-auth examples test-client clean
.PHONY: all lib dev static static-debug static-arm64 firmware-feather test test-integration test-mnemonic test-mnemonic-input test-role test-selector test-enforcement test-dispatcher test-policy test-socket-name test-auth-envelope test-qrexec-auth test-mine-event test-pq-crypto test-ed25519-x25519 test-ml-dsa-65 test-slh-dsa-128s test-ml-kem-768 test-pubkey-format test-algorithm-api examples test-client clean
all: dev
lib:
cd resources/nostr_core_lib && ./build.sh --nips=1,4,6,19,44
cd resources/nostr_core_lib && ./build.sh --nips=1,4,6,13,19,44
dev: lib $(TARGET_DEV)
@@ -71,7 +117,7 @@ static-arm64:
firmware-feather:
cd firmware/feather_s3_tft && idf.py build
test: lib test-mnemonic test-mnemonic-input test-role test-selector test-enforcement test-dispatcher test-policy test-socket-name test-auth-envelope test-qrexec-auth test-client
test: lib test-mnemonic test-mnemonic-input test-role test-selector test-enforcement test-dispatcher test-policy test-socket-name test-auth-envelope test-qrexec-auth test-mine-event test-pq-crypto test-ed25519-x25519 test-ml-dsa-65 test-slh-dsa-128s test-ml-kem-768 test-pubkey-format test-client
test-integration: $(TEST_INTEGRATION_TARGET) $(TARGET_DEV)
./$(TEST_INTEGRATION_TARGET)
@@ -106,9 +152,33 @@ test-auth-envelope: $(TEST_AUTH_ENVELOPE_TARGET)
test-qrexec-auth: $(TEST_QREXEC_AUTH_TARGET) $(TARGET_DEV)
./$(TEST_QREXEC_AUTH_TARGET)
test-mine-event: $(TEST_MINE_EVENT_TARGET) $(TARGET_DEV)
./$(TEST_MINE_EVENT_TARGET)
test-pq-crypto: $(TEST_PQ_CRYPTO_TARGET)
./$(TEST_PQ_CRYPTO_TARGET)
test-ed25519-x25519: $(TEST_ED25519_X25519_TARGET)
./$(TEST_ED25519_X25519_TARGET)
test-ml-dsa-65: $(TEST_ML_DSA_65_TARGET)
./$(TEST_ML_DSA_65_TARGET)
test-slh-dsa-128s: $(TEST_SLH_DSA_128S_TARGET)
./$(TEST_SLH_DSA_128S_TARGET)
test-ml-kem-768: $(TEST_ML_KEM_768_TARGET)
./$(TEST_ML_KEM_768_TARGET)
test-pubkey-format: $(TEST_PUBKEY_FORMAT_TARGET)
./$(TEST_PUBKEY_FORMAT_TARGET)
test-algorithm-api: $(TEST_ALGORITHM_API_TARGET)
./$(TEST_ALGORITHM_API_TARGET)
test-client: examples
examples: $(EXAMPLE_GET_PUBLIC_KEY_TARGET) $(EXAMPLE_SIGN_EVENT_TARGET)
examples: $(EXAMPLE_GET_PUBLIC_KEY_TARGET) $(EXAMPLE_SIGN_EVENT_TARGET) $(EXAMPLE_GET_PUBKEY_TCP_TARGET) $(EXAMPLE_GET_PUBKEY_QREXEC_TARGET) $(EXAMPLE_PQ_SIGN_TARGET) $(EXAMPLE_PQ_KEM_TARGET) $(EXAMPLE_SSH_SIGN_TARGET) $(DEMO_C99_TARGET)
$(TEST_MNEMONIC_TARGET): $(TEST_DIR)/test_mnemonic.c $(SRC_DIR)/mnemonic.c $(SRC_DIR)/secure_mem.c
@mkdir -p $(BUILD_DIR)
@@ -126,21 +196,21 @@ $(TEST_SELECTOR_TARGET): $(TEST_DIR)/test_selector.c $(SRC_DIR)/selector.c $(SRC
@mkdir -p $(BUILD_DIR)
$(CC) $(CFLAGS) $(TEST_DIR)/test_selector.c $(SRC_DIR)/selector.c $(SRC_DIR)/role_table.c -o $(TEST_SELECTOR_TARGET) $(LDFLAGS)
$(TEST_ENFORCEMENT_TARGET): $(TEST_DIR)/test_enforcement.c $(SRC_DIR)/enforcement.c $(SRC_DIR)/role_table.c
$(TEST_ENFORCEMENT_TARGET): $(TEST_DIR)/test_enforcement.c $(SRC_DIR)/enforcement.c $(SRC_DIR)/role_table.c $(SRC_DIR)/pq_crypto.c
@mkdir -p $(BUILD_DIR)
$(CC) $(CFLAGS) $(TEST_DIR)/test_enforcement.c $(SRC_DIR)/enforcement.c $(SRC_DIR)/role_table.c -o $(TEST_ENFORCEMENT_TARGET) $(LDFLAGS)
$(CC) $(CFLAGS) $(TEST_DIR)/test_enforcement.c $(SRC_DIR)/enforcement.c $(SRC_DIR)/role_table.c $(SRC_DIR)/pq_crypto.c -o $(TEST_ENFORCEMENT_TARGET) $(LDFLAGS)
$(TEST_DISPATCHER_TARGET): $(TEST_DIR)/test_dispatcher.c $(SRC_DIR)/dispatcher.c $(SRC_DIR)/key_store.c $(SRC_DIR)/selector.c $(SRC_DIR)/enforcement.c $(SRC_DIR)/role_table.c $(SRC_DIR)/mnemonic.c $(SRC_DIR)/secure_mem.c
$(TEST_DISPATCHER_TARGET): $(TEST_DIR)/test_dispatcher.c $(SRC_DIR)/dispatcher.c $(SRC_DIR)/key_store.c $(SRC_DIR)/miner.c $(SRC_DIR)/pq_crypto.c $(SRC_DIR)/pq_drbg.c $(PQCLEAN_SOURCES) $(SRC_DIR)/selector.c $(SRC_DIR)/enforcement.c $(SRC_DIR)/role_table.c $(SRC_DIR)/mnemonic.c $(SRC_DIR)/secure_mem.c
@mkdir -p $(BUILD_DIR)
$(CC) $(CFLAGS) $(TEST_DIR)/test_dispatcher.c $(SRC_DIR)/dispatcher.c $(SRC_DIR)/key_store.c $(SRC_DIR)/selector.c $(SRC_DIR)/enforcement.c $(SRC_DIR)/role_table.c $(SRC_DIR)/mnemonic.c $(SRC_DIR)/secure_mem.c -o $(TEST_DISPATCHER_TARGET) $(LDFLAGS)
$(CC) $(CFLAGS) $(TEST_DIR)/test_dispatcher.c $(SRC_DIR)/dispatcher.c $(SRC_DIR)/key_store.c $(SRC_DIR)/miner.c $(SRC_DIR)/pq_crypto.c $(SRC_DIR)/pq_drbg.c $(PQCLEAN_SOURCES) $(SRC_DIR)/selector.c $(SRC_DIR)/enforcement.c $(SRC_DIR)/role_table.c $(SRC_DIR)/mnemonic.c $(SRC_DIR)/secure_mem.c -o $(TEST_DISPATCHER_TARGET) $(LDFLAGS)
$(TEST_POLICY_TARGET): $(TEST_DIR)/test_policy.c $(SRC_DIR)/policy.c
@mkdir -p $(BUILD_DIR)
$(CC) $(CFLAGS) $(TEST_DIR)/test_policy.c $(SRC_DIR)/policy.c -o $(TEST_POLICY_TARGET) $(LDFLAGS)
$(TEST_INTEGRATION_TARGET): $(TEST_DIR)/test_integration.c $(CLIENT_DIR)/nsigner_client.c $(SRC_DIR)/auth_envelope.c
$(TEST_INTEGRATION_TARGET): $(TEST_DIR)/test_integration.c
@mkdir -p $(BUILD_DIR)
$(CC) $(CFLAGS) -I$(CLIENT_DIR) $(TEST_DIR)/test_integration.c $(CLIENT_DIR)/nsigner_client.c $(SRC_DIR)/auth_envelope.c -o $(TEST_INTEGRATION_TARGET) $(LDFLAGS)
$(CC) $(CFLAGS) $(TEST_DIR)/test_integration.c -o $(TEST_INTEGRATION_TARGET) $(LDFLAGS)
$(TEST_SOCKET_NAME_TARGET): $(TEST_DIR)/test_socket_name.c $(SRC_DIR)/socket_name.c
@mkdir -p $(BUILD_DIR)
@@ -154,13 +224,69 @@ $(TEST_QREXEC_AUTH_TARGET): $(TEST_DIR)/test_qrexec_auth.c $(SRC_DIR)/auth_envel
@mkdir -p $(BUILD_DIR)
$(CC) $(CFLAGS) $(TEST_DIR)/test_qrexec_auth.c $(SRC_DIR)/auth_envelope.c -o $(TEST_QREXEC_AUTH_TARGET) $(LDFLAGS)
$(EXAMPLE_GET_PUBLIC_KEY_TARGET): $(EXAMPLES_DIR)/get_public_key_client.c $(CLIENT_DIR)/nsigner_client.c $(SRC_DIR)/auth_envelope.c
$(TEST_MINE_EVENT_TARGET): $(TEST_DIR)/test_mine_event.c $(SRC_DIR)/miner.c $(SRC_DIR)/key_store.c $(SRC_DIR)/pq_crypto.c $(SRC_DIR)/pq_drbg.c $(PQCLEAN_SOURCES) $(SRC_DIR)/dispatcher.c $(SRC_DIR)/selector.c $(SRC_DIR)/enforcement.c $(SRC_DIR)/role_table.c $(SRC_DIR)/mnemonic.c $(SRC_DIR)/secure_mem.c
@mkdir -p $(BUILD_DIR)
$(CC) $(CFLAGS) -I$(CLIENT_DIR) $(EXAMPLES_DIR)/get_public_key_client.c $(CLIENT_DIR)/nsigner_client.c $(SRC_DIR)/auth_envelope.c -o $(EXAMPLE_GET_PUBLIC_KEY_TARGET) $(LDFLAGS)
$(CC) $(CFLAGS) $(TEST_DIR)/test_mine_event.c $(SRC_DIR)/miner.c $(SRC_DIR)/key_store.c $(SRC_DIR)/pq_crypto.c $(SRC_DIR)/pq_drbg.c $(PQCLEAN_SOURCES) $(SRC_DIR)/dispatcher.c $(SRC_DIR)/selector.c $(SRC_DIR)/enforcement.c $(SRC_DIR)/role_table.c $(SRC_DIR)/mnemonic.c $(SRC_DIR)/secure_mem.c -o $(TEST_MINE_EVENT_TARGET) $(LDFLAGS)
$(EXAMPLE_SIGN_EVENT_TARGET): $(EXAMPLES_DIR)/sign_event_client.c $(CLIENT_DIR)/nsigner_client.c $(SRC_DIR)/auth_envelope.c
$(TEST_PQ_CRYPTO_TARGET): $(TEST_DIR)/test_pq_crypto.c $(SRC_DIR)/pq_crypto.c $(SRC_DIR)/role_table.c
@mkdir -p $(BUILD_DIR)
$(CC) $(CFLAGS) -I$(CLIENT_DIR) $(EXAMPLES_DIR)/sign_event_client.c $(CLIENT_DIR)/nsigner_client.c $(SRC_DIR)/auth_envelope.c -o $(EXAMPLE_SIGN_EVENT_TARGET) $(LDFLAGS)
$(CC) $(CFLAGS) $(TEST_DIR)/test_pq_crypto.c $(SRC_DIR)/pq_crypto.c $(SRC_DIR)/role_table.c -o $(TEST_PQ_CRYPTO_TARGET) $(LDFLAGS)
$(TEST_ED25519_X25519_TARGET): $(TEST_DIR)/test_ed25519_x25519.c $(SRC_DIR)/pq_crypto.c $(SRC_DIR)/pq_drbg.c $(PQCLEAN_SOURCES) $(SRC_DIR)/key_store.c $(SRC_DIR)/dispatcher.c $(SRC_DIR)/miner.c $(SRC_DIR)/selector.c $(SRC_DIR)/enforcement.c $(SRC_DIR)/role_table.c $(SRC_DIR)/mnemonic.c $(SRC_DIR)/secure_mem.c
@mkdir -p $(BUILD_DIR)
$(CC) $(CFLAGS) $(TEST_DIR)/test_ed25519_x25519.c $(SRC_DIR)/pq_crypto.c $(SRC_DIR)/pq_drbg.c $(PQCLEAN_SOURCES) $(SRC_DIR)/key_store.c $(SRC_DIR)/dispatcher.c $(SRC_DIR)/miner.c $(SRC_DIR)/selector.c $(SRC_DIR)/enforcement.c $(SRC_DIR)/role_table.c $(SRC_DIR)/mnemonic.c $(SRC_DIR)/secure_mem.c -o $(TEST_ED25519_X25519_TARGET) $(LDFLAGS)
$(TEST_ML_DSA_65_TARGET): $(TEST_DIR)/test_ml_dsa_65.c $(SRC_DIR)/pq_crypto.c $(SRC_DIR)/pq_drbg.c $(PQCLEAN_SOURCES) $(SRC_DIR)/key_store.c $(SRC_DIR)/dispatcher.c $(SRC_DIR)/miner.c $(SRC_DIR)/selector.c $(SRC_DIR)/enforcement.c $(SRC_DIR)/role_table.c $(SRC_DIR)/mnemonic.c $(SRC_DIR)/secure_mem.c
@mkdir -p $(BUILD_DIR)
$(CC) $(CFLAGS) $(TEST_DIR)/test_ml_dsa_65.c $(SRC_DIR)/pq_crypto.c $(SRC_DIR)/pq_drbg.c $(PQCLEAN_SOURCES) $(SRC_DIR)/key_store.c $(SRC_DIR)/dispatcher.c $(SRC_DIR)/miner.c $(SRC_DIR)/selector.c $(SRC_DIR)/enforcement.c $(SRC_DIR)/role_table.c $(SRC_DIR)/mnemonic.c $(SRC_DIR)/secure_mem.c -o $(TEST_ML_DSA_65_TARGET) $(LDFLAGS)
$(TEST_SLH_DSA_128S_TARGET): $(TEST_DIR)/test_slh_dsa_128s.c $(SRC_DIR)/pq_crypto.c $(SRC_DIR)/pq_drbg.c $(PQCLEAN_SOURCES) $(SRC_DIR)/key_store.c $(SRC_DIR)/dispatcher.c $(SRC_DIR)/miner.c $(SRC_DIR)/selector.c $(SRC_DIR)/enforcement.c $(SRC_DIR)/role_table.c $(SRC_DIR)/mnemonic.c $(SRC_DIR)/secure_mem.c
@mkdir -p $(BUILD_DIR)
$(CC) $(CFLAGS) $(TEST_DIR)/test_slh_dsa_128s.c $(SRC_DIR)/pq_crypto.c $(SRC_DIR)/pq_drbg.c $(PQCLEAN_SOURCES) $(SRC_DIR)/key_store.c $(SRC_DIR)/dispatcher.c $(SRC_DIR)/miner.c $(SRC_DIR)/selector.c $(SRC_DIR)/enforcement.c $(SRC_DIR)/role_table.c $(SRC_DIR)/mnemonic.c $(SRC_DIR)/secure_mem.c -o $(TEST_SLH_DSA_128S_TARGET) $(LDFLAGS)
$(TEST_ML_KEM_768_TARGET): $(TEST_DIR)/test_ml_kem_768.c $(SRC_DIR)/pq_crypto.c $(SRC_DIR)/pq_drbg.c $(PQCLEAN_SOURCES) $(SRC_DIR)/key_store.c $(SRC_DIR)/dispatcher.c $(SRC_DIR)/miner.c $(SRC_DIR)/selector.c $(SRC_DIR)/enforcement.c $(SRC_DIR)/role_table.c $(SRC_DIR)/mnemonic.c $(SRC_DIR)/secure_mem.c
@mkdir -p $(BUILD_DIR)
$(CC) $(CFLAGS) $(TEST_DIR)/test_ml_kem_768.c $(SRC_DIR)/pq_crypto.c $(SRC_DIR)/pq_drbg.c $(PQCLEAN_SOURCES) $(SRC_DIR)/key_store.c $(SRC_DIR)/dispatcher.c $(SRC_DIR)/miner.c $(SRC_DIR)/selector.c $(SRC_DIR)/enforcement.c $(SRC_DIR)/role_table.c $(SRC_DIR)/mnemonic.c $(SRC_DIR)/secure_mem.c -o $(TEST_ML_KEM_768_TARGET) $(LDFLAGS)
$(TEST_PUBKEY_FORMAT_TARGET): $(TEST_DIR)/test_pubkey_format.c $(SRC_DIR)/pq_crypto.c $(SRC_DIR)/pq_drbg.c $(PQCLEAN_SOURCES) $(SRC_DIR)/key_store.c $(SRC_DIR)/dispatcher.c $(SRC_DIR)/miner.c $(SRC_DIR)/selector.c $(SRC_DIR)/enforcement.c $(SRC_DIR)/role_table.c $(SRC_DIR)/mnemonic.c $(SRC_DIR)/secure_mem.c
@mkdir -p $(BUILD_DIR)
$(CC) $(CFLAGS) $(TEST_DIR)/test_pubkey_format.c $(SRC_DIR)/pq_crypto.c $(SRC_DIR)/pq_drbg.c $(PQCLEAN_SOURCES) $(SRC_DIR)/key_store.c $(SRC_DIR)/dispatcher.c $(SRC_DIR)/miner.c $(SRC_DIR)/selector.c $(SRC_DIR)/enforcement.c $(SRC_DIR)/role_table.c $(SRC_DIR)/mnemonic.c $(SRC_DIR)/secure_mem.c -o $(TEST_PUBKEY_FORMAT_TARGET) $(LDFLAGS)
$(TEST_ALGORITHM_API_TARGET): $(TEST_DIR)/test_algorithm_api.c $(SRC_DIR)/pq_crypto.c $(SRC_DIR)/pq_drbg.c $(PQCLEAN_SOURCES) $(SRC_DIR)/key_store.c $(SRC_DIR)/dispatcher.c $(SRC_DIR)/miner.c $(SRC_DIR)/selector.c $(SRC_DIR)/enforcement.c $(SRC_DIR)/role_table.c $(SRC_DIR)/mnemonic.c $(SRC_DIR)/secure_mem.c $(SRC_DIR)/policy.c
@mkdir -p $(BUILD_DIR)
$(CC) $(CFLAGS) $(TEST_DIR)/test_algorithm_api.c $(SRC_DIR)/pq_crypto.c $(SRC_DIR)/pq_drbg.c $(PQCLEAN_SOURCES) $(SRC_DIR)/key_store.c $(SRC_DIR)/dispatcher.c $(SRC_DIR)/miner.c $(SRC_DIR)/selector.c $(SRC_DIR)/enforcement.c $(SRC_DIR)/role_table.c $(SRC_DIR)/mnemonic.c $(SRC_DIR)/secure_mem.c $(SRC_DIR)/policy.c -o $(TEST_ALGORITHM_API_TARGET) $(LDFLAGS)
$(EXAMPLE_GET_PUBLIC_KEY_TARGET): $(EXAMPLES_DIR)/get_public_key_client.c
@mkdir -p $(BUILD_DIR)
$(CC) $(CFLAGS) $(EXAMPLES_DIR)/get_public_key_client.c -o $(EXAMPLE_GET_PUBLIC_KEY_TARGET) $(LDFLAGS)
$(EXAMPLE_SIGN_EVENT_TARGET): $(EXAMPLES_DIR)/sign_event_client.c
@mkdir -p $(BUILD_DIR)
$(CC) $(CFLAGS) $(EXAMPLES_DIR)/sign_event_client.c -o $(EXAMPLE_SIGN_EVENT_TARGET) $(LDFLAGS)
$(EXAMPLE_GET_PUBKEY_TCP_TARGET): $(EXAMPLES_DIR)/get_pubkey_tcp.c
@mkdir -p $(BUILD_DIR)
$(CC) $(CFLAGS) $(EXAMPLES_DIR)/get_pubkey_tcp.c -o $(EXAMPLE_GET_PUBKEY_TCP_TARGET) $(LDFLAGS)
$(EXAMPLE_GET_PUBKEY_QREXEC_TARGET): $(EXAMPLES_DIR)/get_pubkey_qrexec.c
@mkdir -p $(BUILD_DIR)
$(CC) $(CFLAGS) $(EXAMPLES_DIR)/get_pubkey_qrexec.c -o $(EXAMPLE_GET_PUBKEY_QREXEC_TARGET) $(LDFLAGS)
$(EXAMPLE_PQ_SIGN_TARGET): $(EXAMPLES_DIR)/pq_sign_example.c
@mkdir -p $(BUILD_DIR)
$(CC) $(CFLAGS) $(EXAMPLES_DIR)/pq_sign_example.c -o $(EXAMPLE_PQ_SIGN_TARGET) $(LDFLAGS)
$(EXAMPLE_PQ_KEM_TARGET): $(EXAMPLES_DIR)/pq_kem_example.c
@mkdir -p $(BUILD_DIR)
$(CC) $(CFLAGS) $(EXAMPLES_DIR)/pq_kem_example.c -o $(EXAMPLE_PQ_KEM_TARGET) $(LDFLAGS)
$(EXAMPLE_SSH_SIGN_TARGET): $(EXAMPLES_DIR)/ssh_sign_example.c
@mkdir -p $(BUILD_DIR)
$(CC) $(CFLAGS) $(EXAMPLES_DIR)/ssh_sign_example.c -o $(EXAMPLE_SSH_SIGN_TARGET) $(LDFLAGS)
$(DEMO_C99_TARGET): $(CLIENT_DIR)/demo_c99.c
@mkdir -p $(BUILD_DIR)
$(CC) $(CFLAGS) $(CLIENT_DIR)/demo_c99.c -o $(DEMO_C99_TARGET) $(LDFLAGS)
clean:
rm -rf $(BUILD_DIR)

452
README.md
View File

@@ -20,7 +20,8 @@ This is a **program, not a daemon**:
- purpose/curve enforcement
- request dispatch
- interactive terminal UI
- transport adapter(s)
- transport adapter(s) (Unix socket, qrexec, FIPS/TCP, HTTP)
- OTP one-time pad encryption (optional, with USB pad)
You run it when you need signing. You stop it when you are done. Closing the terminal or quitting the program ends the trust session and destroys state.
@@ -74,9 +75,16 @@ When started, `n_signer` immediately enters terminal input mode:
- On `E`: prompt for mnemonic with terminal echo disabled, then validate.
- On `G`: generate a fresh 12-word BIP-39 mnemonic from `getrandom(2)`, display it numbered with a "WRITE THIS DOWN — IT WILL NOT BE SHOWN AGAIN" warning, then continue. There is no confirmation step.
2. Build in-memory role/selector state from the mnemonic.
3. Pick the abstract socket name (random BIP-39 pair, or `--socket-name` / `--name` / `-n` override).
4. Initialize transport endpoints and bind the socket.
5. Switch to running status display, with the signer name and socket address shown in the banner.
3. **Interactive transport selection** (if no `--listen` flag given and stdin is a TTY): choose one or more of:
- Local Unix socket
- Qubes qrexec bridge
- FIPS/TCP listener (framed JSON)
- HTTP listener (curl-friendly)
4. **Index whitelist** (optional): restrict which `nostr_index` values this session can access.
5. **OTP pad selection** (optional): auto-scans attached USB drives for OTP pads and offers to bind one. See [`plans/otp_nostr_integration.md`](plans/otp_nostr_integration.md).
6. Pick the abstract socket name (random BIP-39 pair, or `--socket-name` / `--name` / `-n` override).
7. Initialize transport endpoints and bind the socket.
8. Switch to running status display, with the signer name, socket address, and OTP pad status shown in the banner.
No startup files are read or written. The mnemonic — typed or generated — lives only in `mlock`'d memory and is zeroized on shutdown or crash.
@@ -93,7 +101,15 @@ After unlock, terminal becomes a live status and control console. Example layout
```text
n_signer v0.x | foreground session active
transport: unix-abstract:@nsigner
Connections
Server: unix @nsigner (bridge-source-trusted)
Client: nsigner --socket-name nsigner client '<json>'
Qrexec: qrexec-client-vm <target_qube> qubes.NsignerRpc
Server: HTTP 127.0.0.1:11111
Client: curl -X POST http://127.0.0.1:11111/ -H 'Content-Type: application/json' -d '<json>'
OTP pad: 333e9902db839d9d... (offset 288 / 1048576 bytes)
session: unlocked (RAM-only)
Roles
@@ -169,6 +185,145 @@ A single memorized mnemonic can deterministically recover multiple key domains t
Examples include Nostr roles, Bitcoin branches, and future application-specific paths. See [`plans/seed_phrase_uses.md`](plans/seed_phrase_uses.md) for the maintained use-case catalog and caveats.
## 4b. Crypto palette
`n_signer` supports six cryptographic algorithms, all derived deterministically from the same BIP-39 mnemonic. Each algorithm is bound to a specific `(purpose, curve)` pair and a distinct BIP-44 derivation path.
### 4b.1 Algorithms
| Algorithm | Curve label | Purpose | FIPS standard | Key sizes (priv / pub) | Derivation path |
|---|---|---|---|---|---|
| secp256k1 | `secp256k1` | `nostr` | — | 32 / 32 bytes | `m/44'/1237'/<n>'/0/0` (NIP-06) |
| ed25519 | `ed25519` | `ssh` | — | 32 / 32 bytes | `m/44'/102001'/<n>'/0'/0'` (SLIP-0010) |
| x25519 | `x25519` | `age` | — | 32 / 32 bytes | `m/44'/102002'/<n>'/0'/0'` (SLIP-0010) |
| ML-DSA-65 | `ml-dsa-65` | `pq-sig` | FIPS 204 | 4032 / 1952 bytes | `m/44'/102003'/<n>'/0'/0'` → seed → DRBG → PQClean keygen |
| SLH-DSA-128s | `slh-dsa-128s` | `pq-sig` | FIPS 205 | 64 / 32 bytes | `m/44'/102004'/<n>'/0'/0'` → seed → DRBG → PQClean keygen |
| ML-KEM-768 | `ml-kem-768` | `pq-kem` | FIPS 203 | 2400 / 1184 bytes | `m/44'/102005'/<n>'/0'/0'` → seed → DRBG → PQClean keygen |
All six algorithms are always compiled in on every target (host x86_64 static binary and ESP32 firmware). The PQ implementations are vendored from [PQClean](https://github.com/PQClean/PQClean) (public domain / CC0).
### 4b.2 Key derivation
All keys derive deterministically from the BIP-39 mnemonic:
- **secp256k1** uses standard BIP-32/NIP-06 derivation. The 32-byte path output is the private key scalar.
- **ed25519 / x25519** use SLIP-0010 HMAC-SHA512 derivation (all-hardened paths, as required by SLIP-0010 for ed25519). The 32-byte output is the private key.
- **PQ algorithms** (ML-DSA-65, SLH-DSA-128s, ML-KEM-768) use a two-stage approach: the mnemonic-derived 32-byte seed feeds a SHAKE-256 DRBG (NIST SP 800-90A style), which replaces PQClean's `randombytes()` callback during keygen. This produces deterministic PQ key pairs from the mnemonic — same mnemonic, same role, same key pair every time. See [`documents/SECURITY.md`](documents/SECURITY.md) §17 for the security argument.
The new algorithms use BIP-44 coin types `102001``102005` (unregistered in SLIP-44, chosen to avoid collisions with real cryptocurrencies). All non-secp256k1 paths are fully hardened per SLIP-0010.
### 4b.3 Post-quantum context
The three post-quantum algorithms address the **harvest-now-decrypt-later** threat: an adversary recording encrypted traffic today to decrypt it once a quantum computer becomes available. ML-KEM-768 protects key agreement against this threat. ML-DSA-65 and SLH-DSA-128s protect signatures against future quantum forgery.
All three are FIPS-standardized (FIPS 203, 204, 205) and are provided as **additional options**, not replacements for secp256k1. Nostr continues to use secp256k1 exclusively. PQ algorithms are opt-in per role.
Note: OpenSSH does not yet support PQ signing keys. The `pq-sig` purpose is forward-looking — the primitives are ready for when the ecosystem adopts them.
### 4b.4 Structured `get_public_key` response
For secp256k1, `get_public_key` returns the plain 64-hex-char public key string (backward compatible). An optional `{"format": "structured"}` in the options object requests a structured JSON response.
For all other algorithms (ed25519, x25519, ML-DSA-65, SLH-DSA-128s, ML-KEM-768), `get_public_key` always returns a structured JSON object (serialized as a string):
```json
{"algorithm": "ml-dsa-65", "public_key": "<hex>", "key_id": "<16 hex chars>"}
```
The `key_id` is a short display identifier (first 16 hex chars of the public key). PQ public keys are large (ML-DSA-65: 3904 hex chars; ML-KEM-768: 2368 hex chars).
## 4c. Algorithm-based API
In addition to the role-based API, n_signer supports an **algorithm-based API** where the caller specifies the algorithm and derivation index directly, without needing to know role names. This is the preferred API for new clients.
### 4c.1 Verbs
| Verb | Description | Algorithm parameter | Key parameter |
|---|---|---|---|
| `sign` | Sign arbitrary bytes | `algorithm` | `index` |
| `verify` | Verify a signature | `algorithm` | `index` |
| `encapsulate` | KEM encapsulation | `algorithm` | `public_key` (peer's) |
| `decapsulate` | KEM decapsulation | `algorithm` | `index` |
| `derive_shared_secret` | ECDH key agreement (x25519) | `algorithm` | `index` + `peer_public_key` |
| `get_public_key` | Get public key (algorithm-based) | `algorithm` | `index` |
### 4c.2 Algorithm names
| String | Algorithm | Key type |
|---|---|---|
| `secp256k1` | secp256k1 (Schnorr/ECDSA) | Signature |
| `ed25519` | ed25519 | Signature |
| `ml-dsa-65` | ML-DSA-65 (FIPS 204) | Signature |
| `slh-dsa-128s` | SLH-DSA-128s (FIPS 205) | Signature |
| `x25519` | X25519 (ECDH) | Key agreement |
| `ml-kem-768` | ML-KEM-768 (FIPS 203) | KEM |
### 4c.3 Request examples
**Sign with ed25519:**
```json
{"id":"1","method":"sign","params":["68656c6c6f",{"algorithm":"ed25519","index":0}]}
```
Response: `{"id":"1","result":{"signature":"<hex>","algorithm":"ed25519","key_id":"<16hex>"}}`
**Sign with secp256k1 (ECDSA scheme):**
```json
{"id":"2","method":"sign","params":["68656c6c6f",{"algorithm":"secp256k1","index":0,"scheme":"ecdsa"}]}
```
The `scheme` parameter is optional for secp256k1: `"schnorr"` (default, BIP-340) or `"ecdsa"`.
**Get public key (algorithm-based):**
```json
{"id":"3","method":"get_public_key","params":[{"algorithm":"ml-dsa-65","index":0}]}
```
Response: `{"id":"3","result":{"algorithm":"ml-dsa-65","public_key":"<hex>","key_id":"<16hex>"}}`
**KEM encapsulate:**
```json
{"id":"4","method":"encapsulate","params":["<peer_pubkey_hex>",{"algorithm":"ml-kem-768"}]}
```
**KEM decapsulate:**
```json
{"id":"5","method":"decapsulate","params":["<ciphertext_hex>",{"algorithm":"ml-kem-768","index":0}]}
```
**ECDH shared secret (x25519):**
```json
{"id":"6","method":"derive_shared_secret","params":["<peer_pubkey_hex>",{"algorithm":"x25519","index":0}]}
```
### 4c.4 Verb aliases
These verb aliases are also available. When used with the `algorithm` parameter, they map to the algorithm-based verbs:
| Alias | Canonical verb | Default algorithm |
|---|---|---|
| `sign_data` | `sign` | (from `algorithm` parameter) |
| `ssh_sign` | `sign` | `ed25519` |
| `verify_signature` | `verify` | (from `algorithm` parameter) |
| `kem_encapsulate` | `encapsulate` | `ml-kem-768` |
| `kem_decapsulate` | `decapsulate` | `ml-kem-768` |
Without the `algorithm` parameter, these aliases fall through to the role-based path (backward compatible).
### 4c.5 Algorithm-based preapprove
```
nsigner --preapprove caller=uid:1000,algorithm=ed25519,index=0-4,verb=sign,verify
nsigner --preapprove caller=uid:1000,algorithm=ml-kem-768,index=0,verb=decapsulate
```
### 4c.6 Enforcement matrix
| Verb | Valid algorithms |
|---|---|
| `sign` / `verify` | secp256k1, ed25519, ml-dsa-65, slh-dsa-128s |
| `encapsulate` / `decapsulate` | ml-kem-768 |
| `derive_shared_secret` | x25519 |
| `get_public_key` | all algorithms |
| `sign_event` / `nip44_*` / `nip04_*` / `mine_event` | secp256k1 (Nostr protocol) |
## 5. Wire contract (JSON-RPC)
Request shape is JSON-RPC with NIP-46-style methods and optional trailing selector options.
@@ -178,14 +333,96 @@ Request shape is JSON-RPC with NIP-46-style methods and optional trailing select
{ "id": "2", "method": "sign_event", "params": ["<event_json>", { "role": "main" }] }
{ "id": "3", "method": "sign_event", "params": ["<event_json>", { "nostr_index": 7 }] }
{ "id": "4", "method": "sign_event", "params": ["<event_json>", { "role_path": "m/84'/0'/0'/0/5", "purpose": "bitcoin", "curve": "secp256k1" }] }
{ "id": "5", "method": "mine_event", "params": ["<event_json>", { "difficulty": 20, "threads": 4, "timeout_sec": 30, "nostr_index": 0 }] }
```
Implemented signer verbs in this build:
**Nostr verbs** (secp256k1 only, use `role` or `nostr_index` selector):
- `get_public_key`
- `sign_event`
- `nip04_encrypt` / `nip04_decrypt`
- `nip44_encrypt` / `nip44_decrypt`
- `mine_event` — add NIP-13 proof-of-work and sign (see below)
**Algorithm-based verbs** (use `algorithm` + `index` selector, no role needed):
| Verb | Valid algorithms | Description |
|---|---|---|
| `sign` | secp256k1, ed25519, ml-dsa-65, slh-dsa-128s | Sign arbitrary bytes. Returns `{"signature":"<hex>","algorithm":"<alg>","key_id":"<16hex>"}`. |
| `verify` | secp256k1, ed25519, ml-dsa-65, slh-dsa-128s | Verify a signature. Returns `{"valid":true/false}`. |
| `encapsulate` | ml-kem-768 | Encapsulate against a peer's ML-KEM-768 public key. Returns `{"ciphertext":"<hex>","shared_secret":"<hex>","algorithm":"ml-kem-768"}`. |
| `decapsulate` | ml-kem-768 | Decapsulate a ciphertext using the derived ML-KEM-768 private key. Returns `{"shared_secret":"<hex>","algorithm":"ml-kem-768"}`. |
| `derive_shared_secret` | x25519 | ECDH key agreement. Returns `{"shared_secret":"<hex>","algorithm":"x25519"}`. |
| `get_public_key` | all algorithms | Returns the public key for the specified algorithm+index. |
**General encryption verbs** (use `curve` parameter to select encryption method):
| Verb | `curve` value | Description |
|---|---|---|
| `encrypt` | `otp` | One-time pad encryption (requires `--otp-pad-dir` + `--otp-pad`). Returns ASCII-armored or binary ciphertext. |
| `decrypt` | `otp` | One-time pad decryption. Returns plaintext (base64). |
| `encrypt` | `secp256k1` | NIP-44 (default) or NIP-04 encryption. Params: `[peer_pubkey, message, {nip_version: 4\|44}]`. |
| `decrypt` | `secp256k1` | NIP-44 (default) or NIP-04 decryption. Params: `[peer_pubkey, ciphertext, {nip_version: 4\|44}]`. |
| `encrypt` | `x25519` | ECDH + symmetric encryption (not yet implemented — use `derive_shared_secret` + your own cipher). |
| `encrypt` | `ml-kem-768` | KEM-based hybrid encryption (not yet implemented — use `encapsulate`/`decapsulate` + your own cipher). |
**OTP verb aliases** (also available, same as `encrypt`/`decrypt` with `curve: "otp"`):
| Verb | Description |
|---|---|
| `otp_encrypt` | Encrypt plaintext (base64) with the bound OTP pad. Returns ASCII-armored or binary ciphertext. |
| `otp_decrypt` | Decrypt ciphertext with the bound OTP pad. Returns plaintext (base64). |
See [`plans/otp_nostr_integration.md`](plans/otp_nostr_integration.md) for the full OTP design.
Example `sign` request (algorithm-based):
```jsonc
{ "id": "6", "method": "sign", "params": ["<message_hex>", { "algorithm": "ed25519", "index": 0 }] }
```
Example `otp_encrypt` request:
```jsonc
{ "id": "7", "method": "otp_encrypt", "params": ["<plaintext_base64>", { "encoding": "ascii" }] }
```
### `mine_event` — NIP-13 Proof-of-Work
Mines proof-of-work (adds a `nonce` tag per NIP-13) and signs the event in one step. The mining runs in a detached thread so the server stays responsive.
**Parameters (in options object):**
| Option | Required | Default | Description |
|--------|----------|---------|-------------|
| `difficulty` | One of difficulty/timeout | 0 (no target) | Target leading zero bits. Stops early if reached. |
| `timeout_sec` | One of difficulty/timeout | 600 (safety) | Time budget in seconds. Always returns best result found. |
| `threads` | No | 1 | Number of mining threads (max 32). |
At least one of `difficulty` or `timeout_sec` must be specified. If both are given, mining stops when either condition is met. The response always includes the best event found — timeout is not an error.
**Response format:**
```json
{
"id": "5",
"result": {
"event": "<signed event JSON with nonce tag>",
"achieved_difficulty": 18,
"target_difficulty": 20,
"target_reached": false,
"elapsed_sec": 30,
"attempts": 4523456
}
}
```
**Error codes:**
- `1007``no_termination_condition` (neither difficulty nor timeout_sec specified)
- `1008``mining_failed` (internal error)
Selector resolution order:
@@ -208,16 +445,56 @@ Representative error codes:
- `approval_denied`
- `internal_error`
## 6. Purpose and curve enforcement
## 6. Purpose and curve enforcement (role-based API)
Selector resolution chooses *which* role. Enforcement decides *whether the requested method is valid* for that role.
Example:
**Note:** The algorithm-based API (§4c) bypasses purpose/curve enforcement entirely — the caller specifies the algorithm directly, and the dispatcher derives the key on demand. Purpose values are only used by the role-based API for enforcement.
### 6.1 Purpose values (role-based API only)
| Purpose | Description |
|---|---|
| `nostr` | Nostr identities (secp256k1, NIP-06) |
| `bitcoin` | Bitcoin key trees (secp256k1, BIP-44) |
| `ssh` | SSH signing keys (ed25519) |
| `age` | age-style encryption identities (x25519) |
| `fips` | FIPS mesh/service identities |
| `pq-sig` | Post-quantum signatures (ML-DSA-65, SLH-DSA-128s) |
| `pq-kem` | Post-quantum key encapsulation (ML-KEM-768) |
### 6.2 Curve values
| Curve | Algorithms |
|---|---|
| `secp256k1` | ECDSA/Schnorr for Nostr, Bitcoin |
| `ed25519` | Ed25519 for SSH signatures |
| `x25519` | X25519 for key agreement (age) |
| `ml-dsa-65` | ML-DSA-65 (FIPS 204, lattice-based PQ signatures) |
| `slh-dsa-128s` | SLH-DSA-128s (FIPS 205, hash-based PQ signatures) |
| `ml-kem-768` | ML-KEM-768 (FIPS 203, lattice-based PQ KEM) |
### 6.3 Enforcement matrix (role-based API)
| Verb | Required purpose | Required curve |
|---|---|---|
| `sign_event` | `nostr` | `secp256k1` |
| `mine_event` | `nostr` | `secp256k1` |
| `nip04_encrypt` / `nip04_decrypt` | `nostr` | `secp256k1` |
| `nip44_encrypt` / `nip44_decrypt` | `nostr` | `secp256k1` |
| `get_public_key` | any | any (must match role's declared curve) |
| `sign_data` / `ssh_sign` | `ssh` or `pq-sig` | `ed25519`, `ml-dsa-65`, or `slh-dsa-128s` |
| `verify_signature` | `ssh` or `pq-sig` | `ed25519`, `ml-dsa-65`, or `slh-dsa-128s` |
| `kem_encapsulate` / `kem_decapsulate` | `pq-kem` | `ml-kem-768` |
The algorithm-based API (§4c) does not use this matrix — the caller specifies the algorithm directly, and enforcement is based on the verb+algorithm combination (see [§4c.6](#4c6-enforcement-matrix)).
Example (role-based):
- `sign_event` requires `purpose="nostr"` and `curve="secp256k1"`.
- If caller selects a Bitcoin-role key for `sign_event`, request fails with `purpose_mismatch`.
This prevents cross-protocol misuse inside one mnemonic-rooted signer process.
This prevents cross-protocol misuse inside one mnemonic-rooted signer process. Fail-closed: any unlisted `(verb, purpose, curve)` combination is rejected.
## 7. Transport
@@ -246,7 +523,69 @@ Discovery:
- `nsigner list` enumerates currently bound `nsigner_*` abstract sockets by reading `/proc/net/unix`.
- `nsigner --listen stdio` runs one framed JSON-RPC request/response over stdin/stdout.
- `nsigner --listen qrexec` is the same stdio framing mode, but caller identity can be derived from `QREXEC_REMOTE_DOMAIN` (displayed as `qubes:<source-vm>`).
- `nsigner --listen tcp:IPv4:PORT` or `tcp:[IPv6]:PORT` enables TCP listening for non-AF_UNIX clients (for example `tcp:127.0.0.1:8080`, `tcp:[::]:8080`, or `tcp:[fd00::1234]:8080`).
- `nsigner --listen tcp:IPv4:PORT` or `tcp:[IPv6]:PORT` enables FIPS/TCP listening for non-AF_UNIX clients (for example `tcp:127.0.0.1:11111`, `tcp:[::]:11111`, or `tcp:[fd00::1234]:11111`). Uses framed JSON protocol (not HTTP).
- `nsigner --listen http:HOST:PORT` enables HTTP listening for curl-friendly access (for example `http:127.0.0.1:11111`). Uses standard HTTP POST with JSON body — no custom framing. CORS headers included for browser access. Defaults to localhost; pass `http:0.0.0.0:PORT` to expose externally.
- `nsigner bridge --to <socket-name>` is a stateless relay for Qubes qrexec: reads one framed request from stdin, forwards it to a persistent signer's abstract unix socket, and relays the response to stdout. Used as the `qubes.NsignerRpc` service entrypoint. See [§8.3](#83-qubes-os-qube) and [`plans/qrexec_persistent_bridge.md`](plans/qrexec_persistent_bridge.md).
- `--bridge-source-trusted` (unix listener only): marks the socket as a trusted bridge endpoint. Each connection sends a framed `{"qrexec_source":"<vm>"}` preamble before the request, and the caller identity is composed as `qubes:<vm>` — matching the native qrexec identity path. This enables a persistent signer (mnemonic in mlock'd RAM) to receive qrexec-routed requests without spawning a fresh process per call.
#### curl examples (HTTP mode)
Start the signer in HTTP mode:
```bash
nsigner --listen http:127.0.0.1:11111 --allow-all
```
Get a public key:
```bash
curl -s -X POST http://127.0.0.1:11111/ -H 'Content-Type: application/json' \
-d '{"id":"1","method":"get_public_key","params":[{"role":"main"}]}'
```
Sign a Nostr event:
```bash
curl -s -X POST http://127.0.0.1:11111/ -H 'Content-Type: application/json' \
-d '{"id":"1","method":"sign_event","params":[{"pubkey":"...","created_at":1234567890,"kind":1,"tags":[],"content":"hello"}]}'
```
General encrypt (OTP, requires `--otp-pad-dir` and `--otp-pad`):
```bash
curl -s -X POST http://127.0.0.1:11111/ -H 'Content-Type: application/json' \
-d '{"id":"1","method":"encrypt","params":["SGVsbG8sIE9UUCB3b3JsZCE=",{"curve":"otp","encoding":"ascii"}]}'
```
General encrypt (NIP-44, secp256k1):
```bash
curl -s -X POST http://127.0.0.1:11111/ -H 'Content-Type: application/json' \
-d '{"id":"1","method":"encrypt","params":["<peer_pubkey_hex>","Hello!",{"role":"main"}]}'
```
General decrypt (OTP):
```bash
curl -s -X POST http://127.0.0.1:11111/ -H 'Content-Type: application/json' \
-d '{"id":"1","method":"decrypt","params":["-----BEGIN OTP MESSAGE-----...",{"curve":"otp","encoding":"ascii"}]}'
```
OTP verb aliases (same as encrypt/decrypt with curve=otp):
```bash
curl -s -X POST http://127.0.0.1:11111/ -H 'Content-Type: application/json' \
-d '{"id":"1","method":"otp_encrypt","params":["SGVsbG8sIE9UUCB3b3JsZCE=",{"encoding":"ascii"}]}'
```
#### Unix socket examples (framed mode)
```bash
# Get public key
nsigner --socket-name nsigner client '{"id":"1","method":"get_public_key","params":[{"role":"main"}]}'
# Sign event
nsigner --socket-name nsigner client '{"id":"1","method":"sign_event","params":[{"pubkey":"...","created_at":1234567890,"kind":1,"tags":[],"content":"hello"}]}'
# Encrypt (OTP)
nsigner --socket-name nsigner client '{"id":"1","method":"encrypt","params":["SGVsbG8=",{"curve":"otp","encoding":"ascii"}]}'
# Encrypt (NIP-44)
nsigner --socket-name nsigner client '{"id":"1","method":"encrypt","params":["<peer_pubkey>","Hello!",{"role":"main"}]}'
```
### 7.2 ESP32 MCU: TinyUSB composite (CDC + WebUSB)
@@ -283,7 +622,45 @@ MCU target reuses mnemonic/role/selector/enforcement/dispatcher core and swaps t
### 8.3 Qubes OS qube
Qubes deployment runs `n_signer` in a dedicated signer qube as a foreground process under explicit user session control. Transport binding is platform-specific, but lifecycle and memory-only state model are unchanged.
Qubes deployment runs `n_signer` in a dedicated signer qube (e.g. `nostr_signer`) as a foreground process under explicit user session control. The mnemonic lives only in mlock'd RAM in that qube — a compromised agent in a caller qube cannot read it (hypervisor-enforced memory isolation).
Three transport paths are supported:
**FIPS/TCP** — the signer listens on `tcp:[::]:11111` and FIPS carries traffic between qubes as an IPv6 mesh substrate. Uses framed JSON protocol. See [`documents/FIPS_DEPLOYMENT.md`](documents/FIPS_DEPLOYMENT.md).
**HTTP** — the signer listens on `http:127.0.0.1:11111` for curl-friendly access within the same qube. Uses standard HTTP POST with JSON body. No auth envelopes required (relies on localhost binding + policy/approval prompts). Add `--listen http:127.0.0.1:11111` or select option 4 in the interactive transport menu.
**Qubes qrexec bridge** (recommended for no-network deployments) — a persistent signer listens on an abstract unix socket, and a stateless `nsigner bridge` relay (the `qubes.NsignerRpc` qrexec service) forwards one request per qrexec invocation. No network, no FIPS — pure intra-host IPC. Caller identity is `qubes:<source-vm>` (from `QREXEC_REMOTE_DOMAIN`), relayed via a trusted preamble. See [`plans/qrexec_persistent_bridge.md`](plans/qrexec_persistent_bridge.md) for the full design.
#### Qrexec bridge setup
**In the signer qube** (`nostr_signer`):
```bash
# Install nsigner and the qrexec service
bash setup_signer_qube.sh # from packaging/qubes/
# Start the persistent signer (mnemonic entered at terminal, in mlock'd RAM)
~/.local/bin/nsigner --listen unix --socket-name nsigner --bridge-source-trusted
```
**In dom0**:
```bash
# Install policy and tag the signer qube
bash setup_dom0.sh nostr_signer # from packaging/qubes/
```
The dom0 policy allows trusted caller qubes without a popup (memory isolation is the real security boundary) and asks for confirmation from any other qube. The signer's own approval prompt at the `nostr_signer` terminal is the operation-level gate.
**From a caller qube**:
```bash
# JavaScript example (uses qrexec-client-vm, no auth envelope needed)
node examples/n_signer_qube_example_qrexec.js nostr_signer
```
Setup scripts and policy are in [`packaging/qubes/`](packaging/qubes/). See also [`documents/QUBES_OS.md`](documents/QUBES_OS.md) and [`documents/qubes_client_examples.md`](documents/qubes_client_examples.md).
## 9. Usage
@@ -313,10 +690,34 @@ Generic stdio transport mode (single framed request over stdin/stdout):
nsigner --listen stdio
```
TCP transport mode (no TUI; serves requests until terminated):
FIPS/TCP transport mode (framed JSON, no TUI; serves requests until terminated):
```bash
nsigner --listen tcp:[::]:8080
nsigner --listen tcp:[::]:11111
```
HTTP transport mode (curl-friendly, no TUI; serves requests until terminated):
```bash
nsigner --listen http:127.0.0.1:11111
```
With OTP pad bound (auto-detects pads on USB drives in interactive mode):
```bash
nsigner --listen http:127.0.0.1:11111 --otp-pad-dir /media/user/Music/pads --otp-pad 333e9902db839d9d --allow-all
```
Qrexec bridge mode (stateless relay to a persistent signer's unix socket; used as the `qubes.NsignerRpc` service):
```bash
nsigner bridge --to nsigner
```
Persistent signer for qrexec bridge (unix listener with trusted source-qube preamble):
```bash
nsigner --listen unix --socket-name nsigner --bridge-source-trusted
```
### 9.2 Send a request (client mode)
@@ -394,30 +795,3 @@ Static build:
./build/nsigner_static_x86_64 --version
```
## 11. Implemented adjuncts and future work
### Implemented PoC
- **MCU / USB signer (Feather ESP32-S3 Reverse TFT).** Working PoC in [`firmware/feather_s3_tft`](firmware/feather_s3_tft). Single TinyUSB composite USB device exposes both CDC-ACM and WebUSB Vendor interfaces. Same dispatcher serves both transports with auth envelope verification, on-device TFT prompts, and physical button approval. See [`firmware/README.md`](firmware/README.md) and [`plans/feather_tinyusb_composite.md`](plans/feather_tinyusb_composite.md).
### Future work (deferred)
These items are designed and worth doing, but are not in the current implementation scope. They are listed here so they are not lost.
- **`--listen http:[addr]:port` mode.** Today the TCP listener speaks 4-byte big-endian length-prefixed framed JSON-RPC, which is correct for low-overhead local IPC but is not directly reachable from web browsers (`fetch`, `XMLHttpRequest`, `curl`). A small additional listener that wraps the same dispatcher in minimal HTTP/1.1 (`POST /rpc`, `Content-Type: application/json`, `Content-Length`-framed body, JSON response) would let standard HTTP clients talk to `nsigner` without any custom framing code. The existing auth envelope (`kind:27235`) and JSON-RPC contract are unchanged; only the outer framing differs. CORS allow on the response would let browser extensions and (with TLS) HTTPS pages reach a remote `nsigner` over FIPS or any other carrier. See the discussion in [`documents/FIPS_DEPLOYMENT.md`](documents/FIPS_DEPLOYMENT.md) section 9 ("Next hardening steps").
- **NIP-46 bunker / relay transport.** Tracked in [`plans/nip46_bunker_mode.md`](plans/nip46_bunker_mode.md).
- **Browser extension.** Tracked in [`plans/nsigner_browser_extension.md`](plans/nsigner_browser_extension.md). NIP-07 surface forwarding to a running `nsigner` instance.
## 12. Document map
- [`README.md`](README.md): authoritative behavior specification for the foreground single-program model
- [`documents/CLIENT_IMPLEMENTATION.md`](documents/CLIENT_IMPLEMENTATION.md): client integration contract and framing behavior
- [`documents/QUBES_OS.md`](documents/QUBES_OS.md): Qubes OS deployment/integration checklist for dedicated signer qubes
- [`documents/FIPS_DEPLOYMENT.md`](documents/FIPS_DEPLOYMENT.md): Tier-1 FIPS deployment runbook using loopback TCP listener
- [`plans/nsigner.md`](plans/nsigner.md): implementation plan and sequencing
- [`plans/seed_phrase_uses.md`](plans/seed_phrase_uses.md): seed phrase domain/use catalog and caveats
- [`firmware/feather_s3_tft`](firmware/feather_s3_tft): Feather ESP32-S3 Reverse TFT firmware (TinyUSB composite CDC + WebUSB signer PoC)
- [`plans/feather_tinyusb_composite.md`](plans/feather_tinyusb_composite.md): firmware Phase 7b plan and outcome (TinyUSB composite USB transport)
- [`plans/nsigner_browser_extension.md`](plans/nsigner_browser_extension.md): browser extension exposing NIP-07 over `nsigner`
- [`plans/nip46_bunker_mode.md`](plans/nip46_bunker_mode.md): deferred NIP-46 relay-mode signer transport
- [`firmware/README.md`](firmware/README.md): firmware-side notes for MCU transport/UI integration

View File

@@ -1,47 +1,117 @@
# n_signer C Reference Client
# n_signer C Client — migrated to `nostr_core_lib`
This directory provides a minimal copy/paste-friendly C client for `n_signer`.
The hand-rolled `nsigner_client.{c,h}` that previously lived in this directory
has been **removed**. n_signer now uses the shared, transport-pluggable client
stack that lives in [`nostr_core_lib`](../resources/nostr_core_lib):
## Files
- [`nostr_core/nsigner_transport.{h,c}`](../resources/nostr_core_lib/nostr_core/nsigner_transport.h) —
pluggable transport vtable (unix-abstract / tcp / usb-cdc serial / fds) + discovery.
- [`nostr_core/nsigner_client.{h,c}`](../resources/nostr_core_lib/nostr_core/nsigner_client.h) —
heap-allocated client: 4-byte length-prefixed framing, kind-27235 auth envelope
(self-contained), JSON-RPC verbs, cJSON result parsing, RPC error mapping.
- [`nostr_core/nostr_signer.{h,c}`](../resources/nostr_core_lib/nostr_core/nostr_signer.h) —
high-level `nostr_signer_t` abstraction (local + remote backends, 6 verbs).
- `nsigner_client.h` / `nsigner_client.c`:
- Unix abstract socket connect helper
- length-prefixed frame send/receive
- generic request API
- helpers for `get_public_key` and `sign_event`
- optional TCP auth envelope attachment via `auth_envelope_build_for_request()`
This is the single source of truth for the n_signer wire contract. See
[`nostr_core/NSIGNER_INTEGRATION.md`](../resources/nostr_core_lib/nostr_core/NSIGNER_INTEGRATION.md)
for the full integration contract.
## API at a glance
## What moved where
```c
nsigner_client_t client;
nsigner_client_init(&client);
| Old (`client/`) | New (`nostr_core_lib`) |
|---|---|
| `nsigner_client_t` (stack) | `nsigner_client_t*` (heap) or `nostr_signer_t*` |
| `nsigner_client_init` / `connect_unix` / `close` | `nsigner_transport_open_unix` + `nsigner_client_new` / `nsigner_client_free` |
| `nsigner_client_get_public_key` | `nostr_signer_get_public_key` or `nsigner_client_call(..., "get_public_key", ...)` |
| `nsigner_client_sign_event` | `nostr_signer_sign_event` or `nsigner_client_call(..., "sign_event", ...)` |
| `nsigner_client_set_auth` | `nsigner_client_set_auth` or `nostr_signer_nsigner_set_auth` |
| `nsigner_client_request` / `request_raw` | `nsigner_client_call` (returns parsed cJSON result) |
nsigner_client_connect_unix(&client, "nsigner", 5000);
## Consumers (updated)
char *resp = NULL;
nsigner_client_get_public_key(&client, "1", "", &resp);
free(resp);
- [`examples/get_public_key_client.c`](../examples/get_public_key_client.c) — uses `nsigner_transport_open_unix` + `nsigner_client_new` + `nsigner_client_call`.
- [`examples/sign_event_client.c`](../examples/sign_event_client.c) — same pattern.
- [`tests/test_integration.c`](../tests/test_integration.c) — same pattern; cJSON-based assertions.
nsigner_client_close(&client);
```
The `nsigner ... client '<json>'` subcommand in [`src/main.c`](../src/main.c) is
unaffected — it has its own raw framing pass-through and never used this directory.
## Auth envelope usage
## Multi-Algorithm and Post-Quantum Verbs
If transport requires auth envelopes (for TCP mode), set a private key once:
n_signer supports six algorithms: `secp256k1` (Nostr), `ed25519` (SSH),
`x25519` (age/ECDH), `ml-dsa-65` (PQ signatures, FIPS 204), `slh-dsa-128s`
(PQ hash-based signatures, FIPS 205), and `ml-kem-768` (PQ KEM, FIPS 203).
```c
unsigned char privkey[32] = { /* caller key */ };
nsigner_client_set_auth(&client, privkey, "example-client");
```
Use `nsigner_client_call(client, "<verb>", params, &result)` with these verbs:
Subsequent requests automatically include an `auth` object.
| Verb | Algorithms | Description |
|---|---|---|
| `get_public_key` | all | Returns the role's public key (see format below) |
| `sign_event` | secp256k1 | Sign a Nostr event (existing) |
| `nip44_encrypt` / `nip44_decrypt` | secp256k1 | NIP-44 (existing) |
| `nip04_encrypt` / `nip04_decrypt` | secp256k1 | NIP-04 (existing) |
| `mine_event` | secp256k1 | NIP-13 PoW mining + sign (existing) |
| `sign_data` | ed25519, ml-dsa-65, slh-dsa-128s | Sign arbitrary bytes (hex) |
| `verify_signature` | ed25519, ml-dsa-65, slh-dsa-128s | Verify a signature against the role's pubkey |
| `ssh_sign` | ed25519 | Sign an SSH authentication challenge |
| `kem_encapsulate` | ml-kem-768 | Encapsulate with a peer's ML-KEM public key |
| `kem_decapsulate` | ml-kem-768 | Decapsulate a ciphertext with the role's ML-KEM private key |
## Ownership rules
### Algorithm-based API (new)
- Any `out_response_json` returned by the API must be freed by caller using `free()`.
- `nsigner_client_close()` only closes the socket; it does not free the client struct itself.
In addition to the role-based verbs above, the signer supports algorithm-based verbs where the caller specifies `algorithm` and `index` directly, without needing a role:
## License
| Verb | Algorithms | Description |
|---|---|---|
| `sign` | secp256k1, ed25519, ml-dsa-65, slh-dsa-128s | Sign arbitrary bytes (hex) |
| `verify` | secp256k1, ed25519, ml-dsa-65, slh-dsa-128s | Verify a signature |
| `encapsulate` | ml-kem-768 | KEM encapsulation with peer's public key |
| `decapsulate` | ml-kem-768 | KEM decapsulation with derived private key |
| `derive_shared_secret` | x25519 | ECDH key agreement |
| `get_public_key` (with `algorithm`) | all | Get public key for a derived key |
Source files in this directory use SPDX `0BSD` headers for permissive reuse in external projects.
Example: `nsigner_client_call(client, "sign", "[\"68656c6c6f\",{\"algorithm\":\"ed25519\",\"index\":0}]", &result)`
For secp256k1, the optional `scheme` parameter selects `"schnorr"` (default) or `"ecdsa"`.
Old verbs (`sign_data`, `ssh_sign`, `verify_signature`, `kem_encapsulate`, `kem_decapsulate`) also accept the `algorithm` parameter and map to the new verbs. Without `algorithm`, they use the role-based path (backward compatible).
### `get_public_key` response format
- **secp256k1 (backward compatible):** `result` is a plain hex string
(`cJSON_IsString(result)` is true, 64 hex chars).
- **secp256k1 with `{"format":"structured"}` option:** `result` is a JSON
string containing `{"algorithm":"secp256k1","public_key":"<hex>","key_id":"<16 hex>"}`.
- **All other algorithms:** `result` is always a JSON string containing
`{"algorithm":"<alg>","public_key":"<hex>","key_id":"<16 hex>"}`.
Clients should parse the `result` string with `cJSON_Parse` to extract the
`algorithm`, `public_key`, and `key_id` fields for non-secp256k1 algorithms.
### Key sizes
| Algorithm | Pub key | Priv key | Signature | Ciphertext | Shared secret |
|---|---|---|---|---|---|
| secp256k1 | 32 B | 32 B | 64 B | — | — |
| ed25519 | 32 B | 32 B | 64 B | — | — |
| x25519 | 32 B | 32 B | — | — | 32 B |
| ML-DSA-65 | 1952 B | 4032 B | 3309 B | — | — |
| SLH-DSA-128s | 32 B | 64 B | 7856 B | — | — |
| ML-KEM-768 | 1184 B | 2400 B | — | 1088 B | 32 B |
### Example clients
- [`examples/pq_sign_example.c`](../examples/pq_sign_example.c) — ML-DSA-65 sign
- [`examples/pq_kem_example.c`](../examples/pq_kem_example.c) — ML-KEM-768 encaps/decaps
- [`examples/ssh_sign_example.c`](../examples/ssh_sign_example.c) — ed25519 SSH sign
See [`documents/CLIENT_IMPLEMENTATION.md`](../documents/CLIENT_IMPLEMENTATION.md)
section 11 for the full multi-algorithm specification, derivation paths, and
example request/response transcripts.
## Why
Per [`plans/nsigner_integration_plan.md`](../resources/nostr_core_lib/plans/nsigner_integration_plan.md)
(Phase 7): retire per-project hand-rolled clients in favor of the shared module
in `nostr_core_lib`, so the wire contract has one implementation and downstream
projects get unix/tcp/serial/fds transports for free.

322
client/demo_c99.c Normal file
View File

@@ -0,0 +1,322 @@
/*
* demo_c99.c — comprehensive C99 demo for connecting to a running n_signer
* via Qubes qrexec and performing all three core operations:
*
* 1. get_public_key — retrieve a Nostr public key by nostr_index
* 2. sign_event — sign a Nostr event (kind 1 text note)
* 3. nip44_encrypt — encrypt a message to a peer (and decrypt it back)
*
* Note: mine_event (NIP-13 PoW) is also available via the JSON-RPC interface.
* See demo_javascript.js and demo_python.py for mine_event usage examples.
* The high-level nostr_signer API does not yet wrap mine_event.
*
* This uses the high-level nostr_signer API from nostr_core_lib:
* - nostr_signer_nsigner_qrexec() — qrexec transport (no network)
* - nostr_signer_nsigner_set_nostr_index() — select key by NIP-06 index
* - nostr_signer_get_public_key() — get pubkey
* - nostr_signer_sign_event() — sign an event
* - nostr_signer_nip44_encrypt() — encrypt
* - nostr_signer_nip44_decrypt() — decrypt
*
* Prerequisites:
* - n_signer running in the target qube with --bridge-source-trusted
* - qubes.NsignerRpc service installed in the target qube
* - dom0 qrexec policy allowing this qube to call the service
*
* Build (from n_signer repo root):
* make examples
*
* Usage:
* ./build/demo_c99 <target_qube> [nostr_index]
* ./build/demo_c99 nostr_signer 1
*
* If no nostr_index is given, defaults to 0.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <signal.h>
#include "nostr_common.h"
#include "nostr_signer.h"
#include "nip019.h"
#include "../cjson/cJSON.h"
/* Helper: convert 32-byte hex pubkey to bech32 npub */
static int hex_to_npub(const char *hex, char *out_npub, size_t out_sz) {
unsigned char bytes[32];
int i;
if (strlen(hex) != 64) {
return -1;
}
for (i = 0; i < 32; i++) {
unsigned int byte;
if (sscanf(hex + 2 * i, "%2x", &byte) != 1) {
return -1;
}
bytes[i] = (unsigned char)byte;
}
return nostr_key_to_bech32(bytes, "npub", out_npub);
}
/* Helper: print an error with a human-readable description */
static void print_error(const char *operation, int rc) {
const char *desc = "unknown error";
switch (rc) {
case NOSTR_ERROR_INVALID_INPUT:
desc = "invalid input";
break;
case NOSTR_ERROR_CRYPTO_FAILED:
desc = "crypto operation failed";
break;
case NOSTR_ERROR_IO_FAILED:
desc = "I/O failed (transport error)";
break;
case NOSTR_ERROR_NETWORK_FAILED:
desc = "network failed";
break;
case NOSTR_ERROR_NSIGNER_POLICY_DENIED:
desc = "policy denied (caller not approved at signer terminal)";
break;
case NOSTR_ERROR_NSIGNER_INDEX_NOT_ALLOWED:
desc = "index not in signer's whitelist";
break;
default:
/* Try to print the numeric code */
fprintf(stderr, " %s failed: error code %d\n", operation, rc);
return;
}
fprintf(stderr, " %s failed: %s (code %d)\n", operation, desc, rc);
}
/*
* Demo 1: Get a public key by nostr_index.
* Returns the hex pubkey in `out_hex` (must be 65 bytes).
*/
static int demo_get_public_key(nostr_signer_t *signer, int nostr_index,
char *out_hex, size_t hex_sz) {
char npub[128];
int rc;
printf("\n=== Demo 1: get_public_key (nostr_index=%d) ===\n", nostr_index);
rc = nostr_signer_get_public_key(signer, out_hex);
if (rc != NOSTR_SUCCESS) {
print_error("get_public_key", rc);
return rc;
}
if (hex_to_npub(out_hex, npub, sizeof(npub)) == 0) {
printf(" pubkey hex: %s\n", out_hex);
printf(" npub: %s\n", npub);
} else {
printf(" pubkey hex: %s\n", out_hex);
printf(" (npub conversion failed)\n");
}
return NOSTR_SUCCESS;
}
/*
* Demo 2: Sign a Nostr event (kind 1 text note).
* The signed event JSON is printed.
*/
static int demo_sign_event(nostr_signer_t *signer, const char *pubkey_hex) {
cJSON *unsigned_event = NULL;
cJSON *signed_event = NULL;
char *signed_json = NULL;
int rc;
printf("\n=== Demo 2: sign_event (kind 1 text note) ===\n");
/* Build an unsigned Nostr event (kind 1 text note) */
unsigned_event = cJSON_CreateObject();
if (unsigned_event == NULL) {
fprintf(stderr, " failed to create event JSON\n");
return NOSTR_ERROR_MEMORY_FAILED;
}
cJSON_AddNumberToObject(unsigned_event, "kind", 1);
cJSON_AddStringToObject(unsigned_event, "content", "Hello from n_signer C99 demo!");
cJSON_AddNumberToObject(unsigned_event, "created_at", (int)time(NULL));
/* tags: empty array */
cJSON_AddItemToObject(unsigned_event, "tags", cJSON_CreateArray());
/* pubkey: the signer will fill this in, but we include it for completeness */
cJSON_AddStringToObject(unsigned_event, "pubkey", pubkey_hex);
printf(" Unsigned event:\n");
{
char *tmp = cJSON_PrintUnformatted(unsigned_event);
if (tmp) {
printf(" %s\n", tmp);
free(tmp);
}
}
/* Sign it */
rc = nostr_signer_sign_event(signer, unsigned_event, &signed_event);
if (rc != NOSTR_SUCCESS) {
print_error("sign_event", rc);
cJSON_Delete(unsigned_event);
return rc;
}
/* Print the signed event */
signed_json = cJSON_Print(signed_event);
if (signed_json) {
printf(" Signed event:\n");
printf(" %s\n", signed_json);
free(signed_json);
}
/* Extract and show the signature and event id */
{
cJSON *id = cJSON_GetObjectItemCaseSensitive(signed_event, "id");
cJSON *sig = cJSON_GetObjectItemCaseSensitive(signed_event, "sig");
if (id && cJSON_IsString(id)) {
printf(" event id: %s\n", id->valuestring);
}
if (sig && cJSON_IsString(sig)) {
printf(" signature: %s\n", sig->valuestring);
}
}
cJSON_Delete(signed_event);
cJSON_Delete(unsigned_event);
return NOSTR_SUCCESS;
}
/*
* Demo 3: NIP-44 encrypt and decrypt.
* Encrypts a message to ourselves (using our own pubkey as the peer),
* then decrypts it to verify round-trip.
*/
static int demo_nip44(nostr_signer_t *signer, const char *pubkey_hex) {
const char *plaintext = "Secret message from n_signer C99 demo!";
char *ciphertext = NULL;
char *decrypted = NULL;
int rc;
printf("\n=== Demo 3: nip44_encrypt / nip44_decrypt ===\n");
printf(" plaintext: \"%s\"\n", plaintext);
printf(" peer pubkey: %s (self)\n", pubkey_hex);
/* Encrypt */
rc = nostr_signer_nip44_encrypt(signer, pubkey_hex, plaintext, &ciphertext);
if (rc != NOSTR_SUCCESS) {
print_error("nip44_encrypt", rc);
return rc;
}
printf(" ciphertext: %s\n", ciphertext);
/* Decrypt (using our own pubkey as the sender) */
rc = nostr_signer_nip44_decrypt(signer, pubkey_hex, ciphertext, &decrypted);
if (rc != NOSTR_SUCCESS) {
print_error("nip44_decrypt", rc);
free(ciphertext);
return rc;
}
printf(" decrypted: \"%s\"\n", decrypted);
/* Verify round-trip */
if (strcmp(plaintext, decrypted) == 0) {
printf(" ✓ Round-trip verified: plaintext matches decrypted\n");
} else {
printf(" ✗ Round-trip FAILED: plaintext does not match decrypted\n");
rc = NOSTR_ERROR_CRYPTO_FAILED;
}
free(ciphertext);
free(decrypted);
return rc;
}
int main(int argc, char **argv) {
const char *target_qube;
const char *service_name = "qubes.NsignerRpc";
int nostr_index = 0;
nostr_signer_t *signer = NULL;
char pubkey_hex[65];
int rc;
/* Ignore SIGPIPE — qrexec subprocess may close pipes abruptly */
(void)signal(SIGPIPE, SIG_IGN);
if (argc < 2) {
fprintf(stderr, "Usage: %s <target_qube> [nostr_index]\n", argv[0]);
fprintf(stderr, "Example: %s nostr_signer 1\n", argv[0]);
return 1;
}
target_qube = argv[1];
if (argc > 2) {
nostr_index = atoi(argv[2]);
}
/* Initialize the crypto subsystem */
if (nostr_init() != NOSTR_SUCCESS) {
fprintf(stderr, "Failed to initialize crypto subsystem\n");
return 1;
}
printf("=== n_signer C99 Demo ===\n");
printf("Target qube: %s\n", target_qube);
printf("Service: %s\n", service_name);
printf("nostr_index: %d\n", nostr_index);
printf("\n");
/* Create a high-level signer backed by qrexec transport */
printf("Connecting to n_signer via qrexec...\n");
signer = nostr_signer_nsigner_qrexec(target_qube, service_name, NULL, 30000);
if (signer == NULL) {
fprintf(stderr, "Failed to create qrexec signer.\n");
fprintf(stderr, "Is qrexec-client-vm available? Is the service installed?\n");
nostr_cleanup();
return 1;
}
printf("Connected.\n");
/* Select key by nostr_index (NIP-06 m/44'/1237'/N'/0/0) */
rc = nostr_signer_nsigner_set_nostr_index(signer, nostr_index);
if (rc != NOSTR_SUCCESS) {
print_error("set_nostr_index", rc);
nostr_signer_free(signer);
nostr_cleanup();
return 1;
}
/* Demo 1: Get public key */
rc = demo_get_public_key(signer, nostr_index, pubkey_hex, sizeof(pubkey_hex));
if (rc != NOSTR_SUCCESS) {
goto cleanup;
}
/* Demo 2: Sign an event */
rc = demo_sign_event(signer, pubkey_hex);
if (rc != NOSTR_SUCCESS) {
goto cleanup;
}
/* Demo 3: NIP-44 encrypt/decrypt */
rc = demo_nip44(signer, pubkey_hex);
cleanup:
printf("\n=== Summary ===\n");
if (rc == NOSTR_SUCCESS) {
printf("All demos completed successfully.\n");
} else {
printf("Demo failed with error code %d.\n", rc);
}
nostr_signer_free(signer);
nostr_cleanup();
return (rc == NOSTR_SUCCESS) ? 0 : 1;
}

268
client/demo_javascript.js Normal file
View File

@@ -0,0 +1,268 @@
#!/usr/bin/env node
/**
* demo_javascript.js — comprehensive JavaScript demo for connecting to a
* running n_signer via Qubes qrexec and performing all three core operations:
*
* 1. get_public_key — retrieve a Nostr public key by nostr_index
* 2. sign_event — sign a Nostr event (kind 1 text note)
* 3. nip44_encrypt — encrypt a message to a peer (and decrypt it back)
*
* Uses qrexec-client-vm (Qubes OS inter-qube IPC). No auth envelope needed —
* identity comes from QREXEC_REMOTE_DOMAIN on the server side.
*
* Prerequisites:
* - n_signer running in the target qube with --bridge-source-trusted
* - qubes.NsignerRpc service installed in the target qube
* - dom0 qrexec policy allowing this qube to call the service
* - nostr-tools and @noble/secp256k1 npm packages installed
*
* Install dependencies (from n_signer repo root):
* npm install nostr-tools @noble/secp256k1
*
* Usage:
* node client/demo_javascript.js <target_qube> [nostr_index]
* node client/demo_javascript.js nostr_signer 1
*
* If no nostr_index is given, defaults to 0.
*/
const { spawn } = require("child_process");
const crypto = require("crypto");
const secp = require("@noble/secp256k1");
const { nip19 } = require("nostr-tools");
// @noble/secp256k1 v3 requires sync sha256/hmacSha256
secp.hashes.sha256 = (msg) => new Uint8Array(crypto.createHash("sha256").update(msg).digest());
secp.hashes.hmacSha256 = (key, msg) =>
new Uint8Array(crypto.createHmac("sha256", key).update(msg).digest());
/**
* Call n_signer via qrexec. Sends one framed JSON-RPC request, receives one
* framed response. Each call spawns a fresh qrexec-client-vm process.
*
* Framing: 4-byte big-endian length prefix + JSON payload.
* No auth envelope needed for qrexec (identity from QREXEC_REMOTE_DOMAIN).
*/
function callNsigner(targetQube, request) {
return new Promise((resolve, reject) => {
const payload = Buffer.from(JSON.stringify(request), "utf8");
const header = Buffer.alloc(4);
header.writeUInt32BE(payload.length, 0);
const framed = Buffer.concat([header, payload]);
const proc = spawn("qrexec-client-vm", [targetQube, "qubes.NsignerRpc"], {
stdio: ["pipe", "pipe", "pipe"],
});
const stdoutChunks = [];
const stderrChunks = [];
proc.stdout.on("data", (chunk) => stdoutChunks.push(chunk));
proc.stderr.on("data", (chunk) => stderrChunks.push(chunk));
proc.on("error", (err) => {
reject(new Error(`failed to spawn qrexec-client-vm: ${err.message}`));
});
proc.on("close", (code) => {
if (code !== 0) {
const stderr = Buffer.concat(stderrChunks).toString("utf8");
reject(new Error(`qrexec-client-vm exited with code ${code}: ${stderr.trim()}`));
return;
}
const buf = Buffer.concat(stdoutChunks);
if (buf.length < 4) {
reject(new Error("short response (missing frame header)"));
return;
}
const len = buf.readUInt32BE(0);
const body = buf.subarray(4, 4 + len);
if (body.length !== len) {
reject(new Error(`short response payload: expected ${len}, got ${body.length}`));
return;
}
try {
resolve(JSON.parse(body.toString("utf8")));
} catch (e) {
reject(new Error(`failed to parse response: ${e.message}`));
}
});
proc.stdin.write(framed);
proc.stdin.end();
});
}
/**
* Demo 1: Get a public key by nostr_index.
*/
async function demoGetPublicKey(targetQube, nostrIndex) {
console.log(`\n=== Demo 1: get_public_key (nostr_index=${nostrIndex}) ===`);
const response = await callNsigner(targetQube, {
id: "1",
method: "get_public_key",
params: [{ nostr_index: nostrIndex }],
});
if (response.error) {
throw new Error(`get_public_key failed: ${JSON.stringify(response.error)}`);
}
const pubkeyHex = response.result;
const npub = nip19.npubEncode(pubkeyHex);
console.log(` pubkey hex: ${pubkeyHex}`);
console.log(` npub: ${npub}`);
return pubkeyHex;
}
/**
* Demo 2: Sign a Nostr event (kind 1 text note).
*/
async function demoSignEvent(targetQube, nostrIndex, pubkeyHex) {
console.log("\n=== Demo 2: sign_event (kind 1 text note) ===");
const unsignedEvent = {
kind: 1,
content: "Hello from n_signer JavaScript demo!",
created_at: Math.floor(Date.now() / 1000),
tags: [],
pubkey: pubkeyHex,
};
console.log(" Unsigned event:");
console.log(` ${JSON.stringify(unsignedEvent)}`);
const response = await callNsigner(targetQube, {
id: "2",
method: "sign_event",
params: [JSON.stringify(unsignedEvent), { nostr_index: nostrIndex }],
});
if (response.error) {
throw new Error(`sign_event failed: ${JSON.stringify(response.error)}`);
}
const signedEvent = JSON.parse(response.result);
console.log(" Signed event:");
console.log(` ${JSON.stringify(signedEvent)}`);
console.log(` event id: ${signedEvent.id}`);
console.log(` signature: ${signedEvent.sig}`);
return signedEvent;
}
/**
* Demo 3: NIP-44 encrypt and decrypt.
* Encrypts a message to ourselves (using our own pubkey as the peer),
* then decrypts it to verify round-trip.
*/
async function demoNip44(targetQube, nostrIndex, pubkeyHex) {
const plaintext = "Secret message from n_signer JavaScript demo!";
console.log("\n=== Demo 3: nip44_encrypt / nip44_decrypt ===");
console.log(` plaintext: "${plaintext}"`);
console.log(` peer pubkey: ${pubkeyHex} (self)`);
// Encrypt
const encResponse = await callNsigner(targetQube, {
id: "3",
method: "nip44_encrypt",
params: [pubkeyHex, plaintext, { nostr_index: nostrIndex }],
});
if (encResponse.error) {
throw new Error(`nip44_encrypt failed: ${JSON.stringify(encResponse.error)}`);
}
const ciphertext = encResponse.result;
console.log(` ciphertext: ${ciphertext}`);
// Decrypt
const decResponse = await callNsigner(targetQube, {
id: "4",
method: "nip44_decrypt",
params: [pubkeyHex, ciphertext, { nostr_index: nostrIndex }],
});
if (decResponse.error) {
throw new Error(`nip44_decrypt failed: ${JSON.stringify(decResponse.error)}`);
}
const decrypted = decResponse.result;
console.log(` decrypted: "${decrypted}"`);
if (plaintext === decrypted) {
console.log(" ✓ Round-trip verified: plaintext matches decrypted");
} else {
throw new Error("Round-trip FAILED: plaintext does not match decrypted");
}
}
async function demoMineEvent(targetQube, nostrIndex) {
console.log("\n--- Demo 4: mine_event (NIP-13 Proof-of-Work) ---");
const event = {
kind: 1,
content: "Hello Nostr with PoW!",
tags: [],
};
console.log(" Mining with difficulty=4, threads=4, timeout_sec=30...");
const response = await callNsigner(targetQube, {
id: "5",
method: "mine_event",
params: [JSON.stringify(event), {
difficulty: 4,
threads: 4,
timeout_sec: 30,
nostr_index: nostrIndex,
}],
});
if (response.error) {
throw new Error(`mine_event failed: ${JSON.stringify(response.error)}`);
}
const result = JSON.parse(response.result);
console.log(` achieved_difficulty: ${result.achieved_difficulty}`);
console.log(` target_reached: ${result.target_reached}`);
console.log(` elapsed_sec: ${result.elapsed_sec}`);
console.log(` attempts: ${result.attempts}`);
const minedEvent = JSON.parse(result.event);
console.log(` event id: ${minedEvent.id}`);
console.log(` nonce tag: ${JSON.stringify(minedEvent.tags[0])}`);
if (result.target_reached) {
console.log(" ✓ Target difficulty reached!");
} else {
console.log(` (Target not reached, best effort: ${result.achieved_difficulty} bits)`);
}
}
async function main() {
const targetQube = process.argv[2] || "nostr_signer";
const nostrIndex = parseInt(process.argv[3] || "0", 10);
console.log("=== n_signer JavaScript Demo ===");
console.log(`Target qube: ${targetQube}`);
console.log(`Service: qubes.NsignerRpc`);
console.log(`nostr_index: ${nostrIndex}`);
console.log("\nConnecting to n_signer via qrexec...");
try {
const pubkeyHex = await demoGetPublicKey(targetQube, nostrIndex);
await demoSignEvent(targetQube, nostrIndex, pubkeyHex);
await demoNip44(targetQube, nostrIndex, pubkeyHex);
await demoMineEvent(targetQube, nostrIndex);
console.log("\n=== Summary ===");
console.log("All demos completed successfully.");
} catch (e) {
console.error("\n=== Summary ===");
console.error(`Demo failed: ${e.message}`);
process.exit(1);
}
}
main();

296
client/demo_python.py Normal file
View File

@@ -0,0 +1,296 @@
#!/usr/bin/env python3
"""
demo_python.py — comprehensive Python demo for connecting to a running n_signer
via Qubes qrexec and performing all three core operations:
1. get_public_key — retrieve a Nostr public key by nostr_index
2. sign_event — sign a Nostr event (kind 1 text note)
3. nip44_encrypt — encrypt a message to a peer (and decrypt it back)
Uses qrexec-client-vm (Qubes OS inter-qube IPC). No auth envelope needed —
identity comes from QREXEC_REMOTE_DOMAIN on the server side.
Prerequisites:
- n_signer running in the target qube with --bridge-source-trusted
- qubes.NsignerRpc service installed in the target qube
- dom0 qrexec policy allowing this qube to call the service
- Python 3 with no external dependencies (uses only stdlib)
Usage:
python3 client/demo_python.py <target_qube> [nostr_index]
python3 client/demo_python.py nostr_signer 1
If no nostr_index is given, defaults to 0.
"""
import json
import struct
import subprocess
import sys
import time
# --- Bech32 encoder (NIP-19 npub conversion, no external dependencies) ---
CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
def bech32_polymod(values):
generator = [0x3B6A57B2, 0x26508E6D, 0x1EA119FA, 0x3D4233DD, 0x2A1462B3]
chk = 1
for v in values:
b = chk >> 25
chk = (chk & 0x1FFFFFF) << 5 ^ v
for i in range(5):
chk ^= generator[i] if ((b >> i) & 1) else 0
return chk
def bech32_hrp_expand(hrp):
return [ord(x) >> 5 for x in hrp] + [0] + [ord(x) & 31 for x in hrp]
def bech32_create_checksum(hrp, data):
values = bech32_hrp_expand(hrp) + data
polymod = bech32_polymod(values + [0, 0, 0, 0, 0, 0]) ^ 1
return [(polymod >> 5 * (5 - i)) & 31 for i in range(6)]
def bech32_encode(hrp, data):
combined = data + bech32_create_checksum(hrp, data)
return hrp + "1" + "".join([CHARSET[d] for d in combined])
def convertbits(data, frombits, tobits, pad=True):
acc = 0
bits = 0
ret = []
maxv = (1 << tobits) - 1
max_acc = (1 << (frombits + tobits - 1)) - 1
for value in data:
acc = ((acc << frombits) | value) & max_acc
bits += frombits
while bits >= tobits:
bits -= tobits
ret.append((acc >> bits) & maxv)
if pad and bits:
ret.append((acc << (tobits - bits)) & maxv)
return ret
def hex_to_npub(pubkey_hex):
"""Convert a 32-byte hex pubkey to bech32 npub format (NIP-19)."""
pubkey_bytes = bytes.fromhex(pubkey_hex)
data = convertbits(pubkey_bytes, 8, 5)
return bech32_encode("npub", data)
# --- n_signer qrexec client ---
def call_nsigner(target_qube, request):
"""
Call n_signer via qrexec. Sends one framed JSON-RPC request, receives one
framed response. Each call spawns a fresh qrexec-client-vm process.
Framing: 4-byte big-endian length prefix + JSON payload.
No auth envelope needed for qrexec (identity from QREXEC_REMOTE_DOMAIN).
"""
payload = json.dumps(request, separators=(",", ":")).encode("utf-8")
frame = struct.pack(">I", len(payload)) + payload
proc = subprocess.Popen(
["qrexec-client-vm", target_qube, "qubes.NsignerRpc"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
out, err = proc.communicate(frame)
if proc.returncode != 0:
raise RuntimeError(
f"qrexec-client-vm exited with code {proc.returncode}: "
f"{err.decode('utf-8', 'replace').strip()}"
)
if len(out) < 4:
raise RuntimeError("short response (missing frame header)")
length = struct.unpack(">I", out[:4])[0]
body = out[4 : 4 + length]
if len(body) != length:
raise RuntimeError(
f"short response payload: expected {length}, got {len(body)}"
)
return json.loads(body.decode("utf-8"))
# --- Demos ---
def demo_get_public_key(target_qube, nostr_index):
"""Demo 1: Get a public key by nostr_index."""
print(f"\n=== Demo 1: get_public_key (nostr_index={nostr_index}) ===")
response = call_nsigner(
target_qube,
{"id": "1", "method": "get_public_key", "params": [{"nostr_index": nostr_index}]},
)
if "error" in response:
raise RuntimeError(f"get_public_key failed: {json.dumps(response['error'])}")
pubkey_hex = response["result"]
npub = hex_to_npub(pubkey_hex)
print(f" pubkey hex: {pubkey_hex}")
print(f" npub: {npub}")
return pubkey_hex
def demo_sign_event(target_qube, nostr_index, pubkey_hex):
"""Demo 2: Sign a Nostr event (kind 1 text note)."""
print("\n=== Demo 2: sign_event (kind 1 text note) ===")
unsigned_event = {
"kind": 1,
"content": "Hello from n_signer Python demo!",
"created_at": int(time.time()),
"tags": [],
"pubkey": pubkey_hex,
}
print(" Unsigned event:")
print(f" {json.dumps(unsigned_event, separators=(',', ':'))}")
response = call_nsigner(
target_qube,
{
"id": "2",
"method": "sign_event",
"params": [json.dumps(unsigned_event, separators=(",", ":")), {"nostr_index": nostr_index}],
},
)
if "error" in response:
raise RuntimeError(f"sign_event failed: {json.dumps(response['error'])}")
signed_event = json.loads(response["result"])
print(" Signed event:")
print(f" {json.dumps(signed_event, separators=(',', ':'))}")
print(f" event id: {signed_event['id']}")
print(f" signature: {signed_event['sig']}")
return signed_event
def demo_nip44(target_qube, nostr_index, pubkey_hex):
"""Demo 3: NIP-44 encrypt and decrypt."""
plaintext = "Secret message from n_signer Python demo!"
print("\n=== Demo 3: nip44_encrypt / nip44_decrypt ===")
print(f' plaintext: "{plaintext}"')
print(f" peer pubkey: {pubkey_hex} (self)")
# Encrypt
enc_response = call_nsigner(
target_qube,
{
"id": "3",
"method": "nip44_encrypt",
"params": [pubkey_hex, plaintext, {"nostr_index": nostr_index}],
},
)
if "error" in enc_response:
raise RuntimeError(f"nip44_encrypt failed: {json.dumps(enc_response['error'])}")
ciphertext = enc_response["result"]
print(f" ciphertext: {ciphertext}")
# Decrypt
dec_response = call_nsigner(
target_qube,
{
"id": "4",
"method": "nip44_decrypt",
"params": [pubkey_hex, ciphertext, {"nostr_index": nostr_index}],
},
)
if "error" in dec_response:
raise RuntimeError(f"nip44_decrypt failed: {json.dumps(dec_response['error'])}")
decrypted = dec_response["result"]
print(f' decrypted: "{decrypted}"')
if plaintext == decrypted:
print(" ✓ Round-trip verified: plaintext matches decrypted")
else:
raise RuntimeError("Round-trip FAILED: plaintext does not match decrypted")
def demo_mine_event(target_qube, nostr_index):
print("\n--- Demo 4: mine_event (NIP-13 Proof-of-Work) ---")
event = {"kind": 1, "content": "Hello Nostr with PoW!", "tags": []}
print(" Mining with difficulty=4, threads=4, timeout_sec=30...")
response = call_nsigner(
target_qube,
{
"id": "5",
"method": "mine_event",
"params": [json.dumps(event), {
"difficulty": 4,
"threads": 4,
"timeout_sec": 30,
"nostr_index": nostr_index,
}],
},
)
if "error" in response:
raise RuntimeError(f"mine_event failed: {json.dumps(response['error'])}")
result = json.loads(response["result"])
print(f" achieved_difficulty: {result['achieved_difficulty']}")
print(f" target_reached: {result['target_reached']}")
print(f" elapsed_sec: {result['elapsed_sec']}")
print(f" attempts: {result['attempts']}")
mined_event = json.loads(result["event"])
print(f" event id: {mined_event['id']}")
print(f" nonce tag: {mined_event['tags'][0]}")
if result["target_reached"]:
print(" ✓ Target difficulty reached!")
else:
print(f" (Target not reached, best effort: {result['achieved_difficulty']} bits)")
# --- Main ---
def main():
target_qube = sys.argv[1] if len(sys.argv) > 1 else "nostr_signer"
nostr_index = int(sys.argv[2]) if len(sys.argv) > 2 else 0
print("=== n_signer Python Demo ===")
print(f"Target qube: {target_qube}")
print(f"Service: qubes.NsignerRpc")
print(f"nostr_index: {nostr_index}")
print("\nConnecting to n_signer via qrexec...")
try:
pubkey_hex = demo_get_public_key(target_qube, nostr_index)
demo_sign_event(target_qube, nostr_index, pubkey_hex)
demo_nip44(target_qube, nostr_index, pubkey_hex)
demo_mine_event(target_qube, nostr_index)
print("\n=== Summary ===")
print("All demos completed successfully.")
except Exception as e:
print("\n=== Summary ===")
print(f"Demo failed: {e}")
sys.exit(1)
if __name__ == "__main__":
main()

View File

@@ -1,369 +0,0 @@
/*
* SPDX-License-Identifier: 0BSD
*/
#define _GNU_SOURCE
#include "nsigner_client.h"
#include <arpa/inet.h>
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <time.h>
#include <unistd.h>
#include <cJSON.h>
#include "auth_envelope.h"
#define NSIGNER_CLIENT_MAX_FRAME (65536U)
static void client_set_error(nsigner_client_t *client, const char *fmt, ...) {
va_list ap;
if (client == NULL) {
return;
}
va_start(ap, fmt);
vsnprintf(client->last_error, sizeof(client->last_error), fmt, ap);
va_end(ap);
}
static int write_full(int fd, const void *buf, size_t len) {
const unsigned char *p = (const unsigned char *)buf;
size_t off = 0;
while (off < len) {
ssize_t n = write(fd, p + off, len - off);
if (n < 0) {
if (errno == EINTR) {
continue;
}
return -1;
}
off += (size_t)n;
}
return 0;
}
static int read_full(int fd, void *buf, size_t len) {
unsigned char *p = (unsigned char *)buf;
size_t off = 0;
while (off < len) {
ssize_t n = read(fd, p + off, len - off);
if (n == 0) {
return -1;
}
if (n < 0) {
if (errno == EINTR) {
continue;
}
return -1;
}
off += (size_t)n;
}
return 0;
}
static int send_framed(int fd, const char *payload) {
uint32_t len;
uint32_t be_len;
if (payload == NULL) {
return -1;
}
len = (uint32_t)strlen(payload);
be_len = htonl(len);
if (write_full(fd, &be_len, sizeof(be_len)) != 0) {
return -1;
}
if (write_full(fd, payload, len) != 0) {
return -1;
}
return 0;
}
static int recv_framed(int fd, char **out_payload) {
uint32_t be_len;
uint32_t len;
char *payload;
if (out_payload == NULL) {
return -1;
}
*out_payload = NULL;
if (read_full(fd, &be_len, sizeof(be_len)) != 0) {
return -1;
}
len = ntohl(be_len);
if (len == 0 || len > NSIGNER_CLIENT_MAX_FRAME) {
return -1;
}
payload = (char *)malloc((size_t)len + 1U);
if (payload == NULL) {
return -1;
}
if (read_full(fd, payload, len) != 0) {
free(payload);
return -1;
}
payload[len] = '\0';
*out_payload = payload;
return 0;
}
static int sleep_ms(int ms) {
struct timespec ts;
ts.tv_sec = ms / 1000;
ts.tv_nsec = (long)(ms % 1000) * 1000000L;
return nanosleep(&ts, NULL);
}
void nsigner_client_init(nsigner_client_t *client) {
if (client == NULL) {
return;
}
memset(client, 0, sizeof(*client));
client->fd = -1;
client->timeout_ms = 5000;
}
void nsigner_client_close(nsigner_client_t *client) {
if (client == NULL) {
return;
}
if (client->fd >= 0) {
close(client->fd);
client->fd = -1;
}
}
int nsigner_client_connect_unix(nsigner_client_t *client,
const char *socket_name,
int timeout_ms) {
struct sockaddr_un addr;
socklen_t addr_len;
int elapsed = 0;
if (client == NULL || socket_name == NULL || socket_name[0] == '\0') {
return -1;
}
timeout_ms = (timeout_ms > 0) ? timeout_ms : 5000;
nsigner_client_close(client);
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
addr.sun_path[0] = '\0';
strncpy(&addr.sun_path[1], socket_name, sizeof(addr.sun_path) - 2);
addr.sun_path[sizeof(addr.sun_path) - 1] = '\0';
addr_len = (socklen_t)(sizeof(sa_family_t) + 1 + strlen(socket_name));
while (elapsed < timeout_ms) {
int fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (fd < 0) {
client_set_error(client, "socket failed: %s", strerror(errno));
return -1;
}
if (connect(fd, (struct sockaddr *)&addr, addr_len) == 0) {
client->fd = fd;
client->timeout_ms = timeout_ms;
client_set_error(client, "ok");
return 0;
}
close(fd);
sleep_ms(100);
elapsed += 100;
}
client_set_error(client, "connect timeout: %s", strerror(errno));
return -1;
}
int nsigner_client_set_auth(nsigner_client_t *client,
const unsigned char privkey[32],
const char *label) {
if (client == NULL || privkey == NULL) {
return -1;
}
memcpy(client->auth_privkey, privkey, 32);
client->auth_enabled = 1;
if (label == NULL) {
label = "";
}
strncpy(client->auth_label, label, sizeof(client->auth_label) - 1);
client->auth_label[sizeof(client->auth_label) - 1] = '\0';
return 0;
}
const char *nsigner_client_last_error(const nsigner_client_t *client) {
if (client == NULL) {
return "invalid_client";
}
return client->last_error;
}
int nsigner_client_request_raw(nsigner_client_t *client,
const char *request_json,
char **out_response_json) {
char *response_json = NULL;
if (client == NULL || request_json == NULL || out_response_json == NULL) {
return -1;
}
if (client->fd < 0) {
client_set_error(client, "not connected");
return -1;
}
*out_response_json = NULL;
if (send_framed(client->fd, request_json) != 0) {
client_set_error(client, "send failed");
return -1;
}
if (recv_framed(client->fd, &response_json) != 0) {
client_set_error(client, "receive failed");
return -1;
}
*out_response_json = response_json;
client_set_error(client, "ok");
return 0;
}
int nsigner_client_request(nsigner_client_t *client,
const char *id,
const char *method,
const cJSON *params,
char **out_response_json) {
cJSON *root = NULL;
cJSON *params_copy = NULL;
cJSON *auth = NULL;
char *request_json = NULL;
int rc = -1;
if (client == NULL || id == NULL || method == NULL || out_response_json == NULL) {
return -1;
}
root = cJSON_CreateObject();
if (root == NULL) {
client_set_error(client, "out of memory");
goto cleanup;
}
cJSON_AddStringToObject(root, "id", id);
cJSON_AddStringToObject(root, "method", method);
if (params != NULL) {
params_copy = cJSON_Duplicate((cJSON *)params, 1);
} else {
params_copy = cJSON_CreateArray();
}
if (params_copy == NULL) {
client_set_error(client, "failed to create params");
goto cleanup;
}
cJSON_AddItemToObject(root, "params", params_copy);
if (client->auth_enabled) {
if (auth_envelope_build_for_request(id,
method,
params_copy,
client->auth_privkey,
client->auth_label,
time(NULL),
&auth) != 0) {
client_set_error(client, "failed to build auth envelope");
goto cleanup;
}
cJSON_AddItemToObject(root, "auth", auth);
auth = NULL;
}
request_json = cJSON_PrintUnformatted(root);
if (request_json == NULL) {
client_set_error(client, "failed to serialize request");
goto cleanup;
}
rc = nsigner_client_request_raw(client, request_json, out_response_json);
cleanup:
cJSON_Delete(root);
cJSON_Delete(auth);
free(request_json);
return rc;
}
int nsigner_client_get_public_key(nsigner_client_t *client,
const char *id,
const char *selector,
char **out_response_json) {
cJSON *params = cJSON_CreateArray();
int rc;
if (params == NULL) {
return -1;
}
cJSON_AddItemToArray(params, cJSON_CreateString((selector != NULL) ? selector : ""));
rc = nsigner_client_request(client, id, "get_public_key", params, out_response_json);
cJSON_Delete(params);
return rc;
}
int nsigner_client_sign_event(nsigner_client_t *client,
const char *id,
const char *event_json,
const char *role,
char **out_response_json) {
cJSON *params = cJSON_CreateArray();
cJSON *opts = cJSON_CreateObject();
int rc;
if (params == NULL || opts == NULL || event_json == NULL) {
cJSON_Delete(params);
cJSON_Delete(opts);
return -1;
}
cJSON_AddItemToArray(params, cJSON_CreateString(event_json));
if (role != NULL && role[0] != '\0') {
cJSON_AddStringToObject(opts, "role", role);
}
cJSON_AddItemToArray(params, opts);
rc = nsigner_client_request(client, id, "sign_event", params, out_response_json);
cJSON_Delete(params);
return rc;
}

View File

@@ -1,56 +0,0 @@
/*
* SPDX-License-Identifier: 0BSD
*/
#ifndef NSIGNER_CLIENT_H
#define NSIGNER_CLIENT_H
#include <stddef.h>
#include <stdint.h>
#include <cJSON.h>
typedef struct {
int fd;
int timeout_ms;
unsigned char auth_privkey[32];
int auth_enabled;
char auth_label[64];
char last_error[128];
} nsigner_client_t;
void nsigner_client_init(nsigner_client_t *client);
void nsigner_client_close(nsigner_client_t *client);
int nsigner_client_connect_unix(nsigner_client_t *client,
const char *socket_name,
int timeout_ms);
int nsigner_client_set_auth(nsigner_client_t *client,
const unsigned char privkey[32],
const char *label);
const char *nsigner_client_last_error(const nsigner_client_t *client);
int nsigner_client_request_raw(nsigner_client_t *client,
const char *request_json,
char **out_response_json);
int nsigner_client_request(nsigner_client_t *client,
const char *id,
const char *method,
const cJSON *params,
char **out_response_json);
int nsigner_client_get_public_key(nsigner_client_t *client,
const char *id,
const char *selector,
char **out_response_json);
int nsigner_client_sign_event(nsigner_client_t *client,
const char *id,
const char *event_json,
const char *role,
char **out_response_json);
#endif

View File

@@ -127,6 +127,25 @@ Methods are NIP-46 style verbs.
- `nip44_encrypt`
- `nip44_decrypt`
### 4.2b Algorithm-based verbs (new)
In addition to the role-based verbs above, the signer supports algorithm-based verbs where the caller specifies `algorithm` and `index` directly:
- `sign` — sign arbitrary bytes (params: `[message_hex, {algorithm, index, scheme?}]`)
- `verify` — verify a signature (params: `[message_hex, signature_hex, {algorithm, index, scheme?}]`)
- `encapsulate` — KEM encapsulation (params: `[peer_pubkey_hex, {algorithm}]`)
- `decapsulate` — KEM decapsulation (params: `[ciphertext_hex, {algorithm, index}]`)
- `derive_shared_secret` — ECDH key agreement (params: `[peer_pubkey_hex, {algorithm, index}]`)
- `get_public_key` with `algorithm` parameter — returns structured JSON
Algorithm names: `secp256k1`, `ed25519`, `ml-dsa-65`, `slh-dsa-128s`, `x25519`, `ml-kem-768`
For secp256k1 `sign`/`verify`, the optional `scheme` parameter selects `"schnorr"` (default, BIP-340) or `"ecdsa"`.
Old verb aliases (`sign_data`, `ssh_sign`, `verify_signature`, `kem_encapsulate`, `kem_decapsulate`) map to the new verbs when used with the `algorithm` parameter. Without `algorithm`, they fall through to the role-based path.
See [README.md §4c](../README.md) for full details.
### 4.3 Selector options
The last param may include selector options:
@@ -484,7 +503,228 @@ Decrypt response:
---
## 11. Compatibility notes
## 11. Post-Quantum and Multi-Algorithm Support
n_signer supports six cryptographic algorithms, all derived deterministically
from the same BIP-39 mnemonic via distinct derivation paths:
| Algorithm | Purpose | Curve string | Purpose string | Derivation path |
|---|---|---|---|---|
| `secp256k1` | Nostr (sign_event, NIP-04/44) | `secp256k1` | `nostr` | `m/44'/1237'/<n>'/0/0` (NIP-06) |
| `ed25519` | SSH signing, general signatures | `ed25519` | `ssh` | `m/44'/102001'/<n>'/0'/0'` (SLIP-0010) |
| `x25519` | Key agreement (age, ECDH) | `x25519` | `age` | `m/44'/102002'/<n>'/0'/0'` (SLIP-0010) |
| `ml-dsa-65` | Post-quantum signatures (FIPS 204) | `ml-dsa-65` | `pq-sig` | `m/44'/102003'/<n>'/0'/0'` → seed → PQClean keygen |
| `slh-dsa-128s` | Post-quantum hash-based signatures (FIPS 205) | `slh-dsa-128s` | `pq-sig` | `m/44'/102004'/<n>'/0'/0'` → seed → PQClean keygen |
| `ml-kem-768` | Post-quantum key encapsulation (FIPS 203) | `ml-kem-768` | `pq-kem` | `m/44'/102005'/<n>'/0'/0'` → seed → PQClean keygen |
The `102XXX` coin types are unregistered in SLIP-44 and reserved by n_signer
for PQ/SSH/age algorithm families. All non-secp256k1 paths use SLIP-0010
all-hardened derivation.
### 11.1 Algorithm key sizes
| Algorithm | Pub key | Priv key | Signature | Ciphertext | Shared secret |
|---|---|---|---|---|---|
| secp256k1 | 32 bytes | 32 bytes | 64 bytes | — | — |
| ed25519 | 32 bytes | 32 bytes | 64 bytes | — | — |
| x25519 | 32 bytes | 32 bytes | — | — | 32 bytes |
| ML-DSA-65 | 1952 bytes | 4032 bytes | 3309 bytes | — | — |
| SLH-DSA-128s | 32 bytes | 64 bytes | 7856 bytes | — | — |
| ML-KEM-768 | 1184 bytes | 2400 bytes | — | 1088 bytes | 32 bytes |
PQ public keys and signatures are much larger than classical ones. Clients
must allocate buffers accordingly (ML-DSA-65 pubkey hex = 3904 chars;
SLH-DSA-128s signature hex = 15712 chars; ML-KEM-768 pubkey hex = 2368 chars).
### 11.2 New verbs
| Verb | Purpose | Allowed (purpose, curve) | Description |
|---|---|---|---|
| `sign_data` | pq-sig, ssh | (pq-sig, ml-dsa-65), (pq-sig, slh-dsa-128s), (ssh, ed25519) | Sign arbitrary bytes (not a Nostr event) |
| `verify_signature` | pq-sig, ssh | same as `sign_data` | Verify a signature against the role's public key |
| `ssh_sign` | ssh | (ssh, ed25519) | Sign an SSH authentication challenge (ed25519) |
| `kem_encapsulate` | pq-kem | (pq-kem, ml-kem-768) | Encapsulate: generate ciphertext + shared secret from a peer's ML-KEM public key |
| `kem_decapsulate` | pq-kem | (pq-kem, ml-kem-768) | Decapsulate: recover shared secret from ciphertext using the role's ML-KEM private key |
The existing Nostr verbs (`sign_event`, `nip44_*`, `nip04_*`, `mine_event`)
remain restricted to `purpose=nostr + curve=secp256k1`.
### 11.3 Structured `get_public_key` response format
`get_public_key` is a universal verb — it works for all six algorithms.
**For secp256k1 (backward compatibility):** the result is a plain hex string
(the existing format). Existing Nostr clients are unaffected.
```json
{ "id": "1", "result": "<64-char hex pubkey>" }
```
**For secp256k1 with `format: "structured"` option:** new clients can request
the structured format for consistency:
Request:
```json
{
"id": "1",
"method": "get_public_key",
"params": [{ "role": "main", "format": "structured" }]
}
```
Response:
```json
{
"id": "1",
"result": "{\"algorithm\":\"secp256k1\",\"public_key\":\"<hex>\",\"key_id\":\"<16 hex>\"}"
}
```
**For all other algorithms (ed25519, x25519, ML-DSA-65, SLH-DSA-128s,
ML-KEM-768):** the result is always a structured JSON object serialized as a
string:
```json
{
"id": "1",
"result": {
"algorithm": "ml-dsa-65",
"public_key": "<hex-encoded public key>",
"key_id": "<first 16 hex chars of public key>"
}
}
```
The `key_id` is the first 16 hex characters of the public key — a short
display identifier similar to an SSH key fingerprint. The `result` field is a
JSON string (the object serialized), so clients must parse it twice: once for
the JSON-RPC envelope, once for the result object.
### 11.4 Example: `sign_data` (ML-DSA-65)
Request:
```json
{
"id": "10",
"method": "sign_data",
"params": ["68656c6c6f", { "role": "pq_sig" }]
}
```
Response:
```json
{
"id": "10",
"result": "{\"signature\":\"<hex>\",\"algorithm\":\"ml-dsa-65\"}"
}
```
The first param is the message bytes as hex. The signature is hex-encoded
(3309 bytes = 6618 hex chars for ML-DSA-65).
### 11.5 Example: `verify_signature` (ed25519)
Request:
```json
{
"id": "11",
"method": "verify_signature",
"params": ["<msg_hex>", "<sig_hex>", { "role": "ssh_main" }]
}
```
Response:
```json
{ "id": "11", "result": "{\"valid\":true}" }
```
The signature is verified against the role's derived public key.
### 11.6 Example: `ssh_sign` (ed25519)
Request:
```json
{
"id": "12",
"method": "ssh_sign",
"params": ["<session_id_hex>", { "role": "ssh_main" }]
}
```
Response:
```json
{
"id": "12",
"result": "{\"signature\":\"<hex>\",\"algorithm\":\"ed25519\"}"
}
```
The first param is the SSH session ID (or challenge) as hex. The signature is
a raw ed25519 signature (64 bytes = 128 hex chars).
### 11.7 Example: `kem_encapsulate` (ML-KEM-768)
Request:
```json
{
"id": "13",
"method": "kem_encapsulate",
"params": ["<peer_pubkey_hex>", { "role": "kem_main" }]
}
```
Response:
```json
{
"id": "13",
"result": "{\"ciphertext\":\"<hex>\",\"shared_secret\":\"<hex>\",\"algorithm\":\"ml-kem-768\"}"
}
```
The first param is the peer's ML-KEM-768 public key as hex (1184 bytes = 2368
hex chars). The response contains the ciphertext (1088 bytes = 2176 hex chars)
and the shared secret (32 bytes = 64 hex chars). The encapsulating party keeps
the shared secret; the ciphertext is sent to the decapsulating party.
### 11.8 Example: `kem_decapsulate` (ML-KEM-768)
Request:
```json
{
"id": "14",
"method": "kem_decapsulate",
"params": ["<ciphertext_hex>", { "role": "kem_main" }]
}
```
Response:
```json
{
"id": "14",
"result": "{\"shared_secret\":\"<hex>\",\"algorithm\":\"ml-kem-768\"}"
}
```
The first param is the ciphertext from `kem_encapsulate` (1088 bytes = 2176
hex chars). The decapsulated shared secret will match the encapsulating
party's shared secret.
### 11.9 Example clients
See the `examples/` directory for working C clients demonstrating the new
verbs:
- [`examples/pq_sign_example.c`](../examples/pq_sign_example.c) — ML-DSA-65
`get_public_key` + `sign_data`
- [`examples/pq_kem_example.c`](../examples/pq_kem_example.c) — ML-KEM-768
`get_public_key` + `kem_encapsulate` + `kem_decapsulate` (verifies shared
secrets match)
- [`examples/ssh_sign_example.c`](../examples/ssh_sign_example.c) — ed25519
`get_public_key` + `ssh_sign`
---
## 12. Compatibility notes
- If you are writing an autonomous agent client, pin to explicit socket name and explicit role selector.
- Keep method support feature-detected (`method_not_found` fallback).

View File

@@ -61,13 +61,13 @@ Operational assumptions:
Run `nsigner` in TCP listen mode:
```bash
./build/nsigner --listen tcp:[::]:8080
./build/nsigner --listen tcp:[::]:11111
```
Or bind to a specific FIPS ULA address:
```bash
./build/nsigner --listen tcp:[fd00::1234]:8080
./build/nsigner --listen tcp:[fd00::1234]:11111
```
Behavior notes:

View File

@@ -215,12 +215,18 @@ The signer enforces a strict `(verb, purpose, curve)` matrix:
| Verb | Required purpose | Required curve |
|---|---|---|
| `sign_event` | `nostr` | `secp256k1` |
| `get_public_key` | `nostr` | `secp256k1` |
| `mine_event` | `nostr` | `secp256k1` |
| `nip04_encrypt` / `nip04_decrypt` | `nostr` | `secp256k1` |
| `nip44_encrypt` / `nip44_decrypt` | `nostr` | `secp256k1` |
| `get_public_key` | any | any (must match role's declared curve) |
| `sign_data` | `ssh` or `pq-sig` | `ed25519`, `ml-dsa-65`, or `slh-dsa-128s` |
| `verify_signature` | `ssh` or `pq-sig` | `ed25519`, `ml-dsa-65`, or `slh-dsa-128s` |
| `ssh_sign` | `ssh` | `ed25519` |
| `kem_encapsulate` | `pq-kem` | `ml-kem-768` |
| `kem_decapsulate` | `pq-kem` | `ml-kem-768` |
| Any other verb | rejected | rejected |
A pre-approval to use a Bitcoin-purposed key for `sign_event` does **not** override the enforcement matrix. The approval grants access to the key; enforcement still gates the verb. **Fail-closed**: unknown verbs are rejected, never passed through.
A pre-approval to use a Bitcoin-purposed key for `sign_event` does **not** override the enforcement matrix. The approval grants access to the key; enforcement still gates the verb. **Fail-closed**: unknown verbs and unlisted `(verb, purpose, curve)` combinations are rejected, never passed through.
This is the layer that prevents (for example) a `bitcoin/secp256k1` key from being used to sign a Nostr event even if some pre-approval entry mistakenly named it. The key's *purpose* is part of its identity; you cannot reuse it across domains.
@@ -508,7 +514,86 @@ If any of these statements becomes false in code, that is a security bug worth f
---
## 16. References
---
## 16. Post-Quantum Cryptography
`n_signer` supports three post-quantum algorithms alongside the classical secp256k1, ed25519, and x25519:
- **ML-DSA-65** (FIPS 204) — lattice-based post-quantum digital signatures
- **SLH-DSA-128s** (FIPS 205) — hash-based post-quantum signatures with minimal trust assumptions
- **ML-KEM-768** (FIPS 203) — lattice-based post-quantum key encapsulation mechanism
These are additional options, not replacements for secp256k1. Nostr continues to use secp256k1 exclusively. PQ algorithms are opt-in per role via `purpose="pq-sig"` or `purpose="pq-kem"`. See [`README.md`](../README.md) §4b for the full crypto palette.
### 16.1 PQ threat model
The primary PQ threat is **harvest-now-decrypt-later**: an adversary records encrypted traffic or key agreement exchanges today, stores them, and decrypts them once a sufficiently large quantum computer becomes available. ML-KEM-768 addresses this for key agreement — a session key encapsulated with ML-KEM-768 cannot be recovered by a future quantum adversary.
For signatures, the future risk is **quantum forgery**: a quantum computer could forge classical signatures (ECDSA, Ed25519) given the public key, undermining authentication retroactively. ML-DSA-65 and SLH-DSA-128s address this by providing signatures that resist quantum forgery. The urgency is lower than for key agreement (signatures are forged when needed, not retroactively decrypted), but forward-looking deployments may want PQ signature keys now.
`n_signer` does not claim to defend against all quantum threats. It provides the PQ primitives; the protocol layer (SSH, TLS, Nostr) must adopt them for the protection to be meaningful.
### 16.2 Deterministic PQ key derivation
PQ private keys are not scalars — they are complex mathematical structures (polynomial matrices for lattice schemes, hypertree seeds for hash-based schemes). You cannot use a 32-byte BIP-32 output directly as a PQ private key.
`n_signer` uses a **non-standard** approach to derive PQ keys deterministically from the mnemonic:
1. Derive a 32-byte seed from the mnemonic using BIP-32/SLIP-0010 HMAC-SHA512 at a PQ-specific derivation path (e.g. `m/44'/102003'/<n>'/0'/0'` for ML-DSA-65).
2. Feed that seed into a SHAKE-256 DRBG (NIST SP 800-90A style).
3. Replace PQClean's `randombytes()` callback with this DRBG so keygen is deterministic.
4. The PQ algorithm expands the DRBG output into the full key pair.
**Security argument:**
- The 32-byte seed from BIP-32 derivation carries full 256 bits of entropy (assuming the mnemonic has full entropy).
- SHAKE-256 is a NIST-approved XOF; using it as a DRBG seeded with 256 bits of entropy is sufficient for all three PQ algorithms.
- Each role uses a distinct derivation path (distinct coin types 102003/102004/102005), so compromising one role's PQ key does not compromise others.
**This is non-standard.** There is no NIST or IETF specification for deriving PQ keys from a BIP-39 mnemonic. The approach preserves `n_signer`'s core crash-equals-wipe model: PQ keys are re-derived from the mnemonic on every startup, same as secp256k1. The alternative (random PQ keys with no mnemonic recovery) would break the model.
**Risk:** If a weakness is found in using DRBG output as PQ keygen randomness, all PQ keys derived this way could be affected. Mitigation: per-role distinct derivation paths limit blast radius. The classical algorithms (secp256k1, ed25519, x25519) are unaffected — they do not use the DRBG.
Implementation: [`src/pq_drbg.c`](../src/pq_drbg.c), [`src/pq_crypto.c`](../src/pq_crypto.c).
### 16.3 PQ algorithm maturity
ML-DSA, SLH-DSA, and ML-KEM are FIPS-standardized (FIPS 203, 204, 205) and have undergone extensive NIST scrutiny. However, they are newer than classical algorithms and have less deployment history. They are provided as **additional options**, not replacements. The enforcement matrix (§5.2) ensures PQ keys cannot be used for Nostr operations and vice versa.
### 16.4 SLH-DSA-128s signing latency
SLH-DSA-128s signing on ESP32 can take **530 seconds**. This is a UX consideration, not a security issue. The hash-based signature scheme is intentionally compute-bound (that is its security foundation). On the Feather/CYD firmware, the approval prompt should show a "signing..." indicator during the operation.
The user should choose whether to use SLH-DSA-128s per role. For interactive use where latency matters, ML-DSA-65 is faster. SLH-DSA-128s is appropriate for low-frequency, high-assurance signing where minimal trust assumptions (hash-based, no number-theoretic hardness assumption) are desired.
### 16.5 Key sizes and memory
PQ private keys are large compared to classical keys:
| Algorithm | Private key | Public key | Signature / Ciphertext |
|---|---|---|---|
| secp256k1 | 32 bytes | 32 bytes | 64 bytes (sig) |
| ed25519 | 32 bytes | 32 bytes | 64 bytes (sig) |
| ML-DSA-65 | 4032 bytes | 1952 bytes | 3309 bytes (sig) |
| SLH-DSA-128s | 64 bytes | 32 bytes | 7856 bytes (sig) |
| ML-KEM-768 | 2400 bytes | 1184 bytes | 1088 bytes (ciphertext) |
With `ROLE_TABLE_MAX_ENTRIES` at 256, a full table of ML-DSA-65 keys would use ~1 MB of `mlock`'d memory (4032 × 256 ≈ 1.03 MB for private keys alone). This is acceptable on host. On ESP32 with 512 KB SRAM, this would not fit — on-demand derivation (deriving a PQ key only when a request targets that role) is the recommended pattern. The existing [`crypto_derive_one`](../src/key_store.c) path already supports this.
### 16.6 No hybrid signatures yet
Hybrid signatures (e.g., ed25519 + ML-DSA combined into one signature object) are **future work**. No standard exists for hybrid SSH signatures yet. `n_signer` provides the individual primitives (`sign_data` for ed25519, ML-DSA-65, and SLH-DSA-128s); a hybrid format can be assembled by the client once standards solidify.
### 16.7 PQ key persistence
**PQ keys are NOT persisted.** They are re-derived from the mnemonic on every startup, same as secp256k1. There is no PQ key file, no PQ key database, no PQ key cache on disk. Crash-equals-wipe (§10) applies unchanged: if the process dies, all PQ keys are gone and must be re-derived from the mnemonic on next startup.
This is a deliberate design choice. The deterministic derivation approach (§16.2) makes it possible to recover PQ keys from the mnemonic alone, so persistence would add risk (key material on disk) without adding capability.
---
## 17. References
- [`README.md`](../README.md) — authoritative behavior spec.
- [`plans/nsigner.md`](../plans/nsigner.md) — root design plan and decisions log.
@@ -517,4 +602,5 @@ If any of these statements becomes false in code, that is a security bug worth f
- [`documents/QUBES_OS.md`](QUBES_OS.md) — Qubes RPC integration.
- [`documents/FIPS_DEPLOYMENT.md`](FIPS_DEPLOYMENT.md) — FIPS-mode deployment notes.
- [`plans/seed_phrase_uses.md`](../plans/seed_phrase_uses.md) — what one mnemonic can become.
- [`src/policy.c`](../src/policy.c), [`src/server.c`](../src/server.c), [`src/dispatcher.c`](../src/dispatcher.c), [`src/role_table.c`](../src/role_table.c), [`src/selector.c`](../src/selector.c), [`src/enforcement.c`](../src/enforcement.c) — the security-related code.
- [`plans/post_quantum_crypto.md`](../plans/post_quantum_crypto.md) — post-quantum and multi-algorithm crypto expansion plan.
- [`src/policy.c`](../src/policy.c), [`src/server.c`](../src/server.c), [`src/dispatcher.c`](../src/dispatcher.c), [`src/role_table.c`](../src/role_table.c), [`src/selector.c`](../src/selector.c), [`src/enforcement.c`](../src/enforcement.c), [`src/pq_crypto.c`](../src/pq_crypto.c), [`src/pq_drbg.c`](../src/pq_drbg.c) — the security-related code.

View File

@@ -8,7 +8,7 @@ import time
from coincurve import PrivateKey
HOST = "npub15uqyclnr3er7r8uhka7f0ae2yt4gkjat8gxdan04q0e6xrnwmtjswcyla3.fips"
PORT = 8080
PORT = 11111
# Demo caller key (32 bytes). Replace with your stable caller key in real use.
PRIVKEY = bytes(range(1, 33))

View File

@@ -0,0 +1,110 @@
/*
* get_pubkey_qrexec.c — connect to a running n_signer in another Qubes qube
* via qrexec, using the high-level nostr_signer API from nostr_core_lib.
*
* This demonstrates the new nostr_core_lib client features:
* - nostr_signer_nsigner_qrexec() — qrexec transport
* - nostr_signer_nsigner_set_nostr_index() — index-based key selection
*
* Usage:
* ./get_pubkey_qrexec <target_qube> [nostr_index]
* ./get_pubkey_qrexec nostr_signer 0
* ./get_pubkey_qrexec nostr_signer 1
*
* No auth envelope needed — qrexec identity comes from QREXEC_REMOTE_DOMAIN
* on the server side.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "nostr_common.h"
#include "nostr_signer.h"
#include "nip019.h"
int main(int argc, char **argv) {
const char *target_qube;
const char *service_name = "qubes.NsignerRpc";
int nostr_index = 0;
nostr_signer_t *signer = NULL;
char pubkey_hex[65];
unsigned char pubkey_bytes[32];
char npub[128];
int rc;
if (argc < 2) {
fprintf(stderr, "Usage: %s <target_qube> [nostr_index]\n", argv[0]);
return 1;
}
target_qube = argv[1];
if (argc > 2) {
nostr_index = atoi(argv[2]);
}
if (nostr_init() != NOSTR_SUCCESS) {
fprintf(stderr, "failed to initialize crypto subsystem\n");
return 1;
}
printf("Connecting to n_signer in qube \"%s\" via qrexec (index %d)...\n",
target_qube, nostr_index);
/* Create a high-level signer backed by qrexec transport */
signer = nostr_signer_nsigner_qrexec(target_qube, service_name, NULL, 30000);
if (signer == NULL) {
fprintf(stderr, "failed to create qrexec signer (is qrexec-client-vm available?)\n");
nostr_cleanup();
return 1;
}
/* Select key by nostr_index (NIP-06 m/44'/1237'/N'/0/0) */
if (nostr_signer_nsigner_set_nostr_index(signer, nostr_index) != NOSTR_SUCCESS) {
fprintf(stderr, "failed to set nostr_index\n");
nostr_signer_free(signer);
nostr_cleanup();
return 1;
}
/* Request the public key */
rc = nostr_signer_get_public_key(signer, pubkey_hex);
if (rc != NOSTR_SUCCESS) {
if (rc == NOSTR_ERROR_NSIGNER_INDEX_NOT_ALLOWED) {
fprintf(stderr, "DENIED: index %d is not in the signer's whitelist\n", nostr_index);
} else if (rc == NOSTR_ERROR_NSIGNER_POLICY_DENIED) {
fprintf(stderr, "DENIED: policy denied (caller not approved at signer terminal)\n");
} else {
fprintf(stderr, "get_public_key failed: error code %d\n", rc);
}
nostr_signer_free(signer);
nostr_cleanup();
return 1;
}
/* Convert hex pubkey to npub (bech32) */
{
int i;
for (i = 0; i < 32; i++) {
unsigned int byte;
if (sscanf(pubkey_hex + 2 * i, "%2x", &byte) != 1) {
fprintf(stderr, "failed to parse hex pubkey\n");
nostr_signer_free(signer);
nostr_cleanup();
return 1;
}
pubkey_bytes[i] = (unsigned char)byte;
}
}
if (nostr_key_to_bech32(pubkey_bytes, "npub", npub) != NOSTR_SUCCESS) {
fprintf(stderr, "failed to convert to npub\n");
nostr_signer_free(signer);
nostr_cleanup();
return 1;
}
printf("index %d: hex=%s npub=%s\n", nostr_index, pubkey_hex, npub);
nostr_signer_free(signer);
nostr_cleanup();
return 0;
}

195
examples/get_pubkey_tcp.c Normal file
View File

@@ -0,0 +1,195 @@
/*
* get_pubkey_tcp.c — connect to a running n_signer over TCP and call
* get_public_key for nostr_index 0 and 1, printing both hex pubkey and
* bech32 npub for each.
*
* This is a cross-qube test client for Qubes OS: the signer runs in the
* nostr_signer qube listening on tcp:[::]:11111, and this client runs in
* a different qube connecting to the signer's FIPS address.
*
* Usage:
* ./get_pubkey_tcp <host> <port>
* ./get_pubkey_tcp npub1xxx...fips 11111
*
* If no arguments are given, defaults to localhost:11111.
*
* Output: for each index, prints:
* index 0: hex=<64 hex chars> npub=npub1...
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "nostr_common.h"
#include "nsigner_transport.h"
#include "nsigner_client.h"
#include "nip019.h"
#include "../cjson/cJSON.h"
/* Demo caller key (32 bytes). Replace with your stable caller key in real use. */
static const unsigned char DEMO_PRIVKEY[32] = {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32
};
static int hex_to_bytes(const char *hex, unsigned char *out, size_t out_len) {
size_t len = strlen(hex);
if (len != out_len * 2) {
return -1;
}
for (size_t i = 0; i < out_len; i++) {
unsigned int byte;
if (sscanf(hex + 2 * i, "%2x", &byte) != 1) {
return -1;
}
out[i] = (unsigned char)byte;
}
return 0;
}
static int query_pubkey(const char *host, int port, int nostr_index,
char *out_hex, size_t hex_size, char *out_npub, size_t npub_size) {
(void)npub_size; /* npub buffer size is enforced by nostr_key_to_bech32 output */
nsigner_transport_t *transport = NULL;
nsigner_client_t *client = NULL;
cJSON *params = NULL;
cJSON *opts = NULL;
cJSON *result = NULL;
const char *hex_pubkey = NULL;
unsigned char pubkey_bytes[32];
int rc = -1;
transport = nsigner_transport_open_tcp(host, port, 10000);
if (transport == NULL) {
fprintf(stderr, "connect failed: cannot open TCP transport to %s:%d\n", host, port);
goto cleanup;
}
client = nsigner_client_new(transport);
if (client == NULL) {
fprintf(stderr, "connect failed: cannot create nsigner client\n");
transport->close(transport);
goto cleanup;
}
transport = NULL; /* owned by client now */
/* Set auth envelope — required for TCP listeners */
if (nsigner_client_set_auth(client, DEMO_PRIVKEY, "get_pubkey_tcp") != NOSTR_SUCCESS) {
fprintf(stderr, "failed to set auth envelope\n");
goto cleanup;
}
/* params: [{"nostr_index": N}] */
params = cJSON_CreateArray();
if (params == NULL) {
fprintf(stderr, "out of memory\n");
goto cleanup;
}
opts = cJSON_CreateObject();
if (opts == NULL) {
fprintf(stderr, "out of memory\n");
goto cleanup;
}
cJSON_AddNumberToObject(opts, "nostr_index", nostr_index);
cJSON_AddItemToArray(params, opts);
opts = NULL;
if (nsigner_client_call(client, "get_public_key", params, &result) != NOSTR_SUCCESS) {
fprintf(stderr, "request failed for index %d: %s\n", nostr_index,
nsigner_client_last_error(client));
params = NULL; /* nsigner_client_call took ownership even on failure */
goto cleanup;
}
params = NULL; /* nsigner_client_call took ownership */
if (!cJSON_IsString(result)) {
fprintf(stderr, "index %d: unexpected result type\n", nostr_index);
goto cleanup;
}
hex_pubkey = result->valuestring;
if (strlen(hex_pubkey) != 64) {
fprintf(stderr, "index %d: unexpected pubkey length: %zu\n", nostr_index, strlen(hex_pubkey));
goto cleanup;
}
strncpy(out_hex, hex_pubkey, hex_size - 1);
out_hex[hex_size - 1] = '\0';
/* Convert hex pubkey to npub (bech32) */
if (hex_to_bytes(hex_pubkey, pubkey_bytes, 32) != 0) {
fprintf(stderr, "index %d: failed to parse hex pubkey\n", nostr_index);
goto cleanup;
}
if (nostr_key_to_bech32(pubkey_bytes, "npub", out_npub) != NOSTR_SUCCESS) {
fprintf(stderr, "index %d: failed to convert to npub\n", nostr_index);
goto cleanup;
}
rc = 0;
cleanup:
cJSON_Delete(opts);
cJSON_Delete(params);
cJSON_Delete(result);
nsigner_client_free(client);
return rc;
}
int main(int argc, char **argv) {
const char *host = "127.0.0.1";
int port = 11111;
char hex0[65], npub0[128];
char hex1[65], npub1[128];
int failures = 0;
if (argc > 1) {
host = argv[1];
}
if (argc > 2) {
port = atoi(argv[2]);
if (port <= 0 || port > 65535) {
fprintf(stderr, "Invalid port: %s\n", argv[2]);
return 1;
}
}
if (nostr_init() != NOSTR_SUCCESS) {
fprintf(stderr, "failed to initialize crypto subsystem\n");
return 1;
}
printf("Connecting to n_signer at %s:%d\n", host, port);
printf("Querying get_public_key for nostr_index 0 and 1...\n\n");
/* Query index 0 */
hex0[0] = '\0';
npub0[0] = '\0';
if (query_pubkey(host, port, 0, hex0, sizeof(hex0), npub0, sizeof(npub0)) == 0) {
printf("index 0: hex=%s npub=%s\n", hex0, npub0);
} else {
printf("index 0: FAILED\n");
failures++;
}
/* Query index 1 */
hex1[0] = '\0';
npub1[0] = '\0';
if (query_pubkey(host, port, 1, hex1, sizeof(hex1), npub1, sizeof(npub1)) == 0) {
printf("index 1: hex=%s npub=%s\n", hex1, npub1);
} else {
printf("index 1: FAILED\n");
failures++;
}
nostr_cleanup();
if (failures > 0) {
printf("\n%d query(s) failed\n", failures);
return 1;
}
printf("\nAll queries succeeded\n");
return 0;
}

View File

@@ -1,32 +1,100 @@
/*
* get_public_key_client.c — connect to a running n_signer over its abstract
* UNIX socket and call get_public_key, using the shared nsigner client from
* nostr_core_lib (nostr_core/nsigner_client.h + nostr_core/nsigner_transport.h).
*
* Usage: ./get_public_key_client [socket_name]
*
* Output: the raw JSON-RPC response string, e.g.
* {"id":"1","result":"<pubkey hex>"}
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../client/nsigner_client.h"
#include "nostr_common.h"
#include "nsigner_transport.h"
#include "nsigner_client.h"
#include "../cjson/cJSON.h"
int main(int argc, char **argv) {
const char *socket_name = "nsigner";
nsigner_client_t client;
char *response = NULL;
nsigner_transport_t *transport = NULL;
nsigner_client_t *client = NULL;
cJSON *params = NULL;
cJSON *result = NULL;
cJSON *response = NULL;
char *response_json = NULL;
int rc = 1;
if (argc > 1 && argv[1] != NULL && argv[1][0] != '\0') {
socket_name = argv[1];
}
nsigner_client_init(&client);
if (nsigner_client_connect_unix(&client, socket_name, 5000) != 0) {
fprintf(stderr, "connect failed: %s\n", nsigner_client_last_error(&client));
if (nostr_init() != NOSTR_SUCCESS) {
fprintf(stderr, "failed to initialize crypto subsystem\n");
return 1;
}
if (nsigner_client_get_public_key(&client, "example-1", "", &response) != 0) {
fprintf(stderr, "request failed: %s\n", nsigner_client_last_error(&client));
nsigner_client_close(&client);
return 1;
transport = nsigner_transport_open_unix(socket_name, 5000);
if (transport == NULL) {
fprintf(stderr, "connect failed: cannot open unix transport @%s\n", socket_name);
goto cleanup;
}
printf("%s\n", response);
free(response);
nsigner_client_close(&client);
return 0;
client = nsigner_client_new(transport);
if (client == NULL) {
fprintf(stderr, "connect failed: cannot create nsigner client\n");
/* nsigner_client_new takes ownership of transport on success only */
transport->close(transport);
goto cleanup;
}
transport = NULL; /* owned by client now */
/* params: [] (empty array — server picks the default role) */
params = cJSON_CreateArray();
if (params == NULL) {
fprintf(stderr, "out of memory\n");
goto cleanup;
}
if (nsigner_client_call(client, "get_public_key", params, &result) != NOSTR_SUCCESS) {
fprintf(stderr, "request failed: %s\n", nsigner_client_last_error(client));
goto cleanup;
}
params = NULL; /* nsigner_client_call takes ownership of params */
/*
* Reconstruct a JSON-RPC response string so the CLI output stays
* backward-compatible with the old client example:
* {"id":"<id>","result":"<pubkey hex>"}
* nsigner_client_call returns only the parsed `result` element and does
* not expose the server-assigned id, so we emit a minimal envelope.
*/
response = cJSON_CreateObject();
if (response == NULL) {
fprintf(stderr, "out of memory\n");
goto cleanup;
}
cJSON_AddStringToObject(response, "id", "1");
cJSON_AddItemReferenceToObject(response, "result", result);
response_json = cJSON_PrintUnformatted(response);
if (response_json == NULL) {
fprintf(stderr, "failed to serialize response\n");
goto cleanup;
}
printf("%s\n", response_json);
rc = 0;
cleanup:
free(response_json);
cJSON_Delete(response);
cJSON_Delete(result);
cJSON_Delete(params);
nsigner_client_free(client); /* also closes/frees the transport */
nostr_cleanup();
return rc;
}

View File

@@ -0,0 +1,257 @@
#!/usr/bin/env node
/**
* n_signer_qube_example.js — connect to a running n_signer over TCP (FIPS mesh)
* and call get_public_key for nostr_index 0 and 1, printing both hex pubkey
* and bech32 npub for each.
*
* This is a cross-qube test client for Qubes OS: the signer runs in the
* nostr_signer qube listening on tcp:[::]:11111, and this client runs in
* a different qube connecting to the signer's FIPS address.
*
* Usage:
* node n_signer_qube_example.js [host] [port]
* node n_signer_qube_example.js fd56:d7c3:f605:719d:15b:18a0:fb06:982f 11111
*
* If no arguments are given, defaults to localhost:11111.
*
* Protocol:
* - 4-byte big-endian length prefix + JSON payload (TCP framing)
* - JSON-RPC: {"id":"...","method":"get_public_key","params":[{"nostr_index":N}],"auth":{...}}
* - Auth envelope: kind 27235 Nostr event with nsigner_rpc, nsigner_method,
* nsigner_body_hash tags. body_hash = sha256(json.dumps(params))
* - Response: {"id":"...","result":"<pubkey hex>"} or {"id":"...","error":{...}}
*/
const net = require("net");
const crypto = require("crypto");
const secp = require("@noble/secp256k1");
// @noble/secp256k1 v3 requires us to provide sync sha256/hmacSha256
secp.hashes.sha256 = (msg) => new Uint8Array(crypto.createHash("sha256").update(msg).digest());
secp.hashes.hmacSha256 = (key, msg) =>
new Uint8Array(crypto.createHmac("sha256", key).update(msg).digest());
const { schnorr } = secp;
/** Convert a Uint8Array to a hex string. */
function bytesToHex(bytes) {
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
}
/** Convert a hex string to a Uint8Array. */
function hexToBytes(hex) {
const arr = new Uint8Array(hex.length / 2);
for (let i = 0; i < arr.length; i++) {
arr[i] = parseInt(hex.substr(i * 2, 2), 16);
}
return arr;
}
// Demo caller key (32 bytes). Replace with your stable caller key in real use.
const DEMO_PRIVKEY = new Uint8Array(Array.from({ length: 32 }, (_, i) => i + 1));
/**
* Compute the body hash for a params array.
* This must match n_signer's hashing: sha256 of canonical JSON (no spaces).
*/
function computeBodyHash(params) {
const canonical = JSON.stringify(params);
return crypto.createHash("sha256").update(canonical).digest("hex");
}
/**
* Build a kind-27235 auth envelope for the given method and params.
* Returns the auth object to include in the JSON-RPC request.
*/
function buildAuthEnvelope(privkey, method, params, requestId) {
const bodyHash = computeBodyHash(params);
const pubkeyHex = bytesToHex(schnorr.getPublicKey(privkey));
const createdAt = Math.floor(Date.now() / 1000);
// nsigner_rpc tag value MUST match the JSON-RPC request "id" field
const tags = [
["nsigner_rpc", requestId],
["nsigner_method", method],
["nsigner_body_hash", bodyHash],
];
const content = "js-example";
// Serialize the event for signing: [0, pubkey, created_at, kind, tags, content]
const serialized = JSON.stringify([
0,
pubkeyHex,
createdAt,
27235,
tags,
content,
]);
const eventId = crypto.createHash("sha256").update(serialized).digest("hex");
const sig = bytesToHex(schnorr.sign(hexToBytes(eventId), privkey, new Uint8Array(32)));
return {
id: eventId,
pubkey: pubkeyHex,
created_at: createdAt,
kind: 27235,
tags: tags,
content: content,
sig: sig,
};
}
/**
* Send a framed JSON-RPC request over a TCP socket and receive the response.
* Framing: 4-byte big-endian length prefix + JSON payload.
*/
function sendRequest(socket, request) {
return new Promise((resolve, reject) => {
const payload = Buffer.from(JSON.stringify(request), "utf8");
const header = Buffer.alloc(4);
header.writeUInt32BE(payload.length, 0);
socket.write(Buffer.concat([header, payload]));
let headerBuf = Buffer.alloc(0);
let bodyBuf = Buffer.alloc(0);
let bodyLen = 0;
let state = "header";
const onData = (chunk) => {
if (state === "header") {
headerBuf = Buffer.concat([headerBuf, chunk]);
if (headerBuf.length >= 4) {
bodyLen = headerBuf.readUInt32BE(0);
const remaining = headerBuf.subarray(4);
headerBuf = Buffer.alloc(0);
state = "body";
if (remaining.length > 0) {
bodyBuf = Buffer.concat([bodyBuf, remaining]);
}
if (bodyBuf.length >= bodyLen) {
finish();
}
}
} else if (state === "body") {
bodyBuf = Buffer.concat([bodyBuf, chunk]);
if (bodyBuf.length >= bodyLen) {
finish();
}
}
};
function finish() {
socket.off("data", onData);
socket.off("error", onError);
const body = bodyBuf.subarray(0, bodyLen).toString("utf8");
try {
resolve(JSON.parse(body));
} catch (e) {
reject(new Error(`Failed to parse response: ${e.message}`));
}
}
function onError(err) {
socket.off("data", onData);
reject(err);
}
socket.on("data", onData);
socket.on("error", onError);
});
}
/**
* Query get_public_key for a given nostr_index.
* Opens a fresh TCP connection for each request (n_signer handles one request
* per connection).
*/
async function getPublicKey(host, port, nostrIndex, privkey) {
const params = [{ nostr_index: nostrIndex }];
const requestId = String(nostrIndex);
const auth = buildAuthEnvelope(privkey, "get_public_key", params, requestId);
const request = {
id: requestId,
method: "get_public_key",
params: params,
auth: auth,
};
return new Promise((resolve, reject) => {
const socket = new net.Socket();
socket.setTimeout(15000);
socket.connect(port, host, async () => {
try {
const response = await sendRequest(socket, request);
socket.destroy();
resolve(response);
} catch (e) {
socket.destroy();
reject(e);
}
});
socket.on("timeout", () => {
socket.destroy();
reject(new Error("Connection timed out"));
});
socket.on("error", (err) => {
reject(err);
});
});
}
/**
* Convert a 32-byte hex pubkey to bech32 npub format (NIP-19).
*/
function hexToNpub(pubkeyHex) {
const { nip19 } = require("nostr-tools");
return nip19.npubEncode(pubkeyHex);
}
async function main() {
const host = process.argv[2] || "127.0.0.1";
const port = parseInt(process.argv[3] || "11111", 10);
console.log(`Connecting to n_signer at ${host}:${port}`);
console.log("Querying get_public_key for nostr_index 0 and 1...\n");
let failures = 0;
for (const index of [0, 1]) {
// Small delay between requests to avoid auth nonce collision
// (the auth envelope uses created_at as part of the nonce)
if (index > 0) await new Promise((r) => setTimeout(r, 1100));
try {
const response = await getPublicKey(host, port, index, DEMO_PRIVKEY);
if (response.error) {
console.log(`index ${index}: ERROR: ${JSON.stringify(response.error)}`);
failures++;
continue;
}
const pubkeyHex = response.result;
const npub = hexToNpub(pubkeyHex);
console.log(`index ${index}: hex=${pubkeyHex} npub=${npub}`);
} catch (e) {
console.log(`index ${index}: FAILED - ${e.message}`);
failures++;
}
}
if (failures > 0) {
console.log(`\n${failures} query(s) failed`);
process.exit(1);
}
console.log("\nAll queries succeeded");
}
main().catch((e) => {
console.error(e);
process.exit(1);
});

View File

@@ -0,0 +1,155 @@
#!/usr/bin/env node
/**
* n_signer_qube_example_qrexec.js — connect to n_signer in the nostr_signer
* qube via Qubes qrexec (qubes.NsignerRpc service) and call get_public_key
* for nostr_index 0 and 1, printing both hex pubkey and bech32 npub.
*
* This uses Qubes OS's built-in secure IPC (qrexec) instead of FIPS TCP.
* No network connectivity is required — all traffic stays within the host.
*
* Prerequisites:
* - The qubes.NsignerRpc service must be installed in the nostr_signer qube
* (see packaging/qubes/install-service.sh)
* - The qrexec policy must be installed in dom0
* (see packaging/qubes/install-policy.sh)
* - The nostr_signer qube must be tagged with 'nsigner-signer'
* (qvm-tags nostr_signer add nsigner-signer)
* - A mnemonic file must exist at /home/user/.nsigner_mnemonic in the
* nostr_signer qube
*
* Usage:
* node n_signer_qube_example_qrexec.js [target_qube]
* node n_signer_qube_example_qrexec.js nostr_signer
*
* If no argument is given, defaults to "nostr_signer".
*
* Protocol:
* - qrexec-client-vm spawns the qubes.NsignerRpc service in the target qube
* - The service runs: nsigner --listen qrexec --allow-all --mnemonic-fd 3
* - We send one framed JSON-RPC request via stdin, receive one framed response via stdout
* - Framing: 4-byte big-endian length prefix + JSON payload
* - Auth: not required in qrexec mode (caller identity is qubes:<source-vm>)
*/
const { spawn } = require("child_process");
const { nip19 } = require("nostr-tools");
/**
* Frame a JSON-RPC request: 4-byte big-endian length + JSON payload.
*/
function frameRequest(obj) {
const payload = Buffer.from(JSON.stringify(obj), "utf8");
const header = Buffer.alloc(4);
header.writeUInt32BE(payload.length, 0);
return Buffer.concat([header, payload]);
}
/**
* Parse a framed response from the qrexec stdout buffer.
*/
function parseFramedResponse(buf) {
if (buf.length < 4) {
throw new Error("short response (missing frame header)");
}
const len = buf.readUInt32BE(0);
const payload = buf.subarray(4, 4 + len);
if (payload.length !== len) {
throw new Error(`short response payload: expected ${len}, got ${payload.length}`);
}
return JSON.parse(payload.toString("utf8"));
}
/**
* Call nsigner via qrexec. Sends one framed request, receives one framed response.
* Each call spawns a fresh qrexec-client-vm process (one request per invocation).
*/
function callNsignerQrexec(targetQube, request) {
return new Promise((resolve, reject) => {
const framed = frameRequest(request);
const proc = spawn("qrexec-client-vm", [targetQube, "qubes.NsignerRpc"], {
stdio: ["pipe", "pipe", "pipe"],
});
const stdoutChunks = [];
const stderrChunks = [];
proc.stdout.on("data", (chunk) => stdoutChunks.push(chunk));
proc.stderr.on("data", (chunk) => stderrChunks.push(chunk));
proc.on("error", (err) => {
reject(new Error(`failed to spawn qrexec-client-vm: ${err.message}`));
});
proc.on("close", (code) => {
if (code !== 0) {
const stderr = Buffer.concat(stderrChunks).toString("utf8");
reject(new Error(`qrexec-client-vm exited with code ${code}: ${stderr.trim()}`));
return;
}
try {
const response = parseFramedResponse(Buffer.concat(stdoutChunks));
resolve(response);
} catch (e) {
reject(new Error(`failed to parse response: ${e.message}`));
}
});
// Send the framed request and close stdin
proc.stdin.write(framed);
proc.stdin.end();
});
}
/**
* Query get_public_key for a given nostr_index via qrexec.
* No auth envelope needed — qrexec mode uses qubes:<source-vm> as caller identity.
*/
async function getPublicKey(targetQube, nostrIndex) {
const request = {
id: String(nostrIndex),
method: "get_public_key",
params: [{ nostr_index: nostrIndex }],
};
return callNsignerQrexec(targetQube, request);
}
async function main() {
const targetQube = process.argv[2] || "nostr_signer";
console.log(`Calling n_signer in qube "${targetQube}" via qrexec...`);
console.log("Querying get_public_key for nostr_index 0 and 1...\n");
let failures = 0;
for (const index of [0, 1]) {
try {
const response = await getPublicKey(targetQube, index);
if (response.error) {
console.log(`index ${index}: ERROR: ${JSON.stringify(response.error)}`);
failures++;
continue;
}
const pubkeyHex = response.result;
const npub = nip19.npubEncode(pubkeyHex);
console.log(`index ${index}: hex=${pubkeyHex} npub=${npub}`);
} catch (e) {
console.log(`index ${index}: FAILED - ${e.message}`);
failures++;
}
}
if (failures > 0) {
console.log(`\n${failures} query(s) failed`);
process.exit(1);
}
console.log("\nAll queries succeeded");
}
main().catch((e) => {
console.error(e);
process.exit(1);
});

219
examples/otp_nostr_30078.py Normal file
View File

@@ -0,0 +1,219 @@
#!/usr/bin/env python3
"""
otp_nostr_30078.py — example: encrypt data with OTP, wrap in a Nostr kind 30078
event, sign it with n_signer, and print the signed event for publishing.
Workflow:
1. Call n_signer's `otp_encrypt` verb to encrypt plaintext with the bound OTP pad.
2. Build a Nostr kind 30078 (replaceable parameterized) event with the ASCII-armored
ciphertext as the `content` field.
3. Call n_signer's `sign_event` verb to sign the event with the secp256k1 key.
4. Print the signed event JSON, ready to publish to Nostr relays.
This is a demo — it does not actually publish to a relay. To publish, send the
signed event to your preferred Nostr relay using a library like nostr-tools,
nostril, or nak.
Usage:
python3 examples/otp_nostr_30078.py "Your secret message here"
Requirements:
- n_signer running with --otp-pad-dir / --otp-pad bound, and a secp256k1
role (e.g. "main") available for sign_event.
- This script connects to n_signer via stdio (one process per request).
See plans/otp_nostr_integration.md for the full design.
"""
import base64
import hashlib
import json
import os
import struct
import subprocess
import sys
import time
NSIGNER = "./build/nsigner"
PAD_DIR = "/media/user/Music/pads"
PAD_SPEC = "333e9902db839d9d"
MNEMONIC_FILE = ".test_mnemonic"
MNEMONIC_TMP = ".test_mnemonic_otp_30078.tmp"
def send_framed(proc, obj):
payload = json.dumps(obj).encode()
proc.stdin.write(struct.pack(">I", len(payload)))
proc.stdin.write(payload)
proc.stdin.flush()
def recv_framed(proc):
"""Read a framed response, skipping any banner text on stdout."""
buf = b""
while True:
b = proc.stdout.read(1)
if not b:
return None
buf = (buf + b)[-4:]
if len(buf) < 4:
continue
(length,) = struct.unpack(">I", buf)
if 1 <= length <= 1024 * 1024:
peek = proc.stdout.read(1)
if peek == b"{":
body = peek + proc.stdout.read(length - 1)
return json.loads(body.decode())
else:
buf = (buf + peek)[-4:]
def run_one_request(req_obj):
"""Run nsigner in stdio mode for a single framed request/response."""
shell_cmd = (
f"exec 3<{MNEMONIC_TMP}; "
f"exec {NSIGNER} --listen stdio --mnemonic-fd 3 "
f"--otp-pad-dir {PAD_DIR} --otp-pad {PAD_SPEC} "
f"--otp-allow-blkback --allow-all"
)
proc = subprocess.Popen(
["bash", "-c", shell_cmd],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
)
import time as _time
_time.sleep(1.0)
if proc.poll() is not None:
err = proc.stderr.read().decode()
print(f"ERROR: nsigner exited early (code {proc.returncode})")
print(f"stderr: {err}")
return None
send_framed(proc, req_obj)
resp = recv_framed(proc)
proc.stdin.close()
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
return resp
def compute_event_id(event):
"""Compute the Nostr event ID (SHA-256 of the canonical serialized event)."""
# Nostr event serialization: [0, pubkey, created_at, kind, tags, content]
serialized = json.dumps([
0,
event["pubkey"],
event["created_at"],
event["kind"],
event["tags"],
event["content"],
], separators=(",", ":"), ensure_ascii=False)
return hashlib.sha256(serialized.encode()).hexdigest()
def main():
plaintext = " ".join(sys.argv[1:]) if len(sys.argv) > 1 else "Secret OTP message"
print(f"Plaintext: {plaintext}")
# Prepare the mnemonic temp file.
with open(MNEMONIC_FILE) as f:
mnemonic = f.read().strip()
with open(MNEMONIC_TMP, "w") as f:
f.write(mnemonic + "\n")
try:
# Step 1: Get the public key for the "main" role
print("\n=== Step 1: get_public_key ===")
resp = run_one_request({
"id": "1",
"method": "get_public_key",
"params": [{"role": "main"}],
})
if resp is None or "result" not in resp:
print("ERROR: get_public_key failed")
print(f"Response: {resp}")
return 1
# The result is a plain hex string for secp256k1 backward compat.
pubkey_hex = resp["result"].strip('"')
print(f"Public key: {pubkey_hex}")
# Step 2: Encrypt the plaintext with OTP
print("\n=== Step 2: otp_encrypt ===")
pt_b64 = base64.b64encode(plaintext.encode()).decode()
resp = run_one_request({
"id": "2",
"method": "otp_encrypt",
"params": [pt_b64, {"encoding": "ascii"}],
})
if resp is None or "result" not in resp:
print("ERROR: otp_encrypt failed")
print(f"Response: {resp}")
return 1
enc_result = json.loads(resp["result"])
ciphertext = enc_result["ciphertext"]
pad_chksum = enc_result["pad_chksum"]
pad_offset = enc_result["pad_offset_after"]
print(f"Pad checksum: {pad_chksum}")
print(f"Pad offset after encrypt: {pad_offset}")
print(f"Ciphertext (first 60 chars): {ciphertext[:60]}...")
# Step 3: Build the Nostr kind 30078 event
print("\n=== Step 3: Build kind 30078 event ===")
# Use a unique d-tag based on the pad checksum and offset.
d_tag = f"otp-{pad_chksum[:16]}-{pad_offset}"
event = {
"pubkey": pubkey_hex,
"created_at": int(time.time()),
"kind": 30078,
"tags": [
["d", d_tag],
["otp-pad", pad_chksum[:16]],
["otp-version", "v0.0.2-otp"],
["otp-encoding", "ascii"],
],
"content": ciphertext,
}
# Compute the event ID.
event_id = compute_event_id(event)
event["id"] = event_id
print(f"Event ID: {event_id}")
print(f"d-tag: {d_tag}")
# Step 4: Sign the event with n_signer
print("\n=== Step 4: sign_event ===")
# sign_event expects the event JSON as the first param (without id/sig).
# The signer computes the id and signature internally.
event_for_signing = {
"pubkey": event["pubkey"],
"created_at": event["created_at"],
"kind": event["kind"],
"tags": event["tags"],
"content": event["content"],
}
resp = run_one_request({
"id": "3",
"method": "sign_event",
"params": [json.dumps(event_for_signing), {"role": "main"}],
})
if resp is None or "result" not in resp:
print("ERROR: sign_event failed")
print(f"Response: {resp}")
return 1
sig = resp["result"].strip('"')
event["sig"] = sig
print(f"Signature: {sig[:60]}...")
# Step 5: Print the signed event
print("\n=== Signed Nostr event (ready to publish) ===")
print(json.dumps(event, indent=2))
print(f"\nTo publish: send this event to a Nostr relay.")
print(f"To decrypt: call otp_decrypt with the content field.")
return 0
finally:
try:
os.unlink(MNEMONIC_TMP)
except OSError:
pass
if __name__ == "__main__":
sys.exit(main())

273
examples/pq_kem_example.c Normal file
View File

@@ -0,0 +1,273 @@
/*
* pq_kem_example.c — connect to a running n_signer over its abstract UNIX
* socket and demonstrate post-quantum key encapsulation with ML-KEM-768.
*
* The example:
* 1. Sends a get_public_key request for an ML-KEM-768 role ("kem_main").
* 2. Prints the structured public key (algorithm, public_key, key_id).
* 3. Sends a kem_encapsulate request with the public key, obtaining a
* ciphertext + shared secret.
* 4. Sends a kem_decapsulate request with the ciphertext, recovering the
* shared secret on the signer side.
* 5. Prints both shared secrets — they should match.
*
* Prerequisites:
* - n_signer must be running with a role configured for purpose=pq-kem,
* curve=ml-kem-768, named "kem_main" (or pass the role name as the 2nd arg).
* - A mnemonic must be loaded in the signer.
*
* Usage: ./pq_kem_example [socket_name] [role_name]
*
* Default socket_name: nsigner
* Default role_name: kem_main
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "nostr_common.h"
#include "nsigner_transport.h"
#include "nsigner_client.h"
#include "../cjson/cJSON.h"
static int get_structured_pubkey(nsigner_client_t *client, const char *role,
char **out_pub_hex) {
cJSON *params = NULL;
cJSON *opts = NULL;
cJSON *result = NULL;
cJSON *parsed = NULL;
int rc = -1;
*out_pub_hex = NULL;
params = cJSON_CreateArray();
if (params == NULL) return -1;
opts = cJSON_CreateObject();
if (opts == NULL) {
cJSON_Delete(params);
return -1;
}
cJSON_AddStringToObject(opts, "role", role);
cJSON_AddItemToArray(params, opts);
opts = NULL;
if (nsigner_client_call(client, "get_public_key", params, &result) != NOSTR_SUCCESS) {
cJSON_Delete(params);
return -1;
}
params = NULL;
if (cJSON_IsString(result)) {
parsed = cJSON_Parse(result->valuestring);
if (parsed != NULL) {
cJSON *pk_item = cJSON_GetObjectItemCaseSensitive(parsed, "public_key");
if (cJSON_IsString(pk_item)) {
*out_pub_hex = strdup(pk_item->valuestring);
rc = 0;
}
}
}
cJSON_Delete(parsed);
cJSON_Delete(result);
cJSON_Delete(params);
return rc;
}
/* kem_encapsulate: returns ciphertext_hex and shared_secret_hex (newly
* allocated, caller frees). */
static int kem_encapsulate(nsigner_client_t *client, const char *role,
const char *pub_hex,
char **out_ct_hex, char **out_ss_hex) {
cJSON *params = NULL;
cJSON *opts = NULL;
cJSON *result = NULL;
int rc = -1;
*out_ct_hex = NULL;
*out_ss_hex = NULL;
params = cJSON_CreateArray();
if (params == NULL) return -1;
cJSON_AddItemToArray(params, cJSON_CreateString(pub_hex));
opts = cJSON_CreateObject();
if (opts == NULL) {
cJSON_Delete(params);
return -1;
}
cJSON_AddStringToObject(opts, "role", role);
cJSON_AddItemToArray(params, opts);
opts = NULL;
if (nsigner_client_call(client, "kem_encapsulate", params, &result) != NOSTR_SUCCESS) {
cJSON_Delete(params);
return -1;
}
params = NULL;
if (cJSON_IsString(result)) {
cJSON *parsed = cJSON_Parse(result->valuestring);
if (parsed != NULL) {
cJSON *ct_item = cJSON_GetObjectItemCaseSensitive(parsed, "ciphertext");
cJSON *ss_item = cJSON_GetObjectItemCaseSensitive(parsed, "shared_secret");
if (cJSON_IsString(ct_item) && cJSON_IsString(ss_item)) {
*out_ct_hex = strdup(ct_item->valuestring);
*out_ss_hex = strdup(ss_item->valuestring);
if (*out_ct_hex != NULL && *out_ss_hex != NULL) {
rc = 0;
}
}
cJSON_Delete(parsed);
}
}
cJSON_Delete(result);
cJSON_Delete(params);
return rc;
}
static char *kem_decapsulate(nsigner_client_t *client, const char *role,
const char *ct_hex) {
cJSON *params = NULL;
cJSON *opts = NULL;
cJSON *result = NULL;
char *ss_hex = NULL;
params = cJSON_CreateArray();
if (params == NULL) return NULL;
cJSON_AddItemToArray(params, cJSON_CreateString(ct_hex));
opts = cJSON_CreateObject();
if (opts == NULL) {
cJSON_Delete(params);
return NULL;
}
cJSON_AddStringToObject(opts, "role", role);
cJSON_AddItemToArray(params, opts);
opts = NULL;
if (nsigner_client_call(client, "kem_decapsulate", params, &result) != NOSTR_SUCCESS) {
cJSON_Delete(params);
return NULL;
}
params = NULL;
if (cJSON_IsString(result)) {
cJSON *parsed = cJSON_Parse(result->valuestring);
if (parsed != NULL) {
cJSON *ss_item = cJSON_GetObjectItemCaseSensitive(parsed, "shared_secret");
if (cJSON_IsString(ss_item)) {
ss_hex = strdup(ss_item->valuestring);
}
cJSON_Delete(parsed);
}
}
cJSON_Delete(result);
cJSON_Delete(params);
return ss_hex;
}
int main(int argc, char **argv) {
const char *socket_name = "nsigner";
const char *role = "kem_main";
nsigner_transport_t *transport = NULL;
nsigner_client_t *client = NULL;
char *pub_hex = NULL;
char *ct_hex = NULL;
char *encap_ss_hex = NULL;
char *decap_ss_hex = NULL;
int rc = 1;
if (argc > 1 && argv[1] != NULL && argv[1][0] != '\0') {
socket_name = argv[1];
}
if (argc > 2 && argv[2] != NULL && argv[2][0] != '\0') {
role = argv[2];
}
if (nostr_init() != NOSTR_SUCCESS) {
fprintf(stderr, "failed to initialize crypto subsystem\n");
return 1;
}
transport = nsigner_transport_open_unix(socket_name, 10000);
if (transport == NULL) {
fprintf(stderr, "connect failed: cannot open unix transport @%s\n", socket_name);
goto cleanup;
}
client = nsigner_client_new(transport);
if (client == NULL) {
fprintf(stderr, "connect failed: cannot create nsigner client\n");
transport->close(transport);
goto cleanup;
}
transport = NULL;
printf("=== PQ KEM Example (ML-KEM-768) ===\n");
printf("socket: %s\n", socket_name);
printf("role: %s\n", role);
printf("\n");
/* 1. Get the ML-KEM-768 public key. */
if (get_structured_pubkey(client, role, &pub_hex) != 0 || pub_hex == NULL) {
fprintf(stderr, "get_public_key failed: %s\n",
nsigner_client_last_error(client));
goto cleanup;
}
printf("Public Key:\n");
printf(" pub_len: %zu hex chars (%zu bytes)\n",
strlen(pub_hex), strlen(pub_hex) / 2);
printf(" pub_head: %.64s...\n", pub_hex);
printf("\n");
/* 2. Encapsulate with the public key. */
printf("Encapsulating with public key...\n");
if (kem_encapsulate(client, role, pub_hex, &ct_hex, &encap_ss_hex) != 0) {
fprintf(stderr, "kem_encapsulate failed: %s\n",
nsigner_client_last_error(client));
goto cleanup;
}
printf("Ciphertext:\n");
printf(" ct_len: %zu hex chars (%zu bytes)\n",
strlen(ct_hex), strlen(ct_hex) / 2);
printf(" ct_head: %.64s...\n", ct_hex);
printf("Encapsulated shared secret:\n");
printf(" ss: %s\n", encap_ss_hex);
printf("\n");
/* 3. Decapsulate with the ciphertext (uses the role's private key). */
printf("Decapsulating ciphertext on signer side...\n");
decap_ss_hex = kem_decapsulate(client, role, ct_hex);
if (decap_ss_hex == NULL) {
fprintf(stderr, "kem_decapsulate failed: %s\n",
nsigner_client_last_error(client));
goto cleanup;
}
printf("Decapsulated shared secret:\n");
printf(" ss: %s\n", decap_ss_hex);
printf("\n");
/* 4. Verify the shared secrets match. */
if (strcmp(encap_ss_hex, decap_ss_hex) == 0) {
printf("SUCCESS: shared secrets match!\n");
rc = 0;
} else {
printf("FAILURE: shared secrets do NOT match!\n");
}
cleanup:
free(pub_hex);
free(ct_hex);
free(encap_ss_hex);
free(decap_ss_hex);
nsigner_client_free(client);
nostr_cleanup();
return rc;
}

215
examples/pq_sign_example.c Normal file
View File

@@ -0,0 +1,215 @@
/*
* pq_sign_example.c — connect to a running n_signer over its abstract UNIX
* socket and demonstrate post-quantum signing with ML-DSA-65.
*
* The example:
* 1. Sends a get_public_key request for an ML-DSA-65 role ("pq_sig").
* 2. Prints the structured public key (algorithm, public_key, key_id).
* 3. Sends a sign_data request with a test message.
* 4. Prints the signature (hex) and algorithm.
*
* Prerequisites:
* - n_signer must be running with a role configured for purpose=pq-sig,
* curve=ml-dsa-65, named "pq_sig" (or pass the role name as the 2nd arg).
* - A mnemonic must be loaded in the signer.
*
* Usage: ./pq_sign_example [socket_name] [role_name]
*
* Default socket_name: nsigner
* Default role_name: pq_sig
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "nostr_common.h"
#include "nsigner_transport.h"
#include "nsigner_client.h"
#include "../cjson/cJSON.h"
static int get_structured_pubkey(nsigner_client_t *client, const char *role,
cJSON **out_obj) {
cJSON *params = NULL;
cJSON *opts = NULL;
cJSON *result = NULL;
cJSON *parsed = NULL;
int rc = -1;
*out_obj = NULL;
params = cJSON_CreateArray();
if (params == NULL) return -1;
opts = cJSON_CreateObject();
if (opts == NULL) {
cJSON_Delete(params);
return -1;
}
cJSON_AddStringToObject(opts, "role", role);
cJSON_AddItemToArray(params, opts);
opts = NULL;
if (nsigner_client_call(client, "get_public_key", params, &result) != NOSTR_SUCCESS) {
cJSON_Delete(params);
return -1;
}
params = NULL;
/* result is a cJSON string containing the serialized structured object. */
if (cJSON_IsString(result)) {
parsed = cJSON_Parse(result->valuestring);
if (parsed != NULL && cJSON_IsObject(parsed)) {
*out_obj = parsed;
parsed = NULL;
rc = 0;
}
}
cJSON_Delete(parsed);
cJSON_Delete(result);
cJSON_Delete(params);
return rc;
}
static char *sign_data(nsigner_client_t *client, const char *role,
const char *msg_hex) {
cJSON *params = NULL;
cJSON *opts = NULL;
cJSON *result = NULL;
char *sig_hex = NULL;
params = cJSON_CreateArray();
if (params == NULL) return NULL;
cJSON_AddItemToArray(params, cJSON_CreateString(msg_hex));
opts = cJSON_CreateObject();
if (opts == NULL) {
cJSON_Delete(params);
return NULL;
}
cJSON_AddStringToObject(opts, "role", role);
cJSON_AddItemToArray(params, opts);
opts = NULL;
if (nsigner_client_call(client, "sign_data", params, &result) != NOSTR_SUCCESS) {
cJSON_Delete(params);
return NULL;
}
params = NULL;
/* result is a string containing {"signature":"<hex>","algorithm":"<alg>"} */
if (cJSON_IsString(result)) {
cJSON *parsed = cJSON_Parse(result->valuestring);
if (parsed != NULL) {
cJSON *sig_item = cJSON_GetObjectItemCaseSensitive(parsed, "signature");
if (cJSON_IsString(sig_item)) {
sig_hex = strdup(sig_item->valuestring);
}
cJSON_Delete(parsed);
}
}
cJSON_Delete(result);
cJSON_Delete(params);
return sig_hex;
}
int main(int argc, char **argv) {
const char *socket_name = "nsigner";
const char *role = "pq_sig";
/* "hello post-quantum world" in hex */
const char *msg_hex = "68656c6c6f20706f73742d7175616e74756d20776f726c64";
nsigner_transport_t *transport = NULL;
nsigner_client_t *client = NULL;
cJSON *pubkey_obj = NULL;
char *sig_hex = NULL;
int rc = 1;
if (argc > 1 && argv[1] != NULL && argv[1][0] != '\0') {
socket_name = argv[1];
}
if (argc > 2 && argv[2] != NULL && argv[2][0] != '\0') {
role = argv[2];
}
if (nostr_init() != NOSTR_SUCCESS) {
fprintf(stderr, "failed to initialize crypto subsystem\n");
return 1;
}
transport = nsigner_transport_open_unix(socket_name, 10000);
if (transport == NULL) {
fprintf(stderr, "connect failed: cannot open unix transport @%s\n", socket_name);
goto cleanup;
}
client = nsigner_client_new(transport);
if (client == NULL) {
fprintf(stderr, "connect failed: cannot create nsigner client\n");
transport->close(transport);
goto cleanup;
}
transport = NULL;
printf("=== PQ Sign Example (ML-DSA-65) ===\n");
printf("socket: %s\n", socket_name);
printf("role: %s\n", role);
printf("\n");
/* 1. Get the structured public key. */
if (get_structured_pubkey(client, role, &pubkey_obj) != 0 || pubkey_obj == NULL) {
fprintf(stderr, "get_public_key failed: %s\n",
nsigner_client_last_error(client));
goto cleanup;
}
{
cJSON *alg_item = cJSON_GetObjectItemCaseSensitive(pubkey_obj, "algorithm");
cJSON *pk_item = cJSON_GetObjectItemCaseSensitive(pubkey_obj, "public_key");
cJSON *kid_item = cJSON_GetObjectItemCaseSensitive(pubkey_obj, "key_id");
printf("Public Key:\n");
printf(" algorithm: %s\n",
(cJSON_IsString(alg_item)) ? alg_item->valuestring : "?");
printf(" key_id: %s\n",
(cJSON_IsString(kid_item)) ? kid_item->valuestring : "?");
if (cJSON_IsString(pk_item)) {
/* ML-DSA-65 public key is 3904 hex chars — print length + prefix. */
printf(" pub_len: %zu hex chars (%zu bytes)\n",
strlen(pk_item->valuestring), strlen(pk_item->valuestring) / 2);
printf(" pub_head: %.64s...\n", pk_item->valuestring);
} else {
printf(" public_key: (missing)\n");
}
}
printf("\n");
/* 2. Sign a test message. */
printf("Signing message (hex): %s\n", msg_hex);
sig_hex = sign_data(client, role, msg_hex);
if (sig_hex == NULL) {
fprintf(stderr, "sign_data failed: %s\n",
nsigner_client_last_error(client));
goto cleanup;
}
printf("Signature:\n");
printf(" sig_len: %zu hex chars (%zu bytes)\n",
strlen(sig_hex), strlen(sig_hex) / 2);
printf(" sig_head: %.64s...\n", sig_hex);
printf("\n");
printf("To verify externally, use ML-DSA-65 (FIPS 204) verify with the\n");
printf("public key above, the message, and this signature.\n");
rc = 0;
cleanup:
free(sig_hex);
cJSON_Delete(pubkey_obj);
nsigner_client_free(client);
nostr_cleanup();
return rc;
}

View File

@@ -1,33 +1,114 @@
/*
* sign_event_client.c — connect to a running n_signer over its abstract
* UNIX socket and call sign_event, using the shared nsigner client from
* nostr_core_lib (nostr_core/nsigner_client.h + nostr_core/nsigner_transport.h).
*
* Usage: ./sign_event_client [socket_name]
*
* Output: the raw JSON-RPC response string, e.g.
* {"id":"1","result":"{...signed event...}"}
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../client/nsigner_client.h"
#include "nostr_common.h"
#include "nsigner_transport.h"
#include "nsigner_client.h"
#include "../cjson/cJSON.h"
int main(int argc, char **argv) {
const char *socket_name = "nsigner";
const char *event_json = "{\"kind\":1,\"content\":\"hello from client example\",\"tags\":[],\"created_at\":1700000000}";
nsigner_client_t client;
char *response = NULL;
const char *role = "main";
nsigner_transport_t *transport = NULL;
nsigner_client_t *client = NULL;
cJSON *params = NULL;
cJSON *opts = NULL;
cJSON *result = NULL;
cJSON *response = NULL;
char *response_json = NULL;
int rc = 1;
if (argc > 1 && argv[1] != NULL && argv[1][0] != '\0') {
socket_name = argv[1];
}
nsigner_client_init(&client);
if (nsigner_client_connect_unix(&client, socket_name, 5000) != 0) {
fprintf(stderr, "connect failed: %s\n", nsigner_client_last_error(&client));
if (nostr_init() != NOSTR_SUCCESS) {
fprintf(stderr, "failed to initialize crypto subsystem\n");
return 1;
}
if (nsigner_client_sign_event(&client, "example-2", event_json, "main", &response) != 0) {
fprintf(stderr, "request failed: %s\n", nsigner_client_last_error(&client));
nsigner_client_close(&client);
return 1;
transport = nsigner_transport_open_unix(socket_name, 5000);
if (transport == NULL) {
fprintf(stderr, "connect failed: cannot open unix transport @%s\n", socket_name);
goto cleanup;
}
printf("%s\n", response);
free(response);
nsigner_client_close(&client);
return 0;
client = nsigner_client_new(transport);
if (client == NULL) {
fprintf(stderr, "connect failed: cannot create nsigner client\n");
transport->close(transport);
goto cleanup;
}
transport = NULL; /* owned by client now */
/* params: [ "<event_json>", {"role":"main"} ] */
params = cJSON_CreateArray();
if (params == NULL) {
fprintf(stderr, "out of memory\n");
goto cleanup;
}
cJSON_AddItemToArray(params, cJSON_CreateString(event_json));
opts = cJSON_CreateObject();
if (opts == NULL) {
fprintf(stderr, "out of memory\n");
goto cleanup;
}
if (role != NULL && role[0] != '\0') {
cJSON_AddStringToObject(opts, "role", role);
}
cJSON_AddItemToArray(params, opts);
opts = NULL; /* owned by params now */
if (nsigner_client_call(client, "sign_event", params, &result) != NOSTR_SUCCESS) {
fprintf(stderr, "request failed: %s\n", nsigner_client_last_error(client));
goto cleanup;
}
params = NULL; /* nsigner_client_call takes ownership of params */
/*
* Reconstruct a JSON-RPC response string for backward-compatible CLI
* output: {"id":"1","result":"<signed event json>"}
* The server returns the signed event as a JSON string (not an object),
* so result is a cJSON string here.
*/
response = cJSON_CreateObject();
if (response == NULL) {
fprintf(stderr, "out of memory\n");
goto cleanup;
}
cJSON_AddStringToObject(response, "id", "1");
cJSON_AddItemReferenceToObject(response, "result", result);
response_json = cJSON_PrintUnformatted(response);
if (response_json == NULL) {
fprintf(stderr, "failed to serialize response\n");
goto cleanup;
}
printf("%s\n", response_json);
rc = 0;
cleanup:
free(response_json);
cJSON_Delete(response);
cJSON_Delete(result);
cJSON_Delete(params);
cJSON_Delete(opts);
nsigner_client_free(client); /* also closes/frees the transport */
nostr_cleanup();
return rc;
}

212
examples/ssh_sign_example.c Normal file
View File

@@ -0,0 +1,212 @@
/*
* ssh_sign_example.c — connect to a running n_signer over its abstract UNIX
* socket and demonstrate SSH signing with ed25519.
*
* The example:
* 1. Sends a get_public_key request for an SSH/ed25519 role ("ssh_main").
* 2. Prints the structured public key (algorithm, public_key, key_id).
* 3. Sends an ssh_sign request with a test session ID.
* 4. Prints the signature (hex) and algorithm.
*
* Prerequisites:
* - n_signer must be running with a role configured for purpose=ssh,
* curve=ed25519, named "ssh_main" (or pass the role name as the 2nd arg).
* - A mnemonic must be loaded in the signer.
*
* Usage: ./ssh_sign_example [socket_name] [role_name]
*
* Default socket_name: nsigner
* Default role_name: ssh_main
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "nostr_common.h"
#include "nsigner_transport.h"
#include "nsigner_client.h"
#include "../cjson/cJSON.h"
static int get_structured_pubkey(nsigner_client_t *client, const char *role,
char **out_pub_hex, char **out_key_id) {
cJSON *params = NULL;
cJSON *opts = NULL;
cJSON *result = NULL;
cJSON *parsed = NULL;
int rc = -1;
*out_pub_hex = NULL;
*out_key_id = NULL;
params = cJSON_CreateArray();
if (params == NULL) return -1;
opts = cJSON_CreateObject();
if (opts == NULL) {
cJSON_Delete(params);
return -1;
}
cJSON_AddStringToObject(opts, "role", role);
cJSON_AddItemToArray(params, opts);
opts = NULL;
if (nsigner_client_call(client, "get_public_key", params, &result) != NOSTR_SUCCESS) {
cJSON_Delete(params);
return -1;
}
params = NULL;
if (cJSON_IsString(result)) {
parsed = cJSON_Parse(result->valuestring);
if (parsed != NULL) {
cJSON *pk_item = cJSON_GetObjectItemCaseSensitive(parsed, "public_key");
cJSON *kid_item = cJSON_GetObjectItemCaseSensitive(parsed, "key_id");
if (cJSON_IsString(pk_item)) {
*out_pub_hex = strdup(pk_item->valuestring);
}
if (cJSON_IsString(kid_item)) {
*out_key_id = strdup(kid_item->valuestring);
}
if (*out_pub_hex != NULL) {
rc = 0;
}
}
}
cJSON_Delete(parsed);
cJSON_Delete(result);
cJSON_Delete(params);
return rc;
}
static char *ssh_sign(nsigner_client_t *client, const char *role,
const char *msg_hex) {
cJSON *params = NULL;
cJSON *opts = NULL;
cJSON *result = NULL;
char *sig_hex = NULL;
params = cJSON_CreateArray();
if (params == NULL) return NULL;
cJSON_AddItemToArray(params, cJSON_CreateString(msg_hex));
opts = cJSON_CreateObject();
if (opts == NULL) {
cJSON_Delete(params);
return NULL;
}
cJSON_AddStringToObject(opts, "role", role);
cJSON_AddItemToArray(params, opts);
opts = NULL;
if (nsigner_client_call(client, "ssh_sign", params, &result) != NOSTR_SUCCESS) {
cJSON_Delete(params);
return NULL;
}
params = NULL;
if (cJSON_IsString(result)) {
cJSON *parsed = cJSON_Parse(result->valuestring);
if (parsed != NULL) {
cJSON *sig_item = cJSON_GetObjectItemCaseSensitive(parsed, "signature");
if (cJSON_IsString(sig_item)) {
sig_hex = strdup(sig_item->valuestring);
}
cJSON_Delete(parsed);
}
}
cJSON_Delete(result);
cJSON_Delete(params);
return sig_hex;
}
int main(int argc, char **argv) {
const char *socket_name = "nsigner";
const char *role = "ssh_main";
/* A fake SSH session ID (32 bytes = 64 hex chars) for demonstration. */
const char *session_id_hex =
"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
nsigner_transport_t *transport = NULL;
nsigner_client_t *client = NULL;
char *pub_hex = NULL;
char *key_id = NULL;
char *sig_hex = NULL;
int rc = 1;
if (argc > 1 && argv[1] != NULL && argv[1][0] != '\0') {
socket_name = argv[1];
}
if (argc > 2 && argv[2] != NULL && argv[2][0] != '\0') {
role = argv[2];
}
if (nostr_init() != NOSTR_SUCCESS) {
fprintf(stderr, "failed to initialize crypto subsystem\n");
return 1;
}
transport = nsigner_transport_open_unix(socket_name, 10000);
if (transport == NULL) {
fprintf(stderr, "connect failed: cannot open unix transport @%s\n", socket_name);
goto cleanup;
}
client = nsigner_client_new(transport);
if (client == NULL) {
fprintf(stderr, "connect failed: cannot create nsigner client\n");
transport->close(transport);
goto cleanup;
}
transport = NULL;
printf("=== SSH Sign Example (ed25519) ===\n");
printf("socket: %s\n", socket_name);
printf("role: %s\n", role);
printf("\n");
/* 1. Get the ed25519 public key. */
if (get_structured_pubkey(client, role, &pub_hex, &key_id) != 0 ||
pub_hex == NULL) {
fprintf(stderr, "get_public_key failed: %s\n",
nsigner_client_last_error(client));
goto cleanup;
}
printf("Public Key:\n");
printf(" algorithm: ed25519\n");
printf(" key_id: %s\n", (key_id != NULL) ? key_id : "?");
printf(" pub_len: %zu hex chars (%zu bytes)\n",
strlen(pub_hex), strlen(pub_hex) / 2);
printf(" pubkey: %s\n", pub_hex);
printf("\n");
/* 2. Sign a test SSH session ID. */
printf("Signing SSH session ID (hex): %s\n", session_id_hex);
sig_hex = ssh_sign(client, role, session_id_hex);
if (sig_hex == NULL) {
fprintf(stderr, "ssh_sign failed: %s\n",
nsigner_client_last_error(client));
goto cleanup;
}
printf("Signature:\n");
printf(" sig_len: %zu hex chars (%zu bytes)\n",
strlen(sig_hex), strlen(sig_hex) / 2);
printf(" sig: %s\n", sig_hex);
printf("\n");
printf("This ed25519 signature can be verified with the public key above\n");
printf("using standard ed25519 verify (e.g. libsodium, OpenSSL EVP_DigestVerify).\n");
rc = 0;
cleanup:
free(pub_hex);
free(key_id);
free(sig_hex);
nsigner_client_free(client);
nostr_cleanup();
return rc;
}

View File

@@ -99,3 +99,165 @@ Notes:
- Typical working range is ~4.7uF to 22uF; 10uF is recommended
- Keep leads short for best stability
- Auto-reset behavior for flashing may still work, but if flashing ever becomes unreliable, enter bootloader manually
## Post-quantum crypto support (Phase 7)
Both firmware targets (`feather_s3_tft` and `cyd_esp32_2432s028`) now include
the three NIST-standardized post-quantum algorithms alongside the existing
secp256k1 (Nostr) and new ed25519/x25519 classical algorithms:
| Algorithm | Standard | Purpose | Pub key | Priv key | Sig/Ct |
|---|---|---|---|---|---|
| secp256k1 | — | Nostr (existing) | 32 B | 32 B | 64 B |
| ed25519 | RFC 8032 | SSH signatures | 32 B | 32 B | 64 B |
| x25519 | RFC 7748 | Key agreement (age) | 32 B | 32 B | — |
| ML-DSA-65 | FIPS 204 | PQ signatures | 1952 B | 4032 B | 3309 B |
| SLH-DSA-128s | FIPS 205 | PQ hash-based sigs | 32 B | 64 B | 7856 B |
| ML-KEM-768 | FIPS 203 | PQ key encapsulation | 1184 B | 2400 B | 1088 B |
### mbedtls backend (vs OpenSSL on host)
The host build uses OpenSSL EVP for SHA-256, SHA-512, SHA3-256, SHA3-512,
SHAKE-128, and SHAKE-256. On ESP32, OpenSSL is not available. Instead, the
firmware uses a **crypto backend abstraction** ([`resources/pqclean/common/crypto_backend.h`](../resources/pqclean/common/crypto_backend.h))
with two implementations:
- [`resources/pqclean/common/crypto_backend_openssl.c`](../resources/pqclean/common/crypto_backend_openssl.c) — host build (OpenSSL EVP)
- [`resources/pqclean/common/crypto_backend_mbedtls.c`](../resources/pqclean/common/crypto_backend_mbedtls.c) — ESP32 firmware (mbedtls)
The mbedtls backend uses:
- `mbedtls_sha256_ret()` for SHA-256 (ESP32-S3 hardware accelerated)
- `mbedtls_sha512_ret()` for SHA-512 (ESP32-S3 hardware accelerated)
- `mbedtls_md` API for SHA3-256, SHA3-512, SHAKE-128, SHAKE-256
### Enabling SHA3/SHAKE in menuconfig
mbedtls does not enable SHA3/SHAKE by default. You must enable them in
menuconfig before building:
```
Component config → mbedTLS → Hash functions → SHA-3
Component config → mbedTLS → Hash functions → SHAKE
```
Or add to `sdkconfig.defaults`:
```
CONFIG_MBEDTLS_SHA3_C=y
CONFIG_MBEDTLS_SHAKE_C=y
```
If mbedtls does not have SHAKE support, the firmware build will fail at link
time with unresolved `mbedtls_md_info_from_type(MBEDTLS_MD_SHAKE128)`. In that
case, either enable the config options above or patch mbedtls with a
Keccak/SHAKE contribution.
### PQClean component
The PQClean algorithm code is compiled as an ESP-IDF component at
`components/pqclean/`. The component's `CMakeLists.txt` references the shared
source files in [`resources/pqclean/`](../resources/pqclean/) via relative
paths, so there is a single source of truth for both host and firmware builds.
The component includes:
- ML-DSA-65: `sign.c`, `poly.c`, `ntt.c`
- SLH-DSA-128s: `sign.c`, `fors.c`, `wots.c`, `hash.c`, `thash.c`, `address.c`, `utils.c`
- ML-KEM-768: `kem.c`, `indcpa.c`, `poly.c`, `ntt.c`, `cbd.c`, `reduce.c`, `symmetric.c`, `verify.c`
- Common: `fips202.c`, `sha2.c`, `crypto_backend_mbedtls.c`
- Firmware DRBG: `pq_drbg_firmware.c`, `randombytes_mbedtls.c`
### Flash usage estimates
| Algorithm | Code size (approx) |
|---|---|
| ML-DSA-65 | ~150 KB |
| SLH-DSA-128s | ~80 KB |
| ML-KEM-768 | ~120 KB |
| Total PQ code | ~350 KB |
The ESP32-S3 (Feather S3 TFT) has 8 MB flash and the ESP32 (CYD) has 4 MB
flash. The PQ code fits comfortably in both, but partition sizes may need
adjustment if the total app image exceeds the default partition.
### RAM usage notes
PQ key buffers are large compared to classical ECC keys:
| Buffer | Size |
|---|---|
| ML-DSA-65 private key | 4032 bytes |
| ML-DSA-65 public key | 1952 bytes |
| ML-DSA-65 signature | 3309 bytes |
| SLH-DSA-128s signature | 7856 bytes |
| ML-KEM-768 private key | 2400 bytes |
| ML-KEM-768 public key | 1184 bytes |
| ML-KEM-768 ciphertext | 1088 bytes |
The ESP32 has ~320 KB available heap (after WiFi/BT are disabled). These
buffers **must not be stack-allocated** — the default task stack is 8 KB.
Use `malloc()` or static buffers. The firmware derives PQ keys **on demand**
(not all at startup) to keep peak RAM usage low.
### SLH-DSA-128s signing latency warning
SLH-DSA-128s (SPHINCS+-128s) is a hash-based signature scheme with a deep
hypertree structure (7 layers of WOTS+ + Merkle trees). On the ESP32-S3
(240 MHz dual-core), expect:
- **Key generation**: 530 seconds
- **Signing**: 530 seconds
- **Verification**: 0.52 seconds
This is inherent to the algorithm — it trades computation for minimal trust
assumptions (only SHA-256). The firmware logs a warning before SLH-DSA-128s
keygen/signing. Users should choose whether to use SLH-DSA-128s per-role
based on their latency tolerance. ML-DSA-65 is much faster (~100 ms for
signing on ESP32-S3) and is the recommended PQ signature algorithm for
interactive use.
### Derivation paths
All algorithms derive from the mnemonic using BIP-32/HMAC-SHA512 with
SLIP-0010 all-hardened derivation for ed25519/x25519/PQ:
| Algorithm | Path | Notes |
|---|---|---|
| secp256k1 (Nostr) | `m/44'/1237'/<n>'/0/0` | NIP-06, existing |
| ed25519 (SSH) | `m/44'/102001'/<n>'/0'/0'` | SLIP-0010 |
| x25519 (age) | `m/44'/102002'/<n>'/0'/0'` | SLIP-0010 |
| ML-DSA-65 | `m/44'/102003'/<n>'/0'/0'` | seed → PQClean keygen |
| SLH-DSA-128s | `m/44'/102004'/<n>'/0'/0'` | seed → PQClean keygen |
| ML-KEM-768 | `m/44'/102005'/<n>'/0'/0'` | seed → PQClean keygen |
The PQ derivation produces a 32-byte seed that feeds a deterministic
SHAKE-256 DRBG ([`pq_drbg_firmware.c`](feather_s3_tft/components/pqclean/pq_drbg_firmware.c)),
which replaces PQClean's `randombytes()` during keygen. This gives
deterministic, mnemonic-recoverable PQ keys — same mnemonic, same key pair.
### Firmware API
The firmware exposes PQ operations via [`pq_crypto_firmware.h`](feather_s3_tft/main/pq_crypto_firmware.h):
```c
/* Key generation (deterministic from mnemonic-derived seed) */
int fw_pq_ml_dsa_65_keygen(const uint8_t seed[32], uint8_t *pk, uint8_t *sk);
int fw_pq_slh_dsa_128s_keygen(const uint8_t seed[32], uint8_t *pk, uint8_t *sk);
int fw_pq_ml_kem_768_keygen(const uint8_t seed[32], uint8_t *pk, uint8_t *sk);
/* Signing / verification */
int fw_pq_ml_dsa_65_sign(uint8_t *sig, size_t *siglen, ...);
int fw_pq_slh_dsa_128s_sign(uint8_t *sig, size_t *siglen, ...);
/* KEM encaps / decaps */
int fw_pq_ml_kem_768_encaps(uint8_t *ct, uint8_t *ss, const uint8_t *pk);
int fw_pq_ml_kem_768_decaps(uint8_t *ss, const uint8_t *ct, const uint8_t *sk);
```
Key derivation from the mnemonic seed is via [`key_derivation.h`](feather_s3_tft/main/key_derivation.h):
```c
int derive_ed25519_key(const uint8_t seed[64], uint32_t index, ...);
int derive_x25519_key(const uint8_t seed[64], uint32_t index, ...);
int derive_ml_dsa_65_key(const uint8_t seed[64], uint32_t index, ...);
int derive_slh_dsa_128s_key(const uint8_t seed[64], uint32_t index, ...);
int derive_ml_kem_768_key(const uint8_t seed[64], uint32_t index, ...);
```

View File

@@ -0,0 +1,60 @@
# CMakeLists.txt — ESP-IDF component for PQClean post-quantum algorithms.
#
# Compiles the three PQ algorithms (ML-DSA-65, SLH-DSA-128s, ML-KEM-768)
# from the shared resources/pqclean/ source tree, using the mbedtls
# crypto backend (crypto_backend_mbedtls.c) for SHA-2/SHA3/SHAKE.
#
# The source files are referenced via relative paths back to the shared
# resources/pqclean/ directory so there is a single source of truth.
#
# mbedtls requirements:
# CONFIG_MBEDTLS_SHA3_C=y (for SHA3-256, SHA3-512)
# CONFIG_MBEDTLS_SHAKE_C=y (for SHAKE-128, SHAKE-256)
# Enable these in menuconfig under Component config -> mbedTLS ->
# Hash functions -> SHA-3 and SHAKE.
set(PQCLEAN_ROOT "${CMAKE_CURRENT_LIST_DIR}/../../../../resources/pqclean")
idf_component_register(
SRCS
"${PQCLEAN_ROOT}/crypto_sign/ml-dsa-65/sign.c"
"${PQCLEAN_ROOT}/crypto_sign/ml-dsa-65/poly.c"
"${PQCLEAN_ROOT}/crypto_sign/ml-dsa-65/ntt.c"
"${PQCLEAN_ROOT}/crypto_sign/slh-dsa-128s/sign.c"
"${PQCLEAN_ROOT}/crypto_sign/slh-dsa-128s/fors.c"
"${PQCLEAN_ROOT}/crypto_sign/slh-dsa-128s/wots.c"
"${PQCLEAN_ROOT}/crypto_sign/slh-dsa-128s/hash.c"
"${PQCLEAN_ROOT}/crypto_sign/slh-dsa-128s/thash.c"
"${PQCLEAN_ROOT}/crypto_sign/slh-dsa-128s/address.c"
"${PQCLEAN_ROOT}/crypto_sign/slh-dsa-128s/utils.c"
"${PQCLEAN_ROOT}/crypto_kem/ml-kem-768/kem.c"
"${PQCLEAN_ROOT}/crypto_kem/ml-kem-768/indcpa.c"
"${PQCLEAN_ROOT}/crypto_kem/ml-kem-768/poly.c"
"${PQCLEAN_ROOT}/crypto_kem/ml-kem-768/ntt.c"
"${PQCLEAN_ROOT}/crypto_kem/ml-kem-768/cbd.c"
"${PQCLEAN_ROOT}/crypto_kem/ml-kem-768/reduce.c"
"${PQCLEAN_ROOT}/crypto_kem/ml-kem-768/symmetric.c"
"${PQCLEAN_ROOT}/crypto_kem/ml-kem-768/verify.c"
"${PQCLEAN_ROOT}/common/fips202.c"
"${PQCLEAN_ROOT}/common/sha2.c"
"${PQCLEAN_ROOT}/common/crypto_backend_mbedtls.c"
"randombytes_mbedtls.c"
"pq_drbg_firmware.c"
INCLUDE_DIRS
"include"
"${PQCLEAN_ROOT}/common"
"${PQCLEAN_ROOT}/crypto_sign/ml-dsa-65"
"${PQCLEAN_ROOT}/crypto_sign/slh-dsa-128s"
"${PQCLEAN_ROOT}/crypto_kem/ml-kem-768"
REQUIRES
mbedtls
)
# Suppress warnings from the PQClean code (it uses C99 patterns that
# trigger -Wextra warnings under ESP-IDF's default flags).
target_compile_options(${COMPONENT_LIB} PRIVATE
-Wno-unused-parameter
-Wno-sign-compare
-Wno-unused-variable
-Wno-unused-but-set-variable
)

View File

@@ -0,0 +1,5 @@
/* ml_dsa_65_api.h — firmware wrapper that includes the real PQClean header. */
#ifndef FIRMWARE_ML_DSA_65_API_WRAPPER_H
#define FIRMWARE_ML_DSA_65_API_WRAPPER_H
#include "../../../../resources/pqclean/crypto_sign/ml-dsa-65/api.h"
#endif

View File

@@ -0,0 +1,5 @@
/* ml_kem_768_api.h — firmware wrapper that includes the real PQClean header. */
#ifndef FIRMWARE_ML_KEM_768_API_WRAPPER_H
#define FIRMWARE_ML_KEM_768_API_WRAPPER_H
#include "../../../../resources/pqclean/crypto_kem/ml-kem-768/api.h"
#endif

View File

@@ -0,0 +1,38 @@
/* pqclean.h — Umbrella include for the ESP32 firmware PQClean component.
*
* Exposes the three post-quantum algorithms (ML-DSA-65, SLH-DSA-128s,
* ML-KEM-768) and the deterministic DRBG used for mnemonic-recoverable
* key generation.
*
* On ESP32 the underlying hash/SHAKE primitives are provided by the
* mbedtls backend (crypto_backend_mbedtls.c) instead of OpenSSL.
*/
#ifndef FIRMWARE_PQCLEAN_H
#define FIRMWARE_PQCLEAN_H
#include <stddef.h>
#include <stdint.h>
/* --- ML-DSA-65 (FIPS 204, lattice signatures) --- */
#include "ml_dsa_65_api.h"
/* --- SLH-DSA-128s (FIPS 205, hash-based signatures) --- */
#include "slh_dsa_128s_api.h"
/* --- ML-KEM-768 (FIPS 203, lattice KEM) --- */
#include "ml_kem_768_api.h"
/* --- Deterministic DRBG (replaces randombytes() for keygen) --- */
/* Initializes the DRBG with a 32-byte mnemonic-derived seed. Subsequent
* randombytes() calls will produce a deterministic byte stream. */
void pq_drbg_init(const unsigned char *seed, size_t seed_len);
/* Zeroizes the DRBG state (call after keygen to wipe sensitive material). */
void pq_drbg_zeroize(void);
/* randombytes() — called by the PQClean algorithm code.
* On firmware this is provided by randombytes_mbedtls.c (deterministic DRBG
* for keygen, or mbedtls_ctr_drbg for real randomness during encaps). */
int randombytes(unsigned char *buf, size_t len);
#endif /* FIRMWARE_PQCLEAN_H */

View File

@@ -0,0 +1,5 @@
/* slh_dsa_128s_api.h — firmware wrapper that includes the real PQClean header. */
#ifndef FIRMWARE_SLH_DSA_128S_API_WRAPPER_H
#define FIRMWARE_SLH_DSA_128S_API_WRAPPER_H
#include "../../../../resources/pqclean/crypto_sign/slh-dsa-128s/api.h"
#endif

View File

@@ -0,0 +1,108 @@
/* pq_drbg_firmware.c — Deterministic PRNG for PQ key generation on ESP32.
*
* Same algorithm as the host's src/pq_drbg.c but uses the crypto backend
* abstraction (which resolves to mbedtls on ESP32) for SHAKE-256 instead
* of OpenSSL EVP. This allows deterministic PQ key generation from a
* mnemonic-derived seed: same seed -> same randombytes output sequence.
*
* The PRNG: SHAKE-256(seed || counter) produces a stream of pseudo-random
* bytes. The counter is a 64-bit little-endian integer that increments
* each time we need more output.
*/
#include <string.h>
#include <stdlib.h>
#include "crypto_backend.h"
/* --- DRBG state --- */
static unsigned char g_seed[32];
static int g_seed_len = 0;
static uint64_t g_counter = 0;
static unsigned char g_buffer[168]; /* SHAKE-256 rate = 136, 168 for safety */
static size_t g_buffer_pos = sizeof(g_buffer);
static int g_initialized = 0;
/* --- internal: squeeze more bytes from SHAKE-256 --- */
static void drbg_refill(void) {
unsigned char seed_block[32 + 8]; /* seed + counter (8 bytes LE) */
memcpy(seed_block, g_seed, (size_t)g_seed_len);
seed_block[g_seed_len + 0] = (unsigned char)(g_counter & 0xFF);
seed_block[g_seed_len + 1] = (unsigned char)((g_counter >> 8) & 0xFF);
seed_block[g_seed_len + 2] = (unsigned char)((g_counter >> 16) & 0xFF);
seed_block[g_seed_len + 3] = (unsigned char)((g_counter >> 24) & 0xFF);
seed_block[g_seed_len + 4] = (unsigned char)((g_counter >> 32) & 0xFF);
seed_block[g_seed_len + 5] = (unsigned char)((g_counter >> 40) & 0xFF);
seed_block[g_seed_len + 6] = (unsigned char)((g_counter >> 48) & 0xFF);
seed_block[g_seed_len + 7] = (unsigned char)((g_counter >> 56) & 0xFF);
crypto_backend_shake256(seed_block, (size_t)g_seed_len + 8,
g_buffer, sizeof(g_buffer));
g_counter++;
g_buffer_pos = 0;
}
/* --- public API --- */
void pq_drbg_init(const unsigned char *seed, size_t seed_len) {
if (seed == NULL || seed_len == 0) {
return;
}
memset(g_seed, 0, sizeof(g_seed));
if (seed_len > sizeof(g_seed)) {
seed_len = sizeof(g_seed);
}
memcpy(g_seed, seed, seed_len);
g_seed_len = (int)sizeof(g_seed); /* always use 32-byte seed (zero-padded) */
g_counter = 0;
g_buffer_pos = sizeof(g_buffer);
g_initialized = 1;
}
void pq_drbg_zeroize(void) {
crypto_backend_cleanse(g_seed, sizeof(g_seed));
crypto_backend_cleanse(g_buffer, sizeof(g_buffer));
g_seed_len = 0;
g_counter = 0;
g_buffer_pos = sizeof(g_buffer);
g_initialized = 0;
}
/* Returns 1 if the DRBG has been initialized (keygen mode), 0 otherwise.
* Used by randombytes_mbedtls.c to decide between deterministic DRBG and
* hardware RNG. */
int pq_drbg_is_initialized(void) {
return g_initialized;
}
/* pq_drbg_randombytes is called by randombytes() below. */
int pq_drbg_randombytes(unsigned char *buf, size_t len) {
if (buf == NULL || !g_initialized) {
return -1;
}
while (len > 0) {
size_t avail;
size_t to_copy;
if (g_buffer_pos >= sizeof(g_buffer)) {
drbg_refill();
if (g_buffer_pos >= sizeof(g_buffer)) {
return -1; /* refill failed */
}
}
avail = sizeof(g_buffer) - g_buffer_pos;
to_copy = (len < avail) ? len : avail;
memcpy(buf, g_buffer + g_buffer_pos, to_copy);
g_buffer_pos += to_copy;
buf += to_copy;
len -= to_copy;
}
return 0;
}

View File

@@ -0,0 +1,40 @@
/* randombytes_mbedtls.c — randombytes() implementation for ESP32 firmware.
*
* PQClean's algorithm code calls randombytes() for:
* 1. Key generation (keygen) — must be deterministic from the mnemonic
* seed so keys are recoverable. The DRBG is initialized via
* pq_drbg_init() before keygen, so randombytes() draws from the
* deterministic stream.
* 2. Encapsulation (ML-KEM enc) — needs real cryptographic randomness.
* When the DRBG is NOT initialized, randombytes() falls back to
* esp_fill_random() which uses the ESP32 hardware RNG.
*
* This dual-mode behavior matches the host build (src/pq_drbg.c) where
* the DRBG is initialized for keygen and randombytes() returns -1 if
* called without initialization. On firmware we allow the fallback to
* hardware RNG for encaps, which is the correct behavior.
*/
#include <string.h>
#include "esp_random.h"
/* Defined in pq_drbg_firmware.c */
extern int pq_drbg_randombytes(unsigned char *buf, size_t len);
/* Check if the DRBG is initialized (declared in pq_drbg_firmware.c).
* We use a helper to avoid exposing the static directly. */
extern int pq_drbg_is_initialized(void);
int randombytes(unsigned char *buf, size_t len) {
if (buf == NULL) {
return -1;
}
/* If the deterministic DRBG is active (keygen mode), use it. */
if (pq_drbg_is_initialized()) {
return pq_drbg_randombytes(buf, len);
}
/* Otherwise, use the ESP32 hardware RNG for real randomness (encaps). */
esp_fill_random(buf, len);
return 0;
}

View File

@@ -10,6 +10,7 @@ idf_component_register(
"bech32.c"
"mnemonic.c"
"key_derivation.c"
"pq_crypto_firmware.c"
"secure_mem.c"
"../../../resources/nostr_core_lib/nostr_core/nip004.c"
"../../../resources/nostr_core_lib/nostr_core/nip044.c"
@@ -31,6 +32,7 @@ idf_component_register(
esp_driver_uart
mbedtls
secp256k1
pqclean
json)
target_compile_definitions(${COMPONENT_LIB} PUBLIC LV_CONF_INCLUDE_SIMPLE=1)

View File

@@ -1,17 +1,25 @@
#include "key_derivation.h"
#include "pq_crypto_firmware.h"
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "esp_random.h"
#include "esp_log.h"
#include "mbedtls/md.h"
#include "mbedtls/ed25519.h"
#include "mbedtls/ecp.h"
#include "mbedtls/pk.h"
#include "secp256k1.h"
#include "secp256k1_extrakeys.h"
#include "secp256k1_schnorrsig.h"
static const char *KD_TAG = "key_derivation";
#define BIP32_HARDENED_FLAG 0x80000000u
typedef struct {
@@ -253,3 +261,316 @@ int schnorr_sign32(const uint8_t privkey[32], const uint8_t msg32[32], uint8_t s
secp256k1_context_destroy(ctx);
return 0;
}
/* ====================================================================
* Phase 7: ed25519, x25519, and post-quantum key derivation
* ==================================================================== */
/* SLIP-0010 all-hardened derivation for ed25519/x25519.
*
* SLIP-0010 uses HMAC-SHA512 with a "ed25519 seed" or curve-specific key
* for the master key, and all derivation steps are hardened (the parent
* private key is prepended to the index data).
*
* For ed25519/x25519, the derived 512-bit HMAC output is split:
* - first 32 bytes = private key (the scalar)
* - last 32 bytes = chain code
*
* The private key IS the ed25519/x25519 secret — no tweak-add is needed
* (unlike secp256k1 BIP-32 where the child priv = parent_priv + HMAC).
*/
/* SLIP-0010 master key from seed: HMAC-SHA512(key="ed25519 seed", data=seed) */
static int slip10_master_from_seed(const uint8_t seed[64],
uint8_t priv[32], uint8_t chain[32]) {
static const uint8_t kEd25519Seed[] = "ed25519 seed";
uint8_t i64[64] = {0};
if (hmac_sha512(kEd25519Seed, sizeof(kEd25519Seed) - 1,
seed, 64, i64) != 0) {
return -1;
}
memcpy(priv, i64, 32);
memcpy(chain, i64 + 32, 32);
memset(i64, 0, sizeof(i64));
return 0;
}
/* SLIP-0010 hardened child derivation:
* HMAC-SHA512(key=chain, data=0x00 || priv || index_be32) */
static int slip10_ckd_priv(const uint8_t parent_priv[32],
const uint8_t parent_chain[32],
uint32_t index,
uint8_t child_priv[32],
uint8_t child_chain[32]) {
uint8_t data[37];
uint8_t i64[64] = {0};
/* Hardened derivation: 0x00 || priv || index (big-endian) */
data[0] = 0x00;
memcpy(data + 1, parent_priv, 32);
data[33] = (uint8_t)((index >> 24) & 0xFF);
data[34] = (uint8_t)((index >> 16) & 0xFF);
data[35] = (uint8_t)((index >> 8) & 0xFF);
data[36] = (uint8_t)(index & 0xFF);
if (hmac_sha512(parent_chain, 32, data, sizeof(data), i64) != 0) {
memset(data, 0, sizeof(data));
return -1;
}
memcpy(child_priv, i64, 32);
memcpy(child_chain, i64 + 32, 32);
memset(data, 0, sizeof(data));
memset(i64, 0, sizeof(i64));
return 0;
}
/* Derive a 32-byte seed via SLIP-0010 all-hardened path.
* path[] is an array of hardened indices (the caller sets the hardened flag).
* Returns the final 32-byte private material in `out_seed`. */
static int slip10_derive_seed(const uint8_t seed[64],
const uint32_t *path, size_t path_len,
uint8_t out_seed[32]) {
uint8_t priv[32], chain[32], next_priv[32], next_chain[32];
size_t i;
if (slip10_master_from_seed(seed, priv, chain) != 0) {
return -1;
}
for (i = 0; i < path_len; i++) {
if (slip10_ckd_priv(priv, chain, path[i],
next_priv, next_chain) != 0) {
memset(priv, 0, sizeof(priv));
memset(chain, 0, sizeof(chain));
return -1;
}
memcpy(priv, next_priv, 32);
memcpy(chain, next_chain, 32);
}
memcpy(out_seed, priv, 32);
memset(priv, 0, sizeof(priv));
memset(chain, 0, sizeof(chain));
memset(next_priv, 0, sizeof(next_priv));
memset(next_chain, 0, sizeof(next_chain));
return 0;
}
/* --- ed25519 --- */
int derive_ed25519_key(const uint8_t seed[64], uint32_t index,
uint8_t privkey[32], uint8_t pubkey[32]) {
/* m/44'/102001'/<index>'/0'/0' — all hardened (SLIP-0010) */
const uint32_t path[5] = {
44u | BIP32_HARDENED_FLAG,
102001u | BIP32_HARDENED_FLAG,
index | BIP32_HARDENED_FLAG,
0u | BIP32_HARDENED_FLAG,
0u | BIP32_HARDENED_FLAG,
};
uint8_t derived_seed[32];
if (seed == NULL || privkey == NULL || pubkey == NULL) {
return -1;
}
if (slip10_derive_seed(seed, path, 5, derived_seed) != 0) {
return -1;
}
/* The SLIP-0010 derived 32 bytes IS the ed25519 private key.
* Use mbedtls to derive the public key. */
memcpy(privkey, derived_seed, 32);
/* mbedtls_ed25519_make_public: derive pub from priv */
/* Note: mbedtls ed25519 API may vary by version. The ESP-IDF mbedtls
* component provides mbedtls_ed25519_make_public (or via the PK API).
* We use the low-level function if available. */
int ret = mbedtls_ed25519_make_public((unsigned char *)pubkey, 32,
(const unsigned char *)privkey, 32);
if (ret != 0) {
ESP_LOGE(KD_TAG, "ed25519 make_public failed: %d", ret);
memset(derived_seed, 0, sizeof(derived_seed));
memset(privkey, 0, 32);
return -1;
}
memset(derived_seed, 0, sizeof(derived_seed));
return 0;
}
int ed25519_sign32(const uint8_t privkey[32], const uint8_t msg32[32],
uint8_t sig64[64]) {
/* mbedtls_ed25519_sign: sign a message (not pre-hashed) */
int ret = mbedtls_ed25519_sign((unsigned char *)sig64, 64,
(const unsigned char *)msg32, 32,
(const unsigned char *)privkey, 32,
NULL, NULL);
if (ret != 0) {
ESP_LOGE(KD_TAG, "ed25519 sign failed: %d", ret);
return -1;
}
return 0;
}
/* --- x25519 --- */
int derive_x25519_key(const uint8_t seed[64], uint32_t index,
uint8_t privkey[32], uint8_t pubkey[32]) {
/* m/44'/102002'/<index>'/0'/0' — all hardened (SLIP-0010) */
const uint32_t path[5] = {
44u | BIP32_HARDENED_FLAG,
102002u | BIP32_HARDENED_FLAG,
index | BIP32_HARDENED_FLAG,
0u | BIP32_HARDENED_FLAG,
0u | BIP32_HARDENED_FLAG,
};
uint8_t derived_seed[32];
mbedtls_ecp_group grp;
mbedtls_mpi d;
mbedtls_ecp_point Q;
int ret;
if (seed == NULL || privkey == NULL || pubkey == NULL) {
return -1;
}
if (slip10_derive_seed(seed, path, 5, derived_seed) != 0) {
return -1;
}
/* The SLIP-0010 derived 32 bytes IS the x25519 private key.
* Clamp it per RFC 7748 and derive the public key via mbedtls ECDH. */
memcpy(privkey, derived_seed, 32);
memset(derived_seed, 0, sizeof(derived_seed));
/* x25519 clamping: priv[0] &= 248, priv[31] &= 127, priv[31] |= 64 */
privkey[0] &= 248;
privkey[31] &= 127;
privkey[31] |= 64;
mbedtls_ecp_group_init(&grp);
mbedtls_mpi_init(&d);
mbedtls_ecp_point_init(&Q);
ret = mbedtls_ecp_group_load(&grp, MBEDTLS_ECP_DP_CURVE25519);
if (ret != 0) {
ESP_LOGE(KD_TAG, "x25519 group load failed: %d", ret);
goto cleanup;
}
ret = mbedtls_mpi_read_binary_le(d, privkey, 32);
if (ret != 0) {
ESP_LOGE(KD_TAG, "x25519 mpi read failed: %d", ret);
goto cleanup;
}
ret = mbedtls_ecp_mul(&grp, &Q, d, &grp.G, NULL, NULL);
if (ret != 0) {
ESP_LOGE(KD_TAG, "x25519 ecp_mul failed: %d", ret);
goto cleanup;
}
/* Serialize the public key as raw 32 bytes (little-endian) */
{
size_t olen = 0;
ret = mbedtls_ecp_point_write_binary(&grp, &Q,
MBEDTLS_ECP_PF_COMPRESSED,
&olen, pubkey, 32);
if (ret != 0 || olen != 32) {
ESP_LOGE(KD_TAG, "x25519 pub serialize failed: %d", ret);
ret = -1;
}
}
cleanup:
mbedtls_ecp_group_free(&grp);
mbedtls_mpi_free(&d);
mbedtls_ecp_point_free(&Q);
return (ret == 0) ? 0 : -1;
}
/* --- ML-DSA-65 --- */
int derive_ml_dsa_65_key(const uint8_t seed[64], uint32_t index,
uint8_t *pk, uint8_t *sk) {
/* m/44'/102003'/<index>'/0'/0' — all hardened (SLIP-0010) -> 32-byte seed */
const uint32_t path[5] = {
44u | BIP32_HARDENED_FLAG,
102003u | BIP32_HARDENED_FLAG,
index | BIP32_HARDENED_FLAG,
0u | BIP32_HARDENED_FLAG,
0u | BIP32_HARDENED_FLAG,
};
uint8_t pq_seed[32];
if (seed == NULL || pk == NULL || sk == NULL) {
return -1;
}
if (slip10_derive_seed(seed, path, 5, pq_seed) != 0) {
return -1;
}
int ret = fw_pq_ml_dsa_65_keygen(pq_seed, pk, sk);
memset(pq_seed, 0, sizeof(pq_seed));
return ret;
}
/* --- SLH-DSA-128s --- */
int derive_slh_dsa_128s_key(const uint8_t seed[64], uint32_t index,
uint8_t *pk, uint8_t *sk) {
/* m/44'/102004'/<index>'/0'/0' — all hardened (SLIP-0010) -> 32-byte seed */
const uint32_t path[5] = {
44u | BIP32_HARDENED_FLAG,
102004u | BIP32_HARDENED_FLAG,
index | BIP32_HARDENED_FLAG,
0u | BIP32_HARDENED_FLAG,
0u | BIP32_HARDENED_FLAG,
};
uint8_t pq_seed[32];
if (seed == NULL || pk == NULL || sk == NULL) {
return -1;
}
if (slip10_derive_seed(seed, path, 5, pq_seed) != 0) {
return -1;
}
ESP_LOGW(KD_TAG, "SLH-DSA-128s keygen: this takes 5-30 seconds on ESP32");
int ret = fw_pq_slh_dsa_128s_keygen(pq_seed, pk, sk);
memset(pq_seed, 0, sizeof(pq_seed));
return ret;
}
/* --- ML-KEM-768 --- */
int derive_ml_kem_768_key(const uint8_t seed[64], uint32_t index,
uint8_t *pk, uint8_t *sk) {
/* m/44'/102005'/<index>'/0'/0' — all hardened (SLIP-0010) -> 32-byte seed */
const uint32_t path[5] = {
44u | BIP32_HARDENED_FLAG,
102005u | BIP32_HARDENED_FLAG,
index | BIP32_HARDENED_FLAG,
0u | BIP32_HARDENED_FLAG,
0u | BIP32_HARDENED_FLAG,
};
uint8_t pq_seed[32];
if (seed == NULL || pk == NULL || sk == NULL) {
return -1;
}
if (slip10_derive_seed(seed, path, 5, pq_seed) != 0) {
return -1;
}
int ret = fw_pq_ml_kem_768_keygen(pq_seed, pk, sk);
memset(pq_seed, 0, sizeof(pq_seed));
return ret;
}

View File

@@ -1,7 +1,61 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
/* --- secp256k1 (Nostr, existing) --- */
int derive_nostr_key(const uint8_t seed[64], uint8_t privkey[32], uint8_t pubkey[32]);
int derive_nostr_key_index(const uint8_t seed[64], uint32_t nostr_index, uint8_t privkey[32], uint8_t pubkey[32]);
int schnorr_sign32(const uint8_t privkey[32], const uint8_t msg32[32], uint8_t sig64[64]);
/* --- ed25519 (SSH signatures) --- */
/* Derives an ed25519 keypair from the mnemonic seed using SLIP-0010
* all-hardened derivation: m/44'/102001'/<n>'/0'/0'
* privkey: 32-byte ed25519 private scalar
* pubkey: 32-byte ed25519 public key
* Returns 0 on success, -1 on error. */
int derive_ed25519_key(const uint8_t seed[64], uint32_t index,
uint8_t privkey[32], uint8_t pubkey[32]);
/* Signs a 32-byte message digest with ed25519.
* sig: 64-byte ed25519 signature
* Returns 0 on success, -1 on error. */
int ed25519_sign32(const uint8_t privkey[32], const uint8_t msg32[32],
uint8_t sig64[64]);
/* --- x25519 (age encryption / key agreement) --- */
/* Derives an x25519 keypair from the mnemonic seed using SLIP-0010
* all-hardened derivation: m/44'/102002'/<n>'/0'/0'
* privkey: 32-byte x25519 private scalar
* pubkey: 32-byte x25519 public key
* Returns 0 on success, -1 on error. */
int derive_x25519_key(const uint8_t seed[64], uint32_t index,
uint8_t privkey[32], uint8_t pubkey[32]);
/* --- ML-DSA-65 (post-quantum signatures, FIPS 204) --- */
/* Derives an ML-DSA-65 keypair from the mnemonic seed.
* Path: m/44'/102003'/<n>'/0'/0' -> 32-byte seed -> PQClean keygen
* pk: FW_ML_DSA_65_PUBKEY_LEN (1952) bytes — caller must allocate
* sk: FW_ML_DSA_65_PRIVKEY_LEN (4032) bytes — caller must allocate
* Returns 0 on success, -1 on error. */
int derive_ml_dsa_65_key(const uint8_t seed[64], uint32_t index,
uint8_t *pk, uint8_t *sk);
/* --- SLH-DSA-128s (post-quantum hash-based signatures, FIPS 205) --- */
/* Derives an SLH-DSA-128s keypair from the mnemonic seed.
* Path: m/44'/102004'/<n>'/0'/0' -> 32-byte seed -> PQClean keygen
* pk: FW_SLH_DSA_128S_PUBKEY_LEN (32) bytes
* sk: FW_SLH_DSA_128S_PRIVKEY_LEN (64) bytes
* WARNING: Takes 5-30 seconds on ESP32.
* Returns 0 on success, -1 on error. */
int derive_slh_dsa_128s_key(const uint8_t seed[64], uint32_t index,
uint8_t *pk, uint8_t *sk);
/* --- ML-KEM-768 (post-quantum KEM, FIPS 203) --- */
/* Derives an ML-KEM-768 keypair from the mnemonic seed.
* Path: m/44'/102005'/<n>'/0'/0' -> 32-byte seed -> PQClean keygen
* pk: FW_ML_KEM_768_PUBKEY_LEN (1184) bytes — caller must allocate
* sk: FW_ML_KEM_768_PRIVKEY_LEN (2400) bytes — caller must allocate
* Returns 0 on success, -1 on error. */
int derive_ml_kem_768_key(const uint8_t seed[64], uint32_t index,
uint8_t *pk, uint8_t *sk);

View File

@@ -0,0 +1,171 @@
/* pq_crypto_firmware.c — Post-quantum crypto wrappers for ESP32 firmware.
*
* Wraps the PQClean algorithm API (via the pqclean component) with
* firmware-friendly functions that handle the deterministic DRBG setup
* for keygen and provide clean sign/verify/encaps/decaps interfaces.
*
* The PQ key buffers are large (ML-DSA-65 priv = 4032 bytes, SLH-DSA-128s
* sig = 7856 bytes). Callers must allocate these on the heap or as static
* buffers — stack allocation on ESP32 (8KB task stack default) will overflow
* for the larger buffers.
*/
#include "pq_crypto_firmware.h"
#include "pqclean.h"
#include <stdlib.h>
#include <string.h>
/* --- Key generation (deterministic from seed) --- */
int fw_pq_ml_dsa_65_keygen(const uint8_t seed[32],
uint8_t *pk, uint8_t *sk) {
if (seed == NULL || pk == NULL || sk == NULL) {
return -1;
}
/* Initialize the deterministic DRBG with the mnemonic-derived seed */
pq_drbg_init(seed, 32);
/* Run PQClean keygen — randombytes() draws from the DRBG */
int ret = crypto_sign_keypair(pk, sk);
/* Wipe the DRBG state — the seed material is sensitive */
pq_drbg_zeroize();
return ret;
}
int fw_pq_slh_dsa_128s_keygen(const uint8_t seed[32],
uint8_t *pk, uint8_t *sk) {
if (seed == NULL || pk == NULL || sk == NULL) {
return -1;
}
pq_drbg_init(seed, 32);
/* WARNING: This call takes 5-30 seconds on ESP32 due to the
* hypertree construction (7 layers of WOTS+ + Merkle trees). */
int ret = slh_dsa_128s_crypto_sign_keypair(pk, sk);
pq_drbg_zeroize();
return ret;
}
int fw_pq_ml_kem_768_keygen(const uint8_t seed[32],
uint8_t *pk, uint8_t *sk) {
if (seed == NULL || pk == NULL || sk == NULL) {
return -1;
}
pq_drbg_init(seed, 32);
int ret = crypto_kem_keypair(pk, sk);
pq_drbg_zeroize();
return ret;
}
/* --- Signing --- */
int fw_pq_ml_dsa_65_sign(uint8_t *sig, size_t *siglen,
const uint8_t *m, size_t mlen,
const uint8_t *sk) {
if (sig == NULL || siglen == NULL || m == NULL || sk == NULL) {
return -1;
}
return crypto_sign(sig, siglen, m, mlen, sk);
}
int fw_pq_ml_dsa_65_verify(const uint8_t *sig, size_t siglen,
const uint8_t *m, size_t mlen,
const uint8_t *pk) {
if (sig == NULL || m == NULL || pk == NULL) {
return -1;
}
/* crypto_sign_open expects (m_out, mlen_out, sm, smlen, pk) where sm
* is the signed message. For detached signatures we reconstruct: the
* PQClean API uses crypto_sign_open with sm = sig || m. */
/* For firmware use, we provide a simple verify by re-signing is not
* possible (non-deterministic). The PQClean crypto_sign_open expects
* the concatenated sig||msg format. Callers should use the PQClean
* API directly for verification, or we build the sm buffer here. */
uint8_t *sm = (uint8_t *)malloc(siglen + mlen);
if (sm == NULL) {
return -1;
}
memcpy(sm, sig, siglen);
memcpy(sm + siglen, m, mlen);
uint8_t *m_out = (uint8_t *)malloc(mlen);
if (m_out == NULL) {
free(sm);
return -1;
}
size_t mlen_out = 0;
int ret = crypto_sign_open(m_out, &mlen_out, sm, siglen + mlen, pk);
free(sm);
free(m_out);
return ret;
}
int fw_pq_slh_dsa_128s_sign(uint8_t *sig, size_t *siglen,
const uint8_t *m, size_t mlen,
const uint8_t *sk) {
if (sig == NULL || siglen == NULL || m == NULL || sk == NULL) {
return -1;
}
/* WARNING: This call takes 5-30 seconds on ESP32. */
return slh_dsa_128s_crypto_sign(sig, siglen, m, mlen, sk);
}
int fw_pq_slh_dsa_128s_verify(const uint8_t *sig, size_t siglen,
const uint8_t *m, size_t mlen,
const uint8_t *pk) {
if (sig == NULL || m == NULL || pk == NULL) {
return -1;
}
uint8_t *sm = (uint8_t *)malloc(siglen + mlen);
if (sm == NULL) {
return -1;
}
memcpy(sm, sig, siglen);
memcpy(sm + siglen, m, mlen);
uint8_t *m_out = (uint8_t *)malloc(mlen);
if (m_out == NULL) {
free(sm);
return -1;
}
size_t mlen_out = 0;
int ret = slh_dsa_128s_crypto_sign_open(m_out, &mlen_out, sm,
siglen + mlen, pk);
free(sm);
free(m_out);
return ret;
}
/* --- KEM --- */
int fw_pq_ml_kem_768_encaps(uint8_t *ct, uint8_t *ss, const uint8_t *pk) {
if (ct == NULL || ss == NULL || pk == NULL) {
return -1;
}
/* encaps uses real randomness (hardware RNG) — the DRBG is not
* initialized, so randombytes() falls back to esp_fill_random(). */
return crypto_kem_enc(ct, ss, pk);
}
int fw_pq_ml_kem_768_decaps(uint8_t *ss, const uint8_t *ct, const uint8_t *sk) {
if (ss == NULL || ct == NULL || sk == NULL) {
return -1;
}
return crypto_kem_dec(ss, ct, sk);
}

View File

@@ -0,0 +1,110 @@
/* pq_crypto_firmware.h — Post-quantum crypto wrappers for ESP32 firmware.
*
* Provides firmware-friendly wrappers around the PQClean algorithms:
* - ML-DSA-65 (FIPS 204 signatures)
* - SLH-DSA-128s (FIPS 205 hash-based signatures)
* - ML-KEM-768 (FIPS 203 key encapsulation)
*
* Key generation is deterministic from a 32-byte seed (derived from the
* mnemonic via BIP-32/HMAC-SHA512). The seed feeds the deterministic DRBG
* (pq_drbg_firmware.c) which replaces PQClean's randombytes() during keygen.
*
* ed25519 and x25519 are handled separately via mbedtls (see
* key_derivation.c) and are not part of this PQClean component.
*/
#ifndef FIRMWARE_PQ_CRYPTO_H
#define FIRMWARE_PQ_CRYPTO_H
#include <stddef.h>
#include <stdint.h>
/* --- Algorithm identifiers --- */
typedef enum {
FW_PQ_ALG_ML_DSA_65 = 0,
FW_PQ_ALG_SLH_DSA_128S,
FW_PQ_ALG_ML_KEM_768,
FW_PQ_ALG_UNKNOWN
} fw_pq_alg_t;
/* --- Key sizes (compile-time constants, matching PQClean api.h) --- */
#define FW_ML_DSA_65_PUBKEY_LEN 1952
#define FW_ML_DSA_65_PRIVKEY_LEN 4032
#define FW_ML_DSA_65_SIG_LEN 3309
#define FW_SLH_DSA_128S_PUBKEY_LEN 32
#define FW_SLH_DSA_128S_PRIVKEY_LEN 64
#define FW_SLH_DSA_128S_SIG_LEN 7856
#define FW_ML_KEM_768_PUBKEY_LEN 1184
#define FW_ML_KEM_768_PRIVKEY_LEN 2400
#define FW_ML_KEM_768_CIPHERTEXT_LEN 1088
#define FW_ML_KEM_768_SHARED_SECRET_LEN 32
/* --- Key generation (deterministic from seed) --- */
/* Generate an ML-DSA-65 keypair from a 32-byte seed.
* pk must be at least FW_ML_DSA_65_PUBKEY_LEN bytes.
* sk must be at least FW_ML_DSA_65_PRIVKEY_LEN bytes.
* Returns 0 on success, -1 on error. */
int fw_pq_ml_dsa_65_keygen(const uint8_t seed[32],
uint8_t *pk, uint8_t *sk);
/* Generate an SLH-DSA-128s keypair from a 32-byte seed.
* pk must be at least FW_SLH_DSA_128S_PUBKEY_LEN bytes.
* sk must be at least FW_SLH_DSA_128S_PRIVKEY_LEN bytes.
* Returns 0 on success, -1 on error.
* WARNING: SLH-DSA-128s keygen takes 5-30 seconds on ESP32. */
int fw_pq_slh_dsa_128s_keygen(const uint8_t seed[32],
uint8_t *pk, uint8_t *sk);
/* Generate an ML-KEM-768 keypair from a 32-byte seed.
* pk must be at least FW_ML_KEM_768_PUBKEY_LEN bytes.
* sk must be at least FW_ML_KEM_768_PRIVKEY_LEN bytes.
* Returns 0 on success, -1 on error. */
int fw_pq_ml_kem_768_keygen(const uint8_t seed[32],
uint8_t *pk, uint8_t *sk);
/* --- Signing (ML-DSA-65, SLH-DSA-128s) --- */
/* Sign a message with ML-DSA-65.
* sig must be at least FW_ML_DSA_65_SIG_LEN bytes.
* Returns 0 on success, -1 on error. */
int fw_pq_ml_dsa_65_sign(uint8_t *sig, size_t *siglen,
const uint8_t *m, size_t mlen,
const uint8_t *sk);
/* Verify an ML-DSA-65 signature.
* Returns 0 on valid, -1 on invalid. */
int fw_pq_ml_dsa_65_verify(const uint8_t *sig, size_t siglen,
const uint8_t *m, size_t mlen,
const uint8_t *pk);
/* Sign a message with SLH-DSA-128s.
* sig must be at least FW_SLH_DSA_128S_SIG_LEN bytes.
* WARNING: SLH-DSA-128s signing takes 5-30 seconds on ESP32.
* Returns 0 on success, -1 on error. */
int fw_pq_slh_dsa_128s_sign(uint8_t *sig, size_t *siglen,
const uint8_t *m, size_t mlen,
const uint8_t *sk);
/* Verify an SLH-DSA-128s signature.
* Returns 0 on valid, -1 on invalid. */
int fw_pq_slh_dsa_128s_verify(const uint8_t *sig, size_t siglen,
const uint8_t *m, size_t mlen,
const uint8_t *pk);
/* --- KEM (ML-KEM-768) --- */
/* Encapsulate: generate ciphertext + shared secret from a public key.
* Uses real randomness (ESP32 hardware RNG) — not the deterministic DRBG.
* ct must be at least FW_ML_KEM_768_CIPHERTEXT_LEN bytes.
* ss must be at least FW_ML_KEM_768_SHARED_SECRET_LEN bytes.
* Returns 0 on success, -1 on error. */
int fw_pq_ml_kem_768_encaps(uint8_t *ct, uint8_t *ss, const uint8_t *pk);
/* Decapsulate: recover shared secret from secret key + ciphertext.
* ss must be at least FW_ML_KEM_768_SHARED_SECRET_LEN bytes.
* Returns 0 on success, -1 on error. */
int fw_pq_ml_kem_768_decaps(uint8_t *ss, const uint8_t *ct, const uint8_t *sk);
#endif /* FIRMWARE_PQ_CRYPTO_H */

View File

@@ -0,0 +1,60 @@
# CMakeLists.txt — ESP-IDF component for PQClean post-quantum algorithms.
#
# Compiles the three PQ algorithms (ML-DSA-65, SLH-DSA-128s, ML-KEM-768)
# from the shared resources/pqclean/ source tree, using the mbedtls
# crypto backend (crypto_backend_mbedtls.c) for SHA-2/SHA3/SHAKE.
#
# The source files are referenced via relative paths back to the shared
# resources/pqclean/ directory so there is a single source of truth.
#
# mbedtls requirements:
# CONFIG_MBEDTLS_SHA3_C=y (for SHA3-256, SHA3-512)
# CONFIG_MBEDTLS_SHAKE_C=y (for SHAKE-128, SHAKE-256)
# Enable these in menuconfig under Component config -> mbedTLS ->
# Hash functions -> SHA-3 and SHAKE.
set(PQCLEAN_ROOT "${CMAKE_CURRENT_LIST_DIR}/../../../../resources/pqclean")
idf_component_register(
SRCS
"${PQCLEAN_ROOT}/crypto_sign/ml-dsa-65/sign.c"
"${PQCLEAN_ROOT}/crypto_sign/ml-dsa-65/poly.c"
"${PQCLEAN_ROOT}/crypto_sign/ml-dsa-65/ntt.c"
"${PQCLEAN_ROOT}/crypto_sign/slh-dsa-128s/sign.c"
"${PQCLEAN_ROOT}/crypto_sign/slh-dsa-128s/fors.c"
"${PQCLEAN_ROOT}/crypto_sign/slh-dsa-128s/wots.c"
"${PQCLEAN_ROOT}/crypto_sign/slh-dsa-128s/hash.c"
"${PQCLEAN_ROOT}/crypto_sign/slh-dsa-128s/thash.c"
"${PQCLEAN_ROOT}/crypto_sign/slh-dsa-128s/address.c"
"${PQCLEAN_ROOT}/crypto_sign/slh-dsa-128s/utils.c"
"${PQCLEAN_ROOT}/crypto_kem/ml-kem-768/kem.c"
"${PQCLEAN_ROOT}/crypto_kem/ml-kem-768/indcpa.c"
"${PQCLEAN_ROOT}/crypto_kem/ml-kem-768/poly.c"
"${PQCLEAN_ROOT}/crypto_kem/ml-kem-768/ntt.c"
"${PQCLEAN_ROOT}/crypto_kem/ml-kem-768/cbd.c"
"${PQCLEAN_ROOT}/crypto_kem/ml-kem-768/reduce.c"
"${PQCLEAN_ROOT}/crypto_kem/ml-kem-768/symmetric.c"
"${PQCLEAN_ROOT}/crypto_kem/ml-kem-768/verify.c"
"${PQCLEAN_ROOT}/common/fips202.c"
"${PQCLEAN_ROOT}/common/sha2.c"
"${PQCLEAN_ROOT}/common/crypto_backend_mbedtls.c"
"randombytes_mbedtls.c"
"pq_drbg_firmware.c"
INCLUDE_DIRS
"include"
"${PQCLEAN_ROOT}/common"
"${PQCLEAN_ROOT}/crypto_sign/ml-dsa-65"
"${PQCLEAN_ROOT}/crypto_sign/slh-dsa-128s"
"${PQCLEAN_ROOT}/crypto_kem/ml-kem-768"
REQUIRES
mbedtls
)
# Suppress warnings from the PQClean code (it uses C99 patterns that
# trigger -Wextra warnings under ESP-IDF's default flags).
target_compile_options(${COMPONENT_LIB} PRIVATE
-Wno-unused-parameter
-Wno-sign-compare
-Wno-unused-variable
-Wno-unused-but-set-variable
)

View File

@@ -0,0 +1,5 @@
/* ml_dsa_65_api.h — firmware wrapper that includes the real PQClean header. */
#ifndef FIRMWARE_ML_DSA_65_API_WRAPPER_H
#define FIRMWARE_ML_DSA_65_API_WRAPPER_H
#include "../../../../resources/pqclean/crypto_sign/ml-dsa-65/api.h"
#endif

View File

@@ -0,0 +1,5 @@
/* ml_kem_768_api.h — firmware wrapper that includes the real PQClean header. */
#ifndef FIRMWARE_ML_KEM_768_API_WRAPPER_H
#define FIRMWARE_ML_KEM_768_API_WRAPPER_H
#include "../../../../resources/pqclean/crypto_kem/ml-kem-768/api.h"
#endif

View File

@@ -0,0 +1,38 @@
/* pqclean.h — Umbrella include for the ESP32 firmware PQClean component.
*
* Exposes the three post-quantum algorithms (ML-DSA-65, SLH-DSA-128s,
* ML-KEM-768) and the deterministic DRBG used for mnemonic-recoverable
* key generation.
*
* On ESP32 the underlying hash/SHAKE primitives are provided by the
* mbedtls backend (crypto_backend_mbedtls.c) instead of OpenSSL.
*/
#ifndef FIRMWARE_PQCLEAN_H
#define FIRMWARE_PQCLEAN_H
#include <stddef.h>
#include <stdint.h>
/* --- ML-DSA-65 (FIPS 204, lattice signatures) --- */
#include "ml_dsa_65_api.h"
/* --- SLH-DSA-128s (FIPS 205, hash-based signatures) --- */
#include "slh_dsa_128s_api.h"
/* --- ML-KEM-768 (FIPS 203, lattice KEM) --- */
#include "ml_kem_768_api.h"
/* --- Deterministic DRBG (replaces randombytes() for keygen) --- */
/* Initializes the DRBG with a 32-byte mnemonic-derived seed. Subsequent
* randombytes() calls will produce a deterministic byte stream. */
void pq_drbg_init(const unsigned char *seed, size_t seed_len);
/* Zeroizes the DRBG state (call after keygen to wipe sensitive material). */
void pq_drbg_zeroize(void);
/* randombytes() — called by the PQClean algorithm code.
* On firmware this is provided by randombytes_mbedtls.c (deterministic DRBG
* for keygen, or mbedtls_ctr_drbg for real randomness during encaps). */
int randombytes(unsigned char *buf, size_t len);
#endif /* FIRMWARE_PQCLEAN_H */

View File

@@ -0,0 +1,5 @@
/* slh_dsa_128s_api.h — firmware wrapper that includes the real PQClean header. */
#ifndef FIRMWARE_SLH_DSA_128S_API_WRAPPER_H
#define FIRMWARE_SLH_DSA_128S_API_WRAPPER_H
#include "../../../../resources/pqclean/crypto_sign/slh-dsa-128s/api.h"
#endif

View File

@@ -0,0 +1,108 @@
/* pq_drbg_firmware.c — Deterministic PRNG for PQ key generation on ESP32.
*
* Same algorithm as the host's src/pq_drbg.c but uses the crypto backend
* abstraction (which resolves to mbedtls on ESP32) for SHAKE-256 instead
* of OpenSSL EVP. This allows deterministic PQ key generation from a
* mnemonic-derived seed: same seed -> same randombytes output sequence.
*
* The PRNG: SHAKE-256(seed || counter) produces a stream of pseudo-random
* bytes. The counter is a 64-bit little-endian integer that increments
* each time we need more output.
*/
#include <string.h>
#include <stdlib.h>
#include "crypto_backend.h"
/* --- DRBG state --- */
static unsigned char g_seed[32];
static int g_seed_len = 0;
static uint64_t g_counter = 0;
static unsigned char g_buffer[168]; /* SHAKE-256 rate = 136, 168 for safety */
static size_t g_buffer_pos = sizeof(g_buffer);
static int g_initialized = 0;
/* --- internal: squeeze more bytes from SHAKE-256 --- */
static void drbg_refill(void) {
unsigned char seed_block[32 + 8]; /* seed + counter (8 bytes LE) */
memcpy(seed_block, g_seed, (size_t)g_seed_len);
seed_block[g_seed_len + 0] = (unsigned char)(g_counter & 0xFF);
seed_block[g_seed_len + 1] = (unsigned char)((g_counter >> 8) & 0xFF);
seed_block[g_seed_len + 2] = (unsigned char)((g_counter >> 16) & 0xFF);
seed_block[g_seed_len + 3] = (unsigned char)((g_counter >> 24) & 0xFF);
seed_block[g_seed_len + 4] = (unsigned char)((g_counter >> 32) & 0xFF);
seed_block[g_seed_len + 5] = (unsigned char)((g_counter >> 40) & 0xFF);
seed_block[g_seed_len + 6] = (unsigned char)((g_counter >> 48) & 0xFF);
seed_block[g_seed_len + 7] = (unsigned char)((g_counter >> 56) & 0xFF);
crypto_backend_shake256(seed_block, (size_t)g_seed_len + 8,
g_buffer, sizeof(g_buffer));
g_counter++;
g_buffer_pos = 0;
}
/* --- public API --- */
void pq_drbg_init(const unsigned char *seed, size_t seed_len) {
if (seed == NULL || seed_len == 0) {
return;
}
memset(g_seed, 0, sizeof(g_seed));
if (seed_len > sizeof(g_seed)) {
seed_len = sizeof(g_seed);
}
memcpy(g_seed, seed, seed_len);
g_seed_len = (int)sizeof(g_seed); /* always use 32-byte seed (zero-padded) */
g_counter = 0;
g_buffer_pos = sizeof(g_buffer);
g_initialized = 1;
}
void pq_drbg_zeroize(void) {
crypto_backend_cleanse(g_seed, sizeof(g_seed));
crypto_backend_cleanse(g_buffer, sizeof(g_buffer));
g_seed_len = 0;
g_counter = 0;
g_buffer_pos = sizeof(g_buffer);
g_initialized = 0;
}
/* Returns 1 if the DRBG has been initialized (keygen mode), 0 otherwise.
* Used by randombytes_mbedtls.c to decide between deterministic DRBG and
* hardware RNG. */
int pq_drbg_is_initialized(void) {
return g_initialized;
}
/* pq_drbg_randombytes is called by randombytes() below. */
int pq_drbg_randombytes(unsigned char *buf, size_t len) {
if (buf == NULL || !g_initialized) {
return -1;
}
while (len > 0) {
size_t avail;
size_t to_copy;
if (g_buffer_pos >= sizeof(g_buffer)) {
drbg_refill();
if (g_buffer_pos >= sizeof(g_buffer)) {
return -1; /* refill failed */
}
}
avail = sizeof(g_buffer) - g_buffer_pos;
to_copy = (len < avail) ? len : avail;
memcpy(buf, g_buffer + g_buffer_pos, to_copy);
g_buffer_pos += to_copy;
buf += to_copy;
len -= to_copy;
}
return 0;
}

View File

@@ -0,0 +1,40 @@
/* randombytes_mbedtls.c — randombytes() implementation for ESP32 firmware.
*
* PQClean's algorithm code calls randombytes() for:
* 1. Key generation (keygen) — must be deterministic from the mnemonic
* seed so keys are recoverable. The DRBG is initialized via
* pq_drbg_init() before keygen, so randombytes() draws from the
* deterministic stream.
* 2. Encapsulation (ML-KEM enc) — needs real cryptographic randomness.
* When the DRBG is NOT initialized, randombytes() falls back to
* esp_fill_random() which uses the ESP32 hardware RNG.
*
* This dual-mode behavior matches the host build (src/pq_drbg.c) where
* the DRBG is initialized for keygen and randombytes() returns -1 if
* called without initialization. On firmware we allow the fallback to
* hardware RNG for encaps, which is the correct behavior.
*/
#include <string.h>
#include "esp_random.h"
/* Defined in pq_drbg_firmware.c */
extern int pq_drbg_randombytes(unsigned char *buf, size_t len);
/* Check if the DRBG is initialized (declared in pq_drbg_firmware.c).
* We use a helper to avoid exposing the static directly. */
extern int pq_drbg_is_initialized(void);
int randombytes(unsigned char *buf, size_t len) {
if (buf == NULL) {
return -1;
}
/* If the deterministic DRBG is active (keygen mode), use it. */
if (pq_drbg_is_initialized()) {
return pq_drbg_randombytes(buf, len);
}
/* Otherwise, use the ESP32 hardware RNG for real randomness (encaps). */
esp_fill_random(buf, len);
return 0;
}

View File

@@ -4,6 +4,7 @@ idf_component_register(
"display.c"
"mnemonic.c"
"key_derivation.c"
"pq_crypto_firmware.c"
"bech32.c"
"usb_transport.c"
"buttons.c"
@@ -23,6 +24,7 @@ idf_component_register(
REQUIRES
mbedtls
secp256k1
pqclean
json
espressif__esp_tinyusb
espressif__tinyusb

View File

@@ -1,17 +1,25 @@
#include "key_derivation.h"
#include "pq_crypto_firmware.h"
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "esp_random.h"
#include "esp_log.h"
#include "mbedtls/md.h"
#include "mbedtls/ed25519.h"
#include "mbedtls/ecp.h"
#include "mbedtls/pk.h"
#include "secp256k1.h"
#include "secp256k1_extrakeys.h"
#include "secp256k1_schnorrsig.h"
static const char *KD_TAG = "key_derivation";
#define BIP32_HARDENED_FLAG 0x80000000u
typedef struct {
@@ -253,3 +261,316 @@ int schnorr_sign32(const uint8_t privkey[32], const uint8_t msg32[32], uint8_t s
secp256k1_context_destroy(ctx);
return 0;
}
/* ====================================================================
* Phase 7: ed25519, x25519, and post-quantum key derivation
* ==================================================================== */
/* SLIP-0010 all-hardened derivation for ed25519/x25519.
*
* SLIP-0010 uses HMAC-SHA512 with a "ed25519 seed" or curve-specific key
* for the master key, and all derivation steps are hardened (the parent
* private key is prepended to the index data).
*
* For ed25519/x25519, the derived 512-bit HMAC output is split:
* - first 32 bytes = private key (the scalar)
* - last 32 bytes = chain code
*
* The private key IS the ed25519/x25519 secret — no tweak-add is needed
* (unlike secp256k1 BIP-32 where the child priv = parent_priv + HMAC).
*/
/* SLIP-0010 master key from seed: HMAC-SHA512(key="ed25519 seed", data=seed) */
static int slip10_master_from_seed(const uint8_t seed[64],
uint8_t priv[32], uint8_t chain[32]) {
static const uint8_t kEd25519Seed[] = "ed25519 seed";
uint8_t i64[64] = {0};
if (hmac_sha512(kEd25519Seed, sizeof(kEd25519Seed) - 1,
seed, 64, i64) != 0) {
return -1;
}
memcpy(priv, i64, 32);
memcpy(chain, i64 + 32, 32);
memset(i64, 0, sizeof(i64));
return 0;
}
/* SLIP-0010 hardened child derivation:
* HMAC-SHA512(key=chain, data=0x00 || priv || index_be32) */
static int slip10_ckd_priv(const uint8_t parent_priv[32],
const uint8_t parent_chain[32],
uint32_t index,
uint8_t child_priv[32],
uint8_t child_chain[32]) {
uint8_t data[37];
uint8_t i64[64] = {0};
/* Hardened derivation: 0x00 || priv || index (big-endian) */
data[0] = 0x00;
memcpy(data + 1, parent_priv, 32);
data[33] = (uint8_t)((index >> 24) & 0xFF);
data[34] = (uint8_t)((index >> 16) & 0xFF);
data[35] = (uint8_t)((index >> 8) & 0xFF);
data[36] = (uint8_t)(index & 0xFF);
if (hmac_sha512(parent_chain, 32, data, sizeof(data), i64) != 0) {
memset(data, 0, sizeof(data));
return -1;
}
memcpy(child_priv, i64, 32);
memcpy(child_chain, i64 + 32, 32);
memset(data, 0, sizeof(data));
memset(i64, 0, sizeof(i64));
return 0;
}
/* Derive a 32-byte seed via SLIP-0010 all-hardened path.
* path[] is an array of hardened indices (the caller sets the hardened flag).
* Returns the final 32-byte private material in `out_seed`. */
static int slip10_derive_seed(const uint8_t seed[64],
const uint32_t *path, size_t path_len,
uint8_t out_seed[32]) {
uint8_t priv[32], chain[32], next_priv[32], next_chain[32];
size_t i;
if (slip10_master_from_seed(seed, priv, chain) != 0) {
return -1;
}
for (i = 0; i < path_len; i++) {
if (slip10_ckd_priv(priv, chain, path[i],
next_priv, next_chain) != 0) {
memset(priv, 0, sizeof(priv));
memset(chain, 0, sizeof(chain));
return -1;
}
memcpy(priv, next_priv, 32);
memcpy(chain, next_chain, 32);
}
memcpy(out_seed, priv, 32);
memset(priv, 0, sizeof(priv));
memset(chain, 0, sizeof(chain));
memset(next_priv, 0, sizeof(next_priv));
memset(next_chain, 0, sizeof(next_chain));
return 0;
}
/* --- ed25519 --- */
int derive_ed25519_key(const uint8_t seed[64], uint32_t index,
uint8_t privkey[32], uint8_t pubkey[32]) {
/* m/44'/102001'/<index>'/0'/0' — all hardened (SLIP-0010) */
const uint32_t path[5] = {
44u | BIP32_HARDENED_FLAG,
102001u | BIP32_HARDENED_FLAG,
index | BIP32_HARDENED_FLAG,
0u | BIP32_HARDENED_FLAG,
0u | BIP32_HARDENED_FLAG,
};
uint8_t derived_seed[32];
if (seed == NULL || privkey == NULL || pubkey == NULL) {
return -1;
}
if (slip10_derive_seed(seed, path, 5, derived_seed) != 0) {
return -1;
}
/* The SLIP-0010 derived 32 bytes IS the ed25519 private key.
* Use mbedtls to derive the public key. */
memcpy(privkey, derived_seed, 32);
/* mbedtls_ed25519_make_public: derive pub from priv */
/* Note: mbedtls ed25519 API may vary by version. The ESP-IDF mbedtls
* component provides mbedtls_ed25519_make_public (or via the PK API).
* We use the low-level function if available. */
int ret = mbedtls_ed25519_make_public((unsigned char *)pubkey, 32,
(const unsigned char *)privkey, 32);
if (ret != 0) {
ESP_LOGE(KD_TAG, "ed25519 make_public failed: %d", ret);
memset(derived_seed, 0, sizeof(derived_seed));
memset(privkey, 0, 32);
return -1;
}
memset(derived_seed, 0, sizeof(derived_seed));
return 0;
}
int ed25519_sign32(const uint8_t privkey[32], const uint8_t msg32[32],
uint8_t sig64[64]) {
/* mbedtls_ed25519_sign: sign a message (not pre-hashed) */
int ret = mbedtls_ed25519_sign((unsigned char *)sig64, 64,
(const unsigned char *)msg32, 32,
(const unsigned char *)privkey, 32,
NULL, NULL);
if (ret != 0) {
ESP_LOGE(KD_TAG, "ed25519 sign failed: %d", ret);
return -1;
}
return 0;
}
/* --- x25519 --- */
int derive_x25519_key(const uint8_t seed[64], uint32_t index,
uint8_t privkey[32], uint8_t pubkey[32]) {
/* m/44'/102002'/<index>'/0'/0' — all hardened (SLIP-0010) */
const uint32_t path[5] = {
44u | BIP32_HARDENED_FLAG,
102002u | BIP32_HARDENED_FLAG,
index | BIP32_HARDENED_FLAG,
0u | BIP32_HARDENED_FLAG,
0u | BIP32_HARDENED_FLAG,
};
uint8_t derived_seed[32];
mbedtls_ecp_group grp;
mbedtls_mpi d;
mbedtls_ecp_point Q;
int ret;
if (seed == NULL || privkey == NULL || pubkey == NULL) {
return -1;
}
if (slip10_derive_seed(seed, path, 5, derived_seed) != 0) {
return -1;
}
/* The SLIP-0010 derived 32 bytes IS the x25519 private key.
* Clamp it per RFC 7748 and derive the public key via mbedtls ECDH. */
memcpy(privkey, derived_seed, 32);
memset(derived_seed, 0, sizeof(derived_seed));
/* x25519 clamping: priv[0] &= 248, priv[31] &= 127, priv[31] |= 64 */
privkey[0] &= 248;
privkey[31] &= 127;
privkey[31] |= 64;
mbedtls_ecp_group_init(&grp);
mbedtls_mpi_init(&d);
mbedtls_ecp_point_init(&Q);
ret = mbedtls_ecp_group_load(&grp, MBEDTLS_ECP_DP_CURVE25519);
if (ret != 0) {
ESP_LOGE(KD_TAG, "x25519 group load failed: %d", ret);
goto cleanup;
}
ret = mbedtls_mpi_read_binary_le(d, privkey, 32);
if (ret != 0) {
ESP_LOGE(KD_TAG, "x25519 mpi read failed: %d", ret);
goto cleanup;
}
ret = mbedtls_ecp_mul(&grp, &Q, d, &grp.G, NULL, NULL);
if (ret != 0) {
ESP_LOGE(KD_TAG, "x25519 ecp_mul failed: %d", ret);
goto cleanup;
}
/* Serialize the public key as raw 32 bytes (little-endian) */
{
size_t olen = 0;
ret = mbedtls_ecp_point_write_binary(&grp, &Q,
MBEDTLS_ECP_PF_COMPRESSED,
&olen, pubkey, 32);
if (ret != 0 || olen != 32) {
ESP_LOGE(KD_TAG, "x25519 pub serialize failed: %d", ret);
ret = -1;
}
}
cleanup:
mbedtls_ecp_group_free(&grp);
mbedtls_mpi_free(&d);
mbedtls_ecp_point_free(&Q);
return (ret == 0) ? 0 : -1;
}
/* --- ML-DSA-65 --- */
int derive_ml_dsa_65_key(const uint8_t seed[64], uint32_t index,
uint8_t *pk, uint8_t *sk) {
/* m/44'/102003'/<index>'/0'/0' — all hardened (SLIP-0010) -> 32-byte seed */
const uint32_t path[5] = {
44u | BIP32_HARDENED_FLAG,
102003u | BIP32_HARDENED_FLAG,
index | BIP32_HARDENED_FLAG,
0u | BIP32_HARDENED_FLAG,
0u | BIP32_HARDENED_FLAG,
};
uint8_t pq_seed[32];
if (seed == NULL || pk == NULL || sk == NULL) {
return -1;
}
if (slip10_derive_seed(seed, path, 5, pq_seed) != 0) {
return -1;
}
int ret = fw_pq_ml_dsa_65_keygen(pq_seed, pk, sk);
memset(pq_seed, 0, sizeof(pq_seed));
return ret;
}
/* --- SLH-DSA-128s --- */
int derive_slh_dsa_128s_key(const uint8_t seed[64], uint32_t index,
uint8_t *pk, uint8_t *sk) {
/* m/44'/102004'/<index>'/0'/0' — all hardened (SLIP-0010) -> 32-byte seed */
const uint32_t path[5] = {
44u | BIP32_HARDENED_FLAG,
102004u | BIP32_HARDENED_FLAG,
index | BIP32_HARDENED_FLAG,
0u | BIP32_HARDENED_FLAG,
0u | BIP32_HARDENED_FLAG,
};
uint8_t pq_seed[32];
if (seed == NULL || pk == NULL || sk == NULL) {
return -1;
}
if (slip10_derive_seed(seed, path, 5, pq_seed) != 0) {
return -1;
}
ESP_LOGW(KD_TAG, "SLH-DSA-128s keygen: this takes 5-30 seconds on ESP32");
int ret = fw_pq_slh_dsa_128s_keygen(pq_seed, pk, sk);
memset(pq_seed, 0, sizeof(pq_seed));
return ret;
}
/* --- ML-KEM-768 --- */
int derive_ml_kem_768_key(const uint8_t seed[64], uint32_t index,
uint8_t *pk, uint8_t *sk) {
/* m/44'/102005'/<index>'/0'/0' — all hardened (SLIP-0010) -> 32-byte seed */
const uint32_t path[5] = {
44u | BIP32_HARDENED_FLAG,
102005u | BIP32_HARDENED_FLAG,
index | BIP32_HARDENED_FLAG,
0u | BIP32_HARDENED_FLAG,
0u | BIP32_HARDENED_FLAG,
};
uint8_t pq_seed[32];
if (seed == NULL || pk == NULL || sk == NULL) {
return -1;
}
if (slip10_derive_seed(seed, path, 5, pq_seed) != 0) {
return -1;
}
int ret = fw_pq_ml_kem_768_keygen(pq_seed, pk, sk);
memset(pq_seed, 0, sizeof(pq_seed));
return ret;
}

View File

@@ -1,7 +1,61 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
/* --- secp256k1 (Nostr, existing) --- */
int derive_nostr_key(const uint8_t seed[64], uint8_t privkey[32], uint8_t pubkey[32]);
int derive_nostr_key_index(const uint8_t seed[64], uint32_t nostr_index, uint8_t privkey[32], uint8_t pubkey[32]);
int schnorr_sign32(const uint8_t privkey[32], const uint8_t msg32[32], uint8_t sig64[64]);
/* --- ed25519 (SSH signatures) --- */
/* Derives an ed25519 keypair from the mnemonic seed using SLIP-0010
* all-hardened derivation: m/44'/102001'/<n>'/0'/0'
* privkey: 32-byte ed25519 private scalar
* pubkey: 32-byte ed25519 public key
* Returns 0 on success, -1 on error. */
int derive_ed25519_key(const uint8_t seed[64], uint32_t index,
uint8_t privkey[32], uint8_t pubkey[32]);
/* Signs a 32-byte message digest with ed25519.
* sig: 64-byte ed25519 signature
* Returns 0 on success, -1 on error. */
int ed25519_sign32(const uint8_t privkey[32], const uint8_t msg32[32],
uint8_t sig64[64]);
/* --- x25519 (age encryption / key agreement) --- */
/* Derives an x25519 keypair from the mnemonic seed using SLIP-0010
* all-hardened derivation: m/44'/102002'/<n>'/0'/0'
* privkey: 32-byte x25519 private scalar
* pubkey: 32-byte x25519 public key
* Returns 0 on success, -1 on error. */
int derive_x25519_key(const uint8_t seed[64], uint32_t index,
uint8_t privkey[32], uint8_t pubkey[32]);
/* --- ML-DSA-65 (post-quantum signatures, FIPS 204) --- */
/* Derives an ML-DSA-65 keypair from the mnemonic seed.
* Path: m/44'/102003'/<n>'/0'/0' -> 32-byte seed -> PQClean keygen
* pk: FW_ML_DSA_65_PUBKEY_LEN (1952) bytes — caller must allocate
* sk: FW_ML_DSA_65_PRIVKEY_LEN (4032) bytes — caller must allocate
* Returns 0 on success, -1 on error. */
int derive_ml_dsa_65_key(const uint8_t seed[64], uint32_t index,
uint8_t *pk, uint8_t *sk);
/* --- SLH-DSA-128s (post-quantum hash-based signatures, FIPS 205) --- */
/* Derives an SLH-DSA-128s keypair from the mnemonic seed.
* Path: m/44'/102004'/<n>'/0'/0' -> 32-byte seed -> PQClean keygen
* pk: FW_SLH_DSA_128S_PUBKEY_LEN (32) bytes
* sk: FW_SLH_DSA_128S_PRIVKEY_LEN (64) bytes
* WARNING: Takes 5-30 seconds on ESP32.
* Returns 0 on success, -1 on error. */
int derive_slh_dsa_128s_key(const uint8_t seed[64], uint32_t index,
uint8_t *pk, uint8_t *sk);
/* --- ML-KEM-768 (post-quantum KEM, FIPS 203) --- */
/* Derives an ML-KEM-768 keypair from the mnemonic seed.
* Path: m/44'/102005'/<n>'/0'/0' -> 32-byte seed -> PQClean keygen
* pk: FW_ML_KEM_768_PUBKEY_LEN (1184) bytes — caller must allocate
* sk: FW_ML_KEM_768_PRIVKEY_LEN (2400) bytes — caller must allocate
* Returns 0 on success, -1 on error. */
int derive_ml_kem_768_key(const uint8_t seed[64], uint32_t index,
uint8_t *pk, uint8_t *sk);

View File

@@ -0,0 +1,171 @@
/* pq_crypto_firmware.c — Post-quantum crypto wrappers for ESP32 firmware.
*
* Wraps the PQClean algorithm API (via the pqclean component) with
* firmware-friendly functions that handle the deterministic DRBG setup
* for keygen and provide clean sign/verify/encaps/decaps interfaces.
*
* The PQ key buffers are large (ML-DSA-65 priv = 4032 bytes, SLH-DSA-128s
* sig = 7856 bytes). Callers must allocate these on the heap or as static
* buffers — stack allocation on ESP32 (8KB task stack default) will overflow
* for the larger buffers.
*/
#include "pq_crypto_firmware.h"
#include "pqclean.h"
#include <stdlib.h>
#include <string.h>
/* --- Key generation (deterministic from seed) --- */
int fw_pq_ml_dsa_65_keygen(const uint8_t seed[32],
uint8_t *pk, uint8_t *sk) {
if (seed == NULL || pk == NULL || sk == NULL) {
return -1;
}
/* Initialize the deterministic DRBG with the mnemonic-derived seed */
pq_drbg_init(seed, 32);
/* Run PQClean keygen — randombytes() draws from the DRBG */
int ret = crypto_sign_keypair(pk, sk);
/* Wipe the DRBG state — the seed material is sensitive */
pq_drbg_zeroize();
return ret;
}
int fw_pq_slh_dsa_128s_keygen(const uint8_t seed[32],
uint8_t *pk, uint8_t *sk) {
if (seed == NULL || pk == NULL || sk == NULL) {
return -1;
}
pq_drbg_init(seed, 32);
/* WARNING: This call takes 5-30 seconds on ESP32 due to the
* hypertree construction (7 layers of WOTS+ + Merkle trees). */
int ret = slh_dsa_128s_crypto_sign_keypair(pk, sk);
pq_drbg_zeroize();
return ret;
}
int fw_pq_ml_kem_768_keygen(const uint8_t seed[32],
uint8_t *pk, uint8_t *sk) {
if (seed == NULL || pk == NULL || sk == NULL) {
return -1;
}
pq_drbg_init(seed, 32);
int ret = crypto_kem_keypair(pk, sk);
pq_drbg_zeroize();
return ret;
}
/* --- Signing --- */
int fw_pq_ml_dsa_65_sign(uint8_t *sig, size_t *siglen,
const uint8_t *m, size_t mlen,
const uint8_t *sk) {
if (sig == NULL || siglen == NULL || m == NULL || sk == NULL) {
return -1;
}
return crypto_sign(sig, siglen, m, mlen, sk);
}
int fw_pq_ml_dsa_65_verify(const uint8_t *sig, size_t siglen,
const uint8_t *m, size_t mlen,
const uint8_t *pk) {
if (sig == NULL || m == NULL || pk == NULL) {
return -1;
}
/* crypto_sign_open expects (m_out, mlen_out, sm, smlen, pk) where sm
* is the signed message. For detached signatures we reconstruct: the
* PQClean API uses crypto_sign_open with sm = sig || m. */
/* For firmware use, we provide a simple verify by re-signing is not
* possible (non-deterministic). The PQClean crypto_sign_open expects
* the concatenated sig||msg format. Callers should use the PQClean
* API directly for verification, or we build the sm buffer here. */
uint8_t *sm = (uint8_t *)malloc(siglen + mlen);
if (sm == NULL) {
return -1;
}
memcpy(sm, sig, siglen);
memcpy(sm + siglen, m, mlen);
uint8_t *m_out = (uint8_t *)malloc(mlen);
if (m_out == NULL) {
free(sm);
return -1;
}
size_t mlen_out = 0;
int ret = crypto_sign_open(m_out, &mlen_out, sm, siglen + mlen, pk);
free(sm);
free(m_out);
return ret;
}
int fw_pq_slh_dsa_128s_sign(uint8_t *sig, size_t *siglen,
const uint8_t *m, size_t mlen,
const uint8_t *sk) {
if (sig == NULL || siglen == NULL || m == NULL || sk == NULL) {
return -1;
}
/* WARNING: This call takes 5-30 seconds on ESP32. */
return slh_dsa_128s_crypto_sign(sig, siglen, m, mlen, sk);
}
int fw_pq_slh_dsa_128s_verify(const uint8_t *sig, size_t siglen,
const uint8_t *m, size_t mlen,
const uint8_t *pk) {
if (sig == NULL || m == NULL || pk == NULL) {
return -1;
}
uint8_t *sm = (uint8_t *)malloc(siglen + mlen);
if (sm == NULL) {
return -1;
}
memcpy(sm, sig, siglen);
memcpy(sm + siglen, m, mlen);
uint8_t *m_out = (uint8_t *)malloc(mlen);
if (m_out == NULL) {
free(sm);
return -1;
}
size_t mlen_out = 0;
int ret = slh_dsa_128s_crypto_sign_open(m_out, &mlen_out, sm,
siglen + mlen, pk);
free(sm);
free(m_out);
return ret;
}
/* --- KEM --- */
int fw_pq_ml_kem_768_encaps(uint8_t *ct, uint8_t *ss, const uint8_t *pk) {
if (ct == NULL || ss == NULL || pk == NULL) {
return -1;
}
/* encaps uses real randomness (hardware RNG) — the DRBG is not
* initialized, so randombytes() falls back to esp_fill_random(). */
return crypto_kem_enc(ct, ss, pk);
}
int fw_pq_ml_kem_768_decaps(uint8_t *ss, const uint8_t *ct, const uint8_t *sk) {
if (ss == NULL || ct == NULL || sk == NULL) {
return -1;
}
return crypto_kem_dec(ss, ct, sk);
}

View File

@@ -0,0 +1,110 @@
/* pq_crypto_firmware.h — Post-quantum crypto wrappers for ESP32 firmware.
*
* Provides firmware-friendly wrappers around the PQClean algorithms:
* - ML-DSA-65 (FIPS 204 signatures)
* - SLH-DSA-128s (FIPS 205 hash-based signatures)
* - ML-KEM-768 (FIPS 203 key encapsulation)
*
* Key generation is deterministic from a 32-byte seed (derived from the
* mnemonic via BIP-32/HMAC-SHA512). The seed feeds the deterministic DRBG
* (pq_drbg_firmware.c) which replaces PQClean's randombytes() during keygen.
*
* ed25519 and x25519 are handled separately via mbedtls (see
* key_derivation.c) and are not part of this PQClean component.
*/
#ifndef FIRMWARE_PQ_CRYPTO_H
#define FIRMWARE_PQ_CRYPTO_H
#include <stddef.h>
#include <stdint.h>
/* --- Algorithm identifiers --- */
typedef enum {
FW_PQ_ALG_ML_DSA_65 = 0,
FW_PQ_ALG_SLH_DSA_128S,
FW_PQ_ALG_ML_KEM_768,
FW_PQ_ALG_UNKNOWN
} fw_pq_alg_t;
/* --- Key sizes (compile-time constants, matching PQClean api.h) --- */
#define FW_ML_DSA_65_PUBKEY_LEN 1952
#define FW_ML_DSA_65_PRIVKEY_LEN 4032
#define FW_ML_DSA_65_SIG_LEN 3309
#define FW_SLH_DSA_128S_PUBKEY_LEN 32
#define FW_SLH_DSA_128S_PRIVKEY_LEN 64
#define FW_SLH_DSA_128S_SIG_LEN 7856
#define FW_ML_KEM_768_PUBKEY_LEN 1184
#define FW_ML_KEM_768_PRIVKEY_LEN 2400
#define FW_ML_KEM_768_CIPHERTEXT_LEN 1088
#define FW_ML_KEM_768_SHARED_SECRET_LEN 32
/* --- Key generation (deterministic from seed) --- */
/* Generate an ML-DSA-65 keypair from a 32-byte seed.
* pk must be at least FW_ML_DSA_65_PUBKEY_LEN bytes.
* sk must be at least FW_ML_DSA_65_PRIVKEY_LEN bytes.
* Returns 0 on success, -1 on error. */
int fw_pq_ml_dsa_65_keygen(const uint8_t seed[32],
uint8_t *pk, uint8_t *sk);
/* Generate an SLH-DSA-128s keypair from a 32-byte seed.
* pk must be at least FW_SLH_DSA_128S_PUBKEY_LEN bytes.
* sk must be at least FW_SLH_DSA_128S_PRIVKEY_LEN bytes.
* Returns 0 on success, -1 on error.
* WARNING: SLH-DSA-128s keygen takes 5-30 seconds on ESP32. */
int fw_pq_slh_dsa_128s_keygen(const uint8_t seed[32],
uint8_t *pk, uint8_t *sk);
/* Generate an ML-KEM-768 keypair from a 32-byte seed.
* pk must be at least FW_ML_KEM_768_PUBKEY_LEN bytes.
* sk must be at least FW_ML_KEM_768_PRIVKEY_LEN bytes.
* Returns 0 on success, -1 on error. */
int fw_pq_ml_kem_768_keygen(const uint8_t seed[32],
uint8_t *pk, uint8_t *sk);
/* --- Signing (ML-DSA-65, SLH-DSA-128s) --- */
/* Sign a message with ML-DSA-65.
* sig must be at least FW_ML_DSA_65_SIG_LEN bytes.
* Returns 0 on success, -1 on error. */
int fw_pq_ml_dsa_65_sign(uint8_t *sig, size_t *siglen,
const uint8_t *m, size_t mlen,
const uint8_t *sk);
/* Verify an ML-DSA-65 signature.
* Returns 0 on valid, -1 on invalid. */
int fw_pq_ml_dsa_65_verify(const uint8_t *sig, size_t siglen,
const uint8_t *m, size_t mlen,
const uint8_t *pk);
/* Sign a message with SLH-DSA-128s.
* sig must be at least FW_SLH_DSA_128S_SIG_LEN bytes.
* WARNING: SLH-DSA-128s signing takes 5-30 seconds on ESP32.
* Returns 0 on success, -1 on error. */
int fw_pq_slh_dsa_128s_sign(uint8_t *sig, size_t *siglen,
const uint8_t *m, size_t mlen,
const uint8_t *sk);
/* Verify an SLH-DSA-128s signature.
* Returns 0 on valid, -1 on invalid. */
int fw_pq_slh_dsa_128s_verify(const uint8_t *sig, size_t siglen,
const uint8_t *m, size_t mlen,
const uint8_t *pk);
/* --- KEM (ML-KEM-768) --- */
/* Encapsulate: generate ciphertext + shared secret from a public key.
* Uses real randomness (ESP32 hardware RNG) — not the deterministic DRBG.
* ct must be at least FW_ML_KEM_768_CIPHERTEXT_LEN bytes.
* ss must be at least FW_ML_KEM_768_SHARED_SECRET_LEN bytes.
* Returns 0 on success, -1 on error. */
int fw_pq_ml_kem_768_encaps(uint8_t *ct, uint8_t *ss, const uint8_t *pk);
/* Decapsulate: recover shared secret from secret key + ciphertext.
* ss must be at least FW_ML_KEM_768_SHARED_SECRET_LEN bytes.
* Returns 0 on success, -1 on error. */
int fw_pq_ml_kem_768_decaps(uint8_t *ss, const uint8_t *ct, const uint8_t *sk);
#endif /* FIRMWARE_PQ_CRYPTO_H */

View File

@@ -1,5 +1,13 @@
#include <Adafruit_TinyUSB.h>
extern "C" {
#include "src/nostr_core/nostr_common.h"
#include "src/nostr_core/utils.h"
#include "src/nostr_core/nip006.h"
#include "src/nostr_core/nip001.h"
#include "src/cjson/cJSON.h"
}
#include "display.h"
#include "mnemonic_kb.h"
@@ -81,10 +89,22 @@ static uint16_t s_enter_selected_indices[12] = {0};
static bool s_enter_committed[12] = {false};
static void signer_enter_ready_screen();
static void set_device_mode(device_mode_t mode, bool blink_led);
// -------------------- Transport framing ----------------------
static uint8_t s_rx_buf[2048];
static size_t s_rx_len = 0;
enum rpc_transport_t {
RPC_TRANSPORT_WEBUSB = 0,
RPC_TRANSPORT_SERIAL = 1,
};
static rpc_transport_t s_rpc_reply_transport = RPC_TRANSPORT_WEBUSB;
static uint8_t s_rx_web_buf[2048];
static size_t s_rx_web_len = 0;
static uint8_t s_rx_serial_buf[2048];
static size_t s_rx_serial_len = 0;
static uint8_t s_tx_buf[2048];
// ---------------------- Encoder state ------------------------
@@ -234,21 +254,107 @@ static bool json_extract_string(const char *json, const char *key, char *out, si
return true;
}
// Deterministic placeholder key derivation for transport integration testing.
static void pseudo_pubkey_hex(char out_hex_64[65]) {
uint32_t h = 2166136261u;
for (size_t i = 0; i < strlen(s_mnemonic); i++) {
h ^= (uint8_t)s_mnemonic[i];
h *= 16777619u;
static bool json_extract_int(const char *json, const char *key, int *out) {
if (!json || !key || !out) {
return false;
}
for (int i = 0; i < 32; i++) {
uint8_t b = (uint8_t)((h >> ((i % 4) * 8)) ^ (i * 37));
static const char *hex = "0123456789abcdef";
out_hex_64[i * 2] = hex[(b >> 4) & 0x0F];
out_hex_64[i * 2 + 1] = hex[b & 0x0F];
char needle[64];
snprintf(needle, sizeof(needle), "\"%s\"", key);
const char *k = strstr(json, needle);
if (!k) {
return false;
}
const char *colon = strchr(k, ':');
if (!colon) {
return false;
}
colon++;
while (*colon == ' ' || *colon == '\t' || *colon == '\r' || *colon == '\n') {
colon++;
}
char *endptr = nullptr;
long v = strtol(colon, &endptr, 10);
if (endptr == colon) {
return false;
}
*out = (int)v;
return true;
}
static bool json_extract_first_param_object(const char *json, char *out, size_t out_sz) {
if (!json || !out || out_sz < 3) {
return false;
}
const char *params = strstr(json, "\"params\"");
if (!params) {
return false;
}
const char *arr = strchr(params, '[');
if (!arr) {
return false;
}
const char *start = strchr(arr, '{');
if (!start) {
return false;
}
int depth = 0;
bool in_string = false;
bool escape = false;
const char *p = start;
for (; *p; ++p) {
const char c = *p;
if (in_string) {
if (escape) {
escape = false;
} else if (c == '\\') {
escape = true;
} else if (c == '"') {
in_string = false;
}
continue;
}
if (c == '"') {
in_string = true;
continue;
}
if (c == '{') {
depth++;
} else if (c == '}') {
depth--;
if (depth == 0) {
const size_t n = (size_t)(p - start + 1);
if (n >= out_sz) {
return false;
}
memcpy(out, start, n);
out[n] = '\0';
return true;
}
}
}
return false;
}
static void secure_zero(void *p, size_t n) {
if (!p || n == 0) return;
volatile uint8_t *vp = reinterpret_cast<volatile uint8_t *>(p);
while (n--) {
*vp++ = 0;
}
out_hex_64[64] = '\0';
}
static void signer_apply_seed(const char *mnemonic) {
@@ -289,35 +395,68 @@ static bool wait_for_user_approval(uint32_t timeout_ms) {
static void send_json_response(const char *json) {
size_t n = strlen(json);
if (n > (sizeof(s_tx_buf) - 4)) return;
write_u32_be(s_tx_buf, (uint32_t)n);
memcpy(s_tx_buf + 4, json, n);
usb_web.write(s_tx_buf, n + 4);
usb_web.flush();
if (s_rpc_reply_transport == RPC_TRANSPORT_SERIAL) {
Serial.write(s_tx_buf, n + 4);
Serial.flush();
} else {
usb_web.write(s_tx_buf, n + 4);
usb_web.flush();
}
s_diag_responses_tx++;
}
static void send_rpc_result(const char *id, const char *result_json) {
char out[2048];
const char *rpc_id = (id && id[0]) ? id : "0";
const char *result = (result_json && result_json[0]) ? result_json : "null";
snprintf(out, sizeof(out), "{\"jsonrpc\":\"2.0\",\"id\":\"%s\",\"result\":%s}", rpc_id, result);
send_json_response(out);
}
static void send_rpc_error(const char *id, int code, const char *message) {
char out[1024];
const char *rpc_id = (id && id[0]) ? id : "0";
const char *msg = (message && message[0]) ? message : "error";
snprintf(out, sizeof(out),
"{\"jsonrpc\":\"2.0\",\"id\":\"%s\",\"error\":{\"code\":%d,\"message\":\"%s\"}}",
rpc_id, code, msg);
send_json_response(out);
}
static void handle_rpc(const char *req_json) {
char rpc_id[96] = {0};
(void)json_extract_string(req_json, "id", rpc_id, sizeof(rpc_id));
int nostr_index = 0;
(void)json_extract_int(req_json, "nostr_index", &nostr_index);
char method[64] = {0};
if (!json_extract_string(req_json, "method", method, sizeof(method))) {
send_json_response("{\"error\":{\"code\":-32600,\"message\":\"invalid request\"}}");
send_rpc_error(rpc_id, -32600, "invalid request");
// display_set_status("RPC invalid request");
return;
}
if (strcmp(method, "ping") == 0) {
send_json_response("{\"result\":\"pong\"}");
send_rpc_result(rpc_id, "\"pong\"");
// display_set_status("RPC ping");
return;
}
if (strcmp(method, "get_status") == 0) {
char resp[256];
snprintf(resp, sizeof(resp),
"{\"result\":{\"mode\":\"%s\",\"seed_loaded\":%s,\"auto_approve\":%s}}",
char result[256];
snprintf(result, sizeof(result),
"{\"mode\":\"%s\",\"seed_loaded\":%s,\"auto_approve\":%s,\"nostr_index\":%d}",
s_mode == MODE_MEDIA ? "media" : "signer",
s_seed_loaded ? "true" : "false",
s_auto_approve ? "true" : "false");
send_json_response(resp);
s_auto_approve ? "true" : "false",
nostr_index);
send_rpc_result(rpc_id, result);
// display_set_status("RPC get_status");
return;
}
@@ -325,7 +464,7 @@ static void handle_rpc(const char *req_json) {
if (strcmp(method, "set_mnemonic") == 0) {
char phrase[256] = {0};
if (!json_extract_string(req_json, "mnemonic", phrase, sizeof(phrase))) {
send_json_response("{\"error\":{\"code\":-32602,\"message\":\"missing mnemonic\"}}");
send_rpc_error(rpc_id, -32602, "missing mnemonic");
// display_set_status("Mnemonic missing");
return;
}
@@ -334,21 +473,21 @@ static void handle_rpc(const char *req_json) {
if (s_mode == MODE_SIGNER && s_seed_loaded) {
signer_enter_ready_screen();
}
send_json_response("{\"result\":\"ok\"}");
send_rpc_result(rpc_id, "\"ok\"");
return;
}
if (strcmp(method, "set_auto_approve") == 0) {
if (strstr(req_json, "\"value\":true") != nullptr) {
s_auto_approve = true;
send_json_response("{\"result\":true}");
send_rpc_result(rpc_id, "true");
// display_set_status("Auto-approve ON");
} else if (strstr(req_json, "\"value\":false") != nullptr) {
s_auto_approve = false;
send_json_response("{\"result\":false}");
send_rpc_result(rpc_id, "false");
// display_set_status("Auto-approve OFF");
} else {
send_json_response("{\"error\":{\"code\":-32602,\"message\":\"missing value\"}}");
send_rpc_error(rpc_id, -32602, "missing value");
// display_set_status("Auto-approve invalid");
}
return;
@@ -356,38 +495,45 @@ static void handle_rpc(const char *req_json) {
if (strcmp(method, "get_public_key") == 0) {
if (!s_seed_loaded) {
send_json_response("{\"error\":{\"code\":2014,\"message\":\"seed not loaded\"}}");
// display_set_status("No seed");
send_rpc_error(rpc_id, 2014, "seed not loaded");
return;
}
char pubhex[65];
pseudo_pubkey_hex(pubhex);
unsigned char private_key[32] = {0};
unsigned char public_key[32] = {0};
if (nostr_derive_keys_from_mnemonic(s_mnemonic, nostr_index, private_key, public_key) != NOSTR_SUCCESS) {
secure_zero(private_key, sizeof(private_key));
secure_zero(public_key, sizeof(public_key));
send_rpc_error(rpc_id, -32603, "key derivation failed");
return;
}
char resp[192];
snprintf(resp, sizeof(resp), "{\"result\":{\"pubkey\":\"%s\"}}", pubhex);
send_json_response(resp);
// display_set_status("Pubkey served");
char pubhex[65] = {0};
nostr_bytes_to_hex(public_key, 32, pubhex);
secure_zero(private_key, sizeof(private_key));
secure_zero(public_key, sizeof(public_key));
char result[96];
snprintf(result, sizeof(result), "\"%s\"", pubhex);
send_rpc_result(rpc_id, result);
return;
}
if (strcmp(method, "sign_event") == 0) {
if (!s_seed_loaded) {
send_json_response("{\"error\":{\"code\":2014,\"message\":\"seed not loaded\"}}");
// display_set_status("Sign blocked:no seed");
send_rpc_error(rpc_id, 2014, "seed not loaded");
return;
}
if (s_mode != MODE_SIGNER) {
send_json_response("{\"error\":{\"code\":2015,\"message\":\"not in signer mode\"}}");
// display_set_status("Sign blocked:mode");
send_rpc_error(rpc_id, 2015, "not in signer mode");
return;
}
bool approved = s_auto_approve ? true : wait_for_user_approval(30000);
if (!approved) {
send_json_response("{\"error\":{\"code\":2001,\"message\":\"user denied or timeout\"}}");
// Return signer UI screen after approval prompt
send_rpc_error(rpc_id, 2001, "user denied or timeout");
if (s_signer_ui_state == SIGNER_UI_MENU) {
display_show_signer_menu(s_signer_menu_selected);
} else if (s_signer_ui_state == SIGNER_UI_READY) {
@@ -396,8 +542,81 @@ static void handle_rpc(const char *req_json) {
return;
}
send_json_response("{\"result\":{\"sig\":\"dev_signature_placeholder\"}}");
// display_set_status("Event signed");
char event_obj[1400] = {0};
if (!json_extract_first_param_object(req_json, event_obj, sizeof(event_obj))) {
send_rpc_error(rpc_id, -32602, "missing event object");
return;
}
cJSON *event_in = cJSON_Parse(event_obj);
if (!event_in || !cJSON_IsObject(event_in)) {
if (event_in) cJSON_Delete(event_in);
send_rpc_error(rpc_id, -32602, "invalid event object");
return;
}
cJSON *kind_item = cJSON_GetObjectItemCaseSensitive(event_in, "kind");
cJSON *content_item = cJSON_GetObjectItemCaseSensitive(event_in, "content");
cJSON *tags_item = cJSON_GetObjectItemCaseSensitive(event_in, "tags");
cJSON *created_at_item = cJSON_GetObjectItemCaseSensitive(event_in, "created_at");
if (!cJSON_IsNumber(kind_item) || !cJSON_IsString(content_item)) {
cJSON_Delete(event_in);
send_rpc_error(rpc_id, -32602, "event missing kind/content");
return;
}
int kind = kind_item->valueint;
const char *content = content_item->valuestring ? content_item->valuestring : "";
time_t created_at = (time_t)time(nullptr);
if (cJSON_IsNumber(created_at_item)) {
created_at = (time_t)created_at_item->valuedouble;
}
cJSON *tags_dup = nullptr;
if (cJSON_IsArray(tags_item)) {
tags_dup = cJSON_Duplicate(tags_item, 1);
if (!tags_dup) {
cJSON_Delete(event_in);
send_rpc_error(rpc_id, -32603, "tags allocation failed");
return;
}
}
unsigned char private_key[32] = {0};
unsigned char public_key[32] = {0};
if (nostr_derive_keys_from_mnemonic(s_mnemonic, nostr_index, private_key, public_key) != NOSTR_SUCCESS) {
if (tags_dup) cJSON_Delete(tags_dup);
cJSON_Delete(event_in);
secure_zero(private_key, sizeof(private_key));
secure_zero(public_key, sizeof(public_key));
send_rpc_error(rpc_id, -32603, "key derivation failed");
return;
}
cJSON *signed_event = nostr_create_and_sign_event(kind, content, tags_dup, private_key, created_at);
secure_zero(private_key, sizeof(private_key));
secure_zero(public_key, sizeof(public_key));
if (tags_dup) cJSON_Delete(tags_dup);
cJSON_Delete(event_in);
if (!signed_event) {
send_rpc_error(rpc_id, -32603, "event signing failed");
return;
}
char *signed_event_json = cJSON_PrintUnformatted(signed_event);
cJSON_Delete(signed_event);
if (!signed_event_json) {
send_rpc_error(rpc_id, -32603, "event serialization failed");
return;
}
send_rpc_result(rpc_id, signed_event_json);
free(signed_event_json);
if (s_signer_ui_state == SIGNER_UI_MENU) {
display_show_signer_menu(s_signer_menu_selected);
} else if (s_signer_ui_state == SIGNER_UI_READY) {
@@ -406,20 +625,52 @@ static void handle_rpc(const char *req_json) {
return;
}
send_json_response("{\"error\":{\"code\":-32601,\"message\":\"method not found\"}}");
send_rpc_error(rpc_id, -32601, "method not found");
// display_set_status("RPC method missing");
}
static void pump_framed_requests(uint8_t *rx_buf, size_t *rx_len, rpc_transport_t transport) {
while (*rx_len >= 4) {
const uint32_t body_len = read_u32_be(rx_buf);
if (body_len > (sizeof(s_rx_web_buf) - 4)) {
*rx_len = 0;
s_rpc_reply_transport = transport;
send_json_response("{\"error\":{\"code\":-32000,\"message\":\"frame too large\"}}");
// display_set_status("Frame too large");
return;
}
if (*rx_len < (size_t)(4 + body_len)) {
return;
}
s_diag_frames_rx++;
char req[1536];
size_t n = body_len;
if (n >= sizeof(req)) n = sizeof(req) - 1;
memcpy(req, rx_buf + 4, n);
req[n] = '\0';
const size_t remain = *rx_len - (4 + body_len);
memmove(rx_buf, rx_buf + 4 + body_len, remain);
*rx_len = remain;
s_rpc_reply_transport = transport;
handle_rpc(req);
}
}
static void webusb_pump_frames() {
while (usb_web.available()) {
if (s_rx_len >= sizeof(s_rx_buf)) {
s_rx_len = 0;
if (s_rx_web_len >= sizeof(s_rx_web_buf)) {
s_rx_web_len = 0;
break;
}
int c = usb_web.read();
const int c = usb_web.read();
if (c < 0) break;
s_rx_buf[s_rx_len++] = (uint8_t)c;
s_rx_web_buf[s_rx_web_len++] = (uint8_t)c;
// DIAG: a byte arrived from the host. Pulse LED + count it so we can
// confirm, with no host tooling, that request bytes reach the device.
@@ -427,32 +678,25 @@ static void webusb_pump_frames() {
digitalWrite(LED_BUILTIN, LOW);
}
while (s_rx_len >= 4) {
s_diag_frames_rx++;
uint32_t body_len = read_u32_be(s_rx_buf);
if (body_len > (sizeof(s_rx_buf) - 4)) {
s_rx_len = 0;
send_json_response("{\"error\":{\"code\":-32000,\"message\":\"frame too large\"}}");
// display_set_status("Frame too large");
return;
pump_framed_requests(s_rx_web_buf, &s_rx_web_len, RPC_TRANSPORT_WEBUSB);
}
static void serial_pump_frames() {
while (Serial.available() > 0) {
if (s_rx_serial_len >= sizeof(s_rx_serial_buf)) {
s_rx_serial_len = 0;
break;
}
if (s_rx_len < (size_t)(4 + body_len)) {
return;
}
const int c = Serial.read();
if (c < 0) break;
s_rx_serial_buf[s_rx_serial_len++] = (uint8_t)c;
char req[1536];
size_t n = body_len;
if (n >= sizeof(req)) n = sizeof(req) - 1;
memcpy(req, s_rx_buf + 4, n);
req[n] = '\0';
size_t remain = s_rx_len - (4 + body_len);
memmove(s_rx_buf, s_rx_buf + 4 + body_len, remain);
s_rx_len = remain;
handle_rpc(req);
s_diag_bytes_rx++;
digitalWrite(LED_BUILTIN, LOW);
}
pump_framed_requests(s_rx_serial_buf, &s_rx_serial_len, RPC_TRANSPORT_SERIAL);
}
static void signer_enter_menu_screen() {
@@ -579,6 +823,24 @@ static void build_entered_mnemonic(char *out, size_t out_sz) {
}
}
static void set_device_mode(device_mode_t mode, bool blink_led) {
s_mode = mode;
display_set_mode(s_mode == MODE_SIGNER);
if (s_mode == MODE_SIGNER) {
display_set_view(DISPLAY_VIEW_SIGNER);
signer_enter_menu_screen();
// display_set_status("Signer mode");
} else {
display_set_view(DISPLAY_VIEW_VOLUME);
// display_set_status("Media mode");
}
if (blink_led) {
led_blink(s_mode == MODE_SIGNER ? 3 : 1, 80, 80);
}
}
static void handle_mode_switch_chord() {
const bool play = btn_pressed(PIN_BTN_PLAY);
const bool prev = btn_pressed(PIN_BTN_PREV);
@@ -589,19 +851,7 @@ static void handle_mode_switch_chord() {
}
s_mode_switch_latched = true;
s_mode = (s_mode == MODE_MEDIA) ? MODE_SIGNER : MODE_MEDIA;
display_set_mode(s_mode == MODE_SIGNER);
if (s_mode == MODE_SIGNER) {
display_set_view(DISPLAY_VIEW_SIGNER);
signer_enter_menu_screen();
// display_set_status("Signer mode");
} else {
display_set_view(DISPLAY_VIEW_VOLUME);
// display_set_status("Media mode");
}
led_blink(s_mode == MODE_SIGNER ? 3 : 1, 80, 80);
set_device_mode((s_mode == MODE_MEDIA) ? MODE_SIGNER : MODE_MEDIA, true);
return;
}
@@ -826,6 +1076,12 @@ void setup() {
pinMode(PIN_BTN_NEXT, INPUT_PULLUP);
pinMode(PIN_BTN_PREV, INPUT_PULLUP);
Serial.begin(115200);
if (nostr_init() != NOSTR_SUCCESS) {
// Keep running transport/UI so host can still diagnose, but signing will fail.
}
usb_web.setLandingPage(&landing_url);
usb_web.setStringDescriptor("n_signer WebUSB");
usb_web.begin();
@@ -881,6 +1137,7 @@ void loop() {
signer_mode_tick();
}
serial_pump_frames();
webusb_pump_frames();
// DIAG: periodically surface transport activity on the OLED status line so

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,306 @@
/*
Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef cJSON__h
#define cJSON__h
#ifdef __cplusplus
extern "C"
{
#endif
#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32))
#define __WINDOWS__
#endif
#ifdef __WINDOWS__
/* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 3 define options:
CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols
CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default)
CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol
For *nix builds that support visibility attribute, you can define similar behavior by
setting default visibility to hidden by adding
-fvisibility=hidden (for gcc)
or
-xldscope=hidden (for sun cc)
to CFLAGS
then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does
*/
#define CJSON_CDECL __cdecl
#define CJSON_STDCALL __stdcall
/* export symbols by default, this is necessary for copy pasting the C and header file */
#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS)
#define CJSON_EXPORT_SYMBOLS
#endif
#if defined(CJSON_HIDE_SYMBOLS)
#define CJSON_PUBLIC(type) type CJSON_STDCALL
#elif defined(CJSON_EXPORT_SYMBOLS)
#define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL
#elif defined(CJSON_IMPORT_SYMBOLS)
#define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL
#endif
#else /* !__WINDOWS__ */
#define CJSON_CDECL
#define CJSON_STDCALL
#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY)
#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type
#else
#define CJSON_PUBLIC(type) type
#endif
#endif
/* project version */
#define CJSON_VERSION_MAJOR 1
#define CJSON_VERSION_MINOR 7
#define CJSON_VERSION_PATCH 18
#include <stddef.h>
/* cJSON Types: */
#define cJSON_Invalid (0)
#define cJSON_False (1 << 0)
#define cJSON_True (1 << 1)
#define cJSON_NULL (1 << 2)
#define cJSON_Number (1 << 3)
#define cJSON_String (1 << 4)
#define cJSON_Array (1 << 5)
#define cJSON_Object (1 << 6)
#define cJSON_Raw (1 << 7) /* raw json */
#define cJSON_IsReference 256
#define cJSON_StringIsConst 512
/* The cJSON structure: */
typedef struct cJSON
{
/* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
struct cJSON *next;
struct cJSON *prev;
/* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
struct cJSON *child;
/* The type of the item, as above. */
int type;
/* The item's string, if type==cJSON_String and type == cJSON_Raw */
char *valuestring;
/* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */
int valueint;
/* The item's number, if type==cJSON_Number */
double valuedouble;
/* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
char *string;
} cJSON;
typedef struct cJSON_Hooks
{
/* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */
void *(CJSON_CDECL *malloc_fn)(size_t sz);
void (CJSON_CDECL *free_fn)(void *ptr);
} cJSON_Hooks;
typedef int cJSON_bool;
/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them.
* This is to prevent stack overflows. */
#ifndef CJSON_NESTING_LIMIT
#define CJSON_NESTING_LIMIT 1000
#endif
/* Limits the length of circular references can be before cJSON rejects to parse them.
* This is to prevent stack overflows. */
#ifndef CJSON_CIRCULAR_LIMIT
#define CJSON_CIRCULAR_LIMIT 10000
#endif
/* returns the version of cJSON as a string */
CJSON_PUBLIC(const char*) cJSON_Version(void);
/* Supply malloc, realloc and free functions to cJSON */
CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks);
/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */
/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */
CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value);
CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length);
/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */
/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */
CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated);
CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated);
/* Render a cJSON entity to text for transfer/storage. */
CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item);
/* Render a cJSON entity to text for transfer/storage without any formatting. */
CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item);
/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */
CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt);
/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */
/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */
CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format);
/* Delete a cJSON entity and all subentities. */
CJSON_PUBLIC(void) cJSON_Delete(cJSON *item);
/* Returns the number of items in an array (or object). */
CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array);
/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */
CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index);
/* Get item "string" from object. Case insensitive. */
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string);
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string);
CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string);
/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void);
/* Check item type and return its value */
CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item);
CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item);
/* These functions check the type of an item */
CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item);
/* These calls create a cJSON item of the appropriate type. */
CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean);
CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num);
CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string);
/* raw json */
CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw);
CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void);
/* Create a string where valuestring references a string so
* it will not be freed by cJSON_Delete */
CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string);
/* Create an object/array that only references it's elements so
* they will not be freed by cJSON_Delete */
CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child);
CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child);
/* These utilities create an Array of count items.
* The parameter count cannot be greater than the number of elements in the number array, otherwise array access will be out of bounds.*/
CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count);
/* Append item to the specified array/object. */
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item);
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item);
/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object.
* WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before
* writing to `item->string` */
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item);
/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item);
/* Remove/Detach items from Arrays/Objects. */
CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which);
CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string);
CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string);
CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string);
/* Update array items. */
CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement);
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem);
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem);
/* Duplicate a cJSON item */
CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse);
/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will
* need to be released. With recurse!=0, it will duplicate any children connected to the item.
* The item->next and ->prev pointers are always zero on return from Duplicate. */
/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal.
* case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */
CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive);
/* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from strings.
* The input pointer json cannot point to a read-only address area, such as a string constant,
* but should point to a readable and writable address area. */
CJSON_PUBLIC(void) cJSON_Minify(char *json);
/* Helper functions for creating and adding items to an object at the same time.
* They return the added item or NULL on failure. */
CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean);
CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number);
CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string);
CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw);
CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name);
/* When assigning an integer value, it needs to be propagated to valuedouble too. */
#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number))
/* helper for the cJSON_SetNumberValue macro */
CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number);
#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number))
/* Change the valuestring of a cJSON_String object, only takes effect when type of object is cJSON_String */
CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring);
/* If the object is not a boolean type this does nothing and returns cJSON_Invalid else it returns the new type*/
#define cJSON_SetBoolValue(object, boolValue) ( \
(object != NULL && ((object)->type & (cJSON_False|cJSON_True))) ? \
(object)->type=((object)->type &(~(cJSON_False|cJSON_True)))|((boolValue)?cJSON_True:cJSON_False) : \
cJSON_Invalid\
)
/* Macro for iterating over an array or object */
#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next)
/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */
CJSON_PUBLIC(void *) cJSON_malloc(size_t size);
CJSON_PUBLIC(void) cJSON_free(void *object);
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -0,0 +1,320 @@
#include "../../secp256k1/include/secp256k1.h"
#include "../../secp256k1/include/secp256k1_schnorrsig.h"
#include "../../secp256k1/include/secp256k1_ecdh.h"
#include <string.h>
#include <stdlib.h>
#include <stddef.h>
#include "../nostr_platform.h"
/*
* PRIVATE INTERNAL FUNCTIONS - NOT EXPORTED
* These functions are for internal library use only.
*/
/** Opaque data structure that holds a parsed and valid public key.
* Guaranteed to be 64 bytes in size, and can be safely copied/moved.
*/
typedef struct nostr_secp256k1_pubkey {
unsigned char data[64];
} nostr_secp256k1_pubkey;
/** Opaque data structure that holds a parsed keypair.
* Guaranteed to be 96 bytes in size, and can be safely copied/moved.
*/
typedef struct nostr_secp256k1_keypair {
unsigned char data[96];
} nostr_secp256k1_keypair;
/** Opaque data structure that holds a parsed x-only public key.
* Guaranteed to be 64 bytes in size, and can be safely copied/moved.
*/
typedef struct nostr_secp256k1_xonly_pubkey {
unsigned char data[64];
} nostr_secp256k1_xonly_pubkey;
// Global context for secp256k1 operations
static secp256k1_context* g_ctx = NULL;
int nostr_secp256k1_context_create(void) {
if (g_ctx != NULL) {
return 1; // Already initialized
}
g_ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY);
if (g_ctx == NULL) {
return 0;
}
// Add randomization to the context using platform entropy.
unsigned char randomize[32];
if (nostr_platform_random(randomize, sizeof(randomize)) != 0) {
secp256k1_context_destroy(g_ctx);
g_ctx = NULL;
return 0;
}
if (!secp256k1_context_randomize(g_ctx, randomize)) {
secp256k1_context_destroy(g_ctx);
g_ctx = NULL;
return 0;
}
return 1;
}
void nostr_secp256k1_context_destroy(void) {
if (g_ctx != NULL) {
secp256k1_context_destroy(g_ctx);
g_ctx = NULL;
}
}
int nostr_secp256k1_ec_seckey_verify(const unsigned char *seckey) {
if (g_ctx == NULL || seckey == NULL) {
return 0;
}
return secp256k1_ec_seckey_verify(g_ctx, seckey);
}
int nostr_secp256k1_ec_pubkey_create(nostr_secp256k1_pubkey *pubkey, const unsigned char *seckey) {
if (g_ctx == NULL || pubkey == NULL || seckey == NULL) {
return 0;
}
secp256k1_pubkey internal_pubkey;
if (!secp256k1_ec_pubkey_create(g_ctx, &internal_pubkey, seckey)) {
return 0;
}
// Copy the internal representation to our wrapper
memcpy(pubkey->data, &internal_pubkey, sizeof(secp256k1_pubkey));
return 1;
}
int nostr_secp256k1_keypair_create(nostr_secp256k1_keypair *keypair, const unsigned char *seckey) {
if (g_ctx == NULL || keypair == NULL || seckey == NULL) {
return 0;
}
secp256k1_keypair internal_keypair;
if (!secp256k1_keypair_create(g_ctx, &internal_keypair, seckey)) {
return 0;
}
// Copy the internal representation to our wrapper
memcpy(keypair->data, &internal_keypair, sizeof(secp256k1_keypair));
return 1;
}
int nostr_secp256k1_keypair_xonly_pub(nostr_secp256k1_xonly_pubkey *pubkey, const nostr_secp256k1_keypair *keypair) {
if (g_ctx == NULL || pubkey == NULL || keypair == NULL) {
return 0;
}
secp256k1_keypair internal_keypair;
secp256k1_xonly_pubkey internal_xonly;
// Copy from our wrapper to internal representation
memcpy(&internal_keypair, keypair->data, sizeof(secp256k1_keypair));
if (!secp256k1_keypair_xonly_pub(g_ctx, &internal_xonly, NULL, &internal_keypair)) {
return 0;
}
// Copy the internal representation to our wrapper
memcpy(pubkey->data, &internal_xonly, sizeof(secp256k1_xonly_pubkey));
return 1;
}
int nostr_secp256k1_xonly_pubkey_parse(nostr_secp256k1_xonly_pubkey *pubkey, const unsigned char *input32) {
if (g_ctx == NULL || pubkey == NULL || input32 == NULL) {
return 0;
}
secp256k1_xonly_pubkey internal_xonly;
if (!secp256k1_xonly_pubkey_parse(g_ctx, &internal_xonly, input32)) {
return 0;
}
// Copy the internal representation to our wrapper
memcpy(pubkey->data, &internal_xonly, sizeof(secp256k1_xonly_pubkey));
return 1;
}
int nostr_secp256k1_xonly_pubkey_serialize(unsigned char *output32, const nostr_secp256k1_xonly_pubkey *pubkey) {
if (g_ctx == NULL || output32 == NULL || pubkey == NULL) {
return 0;
}
secp256k1_xonly_pubkey internal_xonly;
// Copy from our wrapper to internal representation
memcpy(&internal_xonly, pubkey->data, sizeof(secp256k1_xonly_pubkey));
return secp256k1_xonly_pubkey_serialize(g_ctx, output32, &internal_xonly);
}
int nostr_secp256k1_schnorrsig_sign32(unsigned char *sig64, const unsigned char *msghash32, const nostr_secp256k1_keypair *keypair, const unsigned char *aux_rand32) {
if (g_ctx == NULL || sig64 == NULL || msghash32 == NULL || keypair == NULL) {
return 0;
}
secp256k1_keypair internal_keypair;
// Copy from our wrapper to internal representation
memcpy(&internal_keypair, keypair->data, sizeof(secp256k1_keypair));
return secp256k1_schnorrsig_sign32(g_ctx, sig64, msghash32, &internal_keypair, aux_rand32);
}
int nostr_secp256k1_schnorrsig_verify(const unsigned char *sig64, const unsigned char *msghash32, const nostr_secp256k1_xonly_pubkey *pubkey) {
if (g_ctx == NULL || sig64 == NULL || msghash32 == NULL || pubkey == NULL) {
return 0;
}
secp256k1_xonly_pubkey internal_xonly;
// Copy from our wrapper to internal representation
memcpy(&internal_xonly, pubkey->data, sizeof(secp256k1_xonly_pubkey));
return secp256k1_schnorrsig_verify(g_ctx, sig64, msghash32, 32, &internal_xonly);
}
int nostr_secp256k1_ec_pubkey_serialize_compressed(unsigned char *output, const nostr_secp256k1_pubkey *pubkey) {
if (g_ctx == NULL || output == NULL || pubkey == NULL) {
return 0;
}
secp256k1_pubkey internal_pubkey;
size_t outputlen = 33;
// Copy from our wrapper to internal representation
memcpy(&internal_pubkey, pubkey->data, sizeof(secp256k1_pubkey));
return secp256k1_ec_pubkey_serialize(g_ctx, output, &outputlen, &internal_pubkey, SECP256K1_EC_COMPRESSED);
}
int nostr_secp256k1_ec_seckey_tweak_add(unsigned char *seckey, const unsigned char *tweak) {
if (g_ctx == NULL || seckey == NULL || tweak == NULL) {
return 0;
}
return secp256k1_ec_seckey_tweak_add(g_ctx, seckey, tweak);
}
int nostr_secp256k1_ec_pubkey_parse(nostr_secp256k1_pubkey *pubkey, const unsigned char *input, size_t inputlen) {
if (g_ctx == NULL || pubkey == NULL || input == NULL) {
return 0;
}
secp256k1_pubkey internal_pubkey;
if (!secp256k1_ec_pubkey_parse(g_ctx, &internal_pubkey, input, inputlen)) {
return 0;
}
// Copy the internal representation to our wrapper
memcpy(pubkey->data, &internal_pubkey, sizeof(secp256k1_pubkey));
return 1;
}
int nostr_secp256k1_ecdh(unsigned char *result, const nostr_secp256k1_pubkey *pubkey, const unsigned char *seckey, void *hashfp, void *data) {
if (g_ctx == NULL || result == NULL || pubkey == NULL || seckey == NULL) {
return 0;
}
secp256k1_pubkey internal_pubkey;
// Copy from our wrapper to internal representation
memcpy(&internal_pubkey, pubkey->data, sizeof(secp256k1_pubkey));
return secp256k1_ecdh(g_ctx, result, &internal_pubkey, seckey, hashfp, data);
}
int nostr_secp256k1_ec_pubkey_tweak_mul(nostr_secp256k1_pubkey* pubkey, const unsigned char* tweak32) {
if (g_ctx == NULL || pubkey == NULL || tweak32 == NULL) {
return 0;
}
secp256k1_pubkey internal_pubkey;
memcpy(&internal_pubkey, pubkey->data, sizeof(secp256k1_pubkey));
if (!secp256k1_ec_pubkey_tweak_mul(g_ctx, &internal_pubkey, tweak32)) {
return 0;
}
memcpy(pubkey->data, &internal_pubkey, sizeof(secp256k1_pubkey));
return 1;
}
int nostr_secp256k1_ec_pubkey_negate(nostr_secp256k1_pubkey* pubkey) {
if (g_ctx == NULL || pubkey == NULL) {
return 0;
}
secp256k1_pubkey internal_pubkey;
memcpy(&internal_pubkey, pubkey->data, sizeof(secp256k1_pubkey));
if (!secp256k1_ec_pubkey_negate(g_ctx, &internal_pubkey)) {
return 0;
}
memcpy(pubkey->data, &internal_pubkey, sizeof(secp256k1_pubkey));
return 1;
}
int nostr_secp256k1_ec_pubkey_combine(nostr_secp256k1_pubkey* out,
const nostr_secp256k1_pubkey* const* ins,
size_t n) {
if (g_ctx == NULL || out == NULL || ins == NULL || n == 0) {
return 0;
}
secp256k1_pubkey* parsed = (secp256k1_pubkey*)calloc(n, sizeof(secp256k1_pubkey));
const secp256k1_pubkey** ptrs = (const secp256k1_pubkey**)calloc(n, sizeof(secp256k1_pubkey*));
if (!parsed || !ptrs) {
free(parsed);
free(ptrs);
return 0;
}
for (size_t i = 0; i < n; i++) {
if (!ins[i]) {
free(parsed);
free(ptrs);
return 0;
}
memcpy(&parsed[i], ins[i]->data, sizeof(secp256k1_pubkey));
ptrs[i] = &parsed[i];
}
secp256k1_pubkey combined;
int ok = secp256k1_ec_pubkey_combine(g_ctx, &combined, ptrs, n);
free(parsed);
free(ptrs);
if (!ok) {
return 0;
}
memcpy(out->data, &combined, sizeof(secp256k1_pubkey));
return 1;
}
int nostr_secp256k1_get_random_bytes(unsigned char *buf, size_t len) {
if (buf == NULL || len == 0) {
return 0;
}
if (nostr_platform_random(buf, len) != 0) {
return 0;
}
return 1;
}

View File

@@ -0,0 +1,345 @@
/*
* NOSTR Core Library - NIP-001: Basic Protocol Flow
*
* Event creation, signing, serialization and core protocol functions
*/
#include "nip001.h"
#include "utils.h"
#include "../cjson/cJSON.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "../nostr_core/nostr_common.h"
// Forward declarations for crypto functions (private API)
// These functions are implemented in crypto/ but not exposed through public headers
typedef struct {
unsigned char data[64];
} nostr_secp256k1_xonly_pubkey;
int nostr_secp256k1_xonly_pubkey_parse(nostr_secp256k1_xonly_pubkey* pubkey, const unsigned char* input32);
int nostr_secp256k1_schnorrsig_verify(const unsigned char* sig64, const unsigned char* msg32, const nostr_secp256k1_xonly_pubkey* pubkey);
// Declare utility functions
void nostr_bytes_to_hex(const unsigned char* bytes, size_t len, char* hex);
int nostr_hex_to_bytes(const char* hex, unsigned char* bytes, size_t len);
int nostr_sha256(const unsigned char* data, size_t len, unsigned char* hash);
int nostr_ec_public_key_from_private_key(const unsigned char* private_key, unsigned char* public_key);
int nostr_ec_sign(const unsigned char* private_key, const unsigned char* hash, unsigned char* signature);
/**
* Create and sign a NOSTR event
*/
cJSON* nostr_create_and_sign_event(int kind, const char* content, cJSON* tags, const unsigned char* private_key, time_t timestamp) {
if (!private_key) {
return NULL;
}
if (!content) {
content = ""; // Default to empty content
}
// Convert private key to public key
unsigned char public_key[32];
if (nostr_ec_public_key_from_private_key(private_key, public_key) != 0) {
return NULL;
}
// Convert public key to hex
char pubkey_hex[65];
nostr_bytes_to_hex(public_key, 32, pubkey_hex);
// Create event structure
cJSON* event = cJSON_CreateObject();
if (!event) {
return NULL;
}
// Use provided timestamp or current time if timestamp is 0
time_t event_time = (timestamp == 0) ? time(NULL) : timestamp;
cJSON_AddStringToObject(event, "pubkey", pubkey_hex);
cJSON_AddNumberToObject(event, "created_at", (double)event_time);
cJSON_AddNumberToObject(event, "kind", kind);
// Add tags (copy provided tags or create empty array)
if (tags) {
cJSON_AddItemToObject(event, "tags", cJSON_Duplicate(tags, 1));
} else {
cJSON_AddItemToObject(event, "tags", cJSON_CreateArray());
}
cJSON_AddStringToObject(event, "content", content);
// ============================================================================
// INLINE SERIALIZATION AND SIGNING LOGIC
// ============================================================================
// Get event fields for serialization
cJSON* pubkey_item = cJSON_GetObjectItem(event, "pubkey");
cJSON* created_at_item = cJSON_GetObjectItem(event, "created_at");
cJSON* kind_item = cJSON_GetObjectItem(event, "kind");
cJSON* tags_item = cJSON_GetObjectItem(event, "tags");
cJSON* content_item = cJSON_GetObjectItem(event, "content");
if (!pubkey_item || !created_at_item || !kind_item || !tags_item || !content_item) {
cJSON_Delete(event);
return NULL;
}
// Create serialization array: [0, pubkey, created_at, kind, tags, content]
cJSON* serialize_array = cJSON_CreateArray();
if (!serialize_array) {
cJSON_Delete(event);
return NULL;
}
cJSON_AddItemToArray(serialize_array, cJSON_CreateNumber(0));
cJSON_AddItemToArray(serialize_array, cJSON_Duplicate(pubkey_item, 1));
cJSON_AddItemToArray(serialize_array, cJSON_Duplicate(created_at_item, 1));
cJSON_AddItemToArray(serialize_array, cJSON_Duplicate(kind_item, 1));
cJSON_AddItemToArray(serialize_array, cJSON_Duplicate(tags_item, 1));
cJSON_AddItemToArray(serialize_array, cJSON_Duplicate(content_item, 1));
char* serialize_string = cJSON_PrintUnformatted(serialize_array);
cJSON_Delete(serialize_array);
if (!serialize_string) {
cJSON_Delete(event);
return NULL;
}
// Hash the serialized event
unsigned char event_hash[32];
if (nostr_sha256((const unsigned char*)serialize_string, strlen(serialize_string), event_hash) != 0) {
free(serialize_string);
cJSON_Delete(event);
return NULL;
}
// Convert hash to hex for event ID
char event_id[65];
nostr_bytes_to_hex(event_hash, 32, event_id);
// Sign the hash using ECDSA
unsigned char signature[64];
if (nostr_ec_sign(private_key, event_hash, signature) != 0) {
free(serialize_string);
cJSON_Delete(event);
return NULL;
}
// Convert signature to hex
char sig_hex[129];
nostr_bytes_to_hex(signature, 64, sig_hex);
// Add ID and signature to the event
cJSON_AddStringToObject(event, "id", event_id);
cJSON_AddStringToObject(event, "sig", sig_hex);
free(serialize_string);
return event;
}
/**
* Validate the structure of a NOSTR event
* Checks required fields, types, and basic format validation
*/
int nostr_validate_event_structure(cJSON* event) {
if (!event || !cJSON_IsObject(event)) {
return NOSTR_ERROR_EVENT_INVALID_STRUCTURE;
}
// Check required fields exist
cJSON* id_item = cJSON_GetObjectItem(event, "id");
cJSON* pubkey_item = cJSON_GetObjectItem(event, "pubkey");
cJSON* created_at_item = cJSON_GetObjectItem(event, "created_at");
cJSON* kind_item = cJSON_GetObjectItem(event, "kind");
cJSON* tags_item = cJSON_GetObjectItem(event, "tags");
cJSON* content_item = cJSON_GetObjectItem(event, "content");
cJSON* sig_item = cJSON_GetObjectItem(event, "sig");
if (!id_item || !pubkey_item || !created_at_item || !kind_item ||
!tags_item || !content_item || !sig_item) {
return NOSTR_ERROR_EVENT_INVALID_STRUCTURE;
}
// Validate field types
if (!cJSON_IsString(id_item)) return NOSTR_ERROR_EVENT_INVALID_ID;
if (!cJSON_IsString(pubkey_item)) return NOSTR_ERROR_EVENT_INVALID_PUBKEY;
if (!cJSON_IsNumber(created_at_item)) return NOSTR_ERROR_EVENT_INVALID_CREATED_AT;
if (!cJSON_IsNumber(kind_item)) return NOSTR_ERROR_EVENT_INVALID_KIND;
if (!cJSON_IsArray(tags_item)) return NOSTR_ERROR_EVENT_INVALID_TAGS;
if (!cJSON_IsString(content_item)) return NOSTR_ERROR_EVENT_INVALID_CONTENT;
if (!cJSON_IsString(sig_item)) return NOSTR_ERROR_EVENT_INVALID_SIGNATURE;
// Validate hex string lengths
const char* id_str = cJSON_GetStringValue(id_item);
const char* pubkey_str = cJSON_GetStringValue(pubkey_item);
const char* sig_str = cJSON_GetStringValue(sig_item);
if (!id_str || strlen(id_str) != 64) return NOSTR_ERROR_EVENT_INVALID_ID;
if (!pubkey_str || strlen(pubkey_str) != 64) return NOSTR_ERROR_EVENT_INVALID_PUBKEY;
if (!sig_str || strlen(sig_str) != 128) return NOSTR_ERROR_EVENT_INVALID_SIGNATURE;
// Validate hex characters (lowercase)
for (int i = 0; i < 64; i++) {
char c = id_str[i];
if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))) {
return NOSTR_ERROR_EVENT_INVALID_ID;
}
c = pubkey_str[i];
if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))) {
return NOSTR_ERROR_EVENT_INVALID_PUBKEY;
}
}
// Validate signature hex characters (lowercase) - 128 characters
for (int i = 0; i < 128; i++) {
char c = sig_str[i];
if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))) {
return NOSTR_ERROR_EVENT_INVALID_SIGNATURE;
}
}
// Validate created_at is a valid timestamp (positive number)
double created_at = cJSON_GetNumberValue(created_at_item);
if (created_at < 0) return NOSTR_ERROR_EVENT_INVALID_CREATED_AT;
// Validate kind is valid (0-65535)
double kind = cJSON_GetNumberValue(kind_item);
if (kind < 0 || kind > 65535 || kind != (int)kind) {
return NOSTR_ERROR_EVENT_INVALID_KIND;
}
// Validate tags array structure (array of arrays of strings)
cJSON* tag_item;
cJSON_ArrayForEach(tag_item, tags_item) {
if (!cJSON_IsArray(tag_item)) {
return NOSTR_ERROR_EVENT_INVALID_TAGS;
}
cJSON* tag_element;
cJSON_ArrayForEach(tag_element, tag_item) {
if (!cJSON_IsString(tag_element)) {
return NOSTR_ERROR_EVENT_INVALID_TAGS;
}
}
}
return NOSTR_SUCCESS;
}
/**
* Verify the cryptographic signature of a NOSTR event
* Validates event ID and signature according to NIP-01
*/
int nostr_verify_event_signature(cJSON* event) {
if (!event) {
return NOSTR_ERROR_INVALID_INPUT;
}
// Get event fields
cJSON* id_item = cJSON_GetObjectItem(event, "id");
cJSON* pubkey_item = cJSON_GetObjectItem(event, "pubkey");
cJSON* created_at_item = cJSON_GetObjectItem(event, "created_at");
cJSON* kind_item = cJSON_GetObjectItem(event, "kind");
cJSON* tags_item = cJSON_GetObjectItem(event, "tags");
cJSON* content_item = cJSON_GetObjectItem(event, "content");
cJSON* sig_item = cJSON_GetObjectItem(event, "sig");
if (!id_item || !pubkey_item || !created_at_item || !kind_item ||
!tags_item || !content_item || !sig_item) {
return NOSTR_ERROR_EVENT_INVALID_STRUCTURE;
}
// Create serialization array: [0, pubkey, created_at, kind, tags, content]
cJSON* serialize_array = cJSON_CreateArray();
if (!serialize_array) {
return NOSTR_ERROR_MEMORY_FAILED;
}
cJSON_AddItemToArray(serialize_array, cJSON_CreateNumber(0));
cJSON_AddItemToArray(serialize_array, cJSON_Duplicate(pubkey_item, 1));
cJSON_AddItemToArray(serialize_array, cJSON_Duplicate(created_at_item, 1));
cJSON_AddItemToArray(serialize_array, cJSON_Duplicate(kind_item, 1));
cJSON_AddItemToArray(serialize_array, cJSON_Duplicate(tags_item, 1));
cJSON_AddItemToArray(serialize_array, cJSON_Duplicate(content_item, 1));
char* serialize_string = cJSON_PrintUnformatted(serialize_array);
cJSON_Delete(serialize_array);
if (!serialize_string) {
return NOSTR_ERROR_MEMORY_FAILED;
}
// Hash the serialized event
unsigned char event_hash[32];
if (nostr_sha256((const unsigned char*)serialize_string, strlen(serialize_string), event_hash) != 0) {
free(serialize_string);
return NOSTR_ERROR_CRYPTO_FAILED;
}
// Convert hash to hex for event ID verification
char calculated_id[65];
nostr_bytes_to_hex(event_hash, 32, calculated_id);
// Compare with provided event ID
const char* provided_id = cJSON_GetStringValue(id_item);
if (!provided_id || strcmp(calculated_id, provided_id) != 0) {
free(serialize_string);
return NOSTR_ERROR_EVENT_INVALID_ID;
}
// Verify signature
const char* pubkey_str = cJSON_GetStringValue(pubkey_item);
const char* sig_str = cJSON_GetStringValue(sig_item);
if (!pubkey_str || !sig_str) {
free(serialize_string);
return NOSTR_ERROR_EVENT_INVALID_STRUCTURE;
}
// Convert hex strings to bytes
unsigned char pubkey_bytes[32];
unsigned char sig_bytes[64];
if (nostr_hex_to_bytes(pubkey_str, pubkey_bytes, 32) != 0 ||
nostr_hex_to_bytes(sig_str, sig_bytes, 64) != 0) {
free(serialize_string);
return NOSTR_ERROR_CRYPTO_FAILED;
}
// Parse the public key into secp256k1 format
nostr_secp256k1_xonly_pubkey xonly_pubkey;
if (!nostr_secp256k1_xonly_pubkey_parse(&xonly_pubkey, pubkey_bytes)) {
free(serialize_string);
return NOSTR_ERROR_EVENT_INVALID_PUBKEY;
}
// Verify Schnorr signature
if (!nostr_secp256k1_schnorrsig_verify(sig_bytes, event_hash, &xonly_pubkey)) {
free(serialize_string);
return NOSTR_ERROR_EVENT_INVALID_SIGNATURE;
}
free(serialize_string);
return NOSTR_SUCCESS;
}
/**
* Complete validation of a NOSTR event
* Performs both structure and cryptographic validation
*/
int nostr_validate_event(cJSON* event) {
// First validate structure (fast check)
int structure_result = nostr_validate_event_structure(event);
if (structure_result != NOSTR_SUCCESS) {
return structure_result;
}
// Then verify signature (expensive check)
return nostr_verify_event_signature(event);
}

View File

@@ -0,0 +1,23 @@
/*
* NOSTR Core Library - NIP-001: Basic Protocol Flow
*
* Event creation, signing, serialization and core protocol functions
*/
#ifndef NIP001_H
#define NIP001_H
#include <stdint.h>
#include <time.h>
#include "../cjson/cJSON.h"
// Function declarations
cJSON* nostr_create_and_sign_event(int kind, const char* content, cJSON* tags, const unsigned char* private_key, time_t timestamp);
// Event validation functions
int nostr_validate_event_structure(cJSON* event);
int nostr_verify_event_signature(cJSON* event);
int nostr_validate_event(cJSON* event);
#endif // NIP001_H

View File

@@ -0,0 +1,104 @@
/*
* NOSTR Core Library - NIP-006: Key Derivation from Mnemonic
*/
#include "nip006.h"
#include "utils.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include "../nostr_core/nostr_common.h"
#include "nostr_platform.h"
int nostr_generate_keypair(unsigned char* private_key, unsigned char* public_key) {
if (!private_key || !public_key) {
return NOSTR_ERROR_INVALID_INPUT;
}
if (nostr_platform_random(private_key, 32) != 0) {
return NOSTR_ERROR_IO_FAILED;
}
// Validate private key
if (nostr_ec_private_key_verify(private_key) != 0) {
return NOSTR_ERROR_CRYPTO_FAILED;
}
// Generate public key from private key (already x-only for NOSTR)
if (nostr_ec_public_key_from_private_key(private_key, public_key) != 0) {
return NOSTR_ERROR_CRYPTO_FAILED;
}
return NOSTR_SUCCESS;
}
int nostr_generate_mnemonic_and_keys(char* mnemonic, size_t mnemonic_size,
int account, unsigned char* private_key,
unsigned char* public_key) {
if (!mnemonic || mnemonic_size < 256 || !private_key || !public_key) {
return NOSTR_ERROR_INVALID_INPUT;
}
// Generate entropy for 12-word mnemonic
unsigned char entropy[16];
if (nostr_platform_random(entropy, sizeof(entropy)) != 0) {
return NOSTR_ERROR_IO_FAILED;
}
// Generate mnemonic from entropy
if (nostr_bip39_mnemonic_from_bytes(entropy, sizeof(entropy), mnemonic) != 0) {
return NOSTR_ERROR_CRYPTO_FAILED;
}
// Derive keys from the generated mnemonic
return nostr_derive_keys_from_mnemonic(mnemonic, account, private_key, public_key);
}
int nostr_derive_keys_from_mnemonic(const char* mnemonic, int account,
unsigned char* private_key, unsigned char* public_key) {
if (!mnemonic || !private_key || !public_key) {
return NOSTR_ERROR_INVALID_INPUT;
}
// Validate mnemonic
if (nostr_bip39_mnemonic_validate(mnemonic) != 0) {
return NOSTR_ERROR_INVALID_INPUT;
}
// Convert mnemonic to seed
unsigned char seed[64];
if (nostr_bip39_mnemonic_to_seed(mnemonic, "", seed, sizeof(seed)) != 0) {
return NOSTR_ERROR_CRYPTO_FAILED;
}
// Derive master key from seed
nostr_hd_key_t master_key;
if (nostr_bip32_key_from_seed(seed, sizeof(seed), &master_key) != 0) {
return NOSTR_ERROR_CRYPTO_FAILED;
}
// NIP-06 path: m/44'/1237'/account'/0/0
nostr_hd_key_t derived_key;
uint32_t path[] = {
0x80000000 + 44, // 44' (hardened)
0x80000000 + 1237, // 1237' (hardened)
0x80000000 + account, // account' (hardened)
0, // 0 (not hardened)
0 // 0 (not hardened)
};
if (nostr_bip32_derive_path(&master_key, path, sizeof(path) / sizeof(path[0]), &derived_key) != 0) {
return NOSTR_ERROR_CRYPTO_FAILED;
}
// Extract private key and public key
memcpy(private_key, derived_key.private_key, 32);
memcpy(public_key, derived_key.public_key + 1, 32); // Remove compression prefix for x-only
return NOSTR_SUCCESS;
}
// Note: nostr_detect_input_type, nostr_decode_nsec, and nostr_decode_npub
// are implemented in NIP-019 to avoid multiple definitions

View File

@@ -0,0 +1,30 @@
/*
* NOSTR Core Library - NIP-006: Key Derivation from Mnemonic
*/
#ifndef NIP006_H
#define NIP006_H
#include "nip001.h"
#include <stdint.h>
// Input type detection
typedef enum {
NOSTR_INPUT_UNKNOWN = 0,
NOSTR_INPUT_NSEC_HEX,
NOSTR_INPUT_NSEC_BECH32,
NOSTR_INPUT_MNEMONIC
} nostr_input_type_t;
// Function declarations
int nostr_generate_keypair(unsigned char* private_key, unsigned char* public_key);
int nostr_generate_mnemonic_and_keys(char* mnemonic, size_t mnemonic_size,
int account, unsigned char* private_key,
unsigned char* public_key);
int nostr_derive_keys_from_mnemonic(const char* mnemonic, int account,
unsigned char* private_key, unsigned char* public_key);
nostr_input_type_t nostr_detect_input_type(const char* input);
int nostr_decode_nsec(const char* input, unsigned char* private_key);
int nostr_decode_npub(const char* input, unsigned char* public_key);
#endif // NIP006_H

View File

@@ -0,0 +1,265 @@
/*
* NOSTR Core Library - NIP-019: Bech32-encoded Entities
*/
#include "nip019.h"
#include "utils.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "../nostr_core/nostr_common.h"
#define BECH32_CONST 1
static const char bech32_charset[] = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
static const int8_t bech32_charset_rev[128] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
15, -1, 10, 17, 21, 20, 26, 30, 7, 5, -1, -1, -1, -1, -1, -1,
-1, 29, -1, 24, 13, 25, 9, 8, 23, -1, 18, 22, 31, 27, 19, -1,
1, 0, 3, 16, 11, 28, 12, 14, 6, 4, 2, -1, -1, -1, -1, -1,
-1, 29, -1, 24, 13, 25, 9, 8, 23, -1, 18, 22, 31, 27, 19, -1,
1, 0, 3, 16, 11, 28, 12, 14, 6, 4, 2, -1, -1, -1, -1, -1
};
static uint32_t bech32_polymod_step(uint32_t pre) {
uint8_t b = pre >> 25;
return ((pre & 0x1FFFFFF) << 5) ^
(-((b >> 0) & 1) & 0x3b6a57b2UL) ^
(-((b >> 1) & 1) & 0x26508e6dUL) ^
(-((b >> 2) & 1) & 0x1ea119faUL) ^
(-((b >> 3) & 1) & 0x3d4233ddUL) ^
(-((b >> 4) & 1) & 0x2a1462b3UL);
}
static int convert_bits(uint8_t *out, size_t *outlen, int outbits, const uint8_t *in, size_t inlen, int inbits, int pad) {
uint32_t val = 0;
int bits = 0;
uint32_t maxv = (((uint32_t)1) << outbits) - 1;
*outlen = 0;
while (inlen--) {
val = (val << inbits) | *(in++);
bits += inbits;
while (bits >= outbits) {
bits -= outbits;
out[(*outlen)++] = (val >> bits) & maxv;
}
}
if (pad) {
if (bits) {
out[(*outlen)++] = (val << (outbits - bits)) & maxv;
}
} else if (((val << (outbits - bits)) & maxv) || bits >= inbits) {
return 0;
}
return 1;
}
static int bech32_encode(char *output, const char *hrp, const uint8_t *data, size_t data_len) {
uint32_t chk = 1;
size_t i, hrp_len = strlen(hrp);
for (i = 0; i < hrp_len; ++i) {
int ch = hrp[i];
if (ch < 33 || ch > 126) return 0;
if (ch >= 'A' && ch <= 'Z') return 0;
chk = bech32_polymod_step(chk) ^ (ch >> 5);
}
chk = bech32_polymod_step(chk);
for (i = 0; i < hrp_len; ++i) {
chk = bech32_polymod_step(chk) ^ (hrp[i] & 0x1f);
*(output++) = hrp[i];
}
*(output++) = '1';
for (i = 0; i < data_len; ++i) {
if (*data >> 5) return 0;
chk = bech32_polymod_step(chk) ^ (*data);
*(output++) = bech32_charset[*(data++)];
}
for (i = 0; i < 6; ++i) {
chk = bech32_polymod_step(chk);
}
chk ^= BECH32_CONST;
for (i = 0; i < 6; ++i) {
*(output++) = bech32_charset[(chk >> ((5 - i) * 5)) & 0x1f];
}
*output = 0;
return 1;
}
static int bech32_decode(const char* input, const char* hrp, unsigned char* data, size_t* data_len) {
if (!input || !hrp || !data || !data_len) {
return 0;
}
size_t input_len = strlen(input);
size_t hrp_len = strlen(hrp);
if (input_len < hrp_len + 7) return 0;
if (strncmp(input, hrp, hrp_len) != 0) return 0;
if (input[hrp_len] != '1') return 0;
const char* data_part = input + hrp_len + 1;
size_t data_part_len = input_len - hrp_len - 1;
uint8_t values[256];
for (size_t i = 0; i < data_part_len; i++) {
unsigned char c = (unsigned char)data_part[i];
if (c >= 128) return 0;
int8_t val = bech32_charset_rev[c];
if (val == -1) return 0;
values[i] = (uint8_t)val;
}
if (data_part_len < 6) return 0;
uint32_t chk = 1;
for (size_t i = 0; i < hrp_len; i++) {
chk = bech32_polymod_step(chk) ^ (hrp[i] >> 5);
}
chk = bech32_polymod_step(chk);
for (size_t i = 0; i < hrp_len; i++) {
chk = bech32_polymod_step(chk) ^ (hrp[i] & 0x1f);
}
for (size_t i = 0; i < data_part_len; i++) {
chk = bech32_polymod_step(chk) ^ values[i];
}
if (chk != BECH32_CONST) return 0;
size_t payload_len = data_part_len - 6;
size_t decoded_len;
if (!convert_bits(data, &decoded_len, 8, values, payload_len, 5, 0)) {
return 0;
}
*data_len = decoded_len;
return 1;
}
int nostr_key_to_bech32(const unsigned char* key, const char* hrp, char* output) {
if (!key || !hrp || !output) {
return NOSTR_ERROR_INVALID_INPUT;
}
uint8_t conv[64];
size_t conv_len;
if (!convert_bits(conv, &conv_len, 5, key, 32, 8, 1)) {
return NOSTR_ERROR_CRYPTO_FAILED;
}
if (!bech32_encode(output, hrp, conv, conv_len)) {
return NOSTR_ERROR_CRYPTO_FAILED;
}
return NOSTR_SUCCESS;
}
nostr_input_type_t nostr_detect_input_type(const char* input) {
if (!input || strlen(input) == 0) {
return NOSTR_INPUT_UNKNOWN;
}
size_t len = strlen(input);
// Check for bech32 nsec
if (len > 5 && strncmp(input, "nsec1", 5) == 0) {
return NOSTR_INPUT_NSEC_BECH32;
}
// Check for hex nsec (64 characters, all hex)
if (len == 64) {
int is_hex = 1;
for (size_t i = 0; i < len; i++) {
if (!isxdigit((unsigned char)input[i])) {
is_hex = 0;
break;
}
}
if (is_hex) {
return NOSTR_INPUT_NSEC_HEX;
}
}
// Check for mnemonic (space-separated words)
int word_count = 0;
char temp[1024];
strncpy(temp, input, sizeof(temp) - 1);
temp[sizeof(temp) - 1] = '\0';
char* token = strtok(temp, " ");
while (token != NULL) {
word_count++;
token = strtok(NULL, " ");
}
// BIP39 mnemonics are typically 12, 18, or 24 words
if (word_count >= 12 && word_count <= 24) {
return NOSTR_INPUT_MNEMONIC;
}
return NOSTR_INPUT_UNKNOWN;
}
int nostr_decode_nsec(const char* input, unsigned char* private_key) {
if (!input || !private_key) {
return NOSTR_ERROR_INVALID_INPUT;
}
nostr_input_type_t type = nostr_detect_input_type(input);
if (type == NOSTR_INPUT_NSEC_HEX) {
if (nostr_hex_to_bytes(input, private_key, 32) != NOSTR_SUCCESS) {
return NOSTR_ERROR_INVALID_INPUT;
}
} else if (type == NOSTR_INPUT_NSEC_BECH32) {
size_t decoded_len;
if (!bech32_decode(input, "nsec", private_key, &decoded_len)) {
return NOSTR_ERROR_INVALID_INPUT;
}
if (decoded_len != 32) {
return NOSTR_ERROR_INVALID_INPUT;
}
} else {
return NOSTR_ERROR_INVALID_INPUT;
}
// TODO: Add private key validation if crypto functions are available
return NOSTR_SUCCESS;
}
int nostr_decode_npub(const char* input, unsigned char* public_key) {
if (!input || !public_key) {
return NOSTR_ERROR_INVALID_INPUT;
}
nostr_input_type_t type = nostr_detect_input_type(input);
if (type == NOSTR_INPUT_NSEC_HEX) { // Actually public key hex
if (nostr_hex_to_bytes(input, public_key, 32) != NOSTR_SUCCESS) {
return NOSTR_ERROR_INVALID_INPUT;
}
} else if (strncmp(input, "npub1", 4) == 0) { // Bech32 npub
size_t decoded_len;
if (!bech32_decode(input, "npub", public_key, &decoded_len)) {
return NOSTR_ERROR_INVALID_INPUT;
}
if (decoded_len != 32) {
return NOSTR_ERROR_INVALID_INPUT;
}
} else {
return NOSTR_ERROR_INVALID_INPUT;
}
return NOSTR_SUCCESS;
}

View File

@@ -0,0 +1,17 @@
/*
* NOSTR Core Library - NIP-019: Bech32-encoded Entities
*/
#ifndef NIP019_H
#define NIP019_H
#include "nip001.h"
#include "nip006.h" // For nostr_input_type_t enum
// Function declarations
int nostr_key_to_bech32(const unsigned char* key, const char* hrp, char* output);
nostr_input_type_t nostr_detect_input_type(const char* input);
int nostr_decode_nsec(const char* input, unsigned char* private_key);
int nostr_decode_npub(const char* input, unsigned char* public_key);
#endif // NIP019_H

View File

@@ -0,0 +1,106 @@
/*
* NOSTR Core Library - Common Utilities
*
* Common functions and utilities shared across the library
*/
#include "nostr_common.h"
#include "utils.h"
/**
* Convert error code to human-readable string
* Handles all error codes defined in nostr_common.h
*/
const char* nostr_strerror(int error_code) {
switch (error_code) {
case NOSTR_SUCCESS: return "Success";
case NOSTR_ERROR_INVALID_INPUT: return "Invalid input";
case NOSTR_ERROR_CRYPTO_FAILED: return "Cryptographic operation failed";
case NOSTR_ERROR_MEMORY_FAILED: return "Memory allocation failed";
case NOSTR_ERROR_IO_FAILED: return "I/O operation failed";
case NOSTR_ERROR_NETWORK_FAILED: return "Network operation failed";
case NOSTR_ERROR_NIP04_INVALID_FORMAT: return "NIP-04 invalid format";
case NOSTR_ERROR_NIP04_DECRYPT_FAILED: return "NIP-04 decryption failed";
case NOSTR_ERROR_NIP04_BUFFER_TOO_SMALL: return "NIP-04 buffer too small";
case NOSTR_ERROR_NIP44_INVALID_FORMAT: return "NIP-44: Invalid format";
case NOSTR_ERROR_NIP44_DECRYPT_FAILED: return "NIP-44: Decryption failed";
case NOSTR_ERROR_NIP44_BUFFER_TOO_SMALL: return "NIP-44: Buffer too small";
case NOSTR_ERROR_NIP05_INVALID_IDENTIFIER: return "NIP-05: Invalid identifier format";
case NOSTR_ERROR_NIP05_HTTP_FAILED: return "NIP-05: HTTP request failed";
case NOSTR_ERROR_NIP05_JSON_PARSE_FAILED: return "NIP-05: JSON parsing failed";
case NOSTR_ERROR_NIP05_NAME_NOT_FOUND: return "NIP-05: Name not found in .well-known";
case NOSTR_ERROR_NIP05_PUBKEY_MISMATCH: return "NIP-05: Public key mismatch";
case NOSTR_ERROR_EVENT_INVALID_STRUCTURE: return "Event has invalid structure";
case NOSTR_ERROR_EVENT_INVALID_ID: return "Event has invalid ID";
case NOSTR_ERROR_EVENT_INVALID_PUBKEY: return "Event has invalid public key";
case NOSTR_ERROR_EVENT_INVALID_SIGNATURE: return "Event has invalid signature";
case NOSTR_ERROR_EVENT_INVALID_CREATED_AT: return "Event has invalid timestamp";
case NOSTR_ERROR_EVENT_INVALID_KIND: return "Event has invalid kind";
case NOSTR_ERROR_EVENT_INVALID_TAGS: return "Event has invalid tags";
case NOSTR_ERROR_EVENT_INVALID_CONTENT: return "Event has invalid content";
case NOSTR_ERROR_NIP13_INSUFFICIENT: return "NIP-13: Insufficient PoW difficulty";
case NOSTR_ERROR_NIP13_NO_NONCE_TAG: return "NIP-13: Missing nonce tag";
case NOSTR_ERROR_NIP13_INVALID_NONCE_TAG: return "NIP-13: Invalid nonce tag format";
case NOSTR_ERROR_NIP13_TARGET_MISMATCH: return "NIP-13: Target difficulty mismatch";
case NOSTR_ERROR_NIP13_CALCULATION: return "NIP-13: PoW calculation error";
case NOSTR_ERROR_NIP42_INVALID_CHALLENGE: return "NIP-42: Invalid challenge";
case NOSTR_ERROR_NIP42_CHALLENGE_EXPIRED: return "NIP-42: Challenge expired";
case NOSTR_ERROR_NIP42_AUTH_EVENT_INVALID: return "NIP-42: Authentication event invalid";
case NOSTR_ERROR_NIP42_URL_MISMATCH: return "NIP-42: Relay URL mismatch";
case NOSTR_ERROR_NIP42_TIME_TOLERANCE: return "NIP-42: Timestamp outside tolerance";
case NOSTR_ERROR_NIP42_NOT_AUTHENTICATED: return "NIP-42: Client not authenticated";
case NOSTR_ERROR_NIP42_INVALID_MESSAGE_FORMAT: return "NIP-42: Invalid message format";
case NOSTR_ERROR_NIP42_CHALLENGE_TOO_SHORT: return "NIP-42: Challenge too short";
case NOSTR_ERROR_NIP42_CHALLENGE_TOO_LONG: return "NIP-42: Challenge too long";
case NOSTR_ERROR_NIP46_INVALID_BUNKER_URL: return "NIP-46: Invalid bunker URL";
case NOSTR_ERROR_NIP46_INVALID_NOSTRCONNECT: return "NIP-46: Invalid nostrconnect URL";
case NOSTR_ERROR_NIP46_INVALID_REQUEST: return "NIP-46: Invalid request payload";
case NOSTR_ERROR_NIP46_INVALID_RESPONSE: return "NIP-46: Invalid response payload";
case NOSTR_ERROR_NIP46_ENCRYPTION_FAILED: return "NIP-46: Encryption failed";
case NOSTR_ERROR_NIP46_DECRYPTION_FAILED: return "NIP-46: Decryption failed";
case NOSTR_ERROR_NIP46_CONNECTION_FAILED: return "NIP-46: Connection failed";
case NOSTR_ERROR_NIP46_TIMEOUT: return "NIP-46: Timeout";
case NOSTR_ERROR_NIP46_SECRET_MISMATCH: return "NIP-46: Secret mismatch";
case NOSTR_ERROR_NIP46_UNKNOWN_METHOD: return "NIP-46: Unknown method";
case NOSTR_ERROR_NIP46_AUTH_CHALLENGE: return "NIP-46: Auth challenge required";
case NOSTR_ERROR_NIP46_NOT_CONNECTED: return "NIP-46: Not connected";
case NOSTR_ERROR_NIP60_INVALID_WALLET: return "NIP-60: Invalid wallet event";
case NOSTR_ERROR_NIP60_INVALID_TOKEN: return "NIP-60: Invalid token event";
case NOSTR_ERROR_NIP60_INVALID_HISTORY: return "NIP-60: Invalid history event";
case NOSTR_ERROR_NIP60_INVALID_QUOTE: return "NIP-60: Invalid quote event";
case NOSTR_ERROR_NIP60_DECRYPT_FAILED: return "NIP-60: Decryption failed";
case NOSTR_ERROR_NIP60_INVALID_PROOFS: return "NIP-60: Invalid proofs payload";
case NOSTR_ERROR_NIP60_INSUFFICIENT_FUNDS: return "NIP-60: Insufficient funds";
case NOSTR_ERROR_NIP61_INVALID_INFO: return "NIP-61: Invalid info event";
case NOSTR_ERROR_NIP61_INVALID_NUTZAP: return "NIP-61: Invalid nutzap event";
case NOSTR_ERROR_NIP61_MINT_MISMATCH: return "NIP-61: Mint mismatch";
case NOSTR_ERROR_NIP61_PUBKEY_MISMATCH: return "NIP-61: Pubkey mismatch";
case NOSTR_ERROR_NIP61_VERIFICATION_FAILED: return "NIP-61: Verification failed";
case NOSTR_ERROR_CASHU_HTTP_FAILED: return "Cashu: HTTP request failed";
case NOSTR_ERROR_CASHU_JSON_PARSE_FAILED: return "Cashu: JSON parsing failed";
case NOSTR_ERROR_CASHU_MINT_ERROR: return "Cashu: Mint returned an error";
case NOSTR_ERROR_CASHU_QUOTE_NOT_PAID: return "Cashu: Quote not paid";
case NOSTR_ERROR_CASHU_QUOTE_EXPIRED: return "Cashu: Quote expired";
case NOSTR_ERROR_CASHU_PROOFS_SPENT: return "Cashu: One or more proofs are already spent";
case NOSTR_ERROR_CASHU_CRYPTO_FAILED: return "Cashu: Cryptographic operation failed";
case NOSTR_ERROR_CASHU_INVALID_KEYSET: return "Cashu: Invalid keyset";
default: return "Unknown error";
}
}
/**
* Initialize the NOSTR library
*/
int nostr_init(void) {
if (nostr_crypto_init() != 0) {
return NOSTR_ERROR_CRYPTO_FAILED;
}
return NOSTR_SUCCESS;
}
/**
* Cleanup the NOSTR library
*/
void nostr_cleanup(void) {
nostr_crypto_cleanup();
}

View File

@@ -0,0 +1,131 @@
/*
* NOSTR Core - Common Definitions
* Shared error constants and basic types for the modular NOSTR library
*/
#ifndef NOSTR_COMMON_H
#define NOSTR_COMMON_H
#include <stddef.h>
#include <stdint.h>
// Return codes
#define NOSTR_SUCCESS 0
#define NOSTR_ERROR_INVALID_INPUT -1
#define NOSTR_ERROR_CRYPTO_FAILED -2
#define NOSTR_ERROR_MEMORY_FAILED -3
#define NOSTR_ERROR_IO_FAILED -4
#define NOSTR_ERROR_NETWORK_FAILED -5
#define NOSTR_ERROR_NIP04_INVALID_FORMAT -10
#define NOSTR_ERROR_NIP04_DECRYPT_FAILED -11
#define NOSTR_ERROR_NIP04_BUFFER_TOO_SMALL -12
#define NOSTR_ERROR_NIP44_INVALID_FORMAT -13
#define NOSTR_ERROR_NIP44_DECRYPT_FAILED -14
#define NOSTR_ERROR_NIP44_BUFFER_TOO_SMALL -15
#define NOSTR_ERROR_NIP05_INVALID_IDENTIFIER -16
#define NOSTR_ERROR_NIP05_HTTP_FAILED -17
#define NOSTR_ERROR_NIP05_JSON_PARSE_FAILED -18
#define NOSTR_ERROR_NIP05_NAME_NOT_FOUND -19
#define NOSTR_ERROR_NIP05_PUBKEY_MISMATCH -20
#define NOSTR_ERROR_EVENT_INVALID_STRUCTURE -30
#define NOSTR_ERROR_EVENT_INVALID_ID -31
#define NOSTR_ERROR_EVENT_INVALID_PUBKEY -32
#define NOSTR_ERROR_EVENT_INVALID_SIGNATURE -33
#define NOSTR_ERROR_EVENT_INVALID_CREATED_AT -34
#define NOSTR_ERROR_EVENT_INVALID_KIND -35
#define NOSTR_ERROR_EVENT_INVALID_TAGS -36
#define NOSTR_ERROR_EVENT_INVALID_CONTENT -37
// Authentication Rules System Error Codes
#define NOSTR_ERROR_AUTH_RULES_DISABLED -50
#define NOSTR_ERROR_AUTH_RULES_DENIED -51
#define NOSTR_ERROR_AUTH_RULES_DB_FAILED -52
#define NOSTR_ERROR_AUTH_RULES_INVALID_RULE -53
#define NOSTR_ERROR_AUTH_RULES_CACHE_FAILED -54
#define NOSTR_ERROR_AUTH_RULES_BACKEND_NOT_FOUND -55
// NIP-13 PoW-specific error codes
#define NOSTR_ERROR_NIP13_INSUFFICIENT -100
#define NOSTR_ERROR_NIP13_NO_NONCE_TAG -101
#define NOSTR_ERROR_NIP13_INVALID_NONCE_TAG -102
#define NOSTR_ERROR_NIP13_TARGET_MISMATCH -103
#define NOSTR_ERROR_NIP13_CALCULATION -104
// NIP-42 Authentication-specific error codes
#define NOSTR_ERROR_NIP42_INVALID_CHALLENGE -200
#define NOSTR_ERROR_NIP42_CHALLENGE_EXPIRED -201
#define NOSTR_ERROR_NIP42_AUTH_EVENT_INVALID -202
#define NOSTR_ERROR_NIP42_URL_MISMATCH -203
#define NOSTR_ERROR_NIP42_TIME_TOLERANCE -204
#define NOSTR_ERROR_NIP42_NOT_AUTHENTICATED -205
#define NOSTR_ERROR_NIP42_INVALID_MESSAGE_FORMAT -206
#define NOSTR_ERROR_NIP42_CHALLENGE_TOO_SHORT -207
#define NOSTR_ERROR_NIP42_CHALLENGE_TOO_LONG -208
// NIP-46 Remote Signing error codes
#define NOSTR_ERROR_NIP46_INVALID_BUNKER_URL -300
#define NOSTR_ERROR_NIP46_INVALID_NOSTRCONNECT -301
#define NOSTR_ERROR_NIP46_INVALID_REQUEST -302
#define NOSTR_ERROR_NIP46_INVALID_RESPONSE -303
#define NOSTR_ERROR_NIP46_ENCRYPTION_FAILED -304
#define NOSTR_ERROR_NIP46_DECRYPTION_FAILED -305
#define NOSTR_ERROR_NIP46_CONNECTION_FAILED -306
#define NOSTR_ERROR_NIP46_TIMEOUT -307
#define NOSTR_ERROR_NIP46_SECRET_MISMATCH -308
#define NOSTR_ERROR_NIP46_UNKNOWN_METHOD -309
#define NOSTR_ERROR_NIP46_AUTH_CHALLENGE -310
#define NOSTR_ERROR_NIP46_NOT_CONNECTED -311
// NIP-60 Cashu Wallet error codes
#define NOSTR_ERROR_NIP60_INVALID_WALLET -400
#define NOSTR_ERROR_NIP60_INVALID_TOKEN -401
#define NOSTR_ERROR_NIP60_INVALID_HISTORY -402
#define NOSTR_ERROR_NIP60_INVALID_QUOTE -403
#define NOSTR_ERROR_NIP60_DECRYPT_FAILED -404
#define NOSTR_ERROR_NIP60_INVALID_PROOFS -405
#define NOSTR_ERROR_NIP60_INSUFFICIENT_FUNDS -406
// NIP-61 Nutzap error codes
#define NOSTR_ERROR_NIP61_INVALID_INFO -410
#define NOSTR_ERROR_NIP61_INVALID_NUTZAP -411
#define NOSTR_ERROR_NIP61_MINT_MISMATCH -412
#define NOSTR_ERROR_NIP61_PUBKEY_MISMATCH -413
#define NOSTR_ERROR_NIP61_VERIFICATION_FAILED -414
// Cashu Mint client error codes
#define NOSTR_ERROR_CASHU_HTTP_FAILED -420
#define NOSTR_ERROR_CASHU_JSON_PARSE_FAILED -421
#define NOSTR_ERROR_CASHU_MINT_ERROR -422
#define NOSTR_ERROR_CASHU_QUOTE_NOT_PAID -423
#define NOSTR_ERROR_CASHU_QUOTE_EXPIRED -424
#define NOSTR_ERROR_CASHU_PROOFS_SPENT -425
#define NOSTR_ERROR_CASHU_CRYPTO_FAILED -426
#define NOSTR_ERROR_CASHU_INVALID_KEYSET -427
// Constants
#define NOSTR_PRIVATE_KEY_SIZE 32
#define NOSTR_PUBLIC_KEY_SIZE 32
#define NOSTR_HEX_KEY_SIZE 65 // 64 + null terminator
#define NOSTR_BECH32_KEY_SIZE 100
#define NOSTR_MAX_CONTENT_SIZE 2048
#define NOSTR_MAX_URL_SIZE 256
#define NIP05_DEFAULT_TIMEOUT 10
// NIP-04 Constants
#define NOSTR_NIP04_MAX_PLAINTEXT_SIZE 1048576 // 1MB
#define NOSTR_NIP04_MAX_ENCRYPTED_SIZE 22369621 // ~21.3MB (accounts for base64 overhead + IV)
// NIP-44 Constants
#define NOSTR_NIP44_MAX_PLAINTEXT_SIZE 65535 // 64KB - 1 (NIP-44 spec compliant)
// Forward declaration for cJSON (to avoid requiring cJSON.h in header)
struct cJSON;
// Function declarations
const char* nostr_strerror(int error_code);
// Library initialization functions
int nostr_init(void);
void nostr_cleanup(void);
#endif // NOSTR_COMMON_H

View File

@@ -0,0 +1,20 @@
#ifndef NOSTR_PLATFORM_H
#define NOSTR_PLATFORM_H
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* Fill buffer with cryptographically secure random bytes.
* Returns 0 on success, -1 on failure.
*/
int nostr_platform_random(unsigned char *buf, size_t len);
#ifdef __cplusplus
}
#endif
#endif /* NOSTR_PLATFORM_H */

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,189 @@
/*
* NOSTR Core Library - Utilities
*
* General utility functions used across multiple NIPs
*/
#ifndef NOSTR_UTILS_H
#define NOSTR_UTILS_H
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
// =============================================================================
// UTILITY FUNCTIONS
// =============================================================================
// Convert bytes to hexadecimal string
void nostr_bytes_to_hex(const unsigned char *bytes, size_t len, char *hex);
// Convert hexadecimal string to bytes
int nostr_hex_to_bytes(const char *hex, unsigned char *bytes, size_t len);
// Base64 encoding function
size_t base64_encode(const unsigned char *data, size_t len, char *output,
size_t output_size);
// Base64 decoding function
size_t base64_decode(const char *input, unsigned char *output);
// =============================================================================
// CORE CRYPTO FUNCTIONS
// =============================================================================
// Initialize crypto subsystem
int nostr_crypto_init(void);
// Cleanup crypto subsystem
void nostr_crypto_cleanup(void);
// SHA-256 hash function
int nostr_sha256(const unsigned char *data, size_t len, unsigned char *hash);
// =============================================================================
// STREAMING SHA-256 FUNCTIONS
// =============================================================================
// SHA-256 streaming context
typedef struct {
uint32_t state[8]; // Current hash state
unsigned char buffer[64]; // Input buffer for incomplete blocks
uint64_t bitlen; // Total bits processed
size_t buflen; // Current buffer length
} nostr_sha256_ctx_t;
// Initialize SHA-256 streaming context
int nostr_sha256_init(nostr_sha256_ctx_t* ctx);
// Update SHA-256 context with new data
int nostr_sha256_update(nostr_sha256_ctx_t* ctx, const unsigned char* data, size_t len);
// Finalize SHA-256 and output hash
int nostr_sha256_final(nostr_sha256_ctx_t* ctx, unsigned char* hash);
// Stream SHA-256 hash of a file
int nostr_sha256_file_stream(const char* filename, unsigned char* hash);
// HMAC-SHA256
int nostr_hmac_sha256(const unsigned char *key, size_t key_len,
const unsigned char *data, size_t data_len,
unsigned char *output);
// HMAC-SHA512
int nostr_hmac_sha512(const unsigned char *key, size_t key_len,
const unsigned char *data, size_t data_len,
unsigned char *output);
// PBKDF2 with HMAC-SHA512
int nostr_pbkdf2_hmac_sha512(const unsigned char *password, size_t password_len,
const unsigned char *salt, size_t salt_len,
int iterations, unsigned char *output,
size_t output_len);
// SHA-512 implementation (for testing)
int nostr_sha512(const unsigned char *data, size_t len, unsigned char *hash);
// =============================================================================
// SECP256K1 ELLIPTIC CURVE FUNCTIONS
// =============================================================================
// Verify private key is valid
int nostr_ec_private_key_verify(const unsigned char *private_key);
// Generate public key from private key
int nostr_ec_public_key_from_private_key(const unsigned char *private_key,
unsigned char *public_key);
// Sign data with ECDSA
int nostr_ec_sign(const unsigned char *private_key, const unsigned char *hash,
unsigned char *signature);
// RFC 6979 deterministic nonce generation
int nostr_rfc6979_generate_k(const unsigned char *private_key,
const unsigned char *message_hash,
unsigned char *k_out);
int nostr_schnorr_sign(const unsigned char* private_key,
const unsigned char* hash,
unsigned char* signature);
// =============================================================================
// HKDF KEY DERIVATION FUNCTIONS
// =============================================================================
// HKDF Extract step
int nostr_hkdf_extract(const unsigned char *salt, size_t salt_len,
const unsigned char *ikm, size_t ikm_len,
unsigned char *prk);
// HKDF Expand step
int nostr_hkdf_expand(const unsigned char *prk, size_t prk_len,
const unsigned char *info, size_t info_len,
unsigned char *okm, size_t okm_len);
// HKDF (Extract + Expand)
int nostr_hkdf(const unsigned char *salt, size_t salt_len,
const unsigned char *ikm, size_t ikm_len,
const unsigned char *info, size_t info_len, unsigned char *okm,
size_t okm_len);
// ECDH shared secret computation (for debugging)
int ecdh_shared_secret(const unsigned char *private_key,
const unsigned char *public_key_x,
unsigned char *shared_secret);
// =============================================================================
// BIP39 MNEMONIC FUNCTIONS
// =============================================================================
// Generate mnemonic from entropy
int nostr_bip39_mnemonic_from_bytes(const unsigned char *entropy,
size_t entropy_len, char *mnemonic);
// Validate mnemonic
int nostr_bip39_mnemonic_validate(const char *mnemonic);
// Convert mnemonic to seed
int nostr_bip39_mnemonic_to_seed(const char *mnemonic, const char *passphrase,
unsigned char *seed, size_t seed_len);
// =============================================================================
// BIP32 HD WALLET FUNCTIONS
// =============================================================================
typedef struct {
unsigned char private_key[32];
unsigned char public_key[33];
unsigned char chain_code[32];
uint32_t depth;
uint32_t parent_fingerprint;
uint32_t child_number;
} nostr_hd_key_t;
// Create master key from seed
int nostr_bip32_key_from_seed(const unsigned char *seed, size_t seed_len,
nostr_hd_key_t *master_key);
// Derive child key from parent
int nostr_bip32_derive_child(const nostr_hd_key_t *parent_key,
uint32_t child_number, nostr_hd_key_t *child_key);
// Derive key from path
int nostr_bip32_derive_path(const nostr_hd_key_t *master_key,
const uint32_t *path, size_t path_len,
nostr_hd_key_t *derived_key);
#ifdef __cplusplus
}
#endif
#endif // NOSTR_UTILS_H

View File

@@ -0,0 +1,79 @@
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include "../nostr_core/nostr_platform.h"
#if defined(ARDUINO)
#include <Arduino.h>
#endif
#if defined(__has_include)
# if __has_include("pico/rand.h")
# include "pico/rand.h"
# define NOSTR_HAVE_PICO_RAND 1
# endif
# if __has_include("hardware/adc.h")
# include "hardware/adc.h"
# define NOSTR_HAVE_PICO_ADC 1
# endif
#endif
static uint32_t xorshift32(uint32_t *state) {
uint32_t x = *state ? *state : 0xA5A5A5A5u;
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
*state = x;
return x;
}
int nostr_platform_random(unsigned char *buf, size_t len) {
if (!buf) {
return -1;
}
size_t i = 0;
#if defined(NOSTR_HAVE_PICO_RAND)
while (i + 4 <= len) {
uint32_t r = get_rand_32();
memcpy(buf + i, &r, 4);
i += 4;
}
if (i < len) {
uint32_t r = get_rand_32();
memcpy(buf + i, &r, len - i);
}
return 0;
#else
uint32_t seed = 0x13579BDFu;
#if defined(ARDUINO)
seed ^= (uint32_t)micros();
seed ^= ((uint32_t)millis() << 16);
seed ^= (uint32_t)(uintptr_t)&seed;
#endif
#if defined(NOSTR_HAVE_PICO_ADC)
adc_init();
adc_set_temp_sensor_enabled(true);
adc_select_input(4);
for (int k = 0; k < 16; ++k) {
seed ^= ((uint32_t)adc_read() << ((k & 3) * 8));
}
#endif
while (i < len) {
uint32_t r = xorshift32(&seed);
#if defined(ARDUINO)
r ^= (uint32_t)micros();
#endif
size_t take = (len - i >= 4) ? 4 : (len - i);
memcpy(buf + i, &r, take);
i += take;
}
return 0;
#endif
}

View File

@@ -0,0 +1,929 @@
#ifndef SECP256K1_H
#define SECP256K1_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stddef.h>
#include <stdint.h>
/** Unless explicitly stated all pointer arguments must not be NULL.
*
* The following rules specify the order of arguments in API calls:
*
* 1. Context pointers go first, followed by output arguments, combined
* output/input arguments, and finally input-only arguments.
* 2. Array lengths always immediately follow the argument whose length
* they describe, even if this violates rule 1.
* 3. Within the OUT/OUTIN/IN groups, pointers to data that is typically generated
* later go first. This means: signatures, public nonces, secret nonces,
* messages, public keys, secret keys, tweaks.
* 4. Arguments that are not data pointers go last, from more complex to less
* complex: function pointers, algorithm names, messages, void pointers,
* counts, flags, booleans.
* 5. Opaque data pointers follow the function pointer they are to be passed to.
*/
/** Opaque data structure that holds context information
*
* The primary purpose of context objects is to store randomization data for
* enhanced protection against side-channel leakage. This protection is only
* effective if the context is randomized after its creation. See
* secp256k1_context_create for creation of contexts and
* secp256k1_context_randomize for randomization.
*
* A secondary purpose of context objects is to store pointers to callback
* functions that the library will call when certain error states arise. See
* secp256k1_context_set_error_callback as well as
* secp256k1_context_set_illegal_callback for details. Future library versions
* may use context objects for additional purposes.
*
* A constructed context can safely be used from multiple threads
* simultaneously, but API calls that take a non-const pointer to a context
* need exclusive access to it. In particular this is the case for
* secp256k1_context_destroy, secp256k1_context_preallocated_destroy,
* and secp256k1_context_randomize.
*
* Regarding randomization, either do it once at creation time (in which case
* you do not need any locking for the other calls), or use a read-write lock.
*/
typedef struct secp256k1_context_struct secp256k1_context;
/** Opaque data structure that holds a parsed and valid public key.
*
* The exact representation of data inside is implementation defined and not
* guaranteed to be portable between different platforms or versions. It is
* however guaranteed to be 64 bytes in size, and can be safely copied/moved.
* If you need to convert to a format suitable for storage or transmission,
* use secp256k1_ec_pubkey_serialize and secp256k1_ec_pubkey_parse. To
* compare keys, use secp256k1_ec_pubkey_cmp.
*/
typedef struct secp256k1_pubkey {
unsigned char data[64];
} secp256k1_pubkey;
/** Opaque data structure that holds a parsed ECDSA signature.
*
* The exact representation of data inside is implementation defined and not
* guaranteed to be portable between different platforms or versions. It is
* however guaranteed to be 64 bytes in size, and can be safely copied/moved.
* If you need to convert to a format suitable for storage, transmission, or
* comparison, use the secp256k1_ecdsa_signature_serialize_* and
* secp256k1_ecdsa_signature_parse_* functions.
*/
typedef struct secp256k1_ecdsa_signature {
unsigned char data[64];
} secp256k1_ecdsa_signature;
/** A pointer to a function to deterministically generate a nonce.
*
* Returns: 1 if a nonce was successfully generated. 0 will cause signing to fail.
* Out: nonce32: pointer to a 32-byte array to be filled by the function.
* In: msg32: the 32-byte message hash being verified (will not be NULL)
* key32: pointer to a 32-byte secret key (will not be NULL)
* algo16: pointer to a 16-byte array describing the signature
* algorithm (will be NULL for ECDSA for compatibility).
* data: Arbitrary data pointer that is passed through.
* attempt: how many iterations we have tried to find a nonce.
* This will almost always be 0, but different attempt values
* are required to result in a different nonce.
*
* Except for test cases, this function should compute some cryptographic hash of
* the message, the algorithm, the key and the attempt.
*/
typedef int (*secp256k1_nonce_function)(
unsigned char *nonce32,
const unsigned char *msg32,
const unsigned char *key32,
const unsigned char *algo16,
void *data,
unsigned int attempt
);
# if !defined(SECP256K1_GNUC_PREREQ)
# if defined(__GNUC__)&&defined(__GNUC_MINOR__)
# define SECP256K1_GNUC_PREREQ(_maj,_min) \
((__GNUC__<<16)+__GNUC_MINOR__>=((_maj)<<16)+(_min))
# else
# define SECP256K1_GNUC_PREREQ(_maj,_min) 0
# endif
# endif
/* When this header is used at build-time the SECP256K1_BUILD define needs to be set
* to correctly setup export attributes and nullness checks. This is normally done
* by secp256k1.c but to guard against this header being included before secp256k1.c
* has had a chance to set the define (e.g. via test harnesses that just includes
* secp256k1.c) we set SECP256K1_NO_BUILD when this header is processed without the
* BUILD define so this condition can be caught.
*/
#ifndef SECP256K1_BUILD
# define SECP256K1_NO_BUILD
#endif
/* Symbol visibility. */
#if !defined(SECP256K1_API) && defined(SECP256K1_NO_API_VISIBILITY_ATTRIBUTES)
/* The user has requested that we don't specify visibility attributes in
* the public API.
*
* Since all our non-API declarations use the static qualifier, this means
* that the user can use -fvisibility=<value> to set the visibility of the
* API symbols. For instance, -fvisibility=hidden can be useful *even for
* the API symbols*, e.g., when building a static library which is linked
* into a shared library, and the latter should not re-export the
* libsecp256k1 API.
*
* While visibility is a concept that applies only to shared libraries,
* setting visibility will still make a difference when building a static
* library: the visibility settings will be stored in the static library,
* solely for the potential case that the static library will be linked into
* a shared library. In that case, the stored visibility settings will
* resurface and be honored for the shared library. */
# define SECP256K1_API extern
#endif
#if !defined(SECP256K1_API)
# if defined(SECP256K1_BUILD)
/* On Windows, assume a shared library only if explicitly requested.
* 1. If using Libtool, it defines DLL_EXPORT automatically.
* 2. In other cases, SECP256K1_DLL_EXPORT must be defined. */
# if defined(_WIN32) && (defined(SECP256K1_DLL_EXPORT) || defined(DLL_EXPORT))
/* GCC for Windows (e.g., MinGW) accepts the __declspec syntax for
* MSVC compatibility. A __declspec declaration implies (but is not
* exactly equivalent to) __attribute__ ((visibility("default"))),
* and so we actually want __declspec even on GCC, see "Microsoft
* Windows Function Attributes" in the GCC manual and the
* recommendations in https://gcc.gnu.org/wiki/Visibility . */
# define SECP256K1_API extern __declspec(dllexport)
/* Avoid __attribute__ ((visibility("default"))) on Windows to get rid
* of warnings when compiling with -flto due to a bug in GCC, see
* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=116478 . */
# elif !defined(_WIN32) && defined (__GNUC__) && (__GNUC__ >= 4)
# define SECP256K1_API extern __attribute__ ((visibility("default")))
# else
# define SECP256K1_API extern
# endif
# else
/* On Windows, SECP256K1_STATIC must be defined when consuming
* libsecp256k1 as a static library. Note that SECP256K1_STATIC is a
* "consumer-only" macro, and it has no meaning when building
* libsecp256k1. */
# if defined(_WIN32) && !defined(SECP256K1_STATIC)
# define SECP256K1_API extern __declspec(dllimport)
# else
# define SECP256K1_API extern
# endif
# endif
#endif
/* Warning attributes
* NONNULL is not used if SECP256K1_BUILD is set to avoid the compiler optimizing out
* some paranoid null checks. */
# if defined(__GNUC__) && SECP256K1_GNUC_PREREQ(3, 4)
# define SECP256K1_WARN_UNUSED_RESULT __attribute__ ((__warn_unused_result__))
# else
# define SECP256K1_WARN_UNUSED_RESULT
# endif
# if !defined(SECP256K1_BUILD) && defined(__GNUC__) && SECP256K1_GNUC_PREREQ(3, 4)
# define SECP256K1_ARG_NONNULL(_x) __attribute__ ((__nonnull__(_x)))
# else
# define SECP256K1_ARG_NONNULL(_x)
# endif
/* Attribute for marking functions, types, and variables as deprecated */
#if !defined(SECP256K1_BUILD) && defined(__has_attribute)
# if __has_attribute(__deprecated__)
# define SECP256K1_DEPRECATED(_msg) __attribute__ ((__deprecated__(_msg)))
# else
# define SECP256K1_DEPRECATED(_msg)
# endif
#else
# define SECP256K1_DEPRECATED(_msg)
#endif
/* All flags' lower 8 bits indicate what they're for. Do not use directly. */
#define SECP256K1_FLAGS_TYPE_MASK ((1 << 8) - 1)
#define SECP256K1_FLAGS_TYPE_CONTEXT (1 << 0)
#define SECP256K1_FLAGS_TYPE_COMPRESSION (1 << 1)
/* The higher bits contain the actual data. Do not use directly. */
#define SECP256K1_FLAGS_BIT_CONTEXT_VERIFY (1 << 8)
#define SECP256K1_FLAGS_BIT_CONTEXT_SIGN (1 << 9)
#define SECP256K1_FLAGS_BIT_CONTEXT_DECLASSIFY (1 << 10)
#define SECP256K1_FLAGS_BIT_COMPRESSION (1 << 8)
/** Context flags to pass to secp256k1_context_create, secp256k1_context_preallocated_size, and
* secp256k1_context_preallocated_create. */
#define SECP256K1_CONTEXT_NONE (SECP256K1_FLAGS_TYPE_CONTEXT)
/** Deprecated context flags. These flags are treated equivalent to SECP256K1_CONTEXT_NONE. */
#define SECP256K1_CONTEXT_VERIFY (SECP256K1_FLAGS_TYPE_CONTEXT | SECP256K1_FLAGS_BIT_CONTEXT_VERIFY)
#define SECP256K1_CONTEXT_SIGN (SECP256K1_FLAGS_TYPE_CONTEXT | SECP256K1_FLAGS_BIT_CONTEXT_SIGN)
/* Testing flag. Do not use. */
#define SECP256K1_CONTEXT_DECLASSIFY (SECP256K1_FLAGS_TYPE_CONTEXT | SECP256K1_FLAGS_BIT_CONTEXT_DECLASSIFY)
/** Flag to pass to secp256k1_ec_pubkey_serialize. */
#define SECP256K1_EC_COMPRESSED (SECP256K1_FLAGS_TYPE_COMPRESSION | SECP256K1_FLAGS_BIT_COMPRESSION)
#define SECP256K1_EC_UNCOMPRESSED (SECP256K1_FLAGS_TYPE_COMPRESSION)
/** Prefix byte used to tag various encoded curvepoints for specific purposes */
#define SECP256K1_TAG_PUBKEY_EVEN 0x02
#define SECP256K1_TAG_PUBKEY_ODD 0x03
#define SECP256K1_TAG_PUBKEY_UNCOMPRESSED 0x04
#define SECP256K1_TAG_PUBKEY_HYBRID_EVEN 0x06
#define SECP256K1_TAG_PUBKEY_HYBRID_ODD 0x07
/** A built-in constant secp256k1 context object with static storage duration, to be
* used in conjunction with secp256k1_selftest.
*
* This context object offers *only limited functionality* , i.e., it cannot be used
* for API functions that perform computations involving secret keys, e.g., signing
* and public key generation. If this restriction applies to a specific API function,
* it is mentioned in its documentation. See secp256k1_context_create if you need a
* full context object that supports all functionality offered by the library.
*
* It is highly recommended to call secp256k1_selftest before using this context.
*/
SECP256K1_API const secp256k1_context * const secp256k1_context_static;
/** Deprecated alias for secp256k1_context_static. */
SECP256K1_API const secp256k1_context * const secp256k1_context_no_precomp
SECP256K1_DEPRECATED("Use secp256k1_context_static instead");
/** Perform basic self tests (to be used in conjunction with secp256k1_context_static)
*
* This function performs self tests that detect some serious usage errors and
* similar conditions, e.g., when the library is compiled for the wrong endianness.
* This is a last resort measure to be used in production. The performed tests are
* very rudimentary and are not intended as a replacement for running the test
* binaries.
*
* It is highly recommended to call this before using secp256k1_context_static.
* It is not necessary to call this function before using a context created with
* secp256k1_context_create (or secp256k1_context_preallocated_create), which will
* take care of performing the self tests.
*
* If the tests fail, this function will call the default error callback to abort the
* program (see secp256k1_context_set_error_callback).
*/
SECP256K1_API void secp256k1_selftest(void);
/** Create a secp256k1 context object (in dynamically allocated memory).
*
* This function uses malloc to allocate memory. It is guaranteed that malloc is
* called at most once for every call of this function. If you need to avoid dynamic
* memory allocation entirely, see secp256k1_context_static and the functions in
* secp256k1_preallocated.h.
*
* Returns: pointer to a newly created context object.
* In: flags: Always set to SECP256K1_CONTEXT_NONE (see below).
*
* The only valid non-deprecated flag in recent library versions is
* SECP256K1_CONTEXT_NONE, which will create a context sufficient for all functionality
* offered by the library. All other (deprecated) flags will be treated as equivalent
* to the SECP256K1_CONTEXT_NONE flag. Though the flags parameter primarily exists for
* historical reasons, future versions of the library may introduce new flags.
*
* If the context is intended to be used for API functions that perform computations
* involving secret keys, e.g., signing and public key generation, then it is highly
* recommended to call secp256k1_context_randomize on the context before calling
* those API functions. This will provide enhanced protection against side-channel
* leakage, see secp256k1_context_randomize for details.
*
* Do not create a new context object for each operation, as construction and
* randomization can take non-negligible time.
*/
SECP256K1_API secp256k1_context *secp256k1_context_create(
unsigned int flags
) SECP256K1_WARN_UNUSED_RESULT;
/** Copy a secp256k1 context object (into dynamically allocated memory).
*
* This function uses malloc to allocate memory. It is guaranteed that malloc is
* called at most once for every call of this function. If you need to avoid dynamic
* memory allocation entirely, see the functions in secp256k1_preallocated.h.
*
* Cloning secp256k1_context_static is not possible, and should not be emulated by
* the caller (e.g., using memcpy). Create a new context instead.
*
* Returns: pointer to a newly created context object.
* Args: ctx: pointer to a context to copy (not secp256k1_context_static).
*/
SECP256K1_API secp256k1_context *secp256k1_context_clone(
const secp256k1_context *ctx
) SECP256K1_ARG_NONNULL(1) SECP256K1_WARN_UNUSED_RESULT;
/** Destroy a secp256k1 context object (created in dynamically allocated memory).
*
* The context pointer may not be used afterwards.
*
* The context to destroy must have been created using secp256k1_context_create
* or secp256k1_context_clone. If the context has instead been created using
* secp256k1_context_preallocated_create or secp256k1_context_preallocated_clone, the
* behaviour is undefined. In that case, secp256k1_context_preallocated_destroy must
* be used instead.
*
* Args: ctx: pointer to a context to destroy, constructed using
* secp256k1_context_create or secp256k1_context_clone
* (i.e., not secp256k1_context_static).
*/
SECP256K1_API void secp256k1_context_destroy(
secp256k1_context *ctx
) SECP256K1_ARG_NONNULL(1);
/** Set a callback function to be called when an illegal argument is passed to
* an API call. It will only trigger for violations that are mentioned
* explicitly in the header.
*
* The philosophy is that these shouldn't be dealt with through a specific
* return value, as calling code should not have branches to deal with the case
* that this code itself is broken.
*
* On the other hand, during debug stage, one would want to be informed about
* such mistakes, and the default (crashing) may be inadvisable. Should this
* callback return instead of crashing, the return value and output arguments
* of the API function call are undefined. Moreover, the same API call may
* trigger the callback again in this case.
*
* When this function has not been called (or called with fun==NULL), then the
* default callback will be used. The library provides a default callback which
* writes the message to stderr and calls abort. This default callback can be
* replaced at link time if the preprocessor macro
* USE_EXTERNAL_DEFAULT_CALLBACKS is defined, which is the case if the build
* has been configured with --enable-external-default-callbacks (GNU Autotools) or
* -DSECP256K1_USE_EXTERNAL_DEFAULT_CALLBACKS=ON (CMake). Then the
* following two symbols must be provided to link against:
* - void secp256k1_default_illegal_callback_fn(const char *message, void *data);
* - void secp256k1_default_error_callback_fn(const char *message, void *data);
* The library may call a default callback even before a proper callback data
* pointer could have been set using secp256k1_context_set_illegal_callback or
* secp256k1_context_set_error_callback, e.g., when the creation of a context
* fails. In this case, the corresponding default callback will be called with
* the data pointer argument set to NULL.
*
* Args: ctx: pointer to a context object.
* In: fun: pointer to a function to call when an illegal argument is
* passed to the API, taking a message and an opaque pointer.
* (NULL restores the default callback.)
* data: the opaque pointer to pass to fun above, must be NULL for the
* default callback.
*
* See also secp256k1_context_set_error_callback.
*/
SECP256K1_API void secp256k1_context_set_illegal_callback(
secp256k1_context *ctx,
void (*fun)(const char *message, void *data),
const void *data
) SECP256K1_ARG_NONNULL(1);
/** Set a callback function to be called when an internal consistency check
* fails.
*
* The default callback writes an error message to stderr and calls abort
* to abort the program.
*
* This can only trigger in case of a hardware failure, miscompilation,
* memory corruption, serious bug in the library, or other error that would
* result in undefined behaviour. It will not trigger due to mere
* incorrect usage of the API (see secp256k1_context_set_illegal_callback
* for that). After this callback returns, anything may happen, including
* crashing.
*
* Args: ctx: pointer to a context object.
* In: fun: pointer to a function to call when an internal error occurs,
* taking a message and an opaque pointer (NULL restores the
* default callback, see secp256k1_context_set_illegal_callback
* for details).
* data: the opaque pointer to pass to fun above, must be NULL for the
* default callback.
*
* See also secp256k1_context_set_illegal_callback.
*/
SECP256K1_API void secp256k1_context_set_error_callback(
secp256k1_context *ctx,
void (*fun)(const char *message, void *data),
const void *data
) SECP256K1_ARG_NONNULL(1);
/** A pointer to a function implementing SHA256's internal compression function.
*
* This function processes one or more contiguous 64-byte message blocks and
* updates the internal SHA256 state accordingly. The function is not responsible
* for counting consumed blocks or bytes, nor for performing padding.
*
* In/Out: state: pointer to eight 32-bit words representing the current internal state;
* the state is updated in place.
* In: blocks64: pointer to concatenation of n_blocks blocks, of 64 bytes each.
* no alignment guarantees are made for this pointer.
* n_blocks: number of contiguous 64-byte blocks to process.
*/
typedef void (*secp256k1_sha256_compression_function)(
uint32_t *state,
const unsigned char *blocks64,
size_t n_blocks
);
/**
* Set a callback function to override the internal SHA256 compression function.
*
* This installs a function to replace the built-in block-compression
* step used by the library's internal SHA256 implementation.
* The provided callback must exactly implement the effect of n_blocks
* repeated applications of the SHA256 compression function.
*
* 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
* with a different hash function.
*
* Args: ctx: pointer to a context object.
* In: fn_compression: pointer to a function implementing the compression function;
* passing NULL restores the default implementation.
*/
SECP256K1_API void secp256k1_context_set_sha256_compression(
secp256k1_context *ctx,
secp256k1_sha256_compression_function fn_compression
) SECP256K1_ARG_NONNULL(1);
/** Parse a variable-length public key into the pubkey object.
*
* Returns: 1 if the public key was fully valid.
* 0 if the public key could not be parsed or is invalid.
* Args: ctx: pointer to a context object.
* Out: pubkey: pointer to a pubkey object. If 1 is returned, it is set to a
* parsed version of input. If not, its value is undefined.
* In: input: pointer to a serialized public key
* inputlen: length of the array pointed to by input
*
* This function supports parsing compressed (33 bytes, header byte 0x02 or
* 0x03), uncompressed (65 bytes, header byte 0x04), or hybrid (65 bytes, header
* byte 0x06 or 0x07) format public keys.
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_parse(
const secp256k1_context *ctx,
secp256k1_pubkey *pubkey,
const unsigned char *input,
size_t inputlen
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Serialize a pubkey object into a serialized byte sequence.
*
* Returns: 1 always.
* Args: ctx: pointer to a context object.
* Out: output: pointer to a 65-byte (if compressed==0) or 33-byte (if
* compressed==1) byte array to place the serialized key
* in.
* In/Out: outputlen: pointer to an integer which is initially set to the
* size of output, and is overwritten with the written
* size.
* In: pubkey: pointer to a secp256k1_pubkey containing an
* initialized public key.
* flags: SECP256K1_EC_COMPRESSED if serialization should be in
* compressed format, otherwise SECP256K1_EC_UNCOMPRESSED.
*/
SECP256K1_API int secp256k1_ec_pubkey_serialize(
const secp256k1_context *ctx,
unsigned char *output,
size_t *outputlen,
const secp256k1_pubkey *pubkey,
unsigned int flags
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4);
/** Compare two public keys using lexicographic (of compressed serialization) order
*
* Returns: <0 if the first public key is less than the second
* >0 if the first public key is greater than the second
* 0 if the two public keys are equal
* Args: ctx: pointer to a context object
* In: pubkey1: first public key to compare
* pubkey2: second public key to compare
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_cmp(
const secp256k1_context *ctx,
const secp256k1_pubkey *pubkey1,
const secp256k1_pubkey *pubkey2
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Sort public keys using lexicographic (of compressed serialization) order
*
* Returns: 0 if the arguments are invalid. 1 otherwise.
*
* Args: ctx: pointer to a context object
* In: pubkeys: array of pointers to pubkeys to sort
* n_pubkeys: number of elements in the pubkeys array
*/
SECP256K1_API int secp256k1_ec_pubkey_sort(
const secp256k1_context *ctx,
const secp256k1_pubkey **pubkeys,
size_t n_pubkeys
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2);
/** Parse an ECDSA signature in compact (64 bytes) format.
*
* Returns: 1 when the signature could be parsed, 0 otherwise.
* Args: ctx: pointer to a context object
* Out: sig: pointer to a signature object
* In: input64: pointer to the 64-byte array to parse
*
* The signature must consist of a 32-byte big endian R value, followed by a
* 32-byte big endian S value. If R or S fall outside of [0..order-1], the
* encoding is invalid. R and S with value 0 are allowed in the encoding.
*
* After the call, sig will always be initialized. If parsing failed or R or
* S are zero, the resulting sig value is guaranteed to fail verification for
* any message and public key.
*/
SECP256K1_API int secp256k1_ecdsa_signature_parse_compact(
const secp256k1_context *ctx,
secp256k1_ecdsa_signature *sig,
const unsigned char *input64
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Parse a DER ECDSA signature.
*
* Returns: 1 when the signature could be parsed, 0 otherwise.
* Args: ctx: pointer to a context object
* Out: sig: pointer to a signature object
* In: input: pointer to the signature to be parsed
* inputlen: the length of the array pointed to be input
*
* This function will accept any valid DER encoded signature, even if the
* encoded numbers are out of range.
*
* After the call, sig will always be initialized. If parsing failed or the
* encoded numbers are out of range, signature verification with it is
* guaranteed to fail for every message and public key.
*/
SECP256K1_API int secp256k1_ecdsa_signature_parse_der(
const secp256k1_context *ctx,
secp256k1_ecdsa_signature *sig,
const unsigned char *input,
size_t inputlen
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Serialize an ECDSA signature in DER format.
*
* Returns: 1 if enough space was available to serialize, 0 otherwise
* Args: ctx: pointer to a context object
* Out: output: pointer to an array to store the DER serialization
* In/Out: outputlen: pointer to a length integer. Initially, this integer
* should be set to the length of output. After the call
* it will be set to the length of the serialization (even
* if 0 was returned).
* In: sig: pointer to an initialized signature object
*/
SECP256K1_API int secp256k1_ecdsa_signature_serialize_der(
const secp256k1_context *ctx,
unsigned char *output,
size_t *outputlen,
const secp256k1_ecdsa_signature *sig
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4);
/** Serialize an ECDSA signature in compact (64 byte) format.
*
* Returns: 1
* Args: ctx: pointer to a context object
* Out: output64: pointer to a 64-byte array to store the compact serialization
* In: sig: pointer to an initialized signature object
*
* See secp256k1_ecdsa_signature_parse_compact for details about the encoding.
*/
SECP256K1_API int secp256k1_ecdsa_signature_serialize_compact(
const secp256k1_context *ctx,
unsigned char *output64,
const secp256k1_ecdsa_signature *sig
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Verify an ECDSA signature.
*
* Returns: 1: correct signature
* 0: incorrect or unparseable signature
* Args: ctx: pointer to a context object
* In: sig: the signature being verified.
* msghash32: the 32-byte message hash being verified.
* The verifier must make sure to apply a cryptographic
* hash function to the message by itself and not accept an
* msghash32 value directly. Otherwise, it would be easy to
* create a "valid" signature without knowledge of the
* secret key. See also
* https://bitcoin.stackexchange.com/a/81116/35586 for more
* background on this topic.
* pubkey: pointer to an initialized public key to verify with.
*
* To avoid accepting malleable signatures, only ECDSA signatures in lower-S
* form are accepted.
*
* If you need to accept ECDSA signatures from sources that do not obey this
* rule, apply secp256k1_ecdsa_signature_normalize to the signature prior to
* verification, but be aware that doing so results in malleable signatures.
*
* For details, see the comments for that function.
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ecdsa_verify(
const secp256k1_context *ctx,
const secp256k1_ecdsa_signature *sig,
const unsigned char *msghash32,
const secp256k1_pubkey *pubkey
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4);
/** Convert a signature to a normalized lower-S form.
*
* Returns: 1 if sigin was not normalized, 0 if it already was.
* Args: ctx: pointer to a context object
* Out: sigout: pointer to a signature to fill with the normalized form,
* or copy if the input was already normalized. (can be NULL if
* you're only interested in whether the input was already
* normalized).
* In: sigin: pointer to a signature to check/normalize (can be identical to sigout)
*
* With ECDSA a third-party can forge a second distinct signature of the same
* message, given a single initial signature, but without knowing the key. This
* is done by negating the S value modulo the order of the curve, 'flipping'
* the sign of the random point R which is not included in the signature.
*
* Forgery of the same message isn't universally problematic, but in systems
* where message malleability or uniqueness of signatures is important this can
* cause issues. This forgery can be blocked by all verifiers forcing signers
* to use a normalized form.
*
* The lower-S form reduces the size of signatures slightly on average when
* variable length encodings (such as DER) are used and is cheap to verify,
* making it a good choice. Security of always using lower-S is assured because
* anyone can trivially modify a signature after the fact to enforce this
* property anyway.
*
* The lower S value is always between 0x1 and
* 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
* inclusive.
*
* No other forms of ECDSA malleability are known and none seem likely, but
* there is no formal proof that ECDSA, even with this additional restriction,
* is free of other malleability. Commonly used serialization schemes will also
* accept various non-unique encodings, so care should be taken when this
* property is required for an application.
*
* The secp256k1_ecdsa_sign function will by default create signatures in the
* lower-S form, and secp256k1_ecdsa_verify will not accept others. In case
* signatures come from a system that cannot enforce this property,
* secp256k1_ecdsa_signature_normalize must be called before verification.
*/
SECP256K1_API int secp256k1_ecdsa_signature_normalize(
const secp256k1_context *ctx,
secp256k1_ecdsa_signature *sigout,
const secp256k1_ecdsa_signature *sigin
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(3);
/** An implementation of RFC6979 (using HMAC-SHA256) as nonce generation function.
* If a data pointer is passed, it is assumed to be a pointer to 32 bytes of
* extra entropy.
*/
SECP256K1_API const secp256k1_nonce_function secp256k1_nonce_function_rfc6979;
/** A default safe nonce generation function (currently equal to secp256k1_nonce_function_rfc6979). */
SECP256K1_API const secp256k1_nonce_function secp256k1_nonce_function_default;
/** Create an ECDSA signature.
*
* Returns: 1: signature created
* 0: the nonce generation function failed, or the secret key was invalid.
* Args: ctx: pointer to a context object (not secp256k1_context_static).
* Out: sig: pointer to an array where the signature will be placed.
* In: msghash32: the 32-byte message hash being signed.
* seckey: pointer to a 32-byte secret key.
* noncefp: pointer to a nonce generation function. If NULL,
* secp256k1_nonce_function_default is used.
* ndata: pointer to arbitrary data used by the nonce generation function
* (can be NULL). If it is non-NULL and
* secp256k1_nonce_function_default is used, then ndata must be a
* pointer to 32-bytes of additional data.
*
* The created signature is always in lower-S form. See
* secp256k1_ecdsa_signature_normalize for more details.
*/
SECP256K1_API int secp256k1_ecdsa_sign(
const secp256k1_context *ctx,
secp256k1_ecdsa_signature *sig,
const unsigned char *msghash32,
const unsigned char *seckey,
secp256k1_nonce_function noncefp,
const void *ndata
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4);
/** Verify an elliptic curve secret key.
*
* A secret key is valid if it is not 0 and less than the secp256k1 curve order
* when interpreted as an integer (most significant byte first). The
* probability of choosing a 32-byte string uniformly at random which is an
* invalid secret key is negligible. However, if it does happen it should
* be assumed that the randomness source is severely broken and there should
* be no retry.
*
* Returns: 1: secret key is valid
* 0: secret key is invalid
* Args: ctx: pointer to a context object.
* In: seckey: pointer to a 32-byte secret key.
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_seckey_verify(
const secp256k1_context *ctx,
const unsigned char *seckey
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2);
/** Compute the public key for a secret key.
*
* Returns: 1: secret was valid, public key stores.
* 0: secret was invalid, try again.
* Args: ctx: pointer to a context object (not secp256k1_context_static).
* Out: pubkey: pointer to the created public key.
* In: seckey: pointer to a 32-byte secret key.
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_create(
const secp256k1_context *ctx,
secp256k1_pubkey *pubkey,
const unsigned char *seckey
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Negates a secret key in place.
*
* Returns: 0 if the given secret key is invalid according to
* secp256k1_ec_seckey_verify. 1 otherwise
* Args: ctx: pointer to a context object
* In/Out: seckey: pointer to the 32-byte secret key to be negated. If the
* secret key is invalid according to
* secp256k1_ec_seckey_verify, this function returns 0 and
* seckey will be set to some unspecified value.
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_seckey_negate(
const secp256k1_context *ctx,
unsigned char *seckey
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2);
/** Negates a public key in place.
*
* Returns: 1 always
* Args: ctx: pointer to a context object
* In/Out: pubkey: pointer to the public key to be negated.
*/
SECP256K1_API int secp256k1_ec_pubkey_negate(
const secp256k1_context *ctx,
secp256k1_pubkey *pubkey
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2);
/** Tweak a secret key by adding tweak to it.
*
* Returns: 0 if the arguments are invalid or the resulting secret key would be
* invalid (only when the tweak is the negation of the secret key). 1
* otherwise.
* Args: ctx: pointer to a context object.
* In/Out: seckey: pointer to a 32-byte secret key. If the secret key is
* invalid according to secp256k1_ec_seckey_verify, this
* function returns 0. seckey will be set to some unspecified
* value if this function returns 0.
* In: tweak32: pointer to a 32-byte tweak, which must be valid according to
* secp256k1_ec_seckey_verify or 32 zero bytes. For uniformly
* random 32-byte tweaks, the chance of being invalid is
* negligible (around 1 in 2^128).
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_seckey_tweak_add(
const secp256k1_context *ctx,
unsigned char *seckey,
const unsigned char *tweak32
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Tweak a public key by adding tweak times the generator to it.
*
* Returns: 0 if the arguments are invalid or the resulting public key would be
* invalid (only when the tweak is the negation of the corresponding
* secret key). 1 otherwise.
* Args: ctx: pointer to a context object.
* In/Out: pubkey: pointer to a public key object. pubkey will be set to an
* invalid value if this function returns 0.
* In: tweak32: pointer to a 32-byte tweak, which must be valid according to
* secp256k1_ec_seckey_verify or 32 zero bytes. For uniformly
* random 32-byte tweaks, the chance of being invalid is
* negligible (around 1 in 2^128).
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_tweak_add(
const secp256k1_context *ctx,
secp256k1_pubkey *pubkey,
const unsigned char *tweak32
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Tweak a secret key by multiplying it by a tweak.
*
* Returns: 0 if the arguments are invalid. 1 otherwise.
* Args: ctx: pointer to a context object.
* In/Out: seckey: pointer to a 32-byte secret key. If the secret key is
* invalid according to secp256k1_ec_seckey_verify, this
* function returns 0. seckey will be set to some unspecified
* value if this function returns 0.
* In: tweak32: pointer to a 32-byte tweak. If the tweak is invalid according to
* secp256k1_ec_seckey_verify, this function returns 0. For
* uniformly random 32-byte arrays the chance of being invalid
* is negligible (around 1 in 2^128).
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_seckey_tweak_mul(
const secp256k1_context *ctx,
unsigned char *seckey,
const unsigned char *tweak32
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Tweak a public key by multiplying it by a tweak value.
*
* Returns: 0 if the arguments are invalid. 1 otherwise.
* Args: ctx: pointer to a context object.
* In/Out: pubkey: pointer to a public key object. pubkey will be set to an
* invalid value if this function returns 0.
* In: tweak32: pointer to a 32-byte tweak. If the tweak is invalid according to
* secp256k1_ec_seckey_verify, this function returns 0. For
* uniformly random 32-byte arrays the chance of being invalid
* is negligible (around 1 in 2^128).
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_tweak_mul(
const secp256k1_context *ctx,
secp256k1_pubkey *pubkey,
const unsigned char *tweak32
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Randomizes the context to provide enhanced protection against side-channel leakage.
*
* Returns: 1: randomization successful
* 0: error
* Args: ctx: pointer to a context object (not secp256k1_context_static).
* In: seed32: pointer to a 32-byte random seed (NULL resets to initial state).
*
* While secp256k1 code is written and tested to be constant-time no matter what
* secret values are, it is possible that a compiler may output code which is not,
* and also that the CPU may not emit the same radio frequencies or draw the same
* amount of power for all values. Randomization of the context shields against
* side-channel observations which aim to exploit secret-dependent behaviour in
* certain computations which involve secret keys.
*
* It is highly recommended to call this function on contexts returned from
* secp256k1_context_create or secp256k1_context_clone (or from the corresponding
* functions in secp256k1_preallocated.h) before using these contexts to call API
* functions that perform computations involving secret keys, e.g., signing and
* public key generation. It is possible to call this function more than once on
* the same context, and doing so before every few computations involving secret
* keys is recommended as a defense-in-depth measure. Randomization of the static
* context secp256k1_context_static is not supported.
*
* Currently, the random seed is mainly used for blinding multiplications of a
* secret scalar with the elliptic curve base point. Multiplications of this
* kind are performed by exactly those API functions which are documented to
* require a context that is not secp256k1_context_static. As a rule of thumb,
* these are all functions which take a secret key (or a keypair) as an input.
* A notable exception to that rule is the ECDH module, which relies on a different
* kind of elliptic curve point multiplication and thus does not benefit from
* enhanced protection against side-channel leakage currently.
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_context_randomize(
secp256k1_context *ctx,
const unsigned char *seed32
) SECP256K1_ARG_NONNULL(1);
/** Add a number of public keys together.
*
* Returns: 1: the sum of the public keys is valid.
* 0: the sum of the public keys is not valid.
* Args: ctx: pointer to a context object.
* Out: out: pointer to a public key object for placing the resulting public key.
* In: ins: pointer to array of pointers to public keys.
* n: the number of public keys to add together (must be at least 1).
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_combine(
const secp256k1_context *ctx,
secp256k1_pubkey *out,
const secp256k1_pubkey * const *ins,
size_t n
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Compute a tagged hash as defined in BIP-340.
*
* This is useful for creating a message hash and achieving domain separation
* through an application-specific tag. This function returns
* SHA256(SHA256(tag)||SHA256(tag)||msg). Therefore, tagged hash
* implementations optimized for a specific tag can precompute the SHA256 state
* after hashing the tag hashes.
*
* Returns: 1 always.
* Args: ctx: pointer to a context object
* Out: hash32: pointer to a 32-byte array to store the resulting hash
* In: tag: pointer to an array containing the tag
* taglen: length of the tag array
* msg: pointer to an array containing the message
* msglen: length of the message array
*/
SECP256K1_API int secp256k1_tagged_sha256(
const secp256k1_context *ctx,
unsigned char *hash32,
const unsigned char *tag,
size_t taglen,
const unsigned char *msg,
size_t msglen
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(5);
#ifdef __cplusplus
}
#endif
#endif /* SECP256K1_H */

View File

@@ -0,0 +1,63 @@
#ifndef SECP256K1_ECDH_H
#define SECP256K1_ECDH_H
#include "secp256k1.h"
#ifdef __cplusplus
extern "C" {
#endif
/** A pointer to a function that hashes an EC point to obtain an ECDH secret
*
* Returns: 1 if the point was successfully hashed.
* 0 will cause secp256k1_ecdh to fail and return 0.
* Other return values are not allowed, and the behaviour of
* secp256k1_ecdh is undefined for other return values.
* Out: output: pointer to an array to be filled by the function
* In: x32: pointer to a 32-byte x coordinate
* y32: pointer to a 32-byte y coordinate
* data: arbitrary data pointer that is passed through
*/
typedef int (*secp256k1_ecdh_hash_function)(
unsigned char *output,
const unsigned char *x32,
const unsigned char *y32,
void *data
);
/** An implementation of SHA256 hash function that applies to compressed public key.
* Populates the output parameter with 32 bytes. */
SECP256K1_API const secp256k1_ecdh_hash_function secp256k1_ecdh_hash_function_sha256;
/** A default ECDH hash function (currently equal to secp256k1_ecdh_hash_function_sha256).
* Populates the output parameter with 32 bytes. */
SECP256K1_API const secp256k1_ecdh_hash_function secp256k1_ecdh_hash_function_default;
/** Compute an EC Diffie-Hellman secret in constant time
*
* Returns: 1: exponentiation was successful
* 0: scalar was invalid (zero or overflow) or hashfp returned 0
* Args: ctx: pointer to a context object.
* Out: output: pointer to an array to be filled by hashfp.
* In: pubkey: pointer to a secp256k1_pubkey containing an initialized public key.
* seckey: a 32-byte scalar with which to multiply the point.
* hashfp: pointer to a hash function. If NULL,
* secp256k1_ecdh_hash_function_sha256 is used
* (in which case, 32 bytes will be written to output).
* data: arbitrary data pointer that is passed through to hashfp
* (can be NULL for secp256k1_ecdh_hash_function_sha256).
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ecdh(
const secp256k1_context *ctx,
unsigned char *output,
const secp256k1_pubkey *pubkey,
const unsigned char *seckey,
secp256k1_ecdh_hash_function hashfp,
void *data
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4);
#ifdef __cplusplus
}
#endif
#endif /* SECP256K1_ECDH_H */

View File

@@ -0,0 +1,200 @@
#ifndef SECP256K1_ELLSWIFT_H
#define SECP256K1_ELLSWIFT_H
#include "secp256k1.h"
#ifdef __cplusplus
extern "C" {
#endif
/* This module provides an implementation of ElligatorSwift as well as a
* version of x-only ECDH using it (including compatibility with BIP324).
*
* ElligatorSwift is described in https://eprint.iacr.org/2022/759 by
* Chavez-Saab, Rodriguez-Henriquez, and Tibouchi. It permits encoding
* uniformly chosen public keys as 64-byte arrays which are indistinguishable
* from uniformly random arrays.
*
* Let f be the function from pairs of field elements to point X coordinates,
* defined as follows (all operations modulo p = 2^256 - 2^32 - 977)
* f(u,t):
* - Let C = 0xa2d2ba93507f1df233770c2a797962cc61f6d15da14ecd47d8d27ae1cd5f852,
* a square root of -3.
* - If u=0, set u=1 instead.
* - If t=0, set t=1 instead.
* - If u^3 + t^2 + 7 = 0, multiply t by 2.
* - Let X = (u^3 + 7 - t^2) / (2 * t)
* - Let Y = (X + t) / (C * u)
* - Return the first in [u + 4 * Y^2, (-X/Y - u) / 2, (X/Y - u) / 2] that is an
* X coordinate on the curve (at least one of them is, for any u and t).
*
* Then an ElligatorSwift encoding of x consists of the 32-byte big-endian
* encodings of field elements u and t concatenated, where f(u,t) = x.
* The encoding algorithm is described in the paper, and effectively picks a
* uniformly random pair (u,t) among those which encode x.
*
* If the Y coordinate is relevant, it is given the same parity as t.
*
* Changes w.r.t. the paper:
* - The u=0, t=0, and u^3+t^2+7=0 conditions result in decoding to the point
* at infinity in the paper. Here they are remapped to finite points.
* - The paper uses an additional encoding bit for the parity of y. Here the
* parity of t is used (negating t does not affect the decoded x coordinate,
* so this is possible).
*
* For mathematical background about the scheme, see the doc/ellswift.md file.
*/
/** A pointer to a function used by secp256k1_ellswift_xdh to hash the shared X
* coordinate along with the encoded public keys to a uniform shared secret.
*
* Returns: 1 if a shared secret was successfully computed.
* 0 will cause secp256k1_ellswift_xdh to fail and return 0.
* Other return values are not allowed, and the behaviour of
* secp256k1_ellswift_xdh is undefined for other return values.
* Out: output: pointer to an array to be filled by the function
* In: x32: pointer to the 32-byte serialized X coordinate
* of the resulting shared point (will not be NULL)
* ell_a64: pointer to the 64-byte encoded public key of party A
* (will not be NULL)
* ell_b64: pointer to the 64-byte encoded public key of party B
* (will not be NULL)
* data: arbitrary data pointer that is passed through
*/
typedef int (*secp256k1_ellswift_xdh_hash_function)(
unsigned char *output,
const unsigned char *x32,
const unsigned char *ell_a64,
const unsigned char *ell_b64,
void *data
);
/** An implementation of an secp256k1_ellswift_xdh_hash_function which uses
* SHA256(prefix64 || ell_a64 || ell_b64 || x32), where prefix64 is the 64-byte
* array pointed to by data. */
SECP256K1_API const secp256k1_ellswift_xdh_hash_function secp256k1_ellswift_xdh_hash_function_prefix;
/** An implementation of an secp256k1_ellswift_xdh_hash_function compatible with
* BIP324. It returns H_tag(ell_a64 || ell_b64 || x32), where H_tag is the
* BIP340 tagged hash function with tag "bip324_ellswift_xonly_ecdh". Equivalent
* to secp256k1_ellswift_xdh_hash_function_prefix with prefix64 set to
* SHA256("bip324_ellswift_xonly_ecdh")||SHA256("bip324_ellswift_xonly_ecdh").
* The data argument is ignored. */
SECP256K1_API const secp256k1_ellswift_xdh_hash_function secp256k1_ellswift_xdh_hash_function_bip324;
/** Construct a 64-byte ElligatorSwift encoding of a given pubkey.
*
* Returns: 1 always.
* Args: ctx: pointer to a context object
* Out: ell64: pointer to a 64-byte array to be filled
* In: pubkey: pointer to a secp256k1_pubkey containing an
* initialized public key
* rnd32: pointer to 32 bytes of randomness
*
* It is recommended that rnd32 consists of 32 uniformly random bytes, not
* known to any adversary trying to detect whether public keys are being
* encoded, though 16 bytes of randomness (padded to an array of 32 bytes,
* e.g., with zeros) suffice to make the result indistinguishable from
* uniform. The randomness in rnd32 must not be a deterministic function of
* the pubkey (it can be derived from the private key, though).
*
* It is not guaranteed that the computed encoding is stable across versions
* of the library, even if all arguments to this function (including rnd32)
* are the same.
*
* This function runs in variable time.
*/
SECP256K1_API int secp256k1_ellswift_encode(
const secp256k1_context *ctx,
unsigned char *ell64,
const secp256k1_pubkey *pubkey,
const unsigned char *rnd32
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4);
/** Decode a 64-bytes ElligatorSwift encoded public key.
*
* Returns: always 1
* Args: ctx: pointer to a context object
* Out: pubkey: pointer to a secp256k1_pubkey that will be filled
* In: ell64: pointer to a 64-byte array to decode
*
* This function runs in variable time.
*/
SECP256K1_API int secp256k1_ellswift_decode(
const secp256k1_context *ctx,
secp256k1_pubkey *pubkey,
const unsigned char *ell64
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Compute an ElligatorSwift public key for a secret key.
*
* Returns: 1: secret was valid, public key was stored.
* 0: secret was invalid, try again.
* Args: ctx: pointer to a context object (not secp256k1_context_static)
* Out: ell64: pointer to a 64-byte array to receive the ElligatorSwift
* public key
* In: seckey32: pointer to a 32-byte secret key
* auxrnd32: (optional) pointer to 32 bytes of randomness
*
* Constant time in seckey and auxrnd32, but not in the resulting public key.
*
* It is recommended that auxrnd32 contains 32 uniformly random bytes, though
* it is optional (and does result in encodings that are indistinguishable from
* uniform even without any auxrnd32). It differs from the (mandatory) rnd32
* argument to secp256k1_ellswift_encode in this regard.
*
* This function can be used instead of calling secp256k1_ec_pubkey_create
* followed by secp256k1_ellswift_encode. It is safer, as it uses the secret
* key as entropy for the encoding (supplemented with auxrnd32, if provided).
*
* Like secp256k1_ellswift_encode, this function does not guarantee that the
* computed encoding is stable across versions of the library, even if all
* arguments (including auxrnd32) are the same.
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ellswift_create(
const secp256k1_context *ctx,
unsigned char *ell64,
const unsigned char *seckey32,
const unsigned char *auxrnd32
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Given a private key, and ElligatorSwift public keys sent in both directions,
* compute a shared secret using x-only Elliptic Curve Diffie-Hellman (ECDH).
*
* Returns: 1: shared secret was successfully computed
* 0: secret was invalid or hashfp returned 0
* Args: ctx: pointer to a context object.
* Out: output: pointer to an array to be filled by hashfp.
* In: ell_a64: pointer to the 64-byte encoded public key of party A
* (will not be NULL)
* ell_b64: pointer to the 64-byte encoded public key of party B
* (will not be NULL)
* seckey32: pointer to our 32-byte secret key
* party: boolean indicating which party we are: zero if we are
* party A, non-zero if we are party B. seckey32 must be
* the private key corresponding to that party's ell_?64.
* This correspondence is not checked.
* hashfp: pointer to a hash function.
* data: arbitrary data pointer passed through to hashfp.
*
* Constant time in seckey32.
*
* This function is more efficient than decoding the public keys, and performing
* ECDH on them.
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ellswift_xdh(
const secp256k1_context *ctx,
unsigned char *output,
const unsigned char *ell_a64,
const unsigned char *ell_b64,
const unsigned char *seckey32,
int party,
secp256k1_ellswift_xdh_hash_function hashfp,
void *data
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4) SECP256K1_ARG_NONNULL(5) SECP256K1_ARG_NONNULL(7);
#ifdef __cplusplus
}
#endif
#endif /* SECP256K1_ELLSWIFT_H */

View File

@@ -0,0 +1,250 @@
#ifndef SECP256K1_EXTRAKEYS_H
#define SECP256K1_EXTRAKEYS_H
#include "secp256k1.h"
#ifdef __cplusplus
extern "C" {
#endif
/** Opaque data structure that holds a parsed and valid "x-only" public key.
* An x-only pubkey encodes a point whose Y coordinate is even. It is
* serialized using only its X coordinate (32 bytes). See BIP-340 for more
* information about x-only pubkeys.
*
* The exact representation of data inside is implementation defined and not
* guaranteed to be portable between different platforms or versions. It is
* however guaranteed to be 64 bytes in size, and can be safely copied/moved.
* If you need to convert to a format suitable for storage, transmission, use
* use secp256k1_xonly_pubkey_serialize and secp256k1_xonly_pubkey_parse. To
* compare keys, use secp256k1_xonly_pubkey_cmp.
*/
typedef struct secp256k1_xonly_pubkey {
unsigned char data[64];
} secp256k1_xonly_pubkey;
/** Opaque data structure that holds a keypair consisting of a secret and a
* public key.
*
* The exact representation of data inside is implementation defined and not
* guaranteed to be portable between different platforms or versions. It is
* however guaranteed to be 96 bytes in size, and can be safely copied/moved.
*/
typedef struct secp256k1_keypair {
unsigned char data[96];
} secp256k1_keypair;
/** Parse a 32-byte sequence into a xonly_pubkey object.
*
* Returns: 1 if the public key was fully valid.
* 0 if the public key could not be parsed or is invalid.
*
* Args: ctx: pointer to a context object.
* Out: pubkey: pointer to a pubkey object. If 1 is returned, it is set to a
* parsed version of input. If not, it's set to an invalid value.
* In: input32: pointer to a serialized xonly_pubkey.
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_xonly_pubkey_parse(
const secp256k1_context *ctx,
secp256k1_xonly_pubkey *pubkey,
const unsigned char *input32
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Serialize an xonly_pubkey object into a 32-byte sequence.
*
* Returns: 1 always.
*
* Args: ctx: pointer to a context object.
* Out: output32: pointer to a 32-byte array to place the serialized key in.
* In: pubkey: pointer to a secp256k1_xonly_pubkey containing an initialized public key.
*/
SECP256K1_API int secp256k1_xonly_pubkey_serialize(
const secp256k1_context *ctx,
unsigned char *output32,
const secp256k1_xonly_pubkey *pubkey
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Compare two x-only public keys using lexicographic order
*
* Returns: <0 if the first public key is less than the second
* >0 if the first public key is greater than the second
* 0 if the two public keys are equal
* Args: ctx: pointer to a context object.
* In: pubkey1: first public key to compare
* pubkey2: second public key to compare
*/
SECP256K1_API int secp256k1_xonly_pubkey_cmp(
const secp256k1_context *ctx,
const secp256k1_xonly_pubkey *pk1,
const secp256k1_xonly_pubkey *pk2
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Converts a secp256k1_pubkey into a secp256k1_xonly_pubkey.
*
* Returns: 1 always.
*
* Args: ctx: pointer to a context object.
* Out: xonly_pubkey: pointer to an x-only public key object for placing the converted public key.
* pk_parity: Ignored if NULL. Otherwise, pointer to an integer that
* will be set to 1 if the point encoded by xonly_pubkey is
* the negation of the pubkey and set to 0 otherwise.
* In: pubkey: pointer to a public key that is converted.
*/
SECP256K1_API int secp256k1_xonly_pubkey_from_pubkey(
const secp256k1_context *ctx,
secp256k1_xonly_pubkey *xonly_pubkey,
int *pk_parity,
const secp256k1_pubkey *pubkey
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(4);
/** Tweak an x-only public key by adding the generator multiplied with tweak32
* to it.
*
* Note that the resulting point can not in general be represented by an x-only
* pubkey because it may have an odd Y coordinate. Instead, the output_pubkey
* is a normal secp256k1_pubkey.
*
* Returns: 0 if the arguments are invalid or the resulting public key would be
* invalid (only when the tweak is the negation of the corresponding
* secret key). 1 otherwise.
*
* Args: ctx: pointer to a context object.
* Out: output_pubkey: pointer to a public key to store the result. Will be set
* to an invalid value if this function returns 0.
* In: internal_pubkey: pointer to an x-only pubkey to apply the tweak to.
* tweak32: pointer to a 32-byte tweak, which must be valid
* according to secp256k1_ec_seckey_verify or 32 zero
* bytes. For uniformly random 32-byte tweaks, the chance of
* being invalid is negligible (around 1 in 2^128).
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_xonly_pubkey_tweak_add(
const secp256k1_context *ctx,
secp256k1_pubkey *output_pubkey,
const secp256k1_xonly_pubkey *internal_pubkey,
const unsigned char *tweak32
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4);
/** Checks that a tweaked pubkey is the result of calling
* secp256k1_xonly_pubkey_tweak_add with internal_pubkey and tweak32.
*
* The tweaked pubkey is represented by its 32-byte x-only serialization and
* its pk_parity, which can both be obtained by converting the result of
* tweak_add to a secp256k1_xonly_pubkey.
*
* Note that this alone does _not_ verify that the tweaked pubkey is a
* commitment. If the tweak is not chosen in a specific way, the tweaked pubkey
* can easily be the result of a different internal_pubkey and tweak.
*
* Returns: 0 if the arguments are invalid or the tweaked pubkey is not the
* result of tweaking the internal_pubkey with tweak32. 1 otherwise.
* Args: ctx: pointer to a context object.
* In: tweaked_pubkey32: pointer to a serialized xonly_pubkey.
* tweaked_pk_parity: the parity of the tweaked pubkey (whose serialization
* is passed in as tweaked_pubkey32). This must match the
* pk_parity value that is returned when calling
* secp256k1_xonly_pubkey with the tweaked pubkey, or
* this function will fail.
* internal_pubkey: pointer to an x-only public key object to apply the tweak to.
* tweak32: pointer to a 32-byte tweak.
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_xonly_pubkey_tweak_add_check(
const secp256k1_context *ctx,
const unsigned char *tweaked_pubkey32,
int tweaked_pk_parity,
const secp256k1_xonly_pubkey *internal_pubkey,
const unsigned char *tweak32
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(4) SECP256K1_ARG_NONNULL(5);
/** Compute the keypair for a valid secret key.
*
* See the documentation of `secp256k1_ec_seckey_verify` for more information
* about the validity of secret keys.
*
* Returns: 1: secret key is valid
* 0: secret key is invalid
* Args: ctx: pointer to a context object (not secp256k1_context_static).
* Out: keypair: pointer to the created keypair.
* In: seckey: pointer to a 32-byte secret key.
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_keypair_create(
const secp256k1_context *ctx,
secp256k1_keypair *keypair,
const unsigned char *seckey
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Get the secret key from a keypair.
*
* Returns: 1 always.
* Args: ctx: pointer to a context object.
* Out: seckey: pointer to a 32-byte buffer for the secret key.
* In: keypair: pointer to a keypair.
*/
SECP256K1_API int secp256k1_keypair_sec(
const secp256k1_context *ctx,
unsigned char *seckey,
const secp256k1_keypair *keypair
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Get the public key from a keypair.
*
* Returns: 1 always.
* Args: ctx: pointer to a context object.
* Out: pubkey: pointer to a pubkey object, set to the keypair public key.
* In: keypair: pointer to a keypair.
*/
SECP256K1_API int secp256k1_keypair_pub(
const secp256k1_context *ctx,
secp256k1_pubkey *pubkey,
const secp256k1_keypair *keypair
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Get the x-only public key from a keypair.
*
* This is the same as calling secp256k1_keypair_pub and then
* secp256k1_xonly_pubkey_from_pubkey.
*
* Returns: 1 always.
* Args: ctx: pointer to a context object.
* Out: pubkey: pointer to an xonly_pubkey object, set to the keypair
* public key after converting it to an xonly_pubkey.
* pk_parity: Ignored if NULL. Otherwise, pointer to an integer that will be set to the
* pk_parity argument of secp256k1_xonly_pubkey_from_pubkey.
* In: keypair: pointer to a keypair.
*/
SECP256K1_API int secp256k1_keypair_xonly_pub(
const secp256k1_context *ctx,
secp256k1_xonly_pubkey *pubkey,
int *pk_parity,
const secp256k1_keypair *keypair
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(4);
/** Tweak a keypair by adding tweak32 to the secret key and updating the public
* key accordingly.
*
* Calling this function and then secp256k1_keypair_pub results in the same
* public key as calling secp256k1_keypair_xonly_pub and then
* secp256k1_xonly_pubkey_tweak_add.
*
* Returns: 0 if the arguments are invalid or the resulting keypair would be
* invalid (only when the tweak is the negation of the keypair's
* secret key). 1 otherwise.
*
* Args: ctx: pointer to a context object.
* In/Out: keypair: pointer to a keypair to apply the tweak to. Will be set to
* an invalid value if this function returns 0.
* In: tweak32: pointer to a 32-byte tweak, which must be valid according to
* secp256k1_ec_seckey_verify or 32 zero bytes. For uniformly
* random 32-byte tweaks, the chance of being invalid is
* negligible (around 1 in 2^128).
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_keypair_xonly_tweak_add(
const secp256k1_context *ctx,
secp256k1_keypair *keypair,
const unsigned char *tweak32
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
#ifdef __cplusplus
}
#endif
#endif /* SECP256K1_EXTRAKEYS_H */

View File

@@ -0,0 +1,588 @@
#ifndef SECP256K1_MUSIG_H
#define SECP256K1_MUSIG_H
#include "secp256k1_extrakeys.h"
#ifdef __cplusplus
extern "C" {
#endif
#include <stddef.h>
#include <stdint.h>
/** This module implements BIP 327 "MuSig2 for BIP340-compatible
* Multi-Signatures"
* (https://github.com/bitcoin/bips/blob/master/bip-0327.mediawiki)
* v1.0.0. You can find an example demonstrating the musig module in
* examples/musig.c.
*
* The module also supports BIP 341 ("Taproot") public key tweaking.
*
* It is recommended to read the documentation in this include file carefully.
* Further notes on API usage can be found in doc/musig.md
*
* Since the first version of MuSig is essentially replaced by MuSig2, we use
* MuSig, musig and MuSig2 synonymously unless noted otherwise.
*/
/** Opaque data structures
*
* The exact representation of data inside the opaque data structures is
* implementation defined and not guaranteed to be portable between different
* platforms or versions. With the exception of `secp256k1_musig_secnonce`, the
* data structures can be safely copied/moved. If you need to convert to a
* format suitable for storage, transmission, or comparison, use the
* corresponding serialization and parsing functions.
*/
/** Opaque data structure that caches information about public key aggregation.
*
* Guaranteed to be 197 bytes in size. No serialization and parsing functions
* (yet).
*/
typedef struct secp256k1_musig_keyagg_cache {
unsigned char data[197];
} secp256k1_musig_keyagg_cache;
/** Opaque data structure that holds a signer's _secret_ nonce.
*
* Guaranteed to be 132 bytes in size.
*
* WARNING: This structure MUST NOT be copied or read or written to directly. A
* signer who is online throughout the whole process and can keep this
* structure in memory can use the provided API functions for a safe standard
* workflow.
*
* Copying this data structure can result in nonce reuse which will leak the
* secret signing key.
*/
typedef struct secp256k1_musig_secnonce {
unsigned char data[132];
} secp256k1_musig_secnonce;
/** Opaque data structure that holds a signer's public nonce.
*
* Guaranteed to be 132 bytes in size. Serialized and parsed with
* `musig_pubnonce_serialize` and `musig_pubnonce_parse`.
*/
typedef struct secp256k1_musig_pubnonce {
unsigned char data[132];
} secp256k1_musig_pubnonce;
/** Opaque data structure that holds an aggregate public nonce.
*
* Guaranteed to be 132 bytes in size. Serialized and parsed with
* `musig_aggnonce_serialize` and `musig_aggnonce_parse`.
*/
typedef struct secp256k1_musig_aggnonce {
unsigned char data[132];
} secp256k1_musig_aggnonce;
/** Opaque data structure that holds a MuSig session.
*
* This structure is not required to be kept secret for the signing protocol to
* be secure. Guaranteed to be 133 bytes in size. No serialization and parsing
* functions (yet).
*/
typedef struct secp256k1_musig_session {
unsigned char data[133];
} secp256k1_musig_session;
/** Opaque data structure that holds a partial MuSig signature.
*
* Guaranteed to be 36 bytes in size. Serialized and parsed with
* `musig_partial_sig_serialize` and `musig_partial_sig_parse`.
*/
typedef struct secp256k1_musig_partial_sig {
unsigned char data[36];
} secp256k1_musig_partial_sig;
/** Parse a signer's public nonce.
*
* Returns: 1 when the nonce could be parsed, 0 otherwise.
* Args: ctx: pointer to a context object
* Out: nonce: pointer to a nonce object
* In: in66: pointer to the 66-byte nonce to be parsed
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_pubnonce_parse(
const secp256k1_context *ctx,
secp256k1_musig_pubnonce *nonce,
const unsigned char *in66
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Serialize a signer's public nonce
*
* Returns: 1 always
* Args: ctx: pointer to a context object
* Out: out66: pointer to a 66-byte array to store the serialized nonce
* In: nonce: pointer to the nonce
*/
SECP256K1_API int secp256k1_musig_pubnonce_serialize(
const secp256k1_context *ctx,
unsigned char *out66,
const secp256k1_musig_pubnonce *nonce
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Parse an aggregate public nonce.
*
* Returns: 1 when the nonce could be parsed, 0 otherwise.
* Args: ctx: pointer to a context object
* Out: nonce: pointer to a nonce object
* In: in66: pointer to the 66-byte nonce to be parsed
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_aggnonce_parse(
const secp256k1_context *ctx,
secp256k1_musig_aggnonce *nonce,
const unsigned char *in66
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Serialize an aggregate public nonce
*
* Returns: 1 always
* Args: ctx: pointer to a context object
* Out: out66: pointer to a 66-byte array to store the serialized nonce
* In: nonce: pointer to the nonce
*/
SECP256K1_API int secp256k1_musig_aggnonce_serialize(
const secp256k1_context *ctx,
unsigned char *out66,
const secp256k1_musig_aggnonce *nonce
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Parse a MuSig partial signature.
*
* Returns: 1 when the signature could be parsed, 0 otherwise.
* Args: ctx: pointer to a context object
* Out: sig: pointer to a signature object
* In: in32: pointer to the 32-byte signature to be parsed
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_partial_sig_parse(
const secp256k1_context *ctx,
secp256k1_musig_partial_sig *sig,
const unsigned char *in32
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Serialize a MuSig partial signature
*
* Returns: 1 always
* Args: ctx: pointer to a context object
* Out: out32: pointer to a 32-byte array to store the serialized signature
* In: sig: pointer to the signature
*/
SECP256K1_API int secp256k1_musig_partial_sig_serialize(
const secp256k1_context *ctx,
unsigned char *out32,
const secp256k1_musig_partial_sig *sig
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Computes an aggregate public key and uses it to initialize a keyagg_cache
*
* Different orders of `pubkeys` result in different `agg_pk`s.
*
* Before aggregating, the pubkeys can be sorted with `secp256k1_ec_pubkey_sort`
* which ensures the same `agg_pk` result for the same multiset of pubkeys.
* This is useful to do before `pubkey_agg`, such that the order of pubkeys
* does not affect the aggregate public key.
*
* Returns: 0 if the arguments are invalid, 1 otherwise
* Args: ctx: pointer to a context object
* Out: agg_pk: the MuSig-aggregated x-only public key. If you do not need it,
* this arg can be NULL.
* keyagg_cache: if non-NULL, pointer to a musig_keyagg_cache struct that
* is required for signing (or observing the signing session
* and verifying partial signatures).
* In: pubkeys: input array of pointers to public keys to aggregate. The order
* is important; a different order will result in a different
* aggregate public key.
* n_pubkeys: length of pubkeys array. Must be greater than 0.
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_pubkey_agg(
const secp256k1_context *ctx,
secp256k1_xonly_pubkey *agg_pk,
secp256k1_musig_keyagg_cache *keyagg_cache,
const secp256k1_pubkey * const *pubkeys,
size_t n_pubkeys
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(4);
/** Obtain the aggregate public key from a keyagg_cache.
*
* This is only useful if you need the non-xonly public key, in particular for
* plain (non-xonly) tweaking or batch-verifying multiple key aggregations
* (not implemented).
*
* Returns: 0 if the arguments are invalid, 1 otherwise
* Args: ctx: pointer to a context object
* Out: agg_pk: the MuSig-aggregated public key.
* In: keyagg_cache: pointer to a `musig_keyagg_cache` struct initialized by
* `musig_pubkey_agg`
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_pubkey_get(
const secp256k1_context *ctx,
secp256k1_pubkey *agg_pk,
const secp256k1_musig_keyagg_cache *keyagg_cache
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Apply plain "EC" tweaking to a public key in a given keyagg_cache by adding
* the generator multiplied with `tweak32` to it. This is useful for deriving
* child keys from an aggregate public key via BIP 32 where `tweak32` is set to
* a hash as defined in BIP 32.
*
* Callers are responsible for deriving `tweak32` in a way that does not reduce
* the security of MuSig (for example, by following BIP 32).
*
* The tweaking method is the same as `secp256k1_ec_pubkey_tweak_add`. So after
* the following pseudocode buf and buf2 have identical contents (absent
* earlier failures).
*
* secp256k1_musig_pubkey_agg(..., keyagg_cache, pubkeys, ...)
* secp256k1_musig_pubkey_get(..., agg_pk, keyagg_cache)
* secp256k1_musig_pubkey_ec_tweak_add(..., output_pk, tweak32, keyagg_cache)
* secp256k1_ec_pubkey_serialize(..., buf, ..., output_pk, ...)
* secp256k1_ec_pubkey_tweak_add(..., agg_pk, tweak32)
* secp256k1_ec_pubkey_serialize(..., buf2, ..., agg_pk, ...)
*
* This function is required if you want to _sign_ for a tweaked aggregate key.
* If you are only computing a public key but not intending to create a
* signature for it, use `secp256k1_ec_pubkey_tweak_add` instead.
*
* Returns: 0 if the arguments are invalid, 1 otherwise
* Args: ctx: pointer to a context object
* Out: output_pubkey: pointer to a public key to store the result. Will be set
* to an invalid value if this function returns 0. If you
* do not need it, this arg can be NULL.
* In/Out: keyagg_cache: pointer to a `musig_keyagg_cache` struct initialized by
* `musig_pubkey_agg`
* In: tweak32: pointer to a 32-byte tweak. The tweak is valid if it passes
* `secp256k1_ec_seckey_verify` and is not equal to the
* secret key corresponding to the public key represented
* by keyagg_cache or its negation. For uniformly random
* 32-byte arrays the chance of being invalid is
* negligible (around 1 in 2^128).
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_pubkey_ec_tweak_add(
const secp256k1_context *ctx,
secp256k1_pubkey *output_pubkey,
secp256k1_musig_keyagg_cache *keyagg_cache,
const unsigned char *tweak32
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4);
/** Apply x-only tweaking to a public key in a given keyagg_cache by adding the
* generator multiplied with `tweak32` to it. This is useful for creating
* Taproot outputs where `tweak32` is set to a TapTweak hash as defined in BIP
* 341.
*
* Callers are responsible for deriving `tweak32` in a way that does not reduce
* the security of MuSig (for example, by following Taproot BIP 341).
*
* The tweaking method is the same as `secp256k1_xonly_pubkey_tweak_add`. So in
* the following pseudocode xonly_pubkey_tweak_add_check (absent earlier
* failures) returns 1.
*
* secp256k1_musig_pubkey_agg(..., agg_pk, keyagg_cache, pubkeys, ...)
* secp256k1_musig_pubkey_xonly_tweak_add(..., output_pk, keyagg_cache, tweak32)
* secp256k1_xonly_pubkey_serialize(..., buf, output_pk)
* secp256k1_xonly_pubkey_tweak_add_check(..., buf, ..., agg_pk, tweak32)
*
* This function is required if you want to _sign_ for a tweaked aggregate key.
* If you are only computing a public key but not intending to create a
* signature for it, use `secp256k1_xonly_pubkey_tweak_add` instead.
*
* Returns: 0 if the arguments are invalid, 1 otherwise
* Args: ctx: pointer to a context object
* Out: output_pubkey: pointer to a public key to store the result. Will be set
* to an invalid value if this function returns 0. If you
* do not need it, this arg can be NULL.
* In/Out: keyagg_cache: pointer to a `musig_keyagg_cache` struct initialized by
* `musig_pubkey_agg`
* In: tweak32: pointer to a 32-byte tweak. The tweak is valid if it passes
* `secp256k1_ec_seckey_verify` and is not equal to the
* secret key corresponding to the public key represented
* by keyagg_cache or its negation. For uniformly random
* 32-byte arrays the chance of being invalid is
* negligible (around 1 in 2^128).
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_pubkey_xonly_tweak_add(
const secp256k1_context *ctx,
secp256k1_pubkey *output_pubkey,
secp256k1_musig_keyagg_cache *keyagg_cache,
const unsigned char *tweak32
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4);
/** Starts a signing session by generating a nonce
*
* This function outputs a secret nonce that will be required for signing and a
* corresponding public nonce that is intended to be sent to other signers.
*
* MuSig differs from regular Schnorr signing in that implementers _must_ take
* special care to not reuse a nonce. This can be ensured by following these rules:
*
* 1. Each call to this function must have a UNIQUE session_secrand32 that must
* NOT BE REUSED in subsequent calls to this function and must be KEPT
* SECRET (even from other signers).
* 2. If you already know the seckey, message or aggregate public key
* cache, they can be optionally provided to derive the nonce and increase
* misuse-resistance. The extra_input32 argument can be used to provide
* additional data that does not repeat in normal scenarios, such as the
* current time.
* 3. Avoid copying (or serializing) the secnonce. This reduces the possibility
* that it is used more than once for signing.
*
* If you don't have access to good randomness for session_secrand32, but you
* have access to a non-repeating counter, then see
* secp256k1_musig_nonce_gen_counter.
*
* Remember that nonce reuse will leak the secret key!
* Note that using the same seckey for multiple MuSig sessions is fine.
*
* Returns: 0 if the arguments are invalid and 1 otherwise
* Args: ctx: pointer to a context object (not secp256k1_context_static)
* Out: secnonce: pointer to a structure to store the secret nonce
* pubnonce: pointer to a structure to store the public nonce
* In/Out:
* session_secrand32: a 32-byte session_secrand32 as explained above. Must be unique to this
* call to secp256k1_musig_nonce_gen and must be uniformly
* random. If the function call is successful, the
* session_secrand32 buffer is invalidated to prevent reuse.
* In:
* seckey: the 32-byte secret key that will later be used for signing, if
* already known (can be NULL)
* pubkey: public key of the signer creating the nonce. The secnonce
* output of this function cannot be used to sign for any
* other public key. While the public key should correspond
* to the provided seckey, a mismatch will not cause the
* function to return 0.
* msg32: the 32-byte message that will later be signed, if already known
* (can be NULL)
* keyagg_cache: pointer to the keyagg_cache that was used to create the aggregate
* (and potentially tweaked) public key if already known
* (can be NULL)
* extra_input32: an optional 32-byte array that is input to the nonce
* derivation function (can be NULL)
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_nonce_gen(
const secp256k1_context *ctx,
secp256k1_musig_secnonce *secnonce,
secp256k1_musig_pubnonce *pubnonce,
unsigned char *session_secrand32,
const unsigned char *seckey,
const secp256k1_pubkey *pubkey,
const unsigned char *msg32,
const secp256k1_musig_keyagg_cache *keyagg_cache,
const unsigned char *extra_input32
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4) SECP256K1_ARG_NONNULL(6);
/** Alternative way to generate a nonce and start a signing session
*
* This function outputs a secret nonce that will be required for signing and a
* corresponding public nonce that is intended to be sent to other signers.
*
* This function differs from `secp256k1_musig_nonce_gen` by accepting a
* non-repeating counter value instead of a secret random value. This requires
* that a secret key is provided to `secp256k1_musig_nonce_gen_counter`
* (through the keypair argument), as opposed to `secp256k1_musig_nonce_gen`
* where the seckey argument is optional.
*
* MuSig differs from regular Schnorr signing in that implementers _must_ take
* special care to not reuse a nonce. This can be ensured by following these rules:
*
* 1. The nonrepeating_cnt argument must be a counter value that never repeats,
* i.e., you must never call `secp256k1_musig_nonce_gen_counter` twice with
* the same keypair and nonrepeating_cnt value. For example, this implies
* that if the same keypair is used with `secp256k1_musig_nonce_gen_counter`
* on multiple devices, none of the devices should have the same counter
* value as any other device.
* 2. If the seckey, message or aggregate public key cache is already available
* at this stage, any of these can be optionally provided, in which case
* they will be used in the derivation of the nonce and increase
* misuse-resistance. The extra_input32 argument can be used to provide
* additional data that does not repeat in normal scenarios, such as the
* current time.
* 3. Avoid copying (or serializing) the secnonce. This reduces the possibility
* that it is used more than once for signing.
*
* Remember that nonce reuse will leak the secret key!
* Note that using the same keypair for multiple MuSig sessions is fine.
*
* Returns: 0 if the arguments are invalid and 1 otherwise
* Args: ctx: pointer to a context object (not secp256k1_context_static)
* Out: secnonce: pointer to a structure to store the secret nonce
* pubnonce: pointer to a structure to store the public nonce
* In:
* nonrepeating_cnt: the value of a counter as explained above. Must be
* unique to this call to secp256k1_musig_nonce_gen.
* keypair: keypair of the signer creating the nonce. The secnonce
* output of this function cannot be used to sign for any
* other keypair.
* msg32: the 32-byte message that will later be signed, if already known
* (can be NULL)
* keyagg_cache: pointer to the keyagg_cache that was used to create the aggregate
* (and potentially tweaked) public key if already known
* (can be NULL)
* extra_input32: an optional 32-byte array that is input to the nonce
* derivation function (can be NULL)
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_nonce_gen_counter(
const secp256k1_context *ctx,
secp256k1_musig_secnonce *secnonce,
secp256k1_musig_pubnonce *pubnonce,
uint64_t nonrepeating_cnt,
const secp256k1_keypair *keypair,
const unsigned char *msg32,
const secp256k1_musig_keyagg_cache *keyagg_cache,
const unsigned char *extra_input32
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(5);
/** Aggregates the nonces of all signers into a single nonce
*
* This can be done by an untrusted party to reduce the communication
* between signers. Instead of everyone sending nonces to everyone else, there
* can be one party receiving all nonces, aggregating the nonces with this
* function and then sending only the aggregate nonce back to the signers.
*
* If the aggregator does not compute the aggregate nonce correctly, the final
* signature will be invalid.
*
* Returns: 0 if the arguments are invalid, 1 otherwise
* Args: ctx: pointer to a context object
* Out: aggnonce: pointer to an aggregate public nonce object for
* musig_nonce_process
* In: pubnonces: array of pointers to public nonces sent by the
* signers
* n_pubnonces: number of elements in the pubnonces array. Must be
* greater than 0.
*/
SECP256K1_API int secp256k1_musig_nonce_agg(
const secp256k1_context *ctx,
secp256k1_musig_aggnonce *aggnonce,
const secp256k1_musig_pubnonce * const *pubnonces,
size_t n_pubnonces
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Takes the aggregate nonce and creates a session that is required for signing
* and verification of partial signatures.
*
* Returns: 0 if the arguments are invalid, 1 otherwise
* Args: ctx: pointer to a context object
* Out: session: pointer to a struct to store the session
* In: aggnonce: pointer to an aggregate public nonce object that is the
* output of musig_nonce_agg
* msg32: the 32-byte message to sign
* keyagg_cache: pointer to the keyagg_cache that was used to create the
* aggregate (and potentially tweaked) pubkey
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_nonce_process(
const secp256k1_context *ctx,
secp256k1_musig_session *session,
const secp256k1_musig_aggnonce *aggnonce,
const unsigned char *msg32,
const secp256k1_musig_keyagg_cache *keyagg_cache
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4) SECP256K1_ARG_NONNULL(5);
/** Produces a partial signature
*
* This function overwrites the given secnonce with zeros and will abort if given a
* secnonce that is all zeros. This is a best effort attempt to protect against nonce
* reuse. However, this is of course easily defeated if the secnonce has been
* copied (or serialized). Remember that nonce reuse will leak the secret key!
*
* For signing to succeed, the secnonce provided to this function must have
* been generated for the provided keypair. This means that when signing for a
* keypair consisting of a seckey and pubkey, the secnonce must have been
* created by calling musig_nonce_gen with that pubkey. Otherwise, the
* illegal_callback is called.
*
* This function does not verify the output partial signature, deviating from
* the BIP 327 specification. It is recommended to verify the output partial
* signature with `secp256k1_musig_partial_sig_verify` to prevent random or
* adversarially provoked computation errors.
*
* Returns: 0 if the arguments are invalid or the provided secnonce has already
* been used for signing, 1 otherwise
* Args: ctx: pointer to a context object
* Out: partial_sig: pointer to struct to store the partial signature
* In/Out: secnonce: pointer to the secnonce struct created in
* musig_nonce_gen that has been never used in a
* partial_sign call before and has been created for the
* keypair
* In: keypair: pointer to keypair to sign the message with
* keyagg_cache: pointer to the keyagg_cache that was output when the
* aggregate public key for this session
* session: pointer to the session that was created with
* musig_nonce_process
*/
SECP256K1_API int secp256k1_musig_partial_sign(
const secp256k1_context *ctx,
secp256k1_musig_partial_sig *partial_sig,
secp256k1_musig_secnonce *secnonce,
const secp256k1_keypair *keypair,
const secp256k1_musig_keyagg_cache *keyagg_cache,
const secp256k1_musig_session *session
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4) SECP256K1_ARG_NONNULL(5) SECP256K1_ARG_NONNULL(6);
/** Verifies an individual signer's partial signature
*
* The signature is verified for a specific signing session. In order to avoid
* accidentally verifying a signature from a different or non-existing signing
* session, you must ensure the following:
* 1. The `keyagg_cache` argument is identical to the one used to create the
* `session` with `musig_nonce_process`.
* 2. The `pubkey` argument must be identical to the one sent by the signer
* before aggregating it with `musig_pubkey_agg` to create the
* `keyagg_cache`.
* 3. The `pubnonce` argument must be identical to the one sent by the signer
* before aggregating it with `musig_nonce_agg` and using the result to
* create the `session` with `musig_nonce_process`.
*
* It is not required to call this function in regular MuSig sessions, because
* if any partial signature does not verify, the final signature will not
* verify either, so the problem will be caught. However, this function
* provides the ability to identify which specific partial signature fails
* verification.
*
* Returns: 0 if the arguments are invalid or the partial signature does not
* verify, 1 otherwise
* Args ctx: pointer to a context object
* In: partial_sig: pointer to partial signature to verify, sent by
* the signer associated with `pubnonce` and `pubkey`
* pubnonce: public nonce of the signer in the signing session
* pubkey: public key of the signer in the signing session
* keyagg_cache: pointer to the keyagg_cache that was output when the
* aggregate public key for this signing session
* session: pointer to the session that was created with
* `musig_nonce_process`
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_partial_sig_verify(
const secp256k1_context *ctx,
const secp256k1_musig_partial_sig *partial_sig,
const secp256k1_musig_pubnonce *pubnonce,
const secp256k1_pubkey *pubkey,
const secp256k1_musig_keyagg_cache *keyagg_cache,
const secp256k1_musig_session *session
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4) SECP256K1_ARG_NONNULL(5) SECP256K1_ARG_NONNULL(6);
/** Aggregates partial signatures
*
* Returns: 0 if the arguments are invalid, 1 otherwise (which does NOT mean
* the resulting signature verifies).
* Args: ctx: pointer to a context object
* Out: sig64: complete (but possibly invalid) Schnorr signature
* In: session: pointer to the session that was created with
* musig_nonce_process
* partial_sigs: array of pointers to partial signatures to aggregate
* n_sigs: number of elements in the partial_sigs array. Must be
* greater than 0.
*/
SECP256K1_API int secp256k1_musig_partial_sig_agg(
const secp256k1_context *ctx,
unsigned char *sig64,
const secp256k1_musig_session *session,
const secp256k1_musig_partial_sig * const *partial_sigs,
size_t n_sigs
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4);
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -0,0 +1,134 @@
#ifndef SECP256K1_PREALLOCATED_H
#define SECP256K1_PREALLOCATED_H
#include "secp256k1.h"
#ifdef __cplusplus
extern "C" {
#endif
/* The module provided by this header file is intended for settings in which it
* is not possible or desirable to rely on dynamic memory allocation. It provides
* functions for creating, cloning, and destroying secp256k1 context objects in a
* contiguous fixed-size block of memory provided by the caller.
*
* Context objects created by functions in this module can be used like contexts
* objects created by functions in secp256k1.h, i.e., they can be passed to any
* API function that expects a context object (see secp256k1.h for details). The
* only exception is that context objects created by functions in this module
* must be destroyed using secp256k1_context_preallocated_destroy (in this
* module) instead of secp256k1_context_destroy (in secp256k1.h).
*
* It is guaranteed that functions in this module will not call malloc or its
* friends realloc, calloc, and free.
*/
/** Determine the memory size of a secp256k1 context object to be created in
* caller-provided memory.
*
* The purpose of this function is to determine how much memory must be provided
* to secp256k1_context_preallocated_create.
*
* Returns: the required size of the caller-provided memory block
* In: flags: which parts of the context to initialize.
*/
SECP256K1_API size_t secp256k1_context_preallocated_size(
unsigned int flags
) SECP256K1_WARN_UNUSED_RESULT;
/** Create a secp256k1 context object in caller-provided memory.
*
* The caller must provide a pointer to a rewritable contiguous block of memory
* of size at least secp256k1_context_preallocated_size(flags) bytes, suitably
* aligned to hold an object of any type.
*
* The block of memory is exclusively owned by the created context object during
* the lifetime of this context object, which begins with the call to this
* function and ends when a call to secp256k1_context_preallocated_destroy
* (which destroys the context object again) returns. During the lifetime of the
* context object, the caller is obligated not to access this block of memory,
* i.e., the caller may not read or write the memory, e.g., by copying the memory
* contents to a different location or trying to create a second context object
* in the memory. In simpler words, the prealloc pointer (or any pointer derived
* from it) should not be used during the lifetime of the context object.
*
* Returns: pointer to newly created context object.
* In: prealloc: pointer to a rewritable contiguous block of memory of
* size at least secp256k1_context_preallocated_size(flags)
* bytes, as detailed above.
* flags: which parts of the context to initialize.
*
* See secp256k1_context_create (in secp256k1.h) for further details.
*
* See also secp256k1_context_randomize (in secp256k1.h)
* and secp256k1_context_preallocated_destroy.
*/
SECP256K1_API secp256k1_context *secp256k1_context_preallocated_create(
void *prealloc,
unsigned int flags
) SECP256K1_ARG_NONNULL(1) SECP256K1_WARN_UNUSED_RESULT;
/** Determine the memory size of a secp256k1 context object to be copied into
* caller-provided memory.
*
* Returns: the required size of the caller-provided memory block.
* In: ctx: pointer to a context to copy.
*/
SECP256K1_API size_t secp256k1_context_preallocated_clone_size(
const secp256k1_context *ctx
) SECP256K1_ARG_NONNULL(1) SECP256K1_WARN_UNUSED_RESULT;
/** Copy a secp256k1 context object into caller-provided memory.
*
* The caller must provide a pointer to a rewritable contiguous block of memory
* of size at least secp256k1_context_preallocated_size(flags) bytes, suitably
* aligned to hold an object of any type.
*
* The block of memory is exclusively owned by the created context object during
* the lifetime of this context object, see the description of
* secp256k1_context_preallocated_create for details.
*
* Cloning secp256k1_context_static is not possible, and should not be emulated by
* the caller (e.g., using memcpy). Create a new context instead.
*
* Returns: pointer to a newly created context object.
* Args: ctx: pointer to a context to copy (not secp256k1_context_static).
* In: prealloc: pointer to a rewritable contiguous block of memory of
* size at least secp256k1_context_preallocated_size(flags)
* bytes, as detailed above.
*/
SECP256K1_API secp256k1_context *secp256k1_context_preallocated_clone(
const secp256k1_context *ctx,
void *prealloc
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_WARN_UNUSED_RESULT;
/** Destroy a secp256k1 context object that has been created in
* caller-provided memory.
*
* The context pointer may not be used afterwards.
*
* The context to destroy must have been created using
* secp256k1_context_preallocated_create or secp256k1_context_preallocated_clone.
* If the context has instead been created using secp256k1_context_create or
* secp256k1_context_clone, the behaviour is undefined. In that case,
* secp256k1_context_destroy must be used instead.
*
* If required, it is the responsibility of the caller to deallocate the block
* of memory properly after this function returns, e.g., by calling free on the
* preallocated pointer given to secp256k1_context_preallocated_create or
* secp256k1_context_preallocated_clone.
*
* Args: ctx: pointer to a context to destroy, constructed using
* secp256k1_context_preallocated_create or
* secp256k1_context_preallocated_clone
* (i.e., not secp256k1_context_static).
*/
SECP256K1_API void secp256k1_context_preallocated_destroy(
secp256k1_context *ctx
) SECP256K1_ARG_NONNULL(1);
#ifdef __cplusplus
}
#endif
#endif /* SECP256K1_PREALLOCATED_H */

View File

@@ -0,0 +1,123 @@
#ifndef SECP256K1_RECOVERY_H
#define SECP256K1_RECOVERY_H
#include "secp256k1.h"
#ifdef __cplusplus
extern "C" {
#endif
/** Opaque data structure that holds a parsed ECDSA signature,
* supporting pubkey recovery.
*
* The exact representation of data inside is implementation defined and not
* guaranteed to be portable between different platforms or versions. It is
* however guaranteed to be 65 bytes in size, and can be safely copied/moved.
* If you need to convert to a format suitable for storage or transmission, use
* the secp256k1_ecdsa_signature_serialize_* and
* secp256k1_ecdsa_signature_parse_* functions.
*
* Furthermore, it is guaranteed that identical signatures (including their
* recoverability) will have identical representation, so they can be
* memcmp'ed.
*/
typedef struct secp256k1_ecdsa_recoverable_signature {
unsigned char data[65];
} secp256k1_ecdsa_recoverable_signature;
/** Parse a compact ECDSA signature (64 bytes + recovery id).
*
* Returns: 1 when the signature could be parsed, 0 otherwise
* Args: ctx: pointer to a context object
* Out: sig: pointer to a signature object
* In: input64: pointer to a 64-byte compact signature
* recid: the recovery id (0, 1, 2 or 3)
*/
SECP256K1_API int secp256k1_ecdsa_recoverable_signature_parse_compact(
const secp256k1_context *ctx,
secp256k1_ecdsa_recoverable_signature *sig,
const unsigned char *input64,
int recid
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Convert a recoverable signature into a normal signature.
*
* Returns: 1
* Args: ctx: pointer to a context object.
* Out: sig: pointer to a normal signature.
* In: sigin: pointer to a recoverable signature.
*/
SECP256K1_API int secp256k1_ecdsa_recoverable_signature_convert(
const secp256k1_context *ctx,
secp256k1_ecdsa_signature *sig,
const secp256k1_ecdsa_recoverable_signature *sigin
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Serialize an ECDSA signature in compact format (64 bytes + recovery id).
*
* Returns: 1
* Args: ctx: pointer to a context object.
* Out: output64: pointer to a 64-byte array of the compact signature.
* recid: pointer to an integer to hold the recovery id.
* In: sig: pointer to an initialized signature object.
*/
SECP256K1_API int secp256k1_ecdsa_recoverable_signature_serialize_compact(
const secp256k1_context *ctx,
unsigned char *output64,
int *recid,
const secp256k1_ecdsa_recoverable_signature *sig
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4);
/** Create a recoverable ECDSA signature.
*
* Returns: 1: signature created
* 0: the nonce generation function failed, or the secret key was invalid.
* Args: ctx: pointer to a context object (not secp256k1_context_static).
* Out: sig: pointer to an array where the signature will be placed.
* In: msghash32: the 32-byte message hash being signed.
* seckey: pointer to a 32-byte secret key.
* noncefp: pointer to a nonce generation function. If NULL,
* secp256k1_nonce_function_default is used.
* ndata: pointer to arbitrary data used by the nonce generation function
* (can be NULL for secp256k1_nonce_function_default).
*/
SECP256K1_API int secp256k1_ecdsa_sign_recoverable(
const secp256k1_context *ctx,
secp256k1_ecdsa_recoverable_signature *sig,
const unsigned char *msghash32,
const unsigned char *seckey,
secp256k1_nonce_function noncefp,
const void *ndata
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4);
/** Recover an ECDSA public key from a signature.
*
* Successful public key recovery guarantees that the signature, after normalization,
* passes `secp256k1_ecdsa_verify`. Thus, explicit verification is not necessary.
*
* However, a recoverable signature that successfully passes `secp256k1_ecdsa_recover`,
* when converted to a non-recoverable signature (using
* `secp256k1_ecdsa_recoverable_signature_convert`), is not guaranteed to be
* normalized and thus not guaranteed to pass `secp256k1_ecdsa_verify`. If a
* normalized signature is required, call `secp256k1_ecdsa_signature_normalize`
* after `secp256k1_ecdsa_recoverable_signature_convert`.
*
* Returns: 1: public key successfully recovered
* 0: otherwise.
* Args: ctx: pointer to a context object.
* Out: pubkey: pointer to the recovered public key.
* In: sig: pointer to initialized signature that supports pubkey recovery.
* msghash32: the 32-byte message hash assumed to be signed.
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ecdsa_recover(
const secp256k1_context *ctx,
secp256k1_pubkey *pubkey,
const secp256k1_ecdsa_recoverable_signature *sig,
const unsigned char *msghash32
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4);
#ifdef __cplusplus
}
#endif
#endif /* SECP256K1_RECOVERY_H */

View File

@@ -0,0 +1,190 @@
#ifndef SECP256K1_SCHNORRSIG_H
#define SECP256K1_SCHNORRSIG_H
#include "secp256k1.h"
#include "secp256k1_extrakeys.h"
#ifdef __cplusplus
extern "C" {
#endif
/** This module implements a variant of Schnorr signatures compliant with
* Bitcoin Improvement Proposal 340 "Schnorr Signatures for secp256k1"
* (https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki).
*/
/** A pointer to a function to deterministically generate a nonce.
*
* Same as secp256k1_nonce function with the exception of accepting an
* additional pubkey argument and not requiring an attempt argument. The pubkey
* argument can protect signature schemes with key-prefixed challenge hash
* inputs against reusing the nonce when signing with the wrong precomputed
* pubkey.
*
* Returns: 1 if a nonce was successfully generated. 0 will cause signing to
* return an error.
* Out: nonce32: pointer to a 32-byte array to be filled by the function
* In: msg: the message being verified. Is NULL if and only if msglen
* is 0.
* msglen: the length of the message
* key32: pointer to a 32-byte secret key (will not be NULL)
* xonly_pk32: the 32-byte serialized xonly pubkey corresponding to key32
* (will not be NULL)
* algo: pointer to an array describing the signature
* algorithm (will not be NULL)
* algolen: the length of the algo array
* data: arbitrary data pointer that is passed through
*
* Except for test cases, this function should compute some cryptographic hash of
* the message, the key, the pubkey, the algorithm description, and data.
*/
typedef int (*secp256k1_nonce_function_hardened)(
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
);
/** An implementation of the nonce generation function as defined in Bitcoin
* Improvement Proposal 340 "Schnorr Signatures for secp256k1"
* (https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki).
*
* If a data pointer is passed, it is assumed to be a pointer to 32 bytes of
* auxiliary random data as defined in BIP-340. If the data pointer is NULL,
* the nonce derivation procedure follows BIP-340 by setting the auxiliary
* random data to zero. The algo argument must be non-NULL, otherwise the
* function will fail and return 0. The hash will be tagged with algo.
* Therefore, to create BIP-340 compliant signatures, algo must be set to
* "BIP0340/nonce" and algolen to 13.
*/
SECP256K1_API const secp256k1_nonce_function_hardened secp256k1_nonce_function_bip340;
/** Data structure that contains additional arguments for schnorrsig_sign_custom.
*
* A schnorrsig_extraparams structure object can be initialized correctly by
* setting it to SECP256K1_SCHNORRSIG_EXTRAPARAMS_INIT.
*
* Members:
* magic: set to SECP256K1_SCHNORRSIG_EXTRAPARAMS_MAGIC at initialization
* and has no other function than making sure the object is
* initialized.
* noncefp: pointer to a nonce generation function. If NULL,
* secp256k1_nonce_function_bip340 is used
* ndata: pointer to arbitrary data used by the nonce generation function
* (can be NULL). If it is non-NULL and
* secp256k1_nonce_function_bip340 is used, then ndata must be a
* pointer to 32-byte auxiliary randomness as per BIP-340.
*/
typedef struct secp256k1_schnorrsig_extraparams {
unsigned char magic[4];
secp256k1_nonce_function_hardened noncefp;
void *ndata;
} secp256k1_schnorrsig_extraparams;
#define SECP256K1_SCHNORRSIG_EXTRAPARAMS_MAGIC { 0xda, 0x6f, 0xb3, 0x8c }
#define SECP256K1_SCHNORRSIG_EXTRAPARAMS_INIT {\
SECP256K1_SCHNORRSIG_EXTRAPARAMS_MAGIC,\
NULL,\
NULL\
}
/** Create a Schnorr signature.
*
* Does _not_ strictly follow BIP-340 because it does not verify the resulting
* signature. Instead, you can manually use secp256k1_schnorrsig_verify and
* abort if it fails.
*
* This function only signs 32-byte messages. If you have messages of a
* different size (or the same size but without a context-specific tag
* prefix), it is recommended to create a 32-byte message hash with
* secp256k1_tagged_sha256 and then sign the hash. Tagged hashing allows
* providing an context-specific tag for domain separation. This prevents
* signatures from being valid in multiple contexts by accident.
*
* Returns 1 on success, 0 on failure.
* Args: ctx: pointer to a context object (not secp256k1_context_static).
* Out: sig64: pointer to a 64-byte array to store the serialized signature.
* In: msg32: the 32-byte message being signed.
* keypair: pointer to an initialized keypair.
* aux_rand32: 32 bytes of fresh randomness. While recommended to provide
* this, it is only supplemental to security and can be NULL. A
* NULL argument is treated the same as an all-zero one. See
* BIP-340 "Default Signing" for a full explanation of this
* argument and for guidance if randomness is expensive.
*/
SECP256K1_API int secp256k1_schnorrsig_sign32(
const secp256k1_context *ctx,
unsigned char *sig64,
const unsigned char *msg32,
const secp256k1_keypair *keypair,
const unsigned char *aux_rand32
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4);
/** Same as secp256k1_schnorrsig_sign32, but DEPRECATED. Will be removed in
* future versions. */
SECP256K1_API int secp256k1_schnorrsig_sign(
const secp256k1_context *ctx,
unsigned char *sig64,
const unsigned char *msg32,
const secp256k1_keypair *keypair,
const unsigned char *aux_rand32
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4)
SECP256K1_DEPRECATED("Use secp256k1_schnorrsig_sign32 instead");
/** Create a Schnorr signature with a more flexible API.
*
* Same arguments as secp256k1_schnorrsig_sign except that it allows signing
* variable length messages and accepts a pointer to an extraparams object that
* allows customizing signing by passing additional arguments.
*
* Equivalent to secp256k1_schnorrsig_sign32(..., aux_rand32) if msglen is 32
* and extraparams is initialized as follows:
* ```
* secp256k1_schnorrsig_extraparams extraparams = SECP256K1_SCHNORRSIG_EXTRAPARAMS_INIT;
* extraparams.ndata = (unsigned char*)aux_rand32;
* ```
*
* Returns 1 on success, 0 on failure.
* Args: ctx: pointer to a context object (not secp256k1_context_static).
* Out: sig64: pointer to a 64-byte array to store the serialized signature.
* In: msg: the message being signed. Can only be NULL if msglen is 0.
* msglen: length of the message.
* keypair: pointer to an initialized keypair.
* extraparams: pointer to an extraparams object (can be NULL).
*/
SECP256K1_API int secp256k1_schnorrsig_sign_custom(
const secp256k1_context *ctx,
unsigned char *sig64,
const unsigned char *msg,
size_t msglen,
const secp256k1_keypair *keypair,
secp256k1_schnorrsig_extraparams *extraparams
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(5);
/** Verify a Schnorr signature.
*
* Returns: 1: correct signature
* 0: incorrect signature
* Args: ctx: pointer to a context object.
* In: sig64: pointer to the 64-byte signature to verify.
* msg: the message being verified. Can only be NULL if msglen is 0.
* msglen: length of the message
* pubkey: pointer to an x-only public key to verify with
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_schnorrsig_verify(
const secp256k1_context *ctx,
const unsigned char *sig64,
const unsigned char *msg,
size_t msglen,
const secp256k1_xonly_pubkey *pubkey
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(5);
#ifdef __cplusplus
}
#endif
#endif /* SECP256K1_SCHNORRSIG_H */

View File

@@ -0,0 +1,229 @@
add_library(secp256k1)
set_property(TARGET secp256k1 PROPERTY PUBLIC_HEADER
${PROJECT_SOURCE_DIR}/include/secp256k1.h
${PROJECT_SOURCE_DIR}/include/secp256k1_preallocated.h
)
# 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)
set_property(TARGET secp256k1 APPEND PROPERTY PUBLIC_HEADER ${PROJECT_SOURCE_DIR}/include/secp256k1_ellswift.h)
endif()
if(SECP256K1_ENABLE_MODULE_MUSIG)
if(DEFINED SECP256K1_ENABLE_MODULE_SCHNORRSIG AND NOT SECP256K1_ENABLE_MODULE_SCHNORRSIG)
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)
set_property(TARGET secp256k1 APPEND PROPERTY PUBLIC_HEADER ${PROJECT_SOURCE_DIR}/include/secp256k1_musig.h)
endif()
if(SECP256K1_ENABLE_MODULE_SCHNORRSIG)
if(DEFINED SECP256K1_ENABLE_MODULE_EXTRAKEYS AND NOT SECP256K1_ENABLE_MODULE_EXTRAKEYS)
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)
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)
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)
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)
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
)
# Add objects explicitly rather than linking to the object libs to keep them
# from being exported.
target_sources(secp256k1 PRIVATE secp256k1.c $<TARGET_OBJECTS:secp256k1_precomputed>)
if(NOT SECP256K1_ENABLE_API_VISIBILITY_ATTRIBUTES)
target_compile_definitions(secp256k1 PRIVATE SECP256K1_NO_API_VISIBILITY_ATTRIBUTES)
endif()
# Create a helper lib that parent projects can use to link secp256k1 into a
# static lib.
add_library(secp256k1_objs INTERFACE)
target_sources(secp256k1_objs INTERFACE $<TARGET_OBJECTS:secp256k1> $<TARGET_OBJECTS:secp256k1_precomputed>)
add_library(secp256k1_asm INTERFACE)
if(SECP256K1_ASM STREQUAL "arm32")
add_library(secp256k1_asm_arm OBJECT EXCLUDE_FROM_ALL)
target_sources(secp256k1_asm_arm PUBLIC
asm/field_10x26_arm.s
)
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)
endif()
if(WIN32)
# Define our export symbol only for shared libs.
set_target_properties(secp256k1 PROPERTIES DEFINE_SYMBOL SECP256K1_DLL_EXPORT)
target_compile_definitions(secp256k1 INTERFACE $<$<NOT:$<BOOL:${BUILD_SHARED_LIBS}>>:SECP256K1_STATIC>)
endif()
# Object libs don't know if they're being built for a shared or static lib.
# Grab the PIC property from secp256k1 which knows.
get_target_property(use_pic secp256k1 POSITION_INDEPENDENT_CODE)
set_target_properties(secp256k1_precomputed PROPERTIES POSITION_INDEPENDENT_CODE ${use_pic})
# Add the include path for parent projects so that they don't have to manually add it.
target_include_directories(secp256k1 INTERFACE
$<BUILD_INTERFACE:$<$<NOT:$<BOOL:${PROJECT_IS_TOP_LEVEL}>>:${PROJECT_SOURCE_DIR}/include>>
)
set_target_properties(secp256k1_objs PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "$<TARGET_PROPERTY:secp256k1,INTERFACE_COMPILE_DEFINITIONS>"
INTERFACE_INCLUDE_DIRECTORIES "$<TARGET_PROPERTY:secp256k1,INTERFACE_INCLUDE_DIRECTORIES>"
)
# This emulates Libtool to make sure Libtool and CMake agree on the ABI version,
# see below "Calculate the version variables" in autotools-aux/ltmain.sh.
math(EXPR ${PROJECT_NAME}_soversion "${${PROJECT_NAME}_LIB_VERSION_CURRENT} - ${${PROJECT_NAME}_LIB_VERSION_AGE}")
set_target_properties(secp256k1 PROPERTIES
SOVERSION ${${PROJECT_NAME}_soversion}
)
if(CMAKE_SYSTEM_NAME MATCHES "^(Linux|FreeBSD)$")
set_target_properties(secp256k1 PROPERTIES
VERSION ${${PROJECT_NAME}_soversion}.${${PROJECT_NAME}_LIB_VERSION_AGE}.${${PROJECT_NAME}_LIB_VERSION_REVISION}
)
elseif(APPLE)
math(EXPR ${PROJECT_NAME}_compatibility_version "${${PROJECT_NAME}_LIB_VERSION_CURRENT} + 1")
set_target_properties(secp256k1 PROPERTIES
MACHO_COMPATIBILITY_VERSION ${${PROJECT_NAME}_compatibility_version}
MACHO_CURRENT_VERSION ${${PROJECT_NAME}_compatibility_version}.${${PROJECT_NAME}_LIB_VERSION_REVISION}
)
unset(${PROJECT_NAME}_compatibility_version)
elseif(CMAKE_SYSTEM_NAME STREQUAL "Windows")
set(${PROJECT_NAME}_windows "secp256k1")
if(MSVC)
set(${PROJECT_NAME}_windows "${PROJECT_NAME}")
endif()
set_target_properties(secp256k1 PROPERTIES
ARCHIVE_OUTPUT_NAME "${${PROJECT_NAME}_windows}"
RUNTIME_OUTPUT_NAME "${${PROJECT_NAME}_windows}-${${PROJECT_NAME}_soversion}"
)
unset(${PROJECT_NAME}_windows)
endif()
unset(${PROJECT_NAME}_soversion)
if(SECP256K1_BUILD_BENCHMARK)
add_executable(bench bench.c)
target_link_libraries(bench secp256k1)
add_executable(bench_internal bench_internal.c)
target_link_libraries(bench_internal secp256k1_precomputed secp256k1_asm)
add_executable(bench_ecmult bench_ecmult.c)
target_link_libraries(bench_ecmult secp256k1_precomputed secp256k1_asm)
endif()
if(SECP256K1_BUILD_TESTS)
include(CheckIncludeFile)
check_include_file(sys/types.h HAVE_SYS_TYPES_H)
check_include_file(sys/wait.h HAVE_SYS_WAIT_H)
check_include_file(unistd.h HAVE_UNISTD_H)
set(TEST_DEFINITIONS "")
if(HAVE_SYS_TYPES_H AND HAVE_SYS_WAIT_H AND HAVE_UNISTD_H)
list(APPEND TEST_DEFINITIONS SUPPORTS_CONCURRENCY=1)
endif()
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_compile_definitions(${exe_name} PRIVATE ${verify_definition} ${TEST_DEFINITIONS})
include(DiscoverTests)
discover_tests(${exe_name}
DISCOVERY_ARGS "--list_tests"
DISCOVERY_MATCH "^\\t\\\\[ *[0-9]+\\\\] ([^ ].*)$"
TEST_NAME_REPLACEMENT "secp256k1.${exe_name}.\\\\1"
TEST_ARGS_REPLACEMENT "--target=\\\\1 --log=1"
PROPERTIES
LABELS "secp256k1_${exe_name}"
)
endfunction()
add_executable_and_tests(noverify_tests "")
if(NOT CMAKE_BUILD_TYPE STREQUAL "Coverage")
add_executable_and_tests(tests VERIFY)
endif()
unset(TEST_DEFINITIONS)
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_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
LABELS secp256k1_exhaustive
)
endif()
if(SECP256K1_BUILD_CTIME_TESTS)
add_executable(ctime_tests ctime_tests.c)
target_link_libraries(ctime_tests secp256k1)
endif()
if(SECP256K1_INSTALL)
include(GNUInstallDirs)
target_include_directories(secp256k1 INTERFACE
$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
)
install(TARGETS secp256k1
EXPORT ${PROJECT_NAME}-targets
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
)
install(EXPORT ${PROJECT_NAME}-targets
FILE ${PROJECT_NAME}-targets.cmake
NAMESPACE ${PROJECT_NAME}::
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}
)
include(CMakePackageConfigHelpers)
configure_package_config_file(
${PROJECT_SOURCE_DIR}/cmake/config.cmake.in
${PROJECT_NAME}-config.cmake
INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}
NO_SET_AND_CHECK_MACRO
)
write_basic_package_version_file(${PROJECT_NAME}-config-version.cmake
COMPATIBILITY SameMinorVersion
)
install(
FILES
${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}-config.cmake
${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}-config-version.cmake
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}
)
include(GeneratePkgConfigFile)
generate_pkg_config_file(${PROJECT_SOURCE_DIR}/libsecp256k1.pc.in)
install(
FILES
${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.pc
DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig
)
endif()

View File

@@ -0,0 +1,916 @@
@ vim: set tabstop=8 softtabstop=8 shiftwidth=8 noexpandtab syntax=armasm:
/***********************************************************************
* Copyright (c) 2014 Wladimir J. van der Laan *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or https://www.opensource.org/licenses/mit-license.php.*
***********************************************************************/
/*
ARM implementation of field_10x26 inner loops.
Note:
- To avoid unnecessary loads and make use of available registers, two
'passes' have every time been interleaved, with the odd passes accumulating c' and d'
which will be added to c and d respectively in the even passes
*/
.syntax unified
@ eabi attributes - see readelf -A
.eabi_attribute 24, 1 @ Tag_ABI_align_needed = 8-byte
.eabi_attribute 25, 1 @ Tag_ABI_align_preserved = 8-byte, except leaf SP
.text
@ Field constants
.set field_R0, 0x3d10
.set field_R1, 0x400
.set field_not_M, 0xfc000000 @ ~M = ~0x3ffffff
.align 2
.global secp256k1_fe_mul_inner
.type secp256k1_fe_mul_inner, %function
.hidden secp256k1_fe_mul_inner
@ Arguments:
@ r0 r Restrict: can overlap with a, not with b
@ r1 a
@ r2 b
@ Stack (total 4+10*4 = 44)
@ sp + #0 saved 'r' pointer
@ sp + #4 + 4*X t0,t1,t2,t3,t4,t5,t6,t7,u8,t9
secp256k1_fe_mul_inner:
stmfd sp!, {r4, r5, r6, r7, r8, r9, r10, r11, r14}
sub sp, sp, #48 @ frame=44 + alignment
str r0, [sp, #0] @ save result address, we need it only at the end
/******************************************
* Main computation code.
******************************************
Allocation:
r0,r14,r7,r8 scratch
r1 a (pointer)
r2 b (pointer)
r3:r4 c
r5:r6 d
r11:r12 c'
r9:r10 d'
Note: do not write to r[] here, it may overlap with a[]
*/
/* A - interleaved with B */
ldr r7, [r1, #0*4] @ a[0]
ldr r8, [r2, #9*4] @ b[9]
ldr r0, [r1, #1*4] @ a[1]
umull r5, r6, r7, r8 @ d = a[0] * b[9]
ldr r14, [r2, #8*4] @ b[8]
umull r9, r10, r0, r8 @ d' = a[1] * b[9]
ldr r7, [r1, #2*4] @ a[2]
umlal r5, r6, r0, r14 @ d += a[1] * b[8]
ldr r8, [r2, #7*4] @ b[7]
umlal r9, r10, r7, r14 @ d' += a[2] * b[8]
ldr r0, [r1, #3*4] @ a[3]
umlal r5, r6, r7, r8 @ d += a[2] * b[7]
ldr r14, [r2, #6*4] @ b[6]
umlal r9, r10, r0, r8 @ d' += a[3] * b[7]
ldr r7, [r1, #4*4] @ a[4]
umlal r5, r6, r0, r14 @ d += a[3] * b[6]
ldr r8, [r2, #5*4] @ b[5]
umlal r9, r10, r7, r14 @ d' += a[4] * b[6]
ldr r0, [r1, #5*4] @ a[5]
umlal r5, r6, r7, r8 @ d += a[4] * b[5]
ldr r14, [r2, #4*4] @ b[4]
umlal r9, r10, r0, r8 @ d' += a[5] * b[5]
ldr r7, [r1, #6*4] @ a[6]
umlal r5, r6, r0, r14 @ d += a[5] * b[4]
ldr r8, [r2, #3*4] @ b[3]
umlal r9, r10, r7, r14 @ d' += a[6] * b[4]
ldr r0, [r1, #7*4] @ a[7]
umlal r5, r6, r7, r8 @ d += a[6] * b[3]
ldr r14, [r2, #2*4] @ b[2]
umlal r9, r10, r0, r8 @ d' += a[7] * b[3]
ldr r7, [r1, #8*4] @ a[8]
umlal r5, r6, r0, r14 @ d += a[7] * b[2]
ldr r8, [r2, #1*4] @ b[1]
umlal r9, r10, r7, r14 @ d' += a[8] * b[2]
ldr r0, [r1, #9*4] @ a[9]
umlal r5, r6, r7, r8 @ d += a[8] * b[1]
ldr r14, [r2, #0*4] @ b[0]
umlal r9, r10, r0, r8 @ d' += a[9] * b[1]
ldr r7, [r1, #0*4] @ a[0]
umlal r5, r6, r0, r14 @ d += a[9] * b[0]
@ r7,r14 used in B
bic r0, r5, field_not_M @ t9 = d & M
str r0, [sp, #4 + 4*9]
mov r5, r5, lsr #26 @ d >>= 26
orr r5, r5, r6, asl #6
mov r6, r6, lsr #26
/* B */
umull r3, r4, r7, r14 @ c = a[0] * b[0]
adds r5, r5, r9 @ d += d'
adc r6, r6, r10
bic r0, r5, field_not_M @ u0 = d & M
mov r5, r5, lsr #26 @ d >>= 26
orr r5, r5, r6, asl #6
mov r6, r6, lsr #26
movw r14, field_R0 @ c += u0 * R0
umlal r3, r4, r0, r14
bic r14, r3, field_not_M @ t0 = c & M
str r14, [sp, #4 + 0*4]
mov r3, r3, lsr #26 @ c >>= 26
orr r3, r3, r4, asl #6
mov r4, r4, lsr #26
mov r14, field_R1 @ c += u0 * R1
umlal r3, r4, r0, r14
/* C - interleaved with D */
ldr r7, [r1, #0*4] @ a[0]
ldr r8, [r2, #2*4] @ b[2]
ldr r14, [r2, #1*4] @ b[1]
umull r11, r12, r7, r8 @ c' = a[0] * b[2]
ldr r0, [r1, #1*4] @ a[1]
umlal r3, r4, r7, r14 @ c += a[0] * b[1]
ldr r8, [r2, #0*4] @ b[0]
umlal r11, r12, r0, r14 @ c' += a[1] * b[1]
ldr r7, [r1, #2*4] @ a[2]
umlal r3, r4, r0, r8 @ c += a[1] * b[0]
ldr r14, [r2, #9*4] @ b[9]
umlal r11, r12, r7, r8 @ c' += a[2] * b[0]
ldr r0, [r1, #3*4] @ a[3]
umlal r5, r6, r7, r14 @ d += a[2] * b[9]
ldr r8, [r2, #8*4] @ b[8]
umull r9, r10, r0, r14 @ d' = a[3] * b[9]
ldr r7, [r1, #4*4] @ a[4]
umlal r5, r6, r0, r8 @ d += a[3] * b[8]
ldr r14, [r2, #7*4] @ b[7]
umlal r9, r10, r7, r8 @ d' += a[4] * b[8]
ldr r0, [r1, #5*4] @ a[5]
umlal r5, r6, r7, r14 @ d += a[4] * b[7]
ldr r8, [r2, #6*4] @ b[6]
umlal r9, r10, r0, r14 @ d' += a[5] * b[7]
ldr r7, [r1, #6*4] @ a[6]
umlal r5, r6, r0, r8 @ d += a[5] * b[6]
ldr r14, [r2, #5*4] @ b[5]
umlal r9, r10, r7, r8 @ d' += a[6] * b[6]
ldr r0, [r1, #7*4] @ a[7]
umlal r5, r6, r7, r14 @ d += a[6] * b[5]
ldr r8, [r2, #4*4] @ b[4]
umlal r9, r10, r0, r14 @ d' += a[7] * b[5]
ldr r7, [r1, #8*4] @ a[8]
umlal r5, r6, r0, r8 @ d += a[7] * b[4]
ldr r14, [r2, #3*4] @ b[3]
umlal r9, r10, r7, r8 @ d' += a[8] * b[4]
ldr r0, [r1, #9*4] @ a[9]
umlal r5, r6, r7, r14 @ d += a[8] * b[3]
ldr r8, [r2, #2*4] @ b[2]
umlal r9, r10, r0, r14 @ d' += a[9] * b[3]
umlal r5, r6, r0, r8 @ d += a[9] * b[2]
bic r0, r5, field_not_M @ u1 = d & M
mov r5, r5, lsr #26 @ d >>= 26
orr r5, r5, r6, asl #6
mov r6, r6, lsr #26
movw r14, field_R0 @ c += u1 * R0
umlal r3, r4, r0, r14
bic r14, r3, field_not_M @ t1 = c & M
str r14, [sp, #4 + 1*4]
mov r3, r3, lsr #26 @ c >>= 26
orr r3, r3, r4, asl #6
mov r4, r4, lsr #26
mov r14, field_R1 @ c += u1 * R1
umlal r3, r4, r0, r14
/* D */
adds r3, r3, r11 @ c += c'
adc r4, r4, r12
adds r5, r5, r9 @ d += d'
adc r6, r6, r10
bic r0, r5, field_not_M @ u2 = d & M
mov r5, r5, lsr #26 @ d >>= 26
orr r5, r5, r6, asl #6
mov r6, r6, lsr #26
movw r14, field_R0 @ c += u2 * R0
umlal r3, r4, r0, r14
bic r14, r3, field_not_M @ t2 = c & M
str r14, [sp, #4 + 2*4]
mov r3, r3, lsr #26 @ c >>= 26
orr r3, r3, r4, asl #6
mov r4, r4, lsr #26
mov r14, field_R1 @ c += u2 * R1
umlal r3, r4, r0, r14
/* E - interleaved with F */
ldr r7, [r1, #0*4] @ a[0]
ldr r8, [r2, #4*4] @ b[4]
umull r11, r12, r7, r8 @ c' = a[0] * b[4]
ldr r8, [r2, #3*4] @ b[3]
umlal r3, r4, r7, r8 @ c += a[0] * b[3]
ldr r7, [r1, #1*4] @ a[1]
umlal r11, r12, r7, r8 @ c' += a[1] * b[3]
ldr r8, [r2, #2*4] @ b[2]
umlal r3, r4, r7, r8 @ c += a[1] * b[2]
ldr r7, [r1, #2*4] @ a[2]
umlal r11, r12, r7, r8 @ c' += a[2] * b[2]
ldr r8, [r2, #1*4] @ b[1]
umlal r3, r4, r7, r8 @ c += a[2] * b[1]
ldr r7, [r1, #3*4] @ a[3]
umlal r11, r12, r7, r8 @ c' += a[3] * b[1]
ldr r8, [r2, #0*4] @ b[0]
umlal r3, r4, r7, r8 @ c += a[3] * b[0]
ldr r7, [r1, #4*4] @ a[4]
umlal r11, r12, r7, r8 @ c' += a[4] * b[0]
ldr r8, [r2, #9*4] @ b[9]
umlal r5, r6, r7, r8 @ d += a[4] * b[9]
ldr r7, [r1, #5*4] @ a[5]
umull r9, r10, r7, r8 @ d' = a[5] * b[9]
ldr r8, [r2, #8*4] @ b[8]
umlal r5, r6, r7, r8 @ d += a[5] * b[8]
ldr r7, [r1, #6*4] @ a[6]
umlal r9, r10, r7, r8 @ d' += a[6] * b[8]
ldr r8, [r2, #7*4] @ b[7]
umlal r5, r6, r7, r8 @ d += a[6] * b[7]
ldr r7, [r1, #7*4] @ a[7]
umlal r9, r10, r7, r8 @ d' += a[7] * b[7]
ldr r8, [r2, #6*4] @ b[6]
umlal r5, r6, r7, r8 @ d += a[7] * b[6]
ldr r7, [r1, #8*4] @ a[8]
umlal r9, r10, r7, r8 @ d' += a[8] * b[6]
ldr r8, [r2, #5*4] @ b[5]
umlal r5, r6, r7, r8 @ d += a[8] * b[5]
ldr r7, [r1, #9*4] @ a[9]
umlal r9, r10, r7, r8 @ d' += a[9] * b[5]
ldr r8, [r2, #4*4] @ b[4]
umlal r5, r6, r7, r8 @ d += a[9] * b[4]
bic r0, r5, field_not_M @ u3 = d & M
mov r5, r5, lsr #26 @ d >>= 26
orr r5, r5, r6, asl #6
mov r6, r6, lsr #26
movw r14, field_R0 @ c += u3 * R0
umlal r3, r4, r0, r14
bic r14, r3, field_not_M @ t3 = c & M
str r14, [sp, #4 + 3*4]
mov r3, r3, lsr #26 @ c >>= 26
orr r3, r3, r4, asl #6
mov r4, r4, lsr #26
mov r14, field_R1 @ c += u3 * R1
umlal r3, r4, r0, r14
/* F */
adds r3, r3, r11 @ c += c'
adc r4, r4, r12
adds r5, r5, r9 @ d += d'
adc r6, r6, r10
bic r0, r5, field_not_M @ u4 = d & M
mov r5, r5, lsr #26 @ d >>= 26
orr r5, r5, r6, asl #6
mov r6, r6, lsr #26
movw r14, field_R0 @ c += u4 * R0
umlal r3, r4, r0, r14
bic r14, r3, field_not_M @ t4 = c & M
str r14, [sp, #4 + 4*4]
mov r3, r3, lsr #26 @ c >>= 26
orr r3, r3, r4, asl #6
mov r4, r4, lsr #26
mov r14, field_R1 @ c += u4 * R1
umlal r3, r4, r0, r14
/* G - interleaved with H */
ldr r7, [r1, #0*4] @ a[0]
ldr r8, [r2, #6*4] @ b[6]
ldr r14, [r2, #5*4] @ b[5]
umull r11, r12, r7, r8 @ c' = a[0] * b[6]
ldr r0, [r1, #1*4] @ a[1]
umlal r3, r4, r7, r14 @ c += a[0] * b[5]
ldr r8, [r2, #4*4] @ b[4]
umlal r11, r12, r0, r14 @ c' += a[1] * b[5]
ldr r7, [r1, #2*4] @ a[2]
umlal r3, r4, r0, r8 @ c += a[1] * b[4]
ldr r14, [r2, #3*4] @ b[3]
umlal r11, r12, r7, r8 @ c' += a[2] * b[4]
ldr r0, [r1, #3*4] @ a[3]
umlal r3, r4, r7, r14 @ c += a[2] * b[3]
ldr r8, [r2, #2*4] @ b[2]
umlal r11, r12, r0, r14 @ c' += a[3] * b[3]
ldr r7, [r1, #4*4] @ a[4]
umlal r3, r4, r0, r8 @ c += a[3] * b[2]
ldr r14, [r2, #1*4] @ b[1]
umlal r11, r12, r7, r8 @ c' += a[4] * b[2]
ldr r0, [r1, #5*4] @ a[5]
umlal r3, r4, r7, r14 @ c += a[4] * b[1]
ldr r8, [r2, #0*4] @ b[0]
umlal r11, r12, r0, r14 @ c' += a[5] * b[1]
ldr r7, [r1, #6*4] @ a[6]
umlal r3, r4, r0, r8 @ c += a[5] * b[0]
ldr r14, [r2, #9*4] @ b[9]
umlal r11, r12, r7, r8 @ c' += a[6] * b[0]
ldr r0, [r1, #7*4] @ a[7]
umlal r5, r6, r7, r14 @ d += a[6] * b[9]
ldr r8, [r2, #8*4] @ b[8]
umull r9, r10, r0, r14 @ d' = a[7] * b[9]
ldr r7, [r1, #8*4] @ a[8]
umlal r5, r6, r0, r8 @ d += a[7] * b[8]
ldr r14, [r2, #7*4] @ b[7]
umlal r9, r10, r7, r8 @ d' += a[8] * b[8]
ldr r0, [r1, #9*4] @ a[9]
umlal r5, r6, r7, r14 @ d += a[8] * b[7]
ldr r8, [r2, #6*4] @ b[6]
umlal r9, r10, r0, r14 @ d' += a[9] * b[7]
umlal r5, r6, r0, r8 @ d += a[9] * b[6]
bic r0, r5, field_not_M @ u5 = d & M
mov r5, r5, lsr #26 @ d >>= 26
orr r5, r5, r6, asl #6
mov r6, r6, lsr #26
movw r14, field_R0 @ c += u5 * R0
umlal r3, r4, r0, r14
bic r14, r3, field_not_M @ t5 = c & M
str r14, [sp, #4 + 5*4]
mov r3, r3, lsr #26 @ c >>= 26
orr r3, r3, r4, asl #6
mov r4, r4, lsr #26
mov r14, field_R1 @ c += u5 * R1
umlal r3, r4, r0, r14
/* H */
adds r3, r3, r11 @ c += c'
adc r4, r4, r12
adds r5, r5, r9 @ d += d'
adc r6, r6, r10
bic r0, r5, field_not_M @ u6 = d & M
mov r5, r5, lsr #26 @ d >>= 26
orr r5, r5, r6, asl #6
mov r6, r6, lsr #26
movw r14, field_R0 @ c += u6 * R0
umlal r3, r4, r0, r14
bic r14, r3, field_not_M @ t6 = c & M
str r14, [sp, #4 + 6*4]
mov r3, r3, lsr #26 @ c >>= 26
orr r3, r3, r4, asl #6
mov r4, r4, lsr #26
mov r14, field_R1 @ c += u6 * R1
umlal r3, r4, r0, r14
/* I - interleaved with J */
ldr r8, [r2, #8*4] @ b[8]
ldr r7, [r1, #0*4] @ a[0]
ldr r14, [r2, #7*4] @ b[7]
umull r11, r12, r7, r8 @ c' = a[0] * b[8]
ldr r0, [r1, #1*4] @ a[1]
umlal r3, r4, r7, r14 @ c += a[0] * b[7]
ldr r8, [r2, #6*4] @ b[6]
umlal r11, r12, r0, r14 @ c' += a[1] * b[7]
ldr r7, [r1, #2*4] @ a[2]
umlal r3, r4, r0, r8 @ c += a[1] * b[6]
ldr r14, [r2, #5*4] @ b[5]
umlal r11, r12, r7, r8 @ c' += a[2] * b[6]
ldr r0, [r1, #3*4] @ a[3]
umlal r3, r4, r7, r14 @ c += a[2] * b[5]
ldr r8, [r2, #4*4] @ b[4]
umlal r11, r12, r0, r14 @ c' += a[3] * b[5]
ldr r7, [r1, #4*4] @ a[4]
umlal r3, r4, r0, r8 @ c += a[3] * b[4]
ldr r14, [r2, #3*4] @ b[3]
umlal r11, r12, r7, r8 @ c' += a[4] * b[4]
ldr r0, [r1, #5*4] @ a[5]
umlal r3, r4, r7, r14 @ c += a[4] * b[3]
ldr r8, [r2, #2*4] @ b[2]
umlal r11, r12, r0, r14 @ c' += a[5] * b[3]
ldr r7, [r1, #6*4] @ a[6]
umlal r3, r4, r0, r8 @ c += a[5] * b[2]
ldr r14, [r2, #1*4] @ b[1]
umlal r11, r12, r7, r8 @ c' += a[6] * b[2]
ldr r0, [r1, #7*4] @ a[7]
umlal r3, r4, r7, r14 @ c += a[6] * b[1]
ldr r8, [r2, #0*4] @ b[0]
umlal r11, r12, r0, r14 @ c' += a[7] * b[1]
ldr r7, [r1, #8*4] @ a[8]
umlal r3, r4, r0, r8 @ c += a[7] * b[0]
ldr r14, [r2, #9*4] @ b[9]
umlal r11, r12, r7, r8 @ c' += a[8] * b[0]
ldr r0, [r1, #9*4] @ a[9]
umlal r5, r6, r7, r14 @ d += a[8] * b[9]
ldr r8, [r2, #8*4] @ b[8]
umull r9, r10, r0, r14 @ d' = a[9] * b[9]
umlal r5, r6, r0, r8 @ d += a[9] * b[8]
bic r0, r5, field_not_M @ u7 = d & M
mov r5, r5, lsr #26 @ d >>= 26
orr r5, r5, r6, asl #6
mov r6, r6, lsr #26
movw r14, field_R0 @ c += u7 * R0
umlal r3, r4, r0, r14
bic r14, r3, field_not_M @ t7 = c & M
str r14, [sp, #4 + 7*4]
mov r3, r3, lsr #26 @ c >>= 26
orr r3, r3, r4, asl #6
mov r4, r4, lsr #26
mov r14, field_R1 @ c += u7 * R1
umlal r3, r4, r0, r14
/* J */
adds r3, r3, r11 @ c += c'
adc r4, r4, r12
adds r5, r5, r9 @ d += d'
adc r6, r6, r10
bic r0, r5, field_not_M @ u8 = d & M
str r0, [sp, #4 + 8*4]
mov r5, r5, lsr #26 @ d >>= 26
orr r5, r5, r6, asl #6
mov r6, r6, lsr #26
movw r14, field_R0 @ c += u8 * R0
umlal r3, r4, r0, r14
/******************************************
* compute and write back result
******************************************
Allocation:
r0 r
r3:r4 c
r5:r6 d
r7 t0
r8 t1
r9 t2
r11 u8
r12 t9
r1,r2,r10,r14 scratch
Note: do not read from a[] after here, it may overlap with r[]
*/
ldr r0, [sp, #0]
add r1, sp, #4 + 3*4 @ r[3..7] = t3..7, r11=u8, r12=t9
ldmia r1, {r2,r7,r8,r9,r10,r11,r12}
add r1, r0, #3*4
stmia r1, {r2,r7,r8,r9,r10}
bic r2, r3, field_not_M @ r[8] = c & M
str r2, [r0, #8*4]
mov r3, r3, lsr #26 @ c >>= 26
orr r3, r3, r4, asl #6
mov r4, r4, lsr #26
mov r14, field_R1 @ c += u8 * R1
umlal r3, r4, r11, r14
movw r14, field_R0 @ c += d * R0
umlal r3, r4, r5, r14
adds r3, r3, r12 @ c += t9
adc r4, r4, #0
add r1, sp, #4 + 0*4 @ r7,r8,r9 = t0,t1,t2
ldmia r1, {r7,r8,r9}
ubfx r2, r3, #0, #22 @ r[9] = c & (M >> 4)
str r2, [r0, #9*4]
mov r3, r3, lsr #22 @ c >>= 22
orr r3, r3, r4, asl #10
mov r4, r4, lsr #22
movw r14, field_R1 << 4 @ c += d * (R1 << 4)
umlal r3, r4, r5, r14
movw r14, field_R0 >> 4 @ d = c * (R0 >> 4) + t0 (64x64 multiply+add)
umull r5, r6, r3, r14 @ d = c.lo * (R0 >> 4)
adds r5, r5, r7 @ d.lo += t0
mla r6, r14, r4, r6 @ d.hi += c.hi * (R0 >> 4)
adc r6, r6, 0 @ d.hi += carry
bic r2, r5, field_not_M @ r[0] = d & M
str r2, [r0, #0*4]
mov r5, r5, lsr #26 @ d >>= 26
orr r5, r5, r6, asl #6
mov r6, r6, lsr #26
movw r14, field_R1 >> 4 @ d += c * (R1 >> 4) + t1 (64x64 multiply+add)
umull r1, r2, r3, r14 @ tmp = c.lo * (R1 >> 4)
adds r5, r5, r8 @ d.lo += t1
adc r6, r6, #0 @ d.hi += carry
adds r5, r5, r1 @ d.lo += tmp.lo
mla r2, r14, r4, r2 @ tmp.hi += c.hi * (R1 >> 4)
adc r6, r6, r2 @ d.hi += carry + tmp.hi
bic r2, r5, field_not_M @ r[1] = d & M
str r2, [r0, #1*4]
mov r5, r5, lsr #26 @ d >>= 26 (ignore hi)
orr r5, r5, r6, asl #6
add r5, r5, r9 @ d += t2
str r5, [r0, #2*4] @ r[2] = d
add sp, sp, #48
ldmfd sp!, {r4, r5, r6, r7, r8, r9, r10, r11, pc}
.size secp256k1_fe_mul_inner, .-secp256k1_fe_mul_inner
.align 2
.global secp256k1_fe_sqr_inner
.type secp256k1_fe_sqr_inner, %function
.hidden secp256k1_fe_sqr_inner
@ Arguments:
@ r0 r Can overlap with a
@ r1 a
@ Stack (total 4+10*4 = 44)
@ sp + #0 saved 'r' pointer
@ sp + #4 + 4*X t0,t1,t2,t3,t4,t5,t6,t7,u8,t9
secp256k1_fe_sqr_inner:
stmfd sp!, {r4, r5, r6, r7, r8, r9, r10, r11, r14}
sub sp, sp, #48 @ frame=44 + alignment
str r0, [sp, #0] @ save result address, we need it only at the end
/******************************************
* Main computation code.
******************************************
Allocation:
r0,r14,r2,r7,r8 scratch
r1 a (pointer)
r3:r4 c
r5:r6 d
r11:r12 c'
r9:r10 d'
Note: do not write to r[] here, it may overlap with a[]
*/
/* A interleaved with B */
ldr r0, [r1, #1*4] @ a[1]*2
ldr r7, [r1, #0*4] @ a[0]
mov r0, r0, asl #1
ldr r14, [r1, #9*4] @ a[9]
umull r3, r4, r7, r7 @ c = a[0] * a[0]
ldr r8, [r1, #8*4] @ a[8]
mov r7, r7, asl #1
umull r5, r6, r7, r14 @ d = a[0]*2 * a[9]
ldr r7, [r1, #2*4] @ a[2]*2
umull r9, r10, r0, r14 @ d' = a[1]*2 * a[9]
ldr r14, [r1, #7*4] @ a[7]
umlal r5, r6, r0, r8 @ d += a[1]*2 * a[8]
mov r7, r7, asl #1
ldr r0, [r1, #3*4] @ a[3]*2
umlal r9, r10, r7, r8 @ d' += a[2]*2 * a[8]
ldr r8, [r1, #6*4] @ a[6]
umlal r5, r6, r7, r14 @ d += a[2]*2 * a[7]
mov r0, r0, asl #1
ldr r7, [r1, #4*4] @ a[4]*2
umlal r9, r10, r0, r14 @ d' += a[3]*2 * a[7]
ldr r14, [r1, #5*4] @ a[5]
mov r7, r7, asl #1
umlal r5, r6, r0, r8 @ d += a[3]*2 * a[6]
umlal r9, r10, r7, r8 @ d' += a[4]*2 * a[6]
umlal r5, r6, r7, r14 @ d += a[4]*2 * a[5]
umlal r9, r10, r14, r14 @ d' += a[5] * a[5]
bic r0, r5, field_not_M @ t9 = d & M
str r0, [sp, #4 + 9*4]
mov r5, r5, lsr #26 @ d >>= 26
orr r5, r5, r6, asl #6
mov r6, r6, lsr #26
/* B */
adds r5, r5, r9 @ d += d'
adc r6, r6, r10
bic r0, r5, field_not_M @ u0 = d & M
mov r5, r5, lsr #26 @ d >>= 26
orr r5, r5, r6, asl #6
mov r6, r6, lsr #26
movw r14, field_R0 @ c += u0 * R0
umlal r3, r4, r0, r14
bic r14, r3, field_not_M @ t0 = c & M
str r14, [sp, #4 + 0*4]
mov r3, r3, lsr #26 @ c >>= 26
orr r3, r3, r4, asl #6
mov r4, r4, lsr #26
mov r14, field_R1 @ c += u0 * R1
umlal r3, r4, r0, r14
/* C interleaved with D */
ldr r0, [r1, #0*4] @ a[0]*2
ldr r14, [r1, #1*4] @ a[1]
mov r0, r0, asl #1
ldr r8, [r1, #2*4] @ a[2]
umlal r3, r4, r0, r14 @ c += a[0]*2 * a[1]
mov r7, r8, asl #1 @ a[2]*2
umull r11, r12, r14, r14 @ c' = a[1] * a[1]
ldr r14, [r1, #9*4] @ a[9]
umlal r11, r12, r0, r8 @ c' += a[0]*2 * a[2]
ldr r0, [r1, #3*4] @ a[3]*2
ldr r8, [r1, #8*4] @ a[8]
umlal r5, r6, r7, r14 @ d += a[2]*2 * a[9]
mov r0, r0, asl #1
ldr r7, [r1, #4*4] @ a[4]*2
umull r9, r10, r0, r14 @ d' = a[3]*2 * a[9]
ldr r14, [r1, #7*4] @ a[7]
umlal r5, r6, r0, r8 @ d += a[3]*2 * a[8]
mov r7, r7, asl #1
ldr r0, [r1, #5*4] @ a[5]*2
umlal r9, r10, r7, r8 @ d' += a[4]*2 * a[8]
ldr r8, [r1, #6*4] @ a[6]
mov r0, r0, asl #1
umlal r5, r6, r7, r14 @ d += a[4]*2 * a[7]
umlal r9, r10, r0, r14 @ d' += a[5]*2 * a[7]
umlal r5, r6, r0, r8 @ d += a[5]*2 * a[6]
umlal r9, r10, r8, r8 @ d' += a[6] * a[6]
bic r0, r5, field_not_M @ u1 = d & M
mov r5, r5, lsr #26 @ d >>= 26
orr r5, r5, r6, asl #6
mov r6, r6, lsr #26
movw r14, field_R0 @ c += u1 * R0
umlal r3, r4, r0, r14
bic r14, r3, field_not_M @ t1 = c & M
str r14, [sp, #4 + 1*4]
mov r3, r3, lsr #26 @ c >>= 26
orr r3, r3, r4, asl #6
mov r4, r4, lsr #26
mov r14, field_R1 @ c += u1 * R1
umlal r3, r4, r0, r14
/* D */
adds r3, r3, r11 @ c += c'
adc r4, r4, r12
adds r5, r5, r9 @ d += d'
adc r6, r6, r10
bic r0, r5, field_not_M @ u2 = d & M
mov r5, r5, lsr #26 @ d >>= 26
orr r5, r5, r6, asl #6
mov r6, r6, lsr #26
movw r14, field_R0 @ c += u2 * R0
umlal r3, r4, r0, r14
bic r14, r3, field_not_M @ t2 = c & M
str r14, [sp, #4 + 2*4]
mov r3, r3, lsr #26 @ c >>= 26
orr r3, r3, r4, asl #6
mov r4, r4, lsr #26
mov r14, field_R1 @ c += u2 * R1
umlal r3, r4, r0, r14
/* E interleaved with F */
ldr r7, [r1, #0*4] @ a[0]*2
ldr r0, [r1, #1*4] @ a[1]*2
ldr r14, [r1, #2*4] @ a[2]
mov r7, r7, asl #1
ldr r8, [r1, #3*4] @ a[3]
ldr r2, [r1, #4*4]
umlal r3, r4, r7, r8 @ c += a[0]*2 * a[3]
mov r0, r0, asl #1
umull r11, r12, r7, r2 @ c' = a[0]*2 * a[4]
mov r2, r2, asl #1 @ a[4]*2
umlal r11, r12, r0, r8 @ c' += a[1]*2 * a[3]
ldr r8, [r1, #9*4] @ a[9]
umlal r3, r4, r0, r14 @ c += a[1]*2 * a[2]
ldr r0, [r1, #5*4] @ a[5]*2
umlal r11, r12, r14, r14 @ c' += a[2] * a[2]
ldr r14, [r1, #8*4] @ a[8]
mov r0, r0, asl #1
umlal r5, r6, r2, r8 @ d += a[4]*2 * a[9]
ldr r7, [r1, #6*4] @ a[6]*2
umull r9, r10, r0, r8 @ d' = a[5]*2 * a[9]
mov r7, r7, asl #1
ldr r8, [r1, #7*4] @ a[7]
umlal r5, r6, r0, r14 @ d += a[5]*2 * a[8]
umlal r9, r10, r7, r14 @ d' += a[6]*2 * a[8]
umlal r5, r6, r7, r8 @ d += a[6]*2 * a[7]
umlal r9, r10, r8, r8 @ d' += a[7] * a[7]
bic r0, r5, field_not_M @ u3 = d & M
mov r5, r5, lsr #26 @ d >>= 26
orr r5, r5, r6, asl #6
mov r6, r6, lsr #26
movw r14, field_R0 @ c += u3 * R0
umlal r3, r4, r0, r14
bic r14, r3, field_not_M @ t3 = c & M
str r14, [sp, #4 + 3*4]
mov r3, r3, lsr #26 @ c >>= 26
orr r3, r3, r4, asl #6
mov r4, r4, lsr #26
mov r14, field_R1 @ c += u3 * R1
umlal r3, r4, r0, r14
/* F */
adds r3, r3, r11 @ c += c'
adc r4, r4, r12
adds r5, r5, r9 @ d += d'
adc r6, r6, r10
bic r0, r5, field_not_M @ u4 = d & M
mov r5, r5, lsr #26 @ d >>= 26
orr r5, r5, r6, asl #6
mov r6, r6, lsr #26
movw r14, field_R0 @ c += u4 * R0
umlal r3, r4, r0, r14
bic r14, r3, field_not_M @ t4 = c & M
str r14, [sp, #4 + 4*4]
mov r3, r3, lsr #26 @ c >>= 26
orr r3, r3, r4, asl #6
mov r4, r4, lsr #26
mov r14, field_R1 @ c += u4 * R1
umlal r3, r4, r0, r14
/* G interleaved with H */
ldr r7, [r1, #0*4] @ a[0]*2
ldr r0, [r1, #1*4] @ a[1]*2
mov r7, r7, asl #1
ldr r8, [r1, #5*4] @ a[5]
ldr r2, [r1, #6*4] @ a[6]
umlal r3, r4, r7, r8 @ c += a[0]*2 * a[5]
ldr r14, [r1, #4*4] @ a[4]
mov r0, r0, asl #1
umull r11, r12, r7, r2 @ c' = a[0]*2 * a[6]
ldr r7, [r1, #2*4] @ a[2]*2
umlal r11, r12, r0, r8 @ c' += a[1]*2 * a[5]
mov r7, r7, asl #1
ldr r8, [r1, #3*4] @ a[3]
umlal r3, r4, r0, r14 @ c += a[1]*2 * a[4]
mov r0, r2, asl #1 @ a[6]*2
umlal r11, r12, r7, r14 @ c' += a[2]*2 * a[4]
ldr r14, [r1, #9*4] @ a[9]
umlal r3, r4, r7, r8 @ c += a[2]*2 * a[3]
ldr r7, [r1, #7*4] @ a[7]*2
umlal r11, r12, r8, r8 @ c' += a[3] * a[3]
mov r7, r7, asl #1
ldr r8, [r1, #8*4] @ a[8]
umlal r5, r6, r0, r14 @ d += a[6]*2 * a[9]
umull r9, r10, r7, r14 @ d' = a[7]*2 * a[9]
umlal r5, r6, r7, r8 @ d += a[7]*2 * a[8]
umlal r9, r10, r8, r8 @ d' += a[8] * a[8]
bic r0, r5, field_not_M @ u5 = d & M
mov r5, r5, lsr #26 @ d >>= 26
orr r5, r5, r6, asl #6
mov r6, r6, lsr #26
movw r14, field_R0 @ c += u5 * R0
umlal r3, r4, r0, r14
bic r14, r3, field_not_M @ t5 = c & M
str r14, [sp, #4 + 5*4]
mov r3, r3, lsr #26 @ c >>= 26
orr r3, r3, r4, asl #6
mov r4, r4, lsr #26
mov r14, field_R1 @ c += u5 * R1
umlal r3, r4, r0, r14
/* H */
adds r3, r3, r11 @ c += c'
adc r4, r4, r12
adds r5, r5, r9 @ d += d'
adc r6, r6, r10
bic r0, r5, field_not_M @ u6 = d & M
mov r5, r5, lsr #26 @ d >>= 26
orr r5, r5, r6, asl #6
mov r6, r6, lsr #26
movw r14, field_R0 @ c += u6 * R0
umlal r3, r4, r0, r14
bic r14, r3, field_not_M @ t6 = c & M
str r14, [sp, #4 + 6*4]
mov r3, r3, lsr #26 @ c >>= 26
orr r3, r3, r4, asl #6
mov r4, r4, lsr #26
mov r14, field_R1 @ c += u6 * R1
umlal r3, r4, r0, r14
/* I interleaved with J */
ldr r7, [r1, #0*4] @ a[0]*2
ldr r0, [r1, #1*4] @ a[1]*2
mov r7, r7, asl #1
ldr r8, [r1, #7*4] @ a[7]
ldr r2, [r1, #8*4] @ a[8]
umlal r3, r4, r7, r8 @ c += a[0]*2 * a[7]
ldr r14, [r1, #6*4] @ a[6]
mov r0, r0, asl #1
umull r11, r12, r7, r2 @ c' = a[0]*2 * a[8]
ldr r7, [r1, #2*4] @ a[2]*2
umlal r11, r12, r0, r8 @ c' += a[1]*2 * a[7]
ldr r8, [r1, #5*4] @ a[5]
umlal r3, r4, r0, r14 @ c += a[1]*2 * a[6]
ldr r0, [r1, #3*4] @ a[3]*2
mov r7, r7, asl #1
umlal r11, r12, r7, r14 @ c' += a[2]*2 * a[6]
ldr r14, [r1, #4*4] @ a[4]
mov r0, r0, asl #1
umlal r3, r4, r7, r8 @ c += a[2]*2 * a[5]
mov r2, r2, asl #1 @ a[8]*2
umlal r11, r12, r0, r8 @ c' += a[3]*2 * a[5]
umlal r3, r4, r0, r14 @ c += a[3]*2 * a[4]
umlal r11, r12, r14, r14 @ c' += a[4] * a[4]
ldr r8, [r1, #9*4] @ a[9]
umlal r5, r6, r2, r8 @ d += a[8]*2 * a[9]
@ r8 will be used in J
bic r0, r5, field_not_M @ u7 = d & M
mov r5, r5, lsr #26 @ d >>= 26
orr r5, r5, r6, asl #6
mov r6, r6, lsr #26
movw r14, field_R0 @ c += u7 * R0
umlal r3, r4, r0, r14
bic r14, r3, field_not_M @ t7 = c & M
str r14, [sp, #4 + 7*4]
mov r3, r3, lsr #26 @ c >>= 26
orr r3, r3, r4, asl #6
mov r4, r4, lsr #26
mov r14, field_R1 @ c += u7 * R1
umlal r3, r4, r0, r14
/* J */
adds r3, r3, r11 @ c += c'
adc r4, r4, r12
umlal r5, r6, r8, r8 @ d += a[9] * a[9]
bic r0, r5, field_not_M @ u8 = d & M
str r0, [sp, #4 + 8*4]
mov r5, r5, lsr #26 @ d >>= 26
orr r5, r5, r6, asl #6
mov r6, r6, lsr #26
movw r14, field_R0 @ c += u8 * R0
umlal r3, r4, r0, r14
/******************************************
* compute and write back result
******************************************
Allocation:
r0 r
r3:r4 c
r5:r6 d
r7 t0
r8 t1
r9 t2
r11 u8
r12 t9
r1,r2,r10,r14 scratch
Note: do not read from a[] after here, it may overlap with r[]
*/
ldr r0, [sp, #0]
add r1, sp, #4 + 3*4 @ r[3..7] = t3..7, r11=u8, r12=t9
ldmia r1, {r2,r7,r8,r9,r10,r11,r12}
add r1, r0, #3*4
stmia r1, {r2,r7,r8,r9,r10}
bic r2, r3, field_not_M @ r[8] = c & M
str r2, [r0, #8*4]
mov r3, r3, lsr #26 @ c >>= 26
orr r3, r3, r4, asl #6
mov r4, r4, lsr #26
mov r14, field_R1 @ c += u8 * R1
umlal r3, r4, r11, r14
movw r14, field_R0 @ c += d * R0
umlal r3, r4, r5, r14
adds r3, r3, r12 @ c += t9
adc r4, r4, #0
add r1, sp, #4 + 0*4 @ r7,r8,r9 = t0,t1,t2
ldmia r1, {r7,r8,r9}
ubfx r2, r3, #0, #22 @ r[9] = c & (M >> 4)
str r2, [r0, #9*4]
mov r3, r3, lsr #22 @ c >>= 22
orr r3, r3, r4, asl #10
mov r4, r4, lsr #22
movw r14, field_R1 << 4 @ c += d * (R1 << 4)
umlal r3, r4, r5, r14
movw r14, field_R0 >> 4 @ d = c * (R0 >> 4) + t0 (64x64 multiply+add)
umull r5, r6, r3, r14 @ d = c.lo * (R0 >> 4)
adds r5, r5, r7 @ d.lo += t0
mla r6, r14, r4, r6 @ d.hi += c.hi * (R0 >> 4)
adc r6, r6, 0 @ d.hi += carry
bic r2, r5, field_not_M @ r[0] = d & M
str r2, [r0, #0*4]
mov r5, r5, lsr #26 @ d >>= 26
orr r5, r5, r6, asl #6
mov r6, r6, lsr #26
movw r14, field_R1 >> 4 @ d += c * (R1 >> 4) + t1 (64x64 multiply+add)
umull r1, r2, r3, r14 @ tmp = c.lo * (R1 >> 4)
adds r5, r5, r8 @ d.lo += t1
adc r6, r6, #0 @ d.hi += carry
adds r5, r5, r1 @ d.lo += tmp.lo
mla r2, r14, r4, r2 @ tmp.hi += c.hi * (R1 >> 4)
adc r6, r6, r2 @ d.hi += carry + tmp.hi
bic r2, r5, field_not_M @ r[1] = d & M
str r2, [r0, #1*4]
mov r5, r5, lsr #26 @ d >>= 26 (ignore hi)
orr r5, r5, r6, asl #6
add r5, r5, r9 @ d += t2
str r5, [r0, #2*4] @ r[2] = d
add sp, sp, #48
ldmfd sp!, {r4, r5, r6, r7, r8, r9, r10, r11, pc}
.size secp256k1_fe_sqr_inner, .-secp256k1_fe_sqr_inner
.section .note.GNU-stack,"",%progbits

View File

@@ -0,0 +1,87 @@
/***********************************************************************
* Copyright (c) 2020 Pieter Wuille *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or https://www.opensource.org/licenses/mit-license.php.*
***********************************************************************/
#ifndef SECP256K1_ASSUMPTIONS_H
#define SECP256K1_ASSUMPTIONS_H
#include <limits.h>
#include "util.h"
#if defined(SECP256K1_INT128_NATIVE)
#include "int128_native.h"
#endif
/* This library, like most software, relies on a number of compiler implementation defined (but not undefined)
behaviours. Although the behaviours we require are essentially universal we test them specifically here to
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);
/* 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 */
/* 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 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);
#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);
/* 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);
#if defined(SECP256K1_INT128_NATIVE)
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 */

View File

@@ -0,0 +1,174 @@
/***********************************************************************
* Copyright (c) 2014 Pieter Wuille *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or https://www.opensource.org/licenses/mit-license.php.*
***********************************************************************/
#ifndef SECP256K1_BENCH_H
#define SECP256K1_BENCH_H
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "tests_common.h"
#define FP_EXP (6)
#define FP_MULT (1000000LL)
/* Format fixed point number. */
static void print_number(const int64_t x) {
int64_t x_abs, y;
int c, i, rounding, g; /* g = integer part size, c = fractional part size */
size_t ptr;
char buffer[30];
if (x == INT64_MIN) {
/* Prevent UB. */
printf("ERR");
return;
}
x_abs = x < 0 ? -x : x;
/* Determine how many decimals we want to show (more than FP_EXP makes no
* sense). */
y = x_abs;
c = 0;
while (y > 0LL && y < 100LL * FP_MULT && c < FP_EXP) {
y *= 10LL;
c++;
}
/* Round to 'c' decimals. */
y = x_abs;
rounding = 0;
for (i = c; i < FP_EXP; ++i) {
rounding = (y % 10) >= 5;
y /= 10;
}
y += rounding;
/* Format and print the number. */
ptr = sizeof(buffer) - 1;
buffer[ptr] = 0;
g = 0;
if (c != 0) { /* non zero fractional part */
for (i = 0; i < c; ++i) {
buffer[--ptr] = '0' + (y % 10);
y /= 10;
}
} else if (c == 0) { /* fractional part is 0 */
buffer[--ptr] = '0';
}
buffer[--ptr] = '.';
do {
buffer[--ptr] = '0' + (y % 10);
y /= 10;
g++;
} while (y != 0);
if (x < 0) {
buffer[--ptr] = '-';
g++;
}
printf("%5.*s", g, &buffer[ptr]); /* Prints integer part */
printf("%-*s", FP_EXP, &buffer[ptr + g]); /* Prints fractional part */
}
static void run_benchmark(char *name, void (*benchmark)(void*, int), void (*setup)(void*), void (*teardown)(void*, int), void* data, int count, int iter) {
int i;
int64_t min = INT64_MAX;
int64_t sum = 0;
int64_t max = 0;
for (i = 0; i < count; i++) {
int64_t begin, total;
if (setup != NULL) {
setup(data);
}
begin = gettime_i64();
benchmark(data, iter);
total = gettime_i64() - begin;
if (teardown != NULL) {
teardown(data, iter);
}
if (total < min) {
min = total;
}
if (total > max) {
max = total;
}
sum += total;
}
/* ',' is used as a column delimiter */
printf("%-30s, ", name);
print_number(min * FP_MULT / iter);
printf(" , ");
print_number(((sum * FP_MULT) / count) / iter);
printf(" , ");
print_number(max * FP_MULT / iter);
printf("\n");
}
static int have_flag(int argc, char** argv, char *flag) {
char** argm = argv + argc;
argv++;
while (argv != argm) {
if (strcmp(*argv, flag) == 0) {
return 1;
}
argv++;
}
return 0;
}
/* takes an array containing the arguments that the user is allowed to enter on the command-line
returns:
- 1 if the user entered an invalid argument
- 0 if all the user entered arguments are valid */
static int have_invalid_args(int argc, char** argv, char** valid_args, size_t n) {
size_t i;
int found_valid;
char** argm = argv + argc;
argv++;
while (argv != argm) {
found_valid = 0;
for (i = 0; i < n; i++) {
if (strcmp(*argv, valid_args[i]) == 0) {
found_valid = 1; /* user entered a valid arg from the list */
break;
}
}
if (found_valid == 0) {
return 1; /* invalid arg found */
}
argv++;
}
return 0;
}
static int get_iters(int default_iters) {
char* env = getenv("SECP256K1_BENCH_ITERS");
if (env) {
char* endptr;
long int iters = strtol(env, &endptr, 0);
if (*endptr != '\0' || iters <= 0) {
printf("Error: Value of SECP256K1_BENCH_ITERS is not a positive integer: %s\n\n", env);
return 0;
}
return iters;
} else {
return default_iters;
}
}
static void print_output_table_header_row(void) {
char* bench_str = "Benchmark"; /* left justified */
char* min_str = " Min(us) "; /* center alignment */
char* avg_str = " Avg(us) ";
char* max_str = " Max(us) ";
printf("%-30s,%-15s,%-15s,%-15s\n", bench_str, min_str, avg_str, max_str);
printf("\n");
}
#endif /* SECP256K1_BENCH_H */

View File

@@ -0,0 +1,117 @@
/***********************************************************************
* Copyright (c) 2022 Pieter Wuille *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or https://www.opensource.org/licenses/mit-license.php.*
***********************************************************************/
/* The code here is inspired by Kris Kwiatkowski's approach in
* https://github.com/kriskwiatkowski/pqc/blob/main/src/common/ct_check.h
* to provide a general interface for memory-checking mechanisms, primarily
* for constant-time checking.
*/
/* These macros are defined by this header file:
*
* - SECP256K1_CHECKMEM_ENABLED:
* - 1 if memory-checking integration is available, 0 otherwise.
* This is just a compile-time macro. Use the next macro to check it is actually
* available at runtime.
* - SECP256K1_CHECKMEM_RUNNING():
* - Acts like a function call, returning 1 if memory checking is available
* at runtime.
* - SECP256K1_CHECKMEM_CHECK(p, len):
* - Assert or otherwise fail in case the len-byte memory block pointed to by p is
* not considered entirely defined.
* - SECP256K1_CHECKMEM_CHECK_VERIFY(p, len):
* - Like SECP256K1_CHECKMEM_CHECK, but only works in VERIFY mode.
* - SECP256K1_CHECKMEM_UNDEFINE(p, len):
* - marks the len-byte memory block pointed to by p as undefined data (secret data,
* in the context of constant-time checking).
* - SECP256K1_CHECKMEM_DEFINE(p, len):
* - marks the len-byte memory pointed to by p as defined data (public data, in the
* context of constant-time checking).
* - SECP256K1_CHECKMEM_MSAN_DEFINE(p, len):
* - Like SECP256K1_CHECKMEM_DEFINE, but applies only to memory_sanitizer.
*
*/
#ifndef SECP256K1_CHECKMEM_H
#define SECP256K1_CHECKMEM_H
/* Define a statement-like macro that ignores the arguments. */
#define SECP256K1_CHECKMEM_NOOP(p, len) do { (void)(p); (void)(len); } while(0)
/* If compiling under msan, map the SECP256K1_CHECKMEM_* functionality to msan.
* Choose this preferentially, even when VALGRIND is defined, as msan-compiled
* binaries can't be run under valgrind anyway. */
#if defined(__has_feature)
# if __has_feature(memory_sanitizer)
# include <sanitizer/msan_interface.h>
# define SECP256K1_CHECKMEM_ENABLED 1
# if defined(__clang__) && ((__clang_major__ == 21 && __clang_minor__ >= 1) || __clang_major__ >= 22)
# define SECP256K1_CHECKMEM_UNDEFINE(p, len) do { \
/* Work around https://github.com/llvm/llvm-project/issues/160094 */ \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wuninitialized-const-pointer\"") \
__msan_allocated_memory((p), (len)); \
_Pragma("clang diagnostic pop") \
} while(0)
# else
# define SECP256K1_CHECKMEM_UNDEFINE(p, len) __msan_allocated_memory((p), (len))
# endif
# define SECP256K1_CHECKMEM_DEFINE(p, len) __msan_unpoison((p), (len))
# define SECP256K1_CHECKMEM_MSAN_DEFINE(p, len) __msan_unpoison((p), (len))
# define SECP256K1_CHECKMEM_CHECK(p, len) __msan_check_mem_is_initialized((p), (len))
# define SECP256K1_CHECKMEM_RUNNING() (1)
# endif
#endif
#if !defined SECP256K1_CHECKMEM_MSAN_DEFINE
# define SECP256K1_CHECKMEM_MSAN_DEFINE(p, len) SECP256K1_CHECKMEM_NOOP((p), (len))
#endif
/* If valgrind integration is desired (through the VALGRIND define), implement the
* SECP256K1_CHECKMEM_* macros using valgrind. */
#if !defined SECP256K1_CHECKMEM_ENABLED
# if defined VALGRIND
# include <stddef.h>
# if defined(__clang__) && defined(__APPLE__)
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wreserved-identifier"
# elif defined(__GNUC__) && (__GNUC__ >= 15)
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wtrailing-whitespace"
# endif
# include <valgrind/memcheck.h>
# if defined(__clang__) && defined(__APPLE__)
# pragma clang diagnostic pop
# elif defined(__GNUC__) && (__GNUC__ >= 15)
# pragma GCC diagnostic pop
# endif
# define SECP256K1_CHECKMEM_ENABLED 1
# define SECP256K1_CHECKMEM_UNDEFINE(p, len) VALGRIND_MAKE_MEM_UNDEFINED((p), (len))
# define SECP256K1_CHECKMEM_DEFINE(p, len) VALGRIND_MAKE_MEM_DEFINED((p), (len))
# define SECP256K1_CHECKMEM_CHECK(p, len) VALGRIND_CHECK_MEM_IS_DEFINED((p), (len))
/* VALGRIND_MAKE_MEM_DEFINED returns 0 iff not running on memcheck.
* This is more precise than the RUNNING_ON_VALGRIND macro, which
* checks for valgrind in general instead of memcheck specifically. */
# define SECP256K1_CHECKMEM_RUNNING() (VALGRIND_MAKE_MEM_DEFINED(NULL, 0) != 0)
# endif
#endif
/* As a fall-back, map these macros to dummy statements. */
#if !defined SECP256K1_CHECKMEM_ENABLED
# define SECP256K1_CHECKMEM_ENABLED 0
# define SECP256K1_CHECKMEM_UNDEFINE(p, len) SECP256K1_CHECKMEM_NOOP((p), (len))
# define SECP256K1_CHECKMEM_DEFINE(p, len) SECP256K1_CHECKMEM_NOOP((p), (len))
# define SECP256K1_CHECKMEM_CHECK(p, len) SECP256K1_CHECKMEM_NOOP((p), (len))
# define SECP256K1_CHECKMEM_RUNNING() (0)
#endif
#if defined VERIFY
#define SECP256K1_CHECKMEM_CHECK_VERIFY(p, len) SECP256K1_CHECKMEM_CHECK((p), (len))
#else
#define SECP256K1_CHECKMEM_CHECK_VERIFY(p, len) SECP256K1_CHECKMEM_NOOP((p), (len))
#endif
#endif /* SECP256K1_CHECKMEM_H */

View File

@@ -0,0 +1,21 @@
/***********************************************************************
* Copyright (c) 2013, 2014 Pieter Wuille *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or https://www.opensource.org/licenses/mit-license.php.*
***********************************************************************/
#ifndef SECP256K1_ECDSA_H
#define SECP256K1_ECDSA_H
#include <stddef.h>
#include "scalar.h"
#include "group.h"
#include "ecmult.h"
static int secp256k1_ecdsa_sig_parse(secp256k1_scalar *r, secp256k1_scalar *s, const unsigned char *sig, size_t size);
static int secp256k1_ecdsa_sig_serialize(unsigned char *sig, size_t *size, const secp256k1_scalar *r, const secp256k1_scalar *s);
static int secp256k1_ecdsa_sig_verify(const secp256k1_scalar* r, const secp256k1_scalar* s, const secp256k1_ge *pubkey, const secp256k1_scalar *message);
static int secp256k1_ecdsa_sig_sign(const secp256k1_ecmult_gen_context *ctx, secp256k1_scalar* r, secp256k1_scalar* s, const secp256k1_scalar *seckey, const secp256k1_scalar *message, const secp256k1_scalar *nonce, int *recid);
#endif /* SECP256K1_ECDSA_H */

View File

@@ -0,0 +1,312 @@
/***********************************************************************
* Copyright (c) 2013-2015 Pieter Wuille *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or https://www.opensource.org/licenses/mit-license.php.*
***********************************************************************/
#ifndef SECP256K1_ECDSA_IMPL_H
#define SECP256K1_ECDSA_IMPL_H
#include "scalar.h"
#include "field.h"
#include "group.h"
#include "ecmult.h"
#include "ecmult_gen.h"
#include "ecdsa.h"
/** Group order for secp256k1 defined as 'n' in "Standards for Efficient Cryptography" (SEC2) 2.7.1
* $ sage -c 'load("secp256k1_params.sage"); print(hex(N))'
* 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141
*/
static const secp256k1_fe secp256k1_ecdsa_const_order_as_fe = SECP256K1_FE_CONST(
0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFEUL,
0xBAAEDCE6UL, 0xAF48A03BUL, 0xBFD25E8CUL, 0xD0364141UL
);
/** Difference between field and order, values 'p' and 'n' values defined in
* "Standards for Efficient Cryptography" (SEC2) 2.7.1.
* $ sage -c 'load("secp256k1_params.sage"); print(hex(P-N))'
* 0x14551231950b75fc4402da1722fc9baee
*/
static const secp256k1_fe secp256k1_ecdsa_const_p_minus_order = SECP256K1_FE_CONST(
0, 0, 0, 1, 0x45512319UL, 0x50B75FC4UL, 0x402DA172UL, 0x2FC9BAEEUL
);
static int secp256k1_der_read_len(size_t *len, const unsigned char **sigp, const unsigned char *sigend) {
size_t lenleft;
unsigned char b1;
VERIFY_CHECK(len != NULL);
*len = 0;
if (*sigp >= sigend) {
return 0;
}
b1 = *((*sigp)++);
if (b1 == 0xFF) {
/* X.690-0207 8.1.3.5.c the value 0xFF shall not be used. */
return 0;
}
if ((b1 & 0x80) == 0) {
/* X.690-0207 8.1.3.4 short form length octets */
*len = b1;
return 1;
}
if (b1 == 0x80) {
/* Indefinite length is not allowed in DER. */
return 0;
}
/* X.690-207 8.1.3.5 long form length octets */
lenleft = b1 & 0x7F; /* lenleft is at least 1 */
if (lenleft > (size_t)(sigend - *sigp)) {
return 0;
}
if (**sigp == 0) {
/* Not the shortest possible length encoding. */
return 0;
}
if (lenleft > sizeof(size_t)) {
/* The resulting length would exceed the range of a size_t, so
* it is certainly longer than the passed array size. */
return 0;
}
while (lenleft > 0) {
*len = (*len << 8) | **sigp;
(*sigp)++;
lenleft--;
}
if (*len > (size_t)(sigend - *sigp)) {
/* Result exceeds the length of the passed array.
(Checking this is the responsibility of the caller but it
can't hurt do it here, too.) */
return 0;
}
if (*len < 128) {
/* Not the shortest possible length encoding. */
return 0;
}
return 1;
}
static int secp256k1_der_parse_integer(secp256k1_scalar *r, const unsigned char **sig, const unsigned char *sigend) {
int overflow = 0;
unsigned char ra[32] = {0};
size_t rlen;
if (*sig == sigend || **sig != 0x02) {
/* Not a primitive integer (X.690-0207 8.3.1). */
return 0;
}
(*sig)++;
if (secp256k1_der_read_len(&rlen, sig, sigend) == 0) {
return 0;
}
if (rlen == 0 || rlen > (size_t)(sigend - *sig)) {
/* Exceeds bounds or not at least length 1 (X.690-0207 8.3.1). */
return 0;
}
if (**sig == 0x00 && rlen > 1 && (((*sig)[1]) & 0x80) == 0x00) {
/* Excessive 0x00 padding. */
return 0;
}
if (**sig == 0xFF && rlen > 1 && (((*sig)[1]) & 0x80) == 0x80) {
/* Excessive 0xFF padding. */
return 0;
}
if ((**sig & 0x80) == 0x80) {
/* Negative. */
overflow = 1;
}
/* There is at most one leading zero byte:
* if there were two leading zero bytes, we would have failed and returned 0
* because of excessive 0x00 padding already. */
if (rlen > 0 && **sig == 0) {
/* Skip leading zero byte */
rlen--;
(*sig)++;
}
if (rlen > 32) {
overflow = 1;
}
if (!overflow) {
if (rlen) memcpy(ra + 32 - rlen, *sig, rlen);
secp256k1_scalar_set_b32(r, ra, &overflow);
}
if (overflow) {
secp256k1_scalar_set_int(r, 0);
}
(*sig) += rlen;
return 1;
}
static int secp256k1_ecdsa_sig_parse(secp256k1_scalar *rr, secp256k1_scalar *rs, const unsigned char *sig, size_t size) {
const unsigned char *sigend = sig + size;
size_t rlen;
if (sig == sigend || *(sig++) != 0x30) {
/* The encoding doesn't start with a constructed sequence (X.690-0207 8.9.1). */
return 0;
}
if (secp256k1_der_read_len(&rlen, &sig, sigend) == 0) {
return 0;
}
if (rlen != (size_t)(sigend - sig)) {
/* Tuple exceeds bounds or garage after tuple. */
return 0;
}
if (!secp256k1_der_parse_integer(rr, &sig, sigend)) {
return 0;
}
if (!secp256k1_der_parse_integer(rs, &sig, sigend)) {
return 0;
}
if (sig != sigend) {
/* Trailing garbage inside tuple. */
return 0;
}
return 1;
}
static int secp256k1_ecdsa_sig_serialize(unsigned char *sig, size_t *size, const secp256k1_scalar* ar, const secp256k1_scalar* as) {
unsigned char r[33] = {0}, s[33] = {0};
unsigned char *rp = r, *sp = s;
size_t lenR = 33, lenS = 33;
secp256k1_scalar_get_b32(&r[1], ar);
secp256k1_scalar_get_b32(&s[1], as);
while (lenR > 1 && rp[0] == 0 && rp[1] < 0x80) { lenR--; rp++; }
while (lenS > 1 && sp[0] == 0 && sp[1] < 0x80) { lenS--; sp++; }
if (*size < 6+lenS+lenR) {
*size = 6 + lenS + lenR;
return 0;
}
*size = 6 + lenS + lenR;
sig[0] = 0x30;
sig[1] = 4 + lenS + lenR;
sig[2] = 0x02;
sig[3] = lenR;
memcpy(sig+4, rp, lenR);
sig[4+lenR] = 0x02;
sig[5+lenR] = lenS;
memcpy(sig+lenR+6, sp, lenS);
return 1;
}
static int secp256k1_ecdsa_sig_verify(const secp256k1_scalar *sigr, const secp256k1_scalar *sigs, const secp256k1_ge *pubkey, const secp256k1_scalar *message) {
unsigned char c[32];
secp256k1_scalar sn, u1, u2;
#if !defined(EXHAUSTIVE_TEST_ORDER)
int range;
secp256k1_fe xr;
#endif
secp256k1_gej pubkeyj;
secp256k1_gej pr;
if (secp256k1_scalar_is_zero(sigr) || secp256k1_scalar_is_zero(sigs)) {
return 0;
}
secp256k1_scalar_inverse_var(&sn, sigs);
secp256k1_scalar_mul(&u1, &sn, message);
secp256k1_scalar_mul(&u2, &sn, sigr);
secp256k1_gej_set_ge(&pubkeyj, pubkey);
secp256k1_ecmult(&pr, &pubkeyj, &u2, &u1);
if (secp256k1_gej_is_infinity(&pr)) {
return 0;
}
#if defined(EXHAUSTIVE_TEST_ORDER)
{
secp256k1_scalar computed_r;
secp256k1_ge pr_ge;
secp256k1_ge_set_gej(&pr_ge, &pr);
secp256k1_fe_normalize(&pr_ge.x);
secp256k1_fe_get_b32(c, &pr_ge.x);
secp256k1_scalar_set_b32(&computed_r, c, NULL);
return secp256k1_scalar_eq(sigr, &computed_r);
}
#else
/* Interpret sigr as a field element xr */
secp256k1_scalar_get_b32(c, sigr);
range = secp256k1_fe_set_b32_limit(&xr, c);
#ifdef VERIFY
/* We know that c is in range; it comes from a scalar. */
VERIFY_CHECK(range);
#else
(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:
*
* 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)
*
* 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.
*/
if (secp256k1_gej_eq_x_var(&xr, &pr)) {
/* xr * pr.z^2 mod p == pr.x, 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. */
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. */
return 1;
}
return 0;
#endif
}
static int secp256k1_ecdsa_sig_sign(const secp256k1_ecmult_gen_context *ctx, secp256k1_scalar *sigr, secp256k1_scalar *sigs, const secp256k1_scalar *seckey, const secp256k1_scalar *message, const secp256k1_scalar *nonce, int *recid) {
unsigned char b[32];
secp256k1_gej rp;
secp256k1_ge r;
secp256k1_scalar n;
int overflow = 0;
int high;
secp256k1_ecmult_gen(ctx, &rp, nonce);
secp256k1_ge_set_gej(&r, &rp);
secp256k1_fe_normalize(&r.x);
secp256k1_fe_normalize(&r.y);
secp256k1_fe_get_b32(b, &r.x);
secp256k1_scalar_set_b32(sigr, b, &overflow);
if (recid) {
/* The overflow condition is cryptographically unreachable as hitting it requires finding the discrete log
* of some P where P.x >= order, and only 1 in about 2^127 points meet this criteria.
*/
*recid = (overflow << 1) | secp256k1_fe_is_odd(&r.y);
}
secp256k1_scalar_mul(&n, sigr, seckey);
secp256k1_scalar_add(&n, &n, message);
secp256k1_scalar_inverse(sigs, nonce);
secp256k1_scalar_mul(sigs, sigs, &n);
secp256k1_scalar_clear(&n);
secp256k1_gej_clear(&rp);
secp256k1_ge_clear(&r);
high = secp256k1_scalar_is_high(sigs);
secp256k1_scalar_cond_negate(sigs, high);
if (recid) {
*recid ^= high;
}
/* P.x = order is on the curve, so technically sig->r could end up being zero, which would be an invalid signature.
* This is cryptographically unreachable as hitting it requires finding the discrete log of P.x = N.
*/
return (int)(!secp256k1_scalar_is_zero(sigr)) & (int)(!secp256k1_scalar_is_zero(sigs));
}
#endif /* SECP256K1_ECDSA_IMPL_H */

View File

@@ -0,0 +1,28 @@
/***********************************************************************
* Copyright (c) 2013, 2014 Pieter Wuille *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or https://www.opensource.org/licenses/mit-license.php.*
***********************************************************************/
#ifndef SECP256K1_ECKEY_H
#define SECP256K1_ECKEY_H
#include <stddef.h>
#include "group.h"
#include "scalar.h"
#include "ecmult.h"
#include "ecmult_gen.h"
static int secp256k1_eckey_pubkey_parse(secp256k1_ge *elem, const unsigned char *pub, size_t size);
/** Serialize a group element (that is not allowed to be infinity) to a compressed public key (33 bytes). */
static void secp256k1_eckey_pubkey_serialize33(secp256k1_ge *elem, unsigned char *pub33);
/** Serialize a group element (that is not allowed to be infinity) to an uncompressed public key (65 bytes). */
static void secp256k1_eckey_pubkey_serialize65(secp256k1_ge *elem, unsigned char *pub65);
static int secp256k1_eckey_privkey_tweak_add(secp256k1_scalar *key, const secp256k1_scalar *tweak);
static int secp256k1_eckey_pubkey_tweak_add(secp256k1_ge *key, const secp256k1_scalar *tweak);
static int secp256k1_eckey_privkey_tweak_mul(secp256k1_scalar *key, const secp256k1_scalar *tweak);
static int secp256k1_eckey_pubkey_tweak_mul(secp256k1_ge *key, const secp256k1_scalar *tweak);
#endif /* SECP256K1_ECKEY_H */

View File

@@ -0,0 +1,94 @@
/***********************************************************************
* Copyright (c) 2013, 2014 Pieter Wuille *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or https://www.opensource.org/licenses/mit-license.php.*
***********************************************************************/
#ifndef SECP256K1_ECKEY_IMPL_H
#define SECP256K1_ECKEY_IMPL_H
#include "eckey.h"
#include "util.h"
#include "scalar.h"
#include "field.h"
#include "group.h"
#include "ecmult_gen.h"
static int secp256k1_eckey_pubkey_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_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)) {
secp256k1_fe x, y;
if (!secp256k1_fe_set_b32_limit(&x, pub+1) || !secp256k1_fe_set_b32_limit(&y, pub+33)) {
return 0;
}
secp256k1_ge_set_xy(elem, &x, &y);
if ((pub[0] == SECP256K1_TAG_PUBKEY_HYBRID_EVEN || pub[0] == SECP256K1_TAG_PUBKEY_HYBRID_ODD) &&
secp256k1_fe_is_odd(&y) != (pub[0] == SECP256K1_TAG_PUBKEY_HYBRID_ODD)) {
return 0;
}
return secp256k1_ge_is_valid_var(elem);
} else {
return 0;
}
}
static void secp256k1_eckey_pubkey_serialize33(secp256k1_ge *elem, unsigned char *pub33) {
VERIFY_CHECK(!secp256k1_ge_is_infinity(elem));
secp256k1_fe_normalize_var(&elem->x);
secp256k1_fe_normalize_var(&elem->y);
pub33[0] = secp256k1_fe_is_odd(&elem->y) ? SECP256K1_TAG_PUBKEY_ODD : SECP256K1_TAG_PUBKEY_EVEN;
secp256k1_fe_get_b32(&pub33[1], &elem->x);
}
static void secp256k1_eckey_pubkey_serialize65(secp256k1_ge *elem, unsigned char *pub65) {
VERIFY_CHECK(!secp256k1_ge_is_infinity(elem));
secp256k1_fe_normalize_var(&elem->x);
secp256k1_fe_normalize_var(&elem->y);
pub65[0] = SECP256K1_TAG_PUBKEY_UNCOMPRESSED;
secp256k1_fe_get_b32(&pub65[1], &elem->x);
secp256k1_fe_get_b32(&pub65[33], &elem->y);
}
static int secp256k1_eckey_privkey_tweak_add(secp256k1_scalar *key, const secp256k1_scalar *tweak) {
secp256k1_scalar_add(key, key, tweak);
return !secp256k1_scalar_is_zero(key);
}
static int secp256k1_eckey_pubkey_tweak_add(secp256k1_ge *key, const secp256k1_scalar *tweak) {
secp256k1_gej pt;
secp256k1_gej_set_ge(&pt, key);
secp256k1_ecmult(&pt, &pt, &secp256k1_scalar_one, tweak);
if (secp256k1_gej_is_infinity(&pt)) {
return 0;
}
secp256k1_ge_set_gej(key, &pt);
return 1;
}
static int secp256k1_eckey_privkey_tweak_mul(secp256k1_scalar *key, const secp256k1_scalar *tweak) {
int ret;
ret = !secp256k1_scalar_is_zero(tweak);
secp256k1_scalar_mul(key, key, tweak);
return ret;
}
static int secp256k1_eckey_pubkey_tweak_mul(secp256k1_ge *key, const secp256k1_scalar *tweak) {
secp256k1_gej pt;
if (secp256k1_scalar_is_zero(tweak)) {
return 0;
}
secp256k1_gej_set_ge(&pt, key);
secp256k1_ecmult(&pt, &pt, tweak, NULL);
secp256k1_ge_set_gej(key, &pt);
return 1;
}
#endif /* SECP256K1_ECKEY_IMPL_H */

View File

@@ -0,0 +1,64 @@
/***********************************************************************
* Copyright (c) 2013, 2014, 2017 Pieter Wuille, Andrew Poelstra *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or https://www.opensource.org/licenses/mit-license.php.*
***********************************************************************/
#ifndef SECP256K1_ECMULT_H
#define SECP256K1_ECMULT_H
#include "group.h"
#include "scalar.h"
#include "scratch.h"
#ifndef ECMULT_WINDOW_SIZE
# define ECMULT_WINDOW_SIZE 15
# ifdef DEBUG_CONFIG
# pragma message DEBUG_CONFIG_MSG("ECMULT_WINDOW_SIZE undefined, assuming default value")
# endif
#endif
#ifdef DEBUG_CONFIG
# pragma message DEBUG_CONFIG_DEF(ECMULT_WINDOW_SIZE)
#endif
/* No one will ever need more than a window size of 24. The code might
* be correct for larger values of ECMULT_WINDOW_SIZE but this is not
* 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
* 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
* because certain expressions will overflow.
*/
#if ECMULT_WINDOW_SIZE < 2 || ECMULT_WINDOW_SIZE > 24
# error Set ECMULT_WINDOW_SIZE to an integer in range [2..24].
#endif
/** The number of entries a table with precomputed multiples needs to have. */
#define ECMULT_TABLE_SIZE(w) ((size_t)1 << ((w)-2))
/** Double multiply: R = na*A + ng*G
*
* Passing NULL as ng is equivalent to the zero scalar but a tiny bit faster.
*/
static void secp256k1_ecmult(secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_scalar *na, const secp256k1_scalar *ng);
typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data);
/**
* Multi-multiply: R = inp_g_sc * G + sum_i ni * Ai.
* Chooses the right algorithm for a given number of points and scratch space
* size. Resets and overwrites the given scratch space. If the points do not
* fit in the scratch space the algorithm is repeatedly run with batches of
* points. If no scratch space is given then a simple algorithm is used that
* simply multiplies the points with the corresponding scalars and adds them up.
* Returns: 1 on success (including when inp_g_sc is NULL and n is 0)
* 0 if there is not enough scratch space for a single point or
* callback returns 0
*/
static int secp256k1_ecmult_multi_var(const secp256k1_callback* error_callback, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n);
#endif /* SECP256K1_ECMULT_H */

View File

@@ -0,0 +1,16 @@
/*****************************************************************************************************
* Copyright (c) 2013, 2014, 2017, 2021 Pieter Wuille, Andrew Poelstra, Jonas Nick, Russell O'Connor *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or https://www.opensource.org/licenses/mit-license.php. *
*****************************************************************************************************/
#ifndef SECP256K1_ECMULT_COMPUTE_TABLE_H
#define SECP256K1_ECMULT_COMPUTE_TABLE_H
/* Construct table of all odd multiples of gen in range 1..(2**(window_g-1)-1). */
static void secp256k1_ecmult_compute_table(secp256k1_ge_storage* table, int window_g, const secp256k1_gej* gen);
/* Like secp256k1_ecmult_compute_table, but one for both gen and gen*2^128. */
static void secp256k1_ecmult_compute_two_tables(secp256k1_ge_storage* table, secp256k1_ge_storage* table_128, int window_g, const secp256k1_ge* gen);
#endif /* SECP256K1_ECMULT_COMPUTE_TABLE_H */

View File

@@ -0,0 +1,49 @@
/*****************************************************************************************************
* Copyright (c) 2013, 2014, 2017, 2021 Pieter Wuille, Andrew Poelstra, Jonas Nick, Russell O'Connor *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or https://www.opensource.org/licenses/mit-license.php. *
*****************************************************************************************************/
#ifndef SECP256K1_ECMULT_COMPUTE_TABLE_IMPL_H
#define SECP256K1_ECMULT_COMPUTE_TABLE_IMPL_H
#include "ecmult_compute_table.h"
#include "group_impl.h"
#include "field_impl.h"
#include "ecmult.h"
#include "util.h"
static void secp256k1_ecmult_compute_table(secp256k1_ge_storage* table, int window_g, const secp256k1_gej* gen) {
secp256k1_gej gj;
secp256k1_ge ge, dgen;
size_t j;
gj = *gen;
secp256k1_ge_set_gej_var(&ge, &gj);
secp256k1_ge_to_storage(&table[0], &ge);
secp256k1_gej_double_var(&gj, gen, NULL);
secp256k1_ge_set_gej_var(&dgen, &gj);
for (j = 1; j < ECMULT_TABLE_SIZE(window_g); ++j) {
secp256k1_gej_set_ge(&gj, &ge);
secp256k1_gej_add_ge_var(&gj, &gj, &dgen, NULL);
secp256k1_ge_set_gej_var(&ge, &gj);
secp256k1_ge_to_storage(&table[j], &ge);
}
}
/* Like secp256k1_ecmult_compute_table, but one for both gen and gen*2^128. */
static void secp256k1_ecmult_compute_two_tables(secp256k1_ge_storage* table, secp256k1_ge_storage* table_128, int window_g, const secp256k1_ge* gen) {
secp256k1_gej gj;
int i;
secp256k1_gej_set_ge(&gj, gen);
secp256k1_ecmult_compute_table(table, window_g, &gj);
for (i = 0; i < 128; ++i) {
secp256k1_gej_double_var(&gj, &gj, NULL);
}
secp256k1_ecmult_compute_table(table_128, window_g, &gj);
}
#endif /* SECP256K1_ECMULT_COMPUTE_TABLE_IMPL_H */

View File

@@ -0,0 +1,38 @@
/***********************************************************************
* Copyright (c) 2015 Andrew Poelstra *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or https://www.opensource.org/licenses/mit-license.php.*
***********************************************************************/
#ifndef SECP256K1_ECMULT_CONST_H
#define SECP256K1_ECMULT_CONST_H
#include "scalar.h"
#include "group.h"
/**
* 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);
/**
* Same as secp256k1_ecmult_const, 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.
*
* If known_on_curve is 0, a verification is performed that n/d is a valid X
* coordinate, and 0 is returned if not. Otherwise, 1 is returned.
*
* d being NULL is interpreted as d=1. If non-NULL, d must not be zero. q must not be zero.
*
* Constant time in the value of q, but not any other inputs.
*/
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
);
#endif /* SECP256K1_ECMULT_CONST_H */

View File

@@ -0,0 +1,402 @@
/***********************************************************************
* Copyright (c) 2015, 2022 Pieter Wuille, Andrew Poelstra *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or https://www.opensource.org/licenses/mit-license.php.*
***********************************************************************/
#ifndef SECP256K1_ECMULT_CONST_IMPL_H
#define SECP256K1_ECMULT_CONST_IMPL_H
#include "scalar.h"
#include "group.h"
#include "ecmult_const.h"
#include "ecmult_impl.h"
#if defined(EXHAUSTIVE_TEST_ORDER)
/* We need 2^ECMULT_CONST_GROUP_SIZE - 1 to be less than EXHAUSTIVE_TEST_ORDER, because
* the tables cannot have infinities in them (this breaks the effective-affine technique's
* z-ratio tracking) */
# if EXHAUSTIVE_TEST_ORDER == 199
# define ECMULT_CONST_GROUP_SIZE 4
# elif EXHAUSTIVE_TEST_ORDER == 13
# define ECMULT_CONST_GROUP_SIZE 3
# elif EXHAUSTIVE_TEST_ORDER == 7
# define ECMULT_CONST_GROUP_SIZE 2
# else
# error "Unknown EXHAUSTIVE_TEST_ORDER"
# endif
#else
/* Group size 4 or 5 appears optimal. */
# define ECMULT_CONST_GROUP_SIZE 5
#endif
#define ECMULT_CONST_TABLE_SIZE (1L << (ECMULT_CONST_GROUP_SIZE - 1))
#define ECMULT_CONST_GROUPS ((129 + ECMULT_CONST_GROUP_SIZE - 1) / ECMULT_CONST_GROUP_SIZE)
#define ECMULT_CONST_BITS (ECMULT_CONST_GROUPS * ECMULT_CONST_GROUP_SIZE)
/** Fill a table 'pre' with precomputed odd multiples of a.
*
* The resulting point set is brought to a single constant Z denominator, stores the X and Y
* coordinates as ge points in pre, and stores the global Z in globalz.
*
* 'pre' must be an array of size ECMULT_CONST_TABLE_SIZE.
*/
static void secp256k1_ecmult_const_odd_multiples_table_globalz(secp256k1_ge *pre, secp256k1_fe *globalz, const secp256k1_gej *a) {
secp256k1_fe zr[ECMULT_CONST_TABLE_SIZE];
secp256k1_ecmult_odd_multiples_table(ECMULT_CONST_TABLE_SIZE, pre, zr, globalz, a);
secp256k1_ge_table_set_globalz(ECMULT_CONST_TABLE_SIZE, pre, zr);
}
/* Given a table 'pre' with odd multiples of a point, put in r the signed-bit multiplication of n with that point.
*
* For example, if ECMULT_CONST_GROUP_SIZE is 4, then pre is expected to contain 8 entries:
* [1*P, 3*P, 5*P, 7*P, 9*P, 11*P, 13*P, 15*P]. n is then expected to be a 4-bit integer (range 0-15), and its
* bits are interpreted as signs of powers of two to look up.
*
* For example, if n=4, which is 0100 in binary, which is interpreted as [- + - -], so the looked up value is
* [ -(2^3) + (2^2) - (2^1) - (2^0) ]*P = -7*P. Every valid n translates to an odd number in range [-15,15],
* which means we just need to look up one of the precomputed values, and optionally negate it.
*/
#define ECMULT_CONST_TABLE_GET_GE(r,pre,n) do { \
unsigned int m = 0; \
/* If the top bit of n is 0, we want the negation. */ \
volatile unsigned int negative = ((n) >> (ECMULT_CONST_GROUP_SIZE - 1)) ^ 1; \
/* Let n[i] be the i-th bit of n, then the index is
* sum(cnot(n[i]) * 2^i, i=0..l-2)
* where cnot(b) = b if n[l-1] = 1 and 1 - b otherwise.
* For example, if n = 4, in binary 0100, the index is 3, in binary 011.
*
* Proof:
* Let
* x = sum((2*n[i] - 1)*2^i, i=0..l-1)
* = 2*sum(n[i] * 2^i, i=0..l-1) - 2^l + 1
* be the value represented by n.
* The index is (x - 1)/2 if x > 0 and -(x + 1)/2 otherwise.
* Case x > 0:
* n[l-1] = 1
* index = sum(n[i] * 2^i, i=0..l-1) - 2^(l-1)
* = sum(n[i] * 2^i, i=0..l-2)
* Case x <= 0:
* n[l-1] = 0
* index = -(2*sum(n[i] * 2^i, i=0..l-1) - 2^l + 2)/2
* = 2^(l-1) - 1 - sum(n[i] * 2^i, i=0..l-1)
* = sum((1 - n[i]) * 2^i, i=0..l-2)
*/ \
unsigned int index = ((unsigned int)(-negative) ^ n) & ((1U << (ECMULT_CONST_GROUP_SIZE - 1)) - 1U); \
secp256k1_fe neg_y; \
VERIFY_CHECK((n) < (1U << ECMULT_CONST_GROUP_SIZE)); \
VERIFY_CHECK(index < (1U << (ECMULT_CONST_GROUP_SIZE - 1))); \
/* Unconditionally set r->x = (pre)[m].x and r->y = (pre)[m].y because it's either the correct one
* or will get replaced in the later iterations, this is needed to make sure `r` is initialized. */ \
secp256k1_ge_set_xy((r), &(pre)[m].x, &(pre)[m].y); \
for (m = 1; m < ECMULT_CONST_TABLE_SIZE; m++) { \
/* This loop is used to avoid secret data in array indices. See
* the comment in ecmult_gen_impl.h for rationale. */ \
secp256k1_fe_cmov(&(r)->x, &(pre)[m].x, m == index); \
secp256k1_fe_cmov(&(r)->y, &(pre)[m].y, m == index); \
} \
secp256k1_fe_negate(&neg_y, &(r)->y, 1); \
secp256k1_fe_cmov(&(r)->y, &neg_y, negative); \
} while(0)
/* For K as defined in the comment of secp256k1_ecmult_const, we have several precomputed
* formulas/constants.
* - in exhaustive test mode, we give an explicit expression to compute it at compile time: */
#ifdef EXHAUSTIVE_TEST_ORDER
static const secp256k1_scalar secp256k1_ecmult_const_K = ((SECP256K1_SCALAR_CONST(0, 0, 0, (1U << (ECMULT_CONST_BITS - 128)) - 2U, 0, 0, 0, 0) + EXHAUSTIVE_TEST_ORDER - 1U) * (1U + EXHAUSTIVE_TEST_LAMBDA)) % EXHAUSTIVE_TEST_ORDER;
/* - for the real secp256k1 group we have constants for various ECMULT_CONST_BITS values. */
#elif ECMULT_CONST_BITS == 129
/* For GROUP_SIZE = 1,3. */
static const secp256k1_scalar secp256k1_ecmult_const_K = SECP256K1_SCALAR_CONST(0xac9c52b3ul, 0x3fa3cf1ful, 0x5ad9e3fdul, 0x77ed9ba4ul, 0xa880b9fcul, 0x8ec739c2ul, 0xe0cfc810ul, 0xb51283ceul);
#elif ECMULT_CONST_BITS == 130
/* For GROUP_SIZE = 2,5. */
static const secp256k1_scalar secp256k1_ecmult_const_K = SECP256K1_SCALAR_CONST(0xa4e88a7dul, 0xcb13034eul, 0xc2bdd6bful, 0x7c118d6bul, 0x589ae848ul, 0x26ba29e4ul, 0xb5c2c1dcul, 0xde9798d9ul);
#elif ECMULT_CONST_BITS == 132
/* For GROUP_SIZE = 4,6 */
static const secp256k1_scalar secp256k1_ecmult_const_K = SECP256K1_SCALAR_CONST(0x76b1d93dul, 0x0fae3c6bul, 0x3215874bul, 0x94e93813ul, 0x7937fe0dul, 0xb66bcaaful, 0xb3749ca5ul, 0xd7b6171bul);
#else
# error "Unknown ECMULT_CONST_BITS"
#endif
static void secp256k1_ecmult_const(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.
*
* The idea there is to interpret the bits of a scalar as signs (1 = +, 0 = -), and compute a
* point multiplication in that fashion. Let v be an n-bit non-negative integer (0 <= v < 2^n),
* and v[i] its i'th bit (so v = sum(v[i] * 2^i, i=0..n-1)). Then define:
*
* C_l(v, A) = sum((2*v[i] - 1) * 2^i*A, i=0..l-1)
*
* Then it holds that C_l(v, A) = sum((2*v[i] - 1) * 2^i*A, i=0..l-1)
* = (2*sum(v[i] * 2^i, i=0..l-1) + 1 - 2^l) * A
* = (2*v + 1 - 2^l) * A
*
* Thus, one can compute q*A as C_256((q + 2^256 - 1) / 2, A). This is the basis for the
* paper's signed-digit multi-comb algorithm for multiplication using a precomputed table.
*
* It is appealing to try to combine this with the GLV optimization: the idea that a scalar
* s can be written as s1 + lambda*s2, where lambda is a curve-specific constant such that
* lambda*A is easy to compute, and where s1 and s2 are small. In particular we have the
* secp256k1_scalar_split_lambda function which performs such a split with the resulting s1
* and s2 in range (-2^128, 2^128) mod n. This does work, but is uninteresting:
*
* To compute q*A:
* - Let s1, s2 = split_lambda(q)
* - Let R1 = C_256((s1 + 2^256 - 1) / 2, A)
* - Let R2 = C_256((s2 + 2^256 - 1) / 2, lambda*A)
* - Return R1 + R2
*
* The issue is that while s1 and s2 are small-range numbers, (s1 + 2^256 - 1) / 2 (mod n)
* and (s2 + 2^256 - 1) / 2 (mod n) are not, undoing the benefit of the splitting.
*
* To make it work, we want to modify the input scalar q first, before splitting, and then only
* add a 2^128 offset of the split results (so that they end up in the single 129-bit range
* [0,2^129]). A slightly smaller offset would work due to the bounds on the split, but we pick
* 2^128 for simplicity. Let s be the scalar fed to split_lambda, and f(q) the function to
* compute it from q:
*
* To compute q*A:
* - Compute s = f(q)
* - Let s1, s2 = split_lambda(s)
* - Let v1 = s1 + 2^128 (mod n)
* - Let v2 = s2 + 2^128 (mod n)
* - Let R1 = C_l(v1, A)
* - Let R2 = C_l(v2, lambda*A)
* - Return R1 + R2
*
* l will thus need to be at least 129, but we may overshoot by a few bits (see
* further), so keep it as a variable.
*
* To solve for s, we reason:
* q*A = R1 + R2
* <=> q*A = C_l(s1 + 2^128, A) + C_l(s2 + 2^128, lambda*A)
* <=> q*A = (2*(s1 + 2^128) + 1 - 2^l) * A + (2*(s2 + 2^128) + 1 - 2^l) * lambda*A
* <=> q*A = (2*(s1 + s2*lambda) + (2^129 + 1 - 2^l) * (1 + lambda)) * A
* <=> q = 2*(s1 + s2*lambda) + (2^129 + 1 - 2^l) * (1 + lambda) (mod n)
* <=> q = 2*s + (2^129 + 1 - 2^l) * (1 + lambda) (mod n)
* <=> s = (q + (2^l - 2^129 - 1) * (1 + lambda)) / 2 (mod n)
* <=> f(q) = (q + K) / 2 (mod n)
* where K = (2^l - 2^129 - 1)*(1 + lambda) (mod n)
*
* We will process the computation of C_l(v1, A) and C_l(v2, lambda*A) in groups of
* ECMULT_CONST_GROUP_SIZE, so we set l to the smallest multiple of ECMULT_CONST_GROUP_SIZE
* that is not less than 129; this equals ECMULT_CONST_BITS.
*/
/* The offset to add to s1 and s2 to make them non-negative. Equal to 2^128. */
static const secp256k1_scalar S_OFFSET = SECP256K1_SCALAR_CONST(0, 0, 0, 1, 0, 0, 0, 0);
secp256k1_scalar s, v1, v2;
secp256k1_ge pre_a[ECMULT_CONST_TABLE_SIZE];
secp256k1_ge pre_a_lam[ECMULT_CONST_TABLE_SIZE];
secp256k1_fe global_z;
int group, i;
/* We're allowed to be non-constant time in the point, and the code below (in particular,
* secp256k1_ecmult_const_odd_multiples_table_globalz) cannot deal with infinity in a
* constant-time manner anyway. */
if (secp256k1_ge_is_infinity(a)) {
secp256k1_gej_set_infinity(r);
return;
}
/* Compute v1 and v2. */
secp256k1_scalar_add(&s, q, &secp256k1_ecmult_const_K);
secp256k1_scalar_half(&s, &s);
secp256k1_scalar_split_lambda(&v1, &v2, &s);
secp256k1_scalar_add(&v1, &v1, &S_OFFSET);
secp256k1_scalar_add(&v2, &v2, &S_OFFSET);
#ifdef VERIFY
/* Verify that v1 and v2 are in range [0, 2^129-1]. */
for (i = 129; i < 256; ++i) {
VERIFY_CHECK(secp256k1_scalar_get_bits_limb32(&v1, i, 1) == 0);
VERIFY_CHECK(secp256k1_scalar_get_bits_limb32(&v2, i, 1) == 0);
}
#endif
/* Calculate odd multiples of A and A*lambda.
* All multiples are brought to the same Z 'denominator', which is stored
* in global_z. Due to secp256k1' isomorphism we can do all operations pretending
* that the Z coordinate was 1, use affine addition formulae, and correct
* the Z coordinate of the result once at the end.
*/
secp256k1_gej_set_ge(r, a);
secp256k1_ecmult_const_odd_multiples_table_globalz(pre_a, &global_z, r);
for (i = 0; i < ECMULT_CONST_TABLE_SIZE; i++) {
secp256k1_ge_mul_lambda(&pre_a_lam[i], &pre_a[i]);
}
/* Next, we compute r = C_l(v1, A) + C_l(v2, lambda*A).
*
* We proceed in groups of ECMULT_CONST_GROUP_SIZE bits, operating on that many bits
* at a time, from high in v1, v2 to low. Call these bits1 (from v1) and bits2 (from v2).
*
* Now note that ECMULT_CONST_TABLE_GET_GE(&t, pre_a, bits1) loads into t a point equal
* to C_{ECMULT_CONST_GROUP_SIZE}(bits1, A), and analogously for pre_lam_a / bits2.
* This means that all we need to do is add these looked up values together, multiplied
* by 2^(ECMULT_GROUP_SIZE * group).
*/
for (group = ECMULT_CONST_GROUPS - 1; group >= 0; --group) {
/* Using the _var get_bits function is ok here, since it's only variable in offset and count, not in the scalar. */
unsigned int bits1 = secp256k1_scalar_get_bits_var(&v1, group * ECMULT_CONST_GROUP_SIZE, ECMULT_CONST_GROUP_SIZE);
unsigned int bits2 = secp256k1_scalar_get_bits_var(&v2, group * ECMULT_CONST_GROUP_SIZE, ECMULT_CONST_GROUP_SIZE);
secp256k1_ge t;
int j;
ECMULT_CONST_TABLE_GET_GE(&t, pre_a, bits1);
if (group == ECMULT_CONST_GROUPS - 1) {
/* Directly set r in the first iteration. */
secp256k1_gej_set_ge(r, &t);
} else {
/* Shift the result so far up. */
for (j = 0; j < ECMULT_CONST_GROUP_SIZE; ++j) {
secp256k1_gej_double(r, r);
}
secp256k1_gej_add_ge(r, r, &t);
}
ECMULT_CONST_TABLE_GET_GE(&t, pre_a_lam, bits2);
secp256k1_gej_add_ge(r, r, &t);
}
/* Map the result back to the secp256k1 curve from the isomorphic curve. */
secp256k1_fe_mul(&r->z, &r->z, &global_z);
}
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
* avoiding the square root in a random-basepoint x-only multiplication
* on a Weierstrass curve:
* https://mailarchive.ietf.org/arch/msg/cfrg/7DyYY6gg32wDgHAhgSb6XxMDlJA/
*
*
* === Background: the effective affine technique ===
*
* Let phi_u be the isomorphism that maps (x, y) on secp256k1 curve y^2 = x^3 + 7 to
* x' = u^2*x, y' = u^3*y on curve y'^2 = x'^3 + u^6*7. This new curve has the same order as
* the original (it is isomorphic), but moreover, has the same addition/doubling formulas, as
* the curve b=7 coefficient does not appear in those formulas (or at least does not appear in
* the formulas implemented in this codebase, both affine and Jacobian). See also Example 9.5.2
* in https://www.math.auckland.ac.nz/~sgal018/crypto-book/ch9.pdf.
*
* This means any linear combination of secp256k1 points can be computed by applying phi_u
* (with non-zero u) on all input points (including the generator, if used), computing the
* linear combination on the isomorphic curve (using the same group laws), and then applying
* phi_u^{-1} to get back to secp256k1.
*
* Switching to Jacobian coordinates, note that phi_u applied to (X, Y, Z) is simply
* (X, Y, Z/u). Thus, if we want to compute (X1, Y1, Z) + (X2, Y2, Z), with identical Z
* coordinates, we can use phi_Z to transform it to (X1, Y1, 1) + (X2, Y2, 1) on an isomorphic
* curve where the affine addition formula can be used instead.
* If (X3, Y3, Z3) = (X1, Y1) + (X2, Y2) on that curve, then our answer on secp256k1 is
* (X3, Y3, Z3*Z).
*
* This is the effective affine technique: if we have a linear combination of group elements
* to compute, and all those group elements have the same Z coordinate, we can simply pretend
* that all those Z coordinates are 1, perform the computation that way, and then multiply the
* original Z coordinate back in.
*
* The technique works on any a=0 short Weierstrass curve. It is possible to generalize it to
* other curves too, but there the isomorphic curves will have different 'a' coefficients,
* which typically does affect the group laws.
*
*
* === Avoiding the square root for x-only point multiplication ===
*
* In this function, we want to compute the X coordinate of q*(n/d, y), for
* y = sqrt((n/d)^3 + 7). Its negation would also be a valid Y coordinate, but by convention
* we pick whatever sqrt returns (which we assume to be a deterministic function).
*
* Let g = y^2*d^3 = n^3 + 7*d^3. This also means y = sqrt(g/d^3).
* Further let v = sqrt(d*g), which must exist as d*g = y^2*d^4 = (y*d^2)^2.
*
* The input point (n/d, y) also has Jacobian coordinates:
*
* (n/d, y, 1)
* = (n/d * v^2, y * v^3, v)
* = (n/d * d*g, y * sqrt(d^3*g^3), v)
* = (n/d * d*g, sqrt(y^2 * d^3*g^3), v)
* = (n*g, sqrt(g/d^3 * d^3*g^3), v)
* = (n*g, sqrt(g^4), v)
* = (n*g, g^2, v)
*
* It is easy to verify that both (n*g, g^2, v) and its negation (n*g, -g^2, v) have affine X
* coordinate n/d, and this holds even when the square root function doesn't have a
* deterministic sign. We choose the (n*g, g^2, v) version.
*
* Now switch to the effective affine curve using phi_v, where the input point has coordinates
* (n*g, g^2). Compute (X, Y, Z) = q * (n*g, g^2) there.
*
* Back on secp256k1, that means q * (n*g, g^2, v) = (X, Y, v*Z). This last point has affine X
* coordinate X / (v^2*Z^2) = X / (d*g*Z^2). Determining the affine Y coordinate would involve
* a square root, but as long as we only care about the resulting X coordinate, no square root
* is needed anywhere in this computation.
*/
secp256k1_fe g, i;
secp256k1_ge p;
secp256k1_gej rj;
/* Compute g = (n^3 + B*d^3). */
secp256k1_fe_sqr(&g, n);
secp256k1_fe_mul(&g, &g, n);
if (d) {
secp256k1_fe b;
VERIFY_CHECK(!secp256k1_fe_normalizes_to_zero(d));
secp256k1_fe_sqr(&b, d);
VERIFY_CHECK(SECP256K1_B <= 8); /* magnitude of b will be <= 8 after the next call */
secp256k1_fe_mul_int(&b, SECP256K1_B);
secp256k1_fe_mul(&b, &b, d);
secp256k1_fe_add(&g, &b);
if (!known_on_curve) {
/* We need to determine whether (n/d)^3 + 7 is square.
*
* is_square((n/d)^3 + 7)
* <=> is_square(((n/d)^3 + 7) * d^4)
* <=> is_square((n^3 + 7*d^3) * d)
* <=> is_square(g * d)
*/
secp256k1_fe c;
secp256k1_fe_mul(&c, &g, d);
if (!secp256k1_fe_is_square_var(&c)) return 0;
}
} else {
secp256k1_fe_add_int(&g, SECP256K1_B);
if (!known_on_curve) {
/* g at this point equals x^3 + 7. Test if it is square. */
if (!secp256k1_fe_is_square_var(&g)) return 0;
}
}
SECP256K1_FE_VERIFY_MAGNITUDE(&g, 2);
/* Compute base point P = (n*g, g^2), the effective affine version of
* (n*g, g^2, v), which has corresponding affine X coordinate n/d. */
{
secp256k1_fe x, y;
secp256k1_fe_mul(&x, &g, n);
secp256k1_fe_sqr(&y, &g);
secp256k1_ge_set_xy(&p, &x, &y);
}
/* Perform x-only EC multiplication of P with q. */
VERIFY_CHECK(!secp256k1_scalar_is_zero(q));
secp256k1_ecmult_const(&rj, &p, q);
VERIFY_CHECK(!secp256k1_gej_is_infinity(&rj));
/* The resulting (X, Y, Z) point on the effective-affine isomorphic curve corresponds to
* (X, Y, Z*v) on the secp256k1 curve. The affine version of that has X coordinate
* (X / (Z^2*d*g)). */
secp256k1_fe_sqr(&i, &rj.z);
secp256k1_fe_mul(&i, &i, &g);
if (d) secp256k1_fe_mul(&i, &i, d);
secp256k1_fe_inv(&i, &i);
secp256k1_fe_mul(r, &rj.x, &i);
return 1;
}
#endif /* SECP256K1_ECMULT_CONST_IMPL_H */

View File

@@ -0,0 +1,144 @@
/***********************************************************************
* Copyright (c) Pieter Wuille, Peter Dettman *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or https://www.opensource.org/licenses/mit-license.php.*
***********************************************************************/
#ifndef SECP256K1_ECMULT_GEN_H
#define SECP256K1_ECMULT_GEN_H
#include "hash.h"
#include "scalar.h"
#include "group.h"
/* Configuration parameters for the signed-digit multi-comb algorithm:
*
* - COMB_BLOCKS is the number of blocks the input is split into. Each
* has a corresponding table.
* - COMB_TEETH is the number of bits simultaneously covered by one table.
* - COMB_RANGE is the number of bits in supported scalars. For production
* purposes, only 256 is reasonable, but smaller numbers are supported for
* exhaustive test mode.
*
* The comb's spacing (COMB_SPACING), or the distance between the teeth,
* is defined as ceil(COMB_RANGE / (COMB_BLOCKS * COMB_TEETH)). Each block covers
* COMB_SPACING * COMB_TEETH consecutive bits in the input.
*
* The size of the precomputed table is COMB_BLOCKS * (1 << (COMB_TEETH - 1))
* secp256k1_ge_storages.
*
* The number of point additions equals COMB_BLOCKS * COMB_SPACING. Each point
* addition involves a cmov from (1 << (COMB_TEETH - 1)) table entries and a
* conditional negation.
*
* The number of point doublings is COMB_SPACING - 1. */
#if defined(EXHAUSTIVE_TEST_ORDER)
/* We need to control these values for exhaustive tests because
* the table cannot have infinities in them (secp256k1_ge_storage
* doesn't support infinities) */
# undef COMB_BLOCKS
# undef COMB_TEETH
# if EXHAUSTIVE_TEST_ORDER == 7
# define COMB_RANGE 3
# define COMB_BLOCKS 1
# define COMB_TEETH 2
# elif EXHAUSTIVE_TEST_ORDER == 13
# define COMB_RANGE 4
# define COMB_BLOCKS 1
# define COMB_TEETH 2
# elif EXHAUSTIVE_TEST_ORDER == 199
# define COMB_RANGE 8
# define COMB_BLOCKS 2
# define COMB_TEETH 3
# else
# error "Unknown exhaustive test order"
# endif
# if (COMB_RANGE >= 32) || ((EXHAUSTIVE_TEST_ORDER >> (COMB_RANGE - 1)) != 1)
# error "COMB_RANGE != ceil(log2(EXHAUSTIVE_TEST_ORDER+1))"
# endif
#else /* !defined(EXHAUSTIVE_TEST_ORDER) */
# define COMB_RANGE 256
#endif /* defined(EXHAUSTIVE_TEST_ORDER) */
/* Use (11, 6) as default configuration, which results in a 22 kB table. */
#ifndef COMB_BLOCKS
# define COMB_BLOCKS 11
# ifdef DEBUG_CONFIG
# pragma message DEBUG_CONFIG_MSG("COMB_BLOCKS undefined, assuming default value")
# endif
#endif
#ifndef COMB_TEETH
# define COMB_TEETH 6
# ifdef DEBUG_CONFIG
# pragma message DEBUG_CONFIG_MSG("COMB_TEETH undefined, assuming default value")
# endif
#endif
/* Use ceil(COMB_RANGE / (COMB_BLOCKS * COMB_TEETH)) as COMB_SPACING. */
#define COMB_SPACING CEIL_DIV(COMB_RANGE, COMB_BLOCKS * COMB_TEETH)
/* Range checks on the parameters. */
/* The remaining COMB_* parameters are derived values, don't modify these. */
/* - The number of bits covered by all the blocks; must be at least COMB_RANGE. */
#define COMB_BITS (COMB_BLOCKS * COMB_TEETH * COMB_SPACING)
/* - The number of entries per table. */
#define COMB_POINTS (1 << (COMB_TEETH - 1))
/* Sanity checks. */
#if !(1 <= COMB_BLOCKS && COMB_BLOCKS <= 256)
# error "COMB_BLOCKS must be in the range [1, 256]"
#endif
#if !(1 <= COMB_TEETH && COMB_TEETH <= 8)
# error "COMB_TEETH must be in the range [1, 8]"
#endif
#if COMB_BITS < COMB_RANGE
# error "COMB_BLOCKS * COMB_TEETH * COMB_SPACING is too low"
#endif
/* These last 2 checks are not strictly required, but prevent gratuitously inefficient
* configurations. Note that they compare with 256 rather than COMB_RANGE, so they do
* permit somewhat excessive values for the exhaustive test case, where testing with
* suboptimal parameters may be desirable. */
#if (COMB_BLOCKS - 1) * COMB_TEETH * COMB_SPACING >= 256
# error "COMB_BLOCKS can be reduced"
#endif
#if COMB_BLOCKS * (COMB_TEETH - 1) * COMB_SPACING >= 256
# error "COMB_TEETH can be reduced"
#endif
#ifdef DEBUG_CONFIG
# pragma message DEBUG_CONFIG_DEF(COMB_RANGE)
# pragma message DEBUG_CONFIG_DEF(COMB_BLOCKS)
# pragma message DEBUG_CONFIG_DEF(COMB_TEETH)
# pragma message DEBUG_CONFIG_DEF(COMB_SPACING)
#endif
typedef struct {
/* Whether the context has been built. */
int built;
/* Values chosen such that
*
* n*G == comb(n + scalar_offset, G/2) + ge_offset.
*
* This expression lets us use scalar blinding and optimize the comb precomputation. See
* ecmult_gen_impl.h for more details. */
secp256k1_scalar scalar_offset;
secp256k1_ge ge_offset;
/* Factor used for projective blinding. This value is used to rescale the Z
* coordinate of the first table lookup. */
secp256k1_fe proj_blind;
} secp256k1_ecmult_gen_context;
static void secp256k1_ecmult_gen_context_build(secp256k1_ecmult_gen_context* ctx, const secp256k1_hash_ctx *hash_ctx);
static void secp256k1_ecmult_gen_context_clear(secp256k1_ecmult_gen_context* ctx);
/** Multiply with the generator: R = a*G */
static void secp256k1_ecmult_gen(const secp256k1_ecmult_gen_context* ctx, secp256k1_gej *r, const secp256k1_scalar *a);
static void secp256k1_ecmult_gen_blind(secp256k1_ecmult_gen_context *ctx, const secp256k1_hash_ctx *hash_ctx, const unsigned char *seed32);
#endif /* SECP256K1_ECMULT_GEN_H */

View File

@@ -0,0 +1,14 @@
/***********************************************************************
* Copyright (c) Pieter Wuille, Gregory Maxwell *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or https://www.opensource.org/licenses/mit-license.php.*
***********************************************************************/
#ifndef SECP256K1_ECMULT_GEN_COMPUTE_TABLE_H
#define SECP256K1_ECMULT_GEN_COMPUTE_TABLE_H
#include "ecmult_gen.h"
static void secp256k1_ecmult_gen_compute_table(secp256k1_ge_storage* table, const secp256k1_ge* gen, int blocks, int teeth, int spacing);
#endif /* SECP256K1_ECMULT_GEN_COMPUTE_TABLE_H */

View File

@@ -0,0 +1,108 @@
/***********************************************************************
* Copyright (c) Pieter Wuille, Gregory Maxwell, Peter Dettman *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or https://www.opensource.org/licenses/mit-license.php.*
***********************************************************************/
#ifndef SECP256K1_ECMULT_GEN_COMPUTE_TABLE_IMPL_H
#define SECP256K1_ECMULT_GEN_COMPUTE_TABLE_IMPL_H
#include "ecmult_gen_compute_table.h"
#include "group_impl.h"
#include "field_impl.h"
#include "scalar_impl.h"
#include "ecmult_gen.h"
#include "util.h"
static void secp256k1_ecmult_gen_compute_table(secp256k1_ge_storage* table, const secp256k1_ge* gen, int blocks, int teeth, int spacing) {
size_t points = ((size_t)1) << (teeth - 1);
size_t points_total = points * blocks;
secp256k1_ge* prec = checked_malloc(&default_error_callback, points_total * sizeof(*prec));
secp256k1_gej* ds = checked_malloc(&default_error_callback, teeth * sizeof(*ds));
secp256k1_gej* vs = checked_malloc(&default_error_callback, points_total * sizeof(*vs));
secp256k1_gej u;
size_t vs_pos = 0;
secp256k1_scalar half;
int block, i;
VERIFY_CHECK(points_total > 0);
/* u is the running power of two times gen we're working with, initially gen/2. */
secp256k1_scalar_half(&half, &secp256k1_scalar_one);
secp256k1_gej_set_infinity(&u);
for (i = 255; i >= 0; --i) {
/* Use a very simple multiplication ladder to avoid dependency on ecmult. */
secp256k1_gej_double_var(&u, &u, NULL);
if (secp256k1_scalar_get_bits_limb32(&half, i, 1)) {
secp256k1_gej_add_ge_var(&u, &u, gen, NULL);
}
}
#ifdef VERIFY
{
/* Verify that u*2 = gen. */
secp256k1_gej double_u;
secp256k1_gej_double_var(&double_u, &u, NULL);
VERIFY_CHECK(secp256k1_gej_eq_ge_var(&double_u, gen));
}
#endif
for (block = 0; block < blocks; ++block) {
int tooth;
/* Here u = 2^(block*teeth*spacing) * gen/2. */
secp256k1_gej sum;
secp256k1_gej_set_infinity(&sum);
for (tooth = 0; tooth < teeth; ++tooth) {
/* Here u = 2^((block*teeth + tooth)*spacing) * gen/2. */
/* Make sum = sum(2^((block*teeth + t)*spacing), t=0..tooth) * gen/2. */
secp256k1_gej_add_var(&sum, &sum, &u, NULL);
/* Make u = 2^((block*teeth + tooth)*spacing + 1) * gen/2. */
secp256k1_gej_double_var(&u, &u, NULL);
/* Make ds[tooth] = u = 2^((block*teeth + tooth)*spacing + 1) * gen/2. */
ds[tooth] = u;
/* Make u = 2^((block*teeth + tooth + 1)*spacing) * gen/2, unless at the end. */
if (block + tooth != blocks + teeth - 2) {
int bit_off;
for (bit_off = 1; bit_off < spacing; ++bit_off) {
secp256k1_gej_double_var(&u, &u, NULL);
}
}
}
/* Now u = 2^((block*teeth + teeth)*spacing) * gen/2
* = 2^((block+1)*teeth*spacing) * gen/2 */
/* Next, compute the table entries for block number block in Jacobian coordinates.
* The entries will occupy vs[block*points + i] for i=0..points-1.
* We start by computing the first (i=0) value corresponding to all summed
* powers of two times G being negative. */
secp256k1_gej_neg(&vs[vs_pos++], &sum);
/* And then teeth-1 times "double" the range of i values for which the table
* is computed: in each iteration, double the table by taking an existing
* table entry and adding ds[tooth]. */
for (tooth = 0; tooth < teeth - 1; ++tooth) {
size_t stride = ((size_t)1) << tooth;
size_t index;
for (index = 0; index < stride; ++index, ++vs_pos) {
secp256k1_gej_add_var(&vs[vs_pos], &vs[vs_pos - stride], &ds[tooth], NULL);
}
}
}
VERIFY_CHECK(vs_pos == points_total);
/* Convert all points simultaneously from secp256k1_gej to secp256k1_ge. */
secp256k1_ge_set_all_gej_var(prec, vs, points_total);
/* Convert all points from secp256k1_ge to secp256k1_ge_storage output. */
for (block = 0; block < blocks; ++block) {
size_t index;
for (index = 0; index < points; ++index) {
VERIFY_CHECK(!secp256k1_ge_is_infinity(&prec[block * points + index]));
secp256k1_ge_to_storage(&table[block * points + index], &prec[block * points + index]);
}
}
/* Free memory. */
free(vs);
free(ds);
free(prec);
}
#endif /* SECP256K1_ECMULT_GEN_COMPUTE_TABLE_IMPL_H */

View File

@@ -0,0 +1,341 @@
/***********************************************************************
* Copyright (c) Pieter Wuille, Gregory Maxwell, Peter Dettman *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or https://www.opensource.org/licenses/mit-license.php.*
***********************************************************************/
#ifndef SECP256K1_ECMULT_GEN_IMPL_H
#define SECP256K1_ECMULT_GEN_IMPL_H
#include "util.h"
#include "scalar.h"
#include "group.h"
#include "ecmult_gen.h"
#include "hash_impl.h"
#include "precomputed_ecmult_gen.h"
static void secp256k1_ecmult_gen_context_build(secp256k1_ecmult_gen_context *ctx, const secp256k1_hash_ctx *hash_ctx) {
secp256k1_ecmult_gen_blind(ctx, hash_ctx, NULL);
ctx->built = 1;
}
static int secp256k1_ecmult_gen_context_is_built(const secp256k1_ecmult_gen_context* ctx) {
return ctx->built;
}
static void secp256k1_ecmult_gen_context_clear(secp256k1_ecmult_gen_context *ctx) {
ctx->built = 0;
secp256k1_scalar_clear(&ctx->scalar_offset);
secp256k1_ge_clear(&ctx->ge_offset);
secp256k1_fe_clear(&ctx->proj_blind);
}
/* Compute the scalar (2^COMB_BITS - 1) / 2, the difference between the gn argument to
* secp256k1_ecmult_gen, and the scalar whose encoding the table lookup bits are drawn
* from (before applying blinding). */
static void secp256k1_ecmult_gen_scalar_diff(secp256k1_scalar* diff) {
int i;
/* Compute scalar -1/2. */
secp256k1_scalar neghalf;
secp256k1_scalar_half(&neghalf, &secp256k1_scalar_one);
secp256k1_scalar_negate(&neghalf, &neghalf);
/* Compute offset = 2^(COMB_BITS - 1). */
*diff = secp256k1_scalar_one;
for (i = 0; i < COMB_BITS - 1; ++i) {
secp256k1_scalar_add(diff, diff, diff);
}
/* The result is the sum 2^(COMB_BITS - 1) + (-1/2). */
secp256k1_scalar_add(diff, diff, &neghalf);
}
static void secp256k1_ecmult_gen(const secp256k1_ecmult_gen_context *ctx, secp256k1_gej *r, const secp256k1_scalar *gn) {
uint32_t comb_off;
secp256k1_ge add;
secp256k1_fe neg;
secp256k1_ge_storage adds;
secp256k1_scalar d;
/* Array of uint32_t values large enough to store COMB_BITS bits. Only the bottom
* 8 are ever nonzero, but having the zero padding at the end if COMB_BITS>256
* avoids the need to deal with out-of-bounds reads from a scalar. */
uint32_t recoded[(COMB_BITS + 31) >> 5] = {0};
int first = 1, i;
memset(&adds, 0, sizeof(adds));
/* We want to compute R = gn*G.
*
* To blind the scalar used in the computation, we rewrite this to be
* R = (gn - b)*G + b*G, with a blinding value b determined by the context.
*
* The multiplication (gn-b)*G will be performed using a signed-digit multi-comb (see Section
* 3.3 of "Fast and compact elliptic-curve cryptography" by Mike Hamburg,
* https://eprint.iacr.org/2012/309).
*
* Let comb(s, P) = sum((2*s[i]-1)*2^i*P for i=0..COMB_BITS-1), where s[i] is the i'th bit of
* the binary representation of scalar s. So the s[i] values determine whether -2^i*P (s[i]=0)
* or +2^i*P (s[i]=1) are added together. COMB_BITS is at least 256, so all bits of s are
* covered. By manipulating:
*
* comb(s, P) = sum((2*s[i]-1)*2^i*P for i=0..COMB_BITS-1)
* <=> comb(s, P) = sum((2*s[i]-1)*2^i for i=0..COMB_BITS-1) * P
* <=> comb(s, P) = (2*sum(s[i]*2^i for i=0..COMB_BITS-1) - sum(2^i for i=0..COMB_BITS-1)) * P
* <=> comb(s, P) = (2*s - (2^COMB_BITS - 1)) * P
*
* If we wanted to compute (gn-b)*G as comb(s, G), it would need to hold that
*
* (gn - b) * G = (2*s - (2^COMB_BITS - 1)) * G
* <=> s = (gn - b + (2^COMB_BITS - 1))/2 (mod order)
*
* We use an alternative here that avoids the modular division by two: instead we compute
* (gn-b)*G as comb(d, G/2). For that to hold it must be the case that
*
* (gn - b) * G = (2*d - (2^COMB_BITS - 1)) * (G/2)
* <=> d = gn - b + (2^COMB_BITS - 1)/2 (mod order)
*
* Adding precomputation, our final equations become:
*
* ctx->scalar_offset = (2^COMB_BITS - 1)/2 - b (mod order)
* ctx->ge_offset = b*G
* d = gn + ctx->scalar_offset (mod order)
* R = comb(d, G/2) + ctx->ge_offset
*
* comb(d, G/2) function is then computed by summing + or - 2^(i-1)*G, for i=0..COMB_BITS-1,
* depending on the value of the bits d[i] of the binary representation of scalar d.
*/
/* Compute the scalar d = (gn + ctx->scalar_offset). */
secp256k1_scalar_add(&d, &ctx->scalar_offset, gn);
/* Convert to recoded array. */
for (i = 0; i < 8 && i < ((COMB_BITS + 31) >> 5); ++i) {
recoded[i] = secp256k1_scalar_get_bits_limb32(&d, 32 * i, 32);
}
secp256k1_scalar_clear(&d);
/* In secp256k1_ecmult_gen_prec_table we have precomputed sums of the
* (2*d[i]-1) * 2^(i-1) * G points, for various combinations of i positions.
* We rewrite our equation in terms of these table entries.
*
* Let mask(b) = sum(2^((b*COMB_TEETH + t)*COMB_SPACING) for t=0..COMB_TEETH-1),
* with b ranging from 0 to COMB_BLOCKS-1. So for example with COMB_BLOCKS=11,
* COMB_TEETH=6, COMB_SPACING=4, we would have:
* mask(0) = 2^0 + 2^4 + 2^8 + 2^12 + 2^16 + 2^20,
* mask(1) = 2^24 + 2^28 + 2^32 + 2^36 + 2^40 + 2^44,
* mask(2) = 2^48 + 2^52 + 2^56 + 2^60 + 2^64 + 2^68,
* ...
* mask(10) = 2^240 + 2^244 + 2^248 + 2^252 + 2^256 + 2^260
*
* We will split up the bits d[i] using these masks. Specifically, each mask is
* used COMB_SPACING times, with different shifts:
*
* d = (d & mask(0)<<0) + (d & mask(1)<<0) + ... + (d & mask(COMB_BLOCKS-1)<<0) +
* (d & mask(0)<<1) + (d & mask(1)<<1) + ... + (d & mask(COMB_BLOCKS-1)<<1) +
* ...
* (d & mask(0)<<(COMB_SPACING-1)) + ...
*
* Now define table(b, m) = (m - mask(b)/2) * G, and we will precompute these values for
* b=0..COMB_BLOCKS-1, and for all values m which (d & mask(b)) can take (so m can take on
* 2^COMB_TEETH distinct values).
*
* If m=(d & mask(b)), then table(b, m) is the sum of 2^i * (2*d[i]-1) * G/2, with i
* iterating over the set bits in mask(b). In our example, table(2, 2^48 + 2^56 + 2^68)
* would equal (2^48 - 2^52 + 2^56 - 2^60 - 2^64 + 2^68) * G/2.
*
* With that, we can rewrite comb(d, G/2) as:
*
* 2^0 * (table(0, d>>0 & mask(0)) + ... + table(COMB_BLOCKS-1, d>>0 & mask(COMP_BLOCKS-1)))
* + 2^1 * (table(0, d>>1 & mask(0)) + ... + table(COMB_BLOCKS-1, d>>1 & mask(COMP_BLOCKS-1)))
* + 2^2 * (table(0, d>>2 & mask(0)) + ... + table(COMB_BLOCKS-1, d>>2 & mask(COMP_BLOCKS-1)))
* + ...
* + 2^(COMB_SPACING-1) * (table(0, d>>(COMB_SPACING-1) & mask(0)) + ...)
*
* Or more generically as
*
* sum(2^i * sum(table(b, d>>i & mask(b)), b=0..COMB_BLOCKS-1), i=0..COMB_SPACING-1)
*
* This is implemented using an outer loop that runs in reverse order over the lines of this
* equation, which in each iteration runs an inner loop that adds the terms of that line and
* then doubles the result before proceeding to the next line.
*
* In pseudocode:
* c = infinity
* for comb_off in range(COMB_SPACING - 1, -1, -1):
* for block in range(COMB_BLOCKS):
* c += table(block, (d >> comb_off) & mask(block))
* if comb_off > 0:
* c = 2*c
* return c
*
* This computes c = comb(d, G/2), and thus finally R = c + ctx->ge_offset. Note that it would
* be possible to apply an initial offset instead of a final offset (moving ge_offset to take
* the place of infinity above), but the chosen approach allows using (in a future improvement)
* an incomplete addition formula for most of the multiplication.
*
* The last question is how to implement the table(b, m) function. For any value of b,
* m=(d & mask(b)) can only take on at most 2^COMB_TEETH possible values (the last one may have
* fewer as there mask(b) may exceed the curve order). So we could create COMB_BLOCK tables
* which contain a value for each such m value.
*
* Now note that if m=(d & mask(b)), then flipping the relevant bits of m results in negating
* the result of table(b, m). This is because table(b,m XOR mask(b)) = table(b, mask(b) - m) =
* (mask(b) - m - mask(b)/2)*G = (-m + mask(b)/2)*G = -(m - mask(b)/2)*G = -table(b, m).
* Because of this it suffices to only store the first half of the m values for every b. If an
* entry from the second half is needed, we look up its bit-flipped version instead, and negate
* it.
*
* secp256k1_ecmult_gen_prec_table[b][index] stores the table(b, m) entries. Index
* is the relevant mask(b) bits of m packed together without gaps. */
/* Outer loop: iterate over comb_off from COMB_SPACING - 1 down to 0. */
comb_off = COMB_SPACING - 1;
while (1) {
uint32_t block;
uint32_t bit_pos = comb_off;
/* Inner loop: for each block, add table entries to the result. */
for (block = 0; block < COMB_BLOCKS; ++block) {
/* Gather the mask(block)-selected bits of d into bits. They're packed:
* bits[tooth] = d[(block*COMB_TEETH + tooth)*COMB_SPACING + comb_off]. */
uint32_t bits = 0, sign, abs, index, tooth;
/* Instead of reading individual bits here to construct the bits variable,
* build up the result by xoring rotated reads together. In every iteration,
* one additional bit is made correct, starting at the bottom. The bits
* above that contain junk. This reduces leakage by avoiding computations
* on variables that can have only a low number of possible values (e.g.,
* just two values when reading a single bit into a variable.) See:
* https://www.usenix.org/system/files/conference/usenixsecurity18/sec18-alam.pdf
*/
for (tooth = 0; tooth < COMB_TEETH; ++tooth) {
/* Construct bitdata s.t. the bottom bit is the bit we'd like to read.
*
* We could just set bitdata = recoded[bit_pos >> 5] >> (bit_pos & 0x1f)
* but this would simply discard the bits that fall off at the bottom,
* and thus, for example, bitdata could still have only two values if we
* happen to shift by exactly 31 positions. We use a rotation instead,
* which ensures that bitdata doesn't lose entropy. This relies on the
* rotation being atomic, i.e., the compiler emitting an actual rot
* instruction. */
uint32_t bitdata = secp256k1_rotr32(recoded[bit_pos >> 5], bit_pos & 0x1f);
/* Clear the bit at position tooth, but sssh, don't tell clang. */
uint32_t volatile vmask = ~(1 << tooth);
bits &= vmask;
/* Write the bit into position tooth (and junk into higher bits). */
bits ^= bitdata << tooth;
bit_pos += COMB_SPACING;
}
/* If the top bit of bits is 1, flip them all (corresponding to looking up
* the negated table value), and remember to negate the result in sign. */
sign = (bits >> (COMB_TEETH - 1)) & 1;
abs = (bits ^ -sign) & (COMB_POINTS - 1);
VERIFY_CHECK(sign == 0 || sign == 1);
VERIFY_CHECK(abs < COMB_POINTS);
/** This uses a conditional move to avoid any secret data in array indexes.
* _Any_ use of secret indexes has been demonstrated to result in timing
* sidechannels, even when the cache-line access patterns are uniform.
* See also:
* "A word of warning", CHES 2013 Rump Session, by Daniel J. Bernstein and Peter Schwabe
* (https://cryptojedi.org/peter/data/chesrump-20130822.pdf) and
* "Cache Attacks and Countermeasures: the Case of AES", RSA 2006,
* by Dag Arne Osvik, Adi Shamir, and Eran Tromer
* (https://eprint.iacr.org/2005/271.pdf)
*/
for (index = 0; index < COMB_POINTS; ++index) {
secp256k1_ge_storage_cmov(&adds, &secp256k1_ecmult_gen_prec_table[block][index], index == abs);
}
/* Set add=adds or add=-adds, in constant time, based on sign. */
secp256k1_ge_from_storage(&add, &adds);
secp256k1_fe_negate(&neg, &add.y, 1);
secp256k1_fe_cmov(&add.y, &neg, sign);
/* Add the looked up and conditionally negated value to r. */
if (EXPECT(first, 0)) {
/* If this is the first table lookup, we can skip addition. */
secp256k1_gej_set_ge(r, &add);
/* Give the entry a random Z coordinate to blind intermediary results. */
secp256k1_gej_rescale(r, &ctx->proj_blind);
first = 0;
} else {
secp256k1_gej_add_ge(r, r, &add);
}
}
/* Double the result, except in the last iteration. */
if (comb_off-- == 0) break;
secp256k1_gej_double(r, r);
}
/* Correct for the scalar_offset added at the start (ge_offset = b*G, while b was
* subtracted from the input scalar gn). */
secp256k1_gej_add_ge(r, r, &ctx->ge_offset);
/* Cleanup. */
secp256k1_fe_clear(&neg);
secp256k1_ge_clear(&add);
secp256k1_memclear_explicit(&adds, sizeof(adds));
secp256k1_memclear_explicit(&recoded, sizeof(recoded));
}
/* Setup blinding values for secp256k1_ecmult_gen. */
static void secp256k1_ecmult_gen_blind(secp256k1_ecmult_gen_context *ctx, const secp256k1_hash_ctx *hash_ctx, const unsigned char *seed32) {
secp256k1_scalar b;
secp256k1_scalar diff;
secp256k1_gej gb;
secp256k1_fe f;
unsigned char nonce32[32];
secp256k1_rfc6979_hmac_sha256 rng;
unsigned char keydata[64];
/* Compute the (2^COMB_BITS - 1)/2 term once. */
secp256k1_ecmult_gen_scalar_diff(&diff);
if (seed32 == NULL) {
/* When seed is NULL, reset the final point and blinding value. */
secp256k1_ge_neg(&ctx->ge_offset, &secp256k1_ge_const_g);
secp256k1_scalar_add(&ctx->scalar_offset, &secp256k1_scalar_one, &diff);
ctx->proj_blind = secp256k1_fe_one;
return;
}
/* The prior blinding value (if not reset) is chained forward by including it in the hash. */
secp256k1_scalar_get_b32(keydata, &ctx->scalar_offset);
/** Using a CSPRNG allows a failure free interface, avoids needing large amounts of random data,
* and guards against weak or adversarial seeds. This is a simpler and safer interface than
* asking the caller for blinding values directly and expecting them to retry on failure.
*/
VERIFY_CHECK(seed32 != NULL);
memcpy(keydata + 32, seed32, 32);
secp256k1_rfc6979_hmac_sha256_initialize(hash_ctx, &rng, keydata, 64);
secp256k1_memclear_explicit(keydata, sizeof(keydata));
/* Compute projective blinding factor (cannot be 0). */
secp256k1_rfc6979_hmac_sha256_generate(hash_ctx, &rng, nonce32, 32);
secp256k1_fe_set_b32_mod(&f, nonce32);
secp256k1_fe_cmov(&f, &secp256k1_fe_one, secp256k1_fe_normalizes_to_zero(&f));
ctx->proj_blind = f;
/* For a random blinding value b, set scalar_offset=diff-b, ge_offset=bG */
secp256k1_rfc6979_hmac_sha256_generate(hash_ctx, &rng, nonce32, 32);
secp256k1_scalar_set_b32(&b, nonce32, NULL);
/* The blinding value cannot be zero, as that would mean ge_offset = infinity,
* which secp256k1_gej_add_ge cannot handle. */
secp256k1_scalar_cmov(&b, &secp256k1_scalar_one, secp256k1_scalar_is_zero(&b));
secp256k1_rfc6979_hmac_sha256_finalize(&rng);
secp256k1_ecmult_gen(ctx, &gb, &b);
secp256k1_scalar_negate(&b, &b);
secp256k1_scalar_add(&ctx->scalar_offset, &b, &diff);
secp256k1_ge_set_gej(&ctx->ge_offset, &gb);
/* Clean up. */
secp256k1_memclear_explicit(nonce32, sizeof(nonce32));
secp256k1_scalar_clear(&b);
secp256k1_gej_clear(&gb);
secp256k1_fe_clear(&f);
secp256k1_rfc6979_hmac_sha256_clear(&rng);
}
#endif /* SECP256K1_ECMULT_GEN_IMPL_H */

View File

@@ -0,0 +1,869 @@
/******************************************************************************
* Copyright (c) 2013, 2014, 2017 Pieter Wuille, Andrew Poelstra, Jonas Nick *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or https://www.opensource.org/licenses/mit-license.php. *
******************************************************************************/
#ifndef SECP256K1_ECMULT_IMPL_H
#define SECP256K1_ECMULT_IMPL_H
#include <string.h>
#include <stdint.h>
#include "util.h"
#include "group.h"
#include "scalar.h"
#include "ecmult.h"
#include "precomputed_ecmult.h"
#if defined(EXHAUSTIVE_TEST_ORDER)
/* We need to lower these values for exhaustive tests because
* the tables cannot have infinities in them (this breaks the
* affine-isomorphism stuff which tracks z-ratios) */
# if EXHAUSTIVE_TEST_ORDER > 128
# define WINDOW_A 5
# elif EXHAUSTIVE_TEST_ORDER > 8
# define WINDOW_A 4
# else
# define WINDOW_A 2
# endif
#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
#define WNAF_SIZE_BITS(bits, w) CEIL_DIV(bits, w)
#define WNAF_SIZE(w) WNAF_SIZE_BITS(WNAF_BITS, w)
/* The number of objects allocated on the scratch space for ecmult_multi algorithms */
#define PIPPENGER_SCRATCH_OBJECTS 6
#define STRAUSS_SCRATCH_OBJECTS 5
#define PIPPENGER_MAX_BUCKET_WINDOW 12
/* Minimum number of points for which pippenger_wnaf is faster than strauss wnaf */
#define ECMULT_PIPPENGER_THRESHOLD 88
#define ECMULT_MAX_POINTS_PER_BATCH 5000000
/** Fill a table 'pre_a' with precomputed odd multiples of a.
* pre_a will contain [1*a,3*a,...,(2*n-1)*a], so it needs space for n group elements.
* zr needs space for n field elements.
*
* Although pre_a is an array of _ge rather than _gej, it actually represents elements
* in Jacobian coordinates with their z coordinates omitted. The omitted z-coordinates
* can be recovered using z and zr. Using the notation z(b) to represent the omitted
* z coordinate of b:
* - z(pre_a[n-1]) = 'z'
* - z(pre_a[i-1]) = z(pre_a[i]) / zr[i] for n > i > 0
*
* Lastly the zr[0] value, which isn't used above, is set so that:
* - a.z = z(pre_a[0]) / zr[0]
*/
static void secp256k1_ecmult_odd_multiples_table(size_t n, secp256k1_ge *pre_a, secp256k1_fe *zr, secp256k1_fe *z, const secp256k1_gej *a) {
secp256k1_gej d, ai;
secp256k1_ge d_ge;
size_t i;
VERIFY_CHECK(!secp256k1_gej_is_infinity(a));
secp256k1_gej_double_var(&d, a, NULL);
/*
* Perform the additions using an isomorphic curve Y^2 = X^3 + 7*C^6 where C := d.z.
* The isomorphism, phi, maps a secp256k1 point (x, y) to the point (x*C^2, y*C^3) on the other curve.
* In Jacobian coordinates phi maps (x, y, z) to (x*C^2, y*C^3, z) or, equivalently to (x, y, z/C).
*
* phi(x, y, z) = (x*C^2, y*C^3, z) = (x, y, z/C)
* d_ge := phi(d) = (d.x, d.y, 1)
* ai := phi(a) = (a.x*C^2, a.y*C^3, a.z)
*
* The group addition functions work correctly on these isomorphic curves.
* In particular phi(d) is easy to represent in affine coordinates under this isomorphism.
* This lets us use the faster secp256k1_gej_add_ge_var group addition function that we wouldn't be able to use otherwise.
*/
secp256k1_ge_set_xy(&d_ge, &d.x, &d.y);
secp256k1_ge_set_gej_zinv(&pre_a[0], a, &d.z);
secp256k1_gej_set_ge(&ai, &pre_a[0]);
ai.z = a->z;
/* pre_a[0] is the point (a.x*C^2, a.y*C^3, a.z*C) which is equivalent to a.
* Set zr[0] to C, which is the ratio between the omitted z(pre_a[0]) value and a.z.
*/
zr[0] = d.z;
for (i = 1; i < n; i++) {
secp256k1_gej_add_ge_var(&ai, &ai, &d_ge, &zr[i]);
secp256k1_ge_set_xy(&pre_a[i], &ai.x, &ai.y);
}
/* Multiply the last z-coordinate by C to undo the isomorphism.
* Since the z-coordinates of the pre_a values are implied by the zr array of z-coordinate ratios,
* undoing the isomorphism here undoes the isomorphism for all pre_a values.
*/
secp256k1_fe_mul(z, &ai.z, &d.z);
}
SECP256K1_INLINE static void secp256k1_ecmult_table_verify(int n, int w) {
(void)n;
(void)w;
VERIFY_CHECK(((n) & 1) == 1);
VERIFY_CHECK((n) >= -((1 << ((w)-1)) - 1));
VERIFY_CHECK((n) <= ((1 << ((w)-1)) - 1));
}
SECP256K1_INLINE static void secp256k1_ecmult_table_get_ge(secp256k1_ge *r, const secp256k1_ge *pre, int n, int w) {
secp256k1_ecmult_table_verify(n,w);
if (n > 0) {
*r = pre[(n-1)/2];
} else {
*r = pre[(-n-1)/2];
secp256k1_fe_negate(&(r->y), &(r->y), 1);
}
}
SECP256K1_INLINE static void secp256k1_ecmult_table_get_ge_lambda(secp256k1_ge *r, const secp256k1_ge *pre, const secp256k1_fe *x, int n, int w) {
secp256k1_ecmult_table_verify(n,w);
if (n > 0) {
secp256k1_ge_set_xy(r, &x[(n-1)/2], &pre[(n-1)/2].y);
} else {
secp256k1_ge_set_xy(r, &x[(-n-1)/2], &pre[(-n-1)/2].y);
secp256k1_fe_negate(&(r->y), &(r->y), 1);
}
}
SECP256K1_INLINE static void secp256k1_ecmult_table_get_ge_storage(secp256k1_ge *r, const secp256k1_ge_storage *pre, int n, int w) {
secp256k1_ecmult_table_verify(n,w);
if (n > 0) {
secp256k1_ge_from_storage(r, &pre[(n-1)/2]);
} else {
secp256k1_ge_from_storage(r, &pre[(-n-1)/2]);
secp256k1_fe_negate(&(r->y), &(r->y), 1);
}
}
/** Convert a number to WNAF notation. The number becomes represented by sum(2^i * wnaf[i], i=0..bits),
* with the following guarantees:
* - each wnaf[i] is either 0, or an odd integer between -(1<<(w-1) - 1) and (1<<(w-1) - 1)
* - two non-zero entries in wnaf are separated by at least w-1 zeroes.
* - the number of set values in wnaf is returned. This number is at most 256, and at most one more
* than the number of bits in the (absolute value) of the input.
*/
static int secp256k1_ecmult_wnaf(int *wnaf, int len, const secp256k1_scalar *a, int w) {
secp256k1_scalar s;
int last_set_bit = -1;
int bit = 0;
int sign = 1;
int carry = 0;
VERIFY_CHECK(wnaf != NULL);
VERIFY_CHECK(0 <= len && len <= 256);
VERIFY_CHECK(a != NULL);
VERIFY_CHECK(2 <= w && w <= 31);
for (bit = 0; bit < len; bit++) {
wnaf[bit] = 0;
}
s = *a;
if (secp256k1_scalar_get_bits_limb32(&s, 255, 1)) {
secp256k1_scalar_negate(&s, &s);
sign = -1;
}
bit = 0;
while (bit < len) {
int now;
int word;
if (secp256k1_scalar_get_bits_limb32(&s, bit, 1) == (unsigned int)carry) {
bit++;
continue;
}
now = w;
if (now > len - bit) {
now = len - bit;
}
word = secp256k1_scalar_get_bits_var(&s, bit, now) + carry;
carry = (word >> (w-1)) & 1;
word -= carry << w;
wnaf[bit] = sign * word;
last_set_bit = bit;
bit += now;
}
#ifdef VERIFY
{
int verify_bit = bit;
VERIFY_CHECK(carry == 0);
while (verify_bit < 256) {
VERIFY_CHECK(secp256k1_scalar_get_bits_limb32(&s, verify_bit, 1) == 0);
verify_bit++;
}
}
#endif
return last_set_bit + 1;
}
/* Same as secp256k1_ecmult_wnaf, but stores to int8_t array. Requires w <= 8. */
static int secp256k1_ecmult_wnaf_small(int8_t *wnaf, int len, const secp256k1_scalar *a, int w) {
int wnaf_tmp[256];
int ret, i;
VERIFY_CHECK(2 <= w && w <= 8);
ret = secp256k1_ecmult_wnaf(wnaf_tmp, len, a, w);
for (i = 0; i < len; i++) {
wnaf[i] = (int8_t)wnaf_tmp[i];
}
return ret;
}
struct secp256k1_strauss_point_state {
int8_t wnaf_na_1[129];
int8_t wnaf_na_lam[129];
int bits_na_1;
int bits_na_lam;
};
struct secp256k1_strauss_state {
/* aux is used to hold z-ratios, and then used to hold pre_a[i].x * BETA values. */
secp256k1_fe* aux;
secp256k1_ge* pre_a;
struct secp256k1_strauss_point_state* ps;
};
static void secp256k1_ecmult_strauss_wnaf(const struct secp256k1_strauss_state *state, secp256k1_gej *r, size_t num, const secp256k1_gej *a, const secp256k1_scalar *na, const secp256k1_scalar *ng) {
secp256k1_ge tmpa;
secp256k1_fe Z;
/* Split G factors. */
secp256k1_scalar ng_1, ng_128;
int wnaf_ng_1[129];
int bits_ng_1 = 0;
int wnaf_ng_128[129];
int bits_ng_128 = 0;
int i;
int bits = 0;
size_t np;
size_t no = 0;
secp256k1_fe_set_int(&Z, 1);
for (np = 0; np < num; ++np) {
secp256k1_gej tmp;
secp256k1_scalar na_1, na_lam;
if (secp256k1_scalar_is_zero(&na[np]) || secp256k1_gej_is_infinity(&a[np])) {
continue;
}
/* split na into na_1 and na_lam (where na = na_1 + na_lam*lambda, and na_1 and na_lam are ~128 bit) */
secp256k1_scalar_split_lambda(&na_1, &na_lam, &na[np]);
/* build wnaf representation for na_1 and na_lam. */
state->ps[no].bits_na_1 = secp256k1_ecmult_wnaf_small(state->ps[no].wnaf_na_1, 129, &na_1, WINDOW_A);
state->ps[no].bits_na_lam = secp256k1_ecmult_wnaf_small(state->ps[no].wnaf_na_lam, 129, &na_lam, WINDOW_A);
VERIFY_CHECK(state->ps[no].bits_na_1 <= 129);
VERIFY_CHECK(state->ps[no].bits_na_lam <= 129);
if (state->ps[no].bits_na_1 > bits) {
bits = state->ps[no].bits_na_1;
}
if (state->ps[no].bits_na_lam > bits) {
bits = state->ps[no].bits_na_lam;
}
/* Calculate odd multiples of a.
* All multiples are brought to the same Z 'denominator', which is stored
* in Z. Due to secp256k1' isomorphism we can do all operations pretending
* that the Z coordinate was 1, use affine addition formulae, and correct
* the Z coordinate of the result once at the end.
* The exception is the precomputed G table points, which are actually
* affine. Compared to the base used for other points, they have a Z ratio
* of 1/Z, so we can use secp256k1_gej_add_zinv_var, which uses the same
* isomorphism to efficiently add with a known Z inverse.
*/
tmp = a[np];
if (no) {
secp256k1_gej_rescale(&tmp, &Z);
}
secp256k1_ecmult_odd_multiples_table(ECMULT_TABLE_SIZE(WINDOW_A), state->pre_a + no * ECMULT_TABLE_SIZE(WINDOW_A), state->aux + no * ECMULT_TABLE_SIZE(WINDOW_A), &Z, &tmp);
if (no) secp256k1_fe_mul(state->aux + no * ECMULT_TABLE_SIZE(WINDOW_A), state->aux + no * ECMULT_TABLE_SIZE(WINDOW_A), &(a[np].z));
++no;
}
/* Bring them to the same Z denominator. */
if (no) {
secp256k1_ge_table_set_globalz(ECMULT_TABLE_SIZE(WINDOW_A) * no, state->pre_a, state->aux);
}
for (np = 0; np < no; ++np) {
size_t j;
for (j = 0; j < ECMULT_TABLE_SIZE(WINDOW_A); j++) {
secp256k1_fe_mul(&state->aux[np * ECMULT_TABLE_SIZE(WINDOW_A) + j], &state->pre_a[np * ECMULT_TABLE_SIZE(WINDOW_A) + j].x, &secp256k1_const_beta);
}
}
if (ng) {
/* split ng into ng_1 and ng_128 (where gn = gn_1 + gn_128*2^128, and gn_1 and gn_128 are ~128 bit) */
secp256k1_scalar_split_128(&ng_1, &ng_128, ng);
/* Build wnaf representation for ng_1 and ng_128 */
bits_ng_1 = secp256k1_ecmult_wnaf(wnaf_ng_1, 129, &ng_1, WINDOW_G);
bits_ng_128 = secp256k1_ecmult_wnaf(wnaf_ng_128, 129, &ng_128, WINDOW_G);
if (bits_ng_1 > bits) {
bits = bits_ng_1;
}
if (bits_ng_128 > bits) {
bits = bits_ng_128;
}
}
secp256k1_gej_set_infinity(r);
for (i = bits - 1; i >= 0; i--) {
int n;
secp256k1_gej_double_var(r, r, NULL);
for (np = 0; np < no; ++np) {
if (i < state->ps[np].bits_na_1 && (n = state->ps[np].wnaf_na_1[i])) {
secp256k1_ecmult_table_get_ge(&tmpa, state->pre_a + np * ECMULT_TABLE_SIZE(WINDOW_A), n, WINDOW_A);
secp256k1_gej_add_ge_var(r, r, &tmpa, NULL);
}
if (i < state->ps[np].bits_na_lam && (n = state->ps[np].wnaf_na_lam[i])) {
secp256k1_ecmult_table_get_ge_lambda(&tmpa, state->pre_a + np * ECMULT_TABLE_SIZE(WINDOW_A), state->aux + np * ECMULT_TABLE_SIZE(WINDOW_A), n, WINDOW_A);
secp256k1_gej_add_ge_var(r, r, &tmpa, NULL);
}
}
if (i < bits_ng_1 && (n = wnaf_ng_1[i])) {
secp256k1_ecmult_table_get_ge_storage(&tmpa, secp256k1_pre_g, n, WINDOW_G);
secp256k1_gej_add_zinv_var(r, r, &tmpa, &Z);
}
if (i < bits_ng_128 && (n = wnaf_ng_128[i])) {
secp256k1_ecmult_table_get_ge_storage(&tmpa, secp256k1_pre_g_128, n, WINDOW_G);
secp256k1_gej_add_zinv_var(r, r, &tmpa, &Z);
}
}
if (!secp256k1_gej_is_infinity(r)) {
secp256k1_fe_mul(&r->z, &r->z, &Z);
}
}
static void secp256k1_ecmult(secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_scalar *na, const secp256k1_scalar *ng) {
secp256k1_fe aux[ECMULT_TABLE_SIZE(WINDOW_A)];
secp256k1_ge pre_a[ECMULT_TABLE_SIZE(WINDOW_A)];
struct secp256k1_strauss_point_state ps[1];
struct secp256k1_strauss_state state;
state.aux = aux;
state.pre_a = pre_a;
state.ps = ps;
secp256k1_ecmult_strauss_wnaf(&state, r, 1, a, na, ng);
}
static size_t secp256k1_strauss_scratch_size(size_t n_points) {
static const size_t point_size = (sizeof(secp256k1_ge) + sizeof(secp256k1_fe)) * ECMULT_TABLE_SIZE(WINDOW_A) + sizeof(struct secp256k1_strauss_point_state) + sizeof(secp256k1_gej) + sizeof(secp256k1_scalar);
return n_points*point_size;
}
static int secp256k1_ecmult_strauss_batch(const secp256k1_callback* error_callback, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n_points, size_t cb_offset) {
secp256k1_gej* points;
secp256k1_scalar* scalars;
struct secp256k1_strauss_state state;
size_t i;
const size_t scratch_checkpoint = secp256k1_scratch_checkpoint(error_callback, scratch);
secp256k1_gej_set_infinity(r);
if (inp_g_sc == NULL && n_points == 0) {
return 1;
}
/* We allocate STRAUSS_SCRATCH_OBJECTS objects on the scratch space. If these
* allocations change, make sure to update the STRAUSS_SCRATCH_OBJECTS
* constant and strauss_scratch_size accordingly. */
points = (secp256k1_gej*)secp256k1_scratch_alloc(error_callback, scratch, n_points * sizeof(secp256k1_gej));
scalars = (secp256k1_scalar*)secp256k1_scratch_alloc(error_callback, scratch, n_points * sizeof(secp256k1_scalar));
state.aux = (secp256k1_fe*)secp256k1_scratch_alloc(error_callback, scratch, n_points * ECMULT_TABLE_SIZE(WINDOW_A) * sizeof(secp256k1_fe));
state.pre_a = (secp256k1_ge*)secp256k1_scratch_alloc(error_callback, scratch, n_points * ECMULT_TABLE_SIZE(WINDOW_A) * sizeof(secp256k1_ge));
state.ps = (struct secp256k1_strauss_point_state*)secp256k1_scratch_alloc(error_callback, scratch, n_points * sizeof(struct secp256k1_strauss_point_state));
if (points == NULL || scalars == NULL || state.aux == NULL || state.pre_a == NULL || state.ps == NULL) {
secp256k1_scratch_apply_checkpoint(error_callback, scratch, scratch_checkpoint);
return 0;
}
for (i = 0; i < n_points; i++) {
secp256k1_ge point;
if (!cb(&scalars[i], &point, i+cb_offset, cbdata)) {
secp256k1_scratch_apply_checkpoint(error_callback, scratch, scratch_checkpoint);
return 0;
}
secp256k1_gej_set_ge(&points[i], &point);
}
secp256k1_ecmult_strauss_wnaf(&state, r, n_points, points, scalars, inp_g_sc);
secp256k1_scratch_apply_checkpoint(error_callback, scratch, scratch_checkpoint);
return 1;
}
/* Wrapper for secp256k1_ecmult_multi_func interface */
static int secp256k1_ecmult_strauss_batch_single(const secp256k1_callback* error_callback, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n) {
return secp256k1_ecmult_strauss_batch(error_callback, scratch, r, inp_g_sc, cb, cbdata, n, 0);
}
static size_t secp256k1_strauss_max_points(const secp256k1_callback* error_callback, secp256k1_scratch *scratch) {
return secp256k1_scratch_max_allocation(error_callback, scratch, STRAUSS_SCRATCH_OBJECTS) / secp256k1_strauss_scratch_size(1);
}
/** Convert a number to WNAF notation.
* The number becomes represented by sum(2^{wi} * wnaf[i], i=0..WNAF_SIZE(w)+1) - return_val.
* It has the following guarantees:
* - each wnaf[i] is either 0 or an odd integer between -(1 << w) and (1 << w)
* - the number of words set is always WNAF_SIZE(w)
* - the returned skew is 0 or 1
*/
static int secp256k1_wnaf_fixed(int *wnaf, const secp256k1_scalar *s, int w) {
int skew = 0;
int pos;
int max_pos;
int last_w;
const secp256k1_scalar *work = s;
if (secp256k1_scalar_is_zero(s)) {
for (pos = 0; pos < WNAF_SIZE(w); pos++) {
wnaf[pos] = 0;
}
return 0;
}
if (secp256k1_scalar_is_even(s)) {
skew = 1;
}
wnaf[0] = secp256k1_scalar_get_bits_var(work, 0, w) + skew;
/* Compute last window size. Relevant when window size doesn't divide the
* number of bits in the scalar */
last_w = WNAF_BITS - (WNAF_SIZE(w) - 1) * w;
/* Store the position of the first nonzero word in max_pos to allow
* skipping leading zeros when calculating the wnaf. */
for (pos = WNAF_SIZE(w) - 1; pos > 0; pos--) {
int val = secp256k1_scalar_get_bits_var(work, pos * w, pos == WNAF_SIZE(w)-1 ? last_w : w);
if(val != 0) {
break;
}
wnaf[pos] = 0;
}
max_pos = pos;
pos = 1;
while (pos <= max_pos) {
int val = secp256k1_scalar_get_bits_var(work, pos * w, pos == WNAF_SIZE(w)-1 ? last_w : w);
if ((val & 1) == 0) {
wnaf[pos - 1] -= (1 << w);
wnaf[pos] = (val + 1);
} else {
wnaf[pos] = val;
}
/* Set a coefficient to zero if it is 1 or -1 and the proceeding digit
* is strictly negative or strictly positive respectively. Only change
* coefficients at previous positions because above code assumes that
* wnaf[pos - 1] is odd.
*/
if (pos >= 2 && ((wnaf[pos - 1] == 1 && wnaf[pos - 2] < 0) || (wnaf[pos - 1] == -1 && wnaf[pos - 2] > 0))) {
if (wnaf[pos - 1] == 1) {
wnaf[pos - 2] += 1 << w;
} else {
wnaf[pos - 2] -= 1 << w;
}
wnaf[pos - 1] = 0;
}
++pos;
}
return skew;
}
struct secp256k1_pippenger_point_state {
int skew_na;
size_t input_pos;
};
struct secp256k1_pippenger_state {
int *wnaf_na;
struct secp256k1_pippenger_point_state* ps;
};
/*
* pippenger_wnaf computes the result of a multi-point multiplication as
* follows: The scalars are brought into wnaf with n_wnaf elements each. Then
* for every i < n_wnaf, first each point is added to a "bucket" corresponding
* to the point's wnaf[i]. Second, the buckets are added together such that
* r += 1*bucket[0] + 3*bucket[1] + 5*bucket[2] + ...
*/
static int secp256k1_ecmult_pippenger_wnaf(secp256k1_gej *buckets, int bucket_window, struct secp256k1_pippenger_state *state, secp256k1_gej *r, const secp256k1_scalar *sc, const secp256k1_ge *pt, size_t num) {
size_t n_wnaf = WNAF_SIZE(bucket_window+1);
size_t np;
size_t no = 0;
int i;
for (np = 0; np < num; ++np) {
if (secp256k1_scalar_is_zero(&sc[np]) || secp256k1_ge_is_infinity(&pt[np])) {
continue;
}
state->ps[no].input_pos = np;
state->ps[no].skew_na = secp256k1_wnaf_fixed(&state->wnaf_na[no*n_wnaf], &sc[np], bucket_window+1);
no++;
}
secp256k1_gej_set_infinity(r);
if (no == 0) {
return 1;
}
for (i = n_wnaf - 1; i >= 0; i--) {
secp256k1_gej running_sum;
int j;
size_t buc;
for (buc = 0; buc < ECMULT_TABLE_SIZE(bucket_window+2); buc++) {
secp256k1_gej_set_infinity(&buckets[buc]);
}
for (np = 0; np < no; ++np) {
int n = state->wnaf_na[np*n_wnaf + i];
struct secp256k1_pippenger_point_state point_state = state->ps[np];
secp256k1_ge tmp;
if (i == 0) {
/* correct for wnaf skew */
int skew = point_state.skew_na;
if (skew) {
secp256k1_ge_neg(&tmp, &pt[point_state.input_pos]);
secp256k1_gej_add_ge_var(&buckets[0], &buckets[0], &tmp, NULL);
}
}
if (n > 0) {
buc = (n - 1)/2;
secp256k1_gej_add_ge_var(&buckets[buc], &buckets[buc], &pt[point_state.input_pos], NULL);
} else if (n < 0) {
buc = -(n + 1)/2;
secp256k1_ge_neg(&tmp, &pt[point_state.input_pos]);
secp256k1_gej_add_ge_var(&buckets[buc], &buckets[buc], &tmp, NULL);
}
}
for (j = 0; j < bucket_window; j++) {
secp256k1_gej_double_var(r, r, NULL);
}
secp256k1_gej_set_infinity(&running_sum);
/* Accumulate the sum: bucket[0] + 3*bucket[1] + 5*bucket[2] + 7*bucket[3] + ...
* = bucket[0] + bucket[1] + bucket[2] + bucket[3] + ...
* + 2 * (bucket[1] + 2*bucket[2] + 3*bucket[3] + ...)
* using an intermediate running sum:
* running_sum = bucket[0] + bucket[1] + bucket[2] + ...
*
* The doubling is done implicitly by deferring the final window doubling (of 'r').
*/
for (buc = ECMULT_TABLE_SIZE(bucket_window+2) - 1; buc > 0; buc--) {
secp256k1_gej_add_var(&running_sum, &running_sum, &buckets[buc], NULL);
secp256k1_gej_add_var(r, r, &running_sum, NULL);
}
secp256k1_gej_add_var(&running_sum, &running_sum, &buckets[0], NULL);
secp256k1_gej_double_var(r, r, NULL);
secp256k1_gej_add_var(r, r, &running_sum, NULL);
}
return 1;
}
/**
* Returns optimal bucket_window (number of bits of a scalar represented by a
* set of buckets) for a given number of points.
*/
static int secp256k1_pippenger_bucket_window(size_t n) {
if (n <= 1) {
return 1;
} else if (n <= 4) {
return 2;
} else if (n <= 20) {
return 3;
} else if (n <= 57) {
return 4;
} else if (n <= 136) {
return 5;
} else if (n <= 235) {
return 6;
} else if (n <= 1260) {
return 7;
} else if (n <= 4420) {
return 9;
} else if (n <= 7880) {
return 10;
} else if (n <= 16050) {
return 11;
} else {
return PIPPENGER_MAX_BUCKET_WINDOW;
}
}
/**
* Returns the maximum optimal number of points for a bucket_window.
*/
static size_t secp256k1_pippenger_bucket_window_inv(int bucket_window) {
switch(bucket_window) {
case 1: return 1;
case 2: return 4;
case 3: return 20;
case 4: return 57;
case 5: return 136;
case 6: return 235;
case 7: return 1260;
case 8: return 1260;
case 9: return 4420;
case 10: return 7880;
case 11: return 16050;
case PIPPENGER_MAX_BUCKET_WINDOW: return SIZE_MAX;
}
return 0;
}
SECP256K1_INLINE static void secp256k1_ecmult_endo_split(secp256k1_scalar *s1, secp256k1_scalar *s2, secp256k1_ge *p1, secp256k1_ge *p2) {
secp256k1_scalar tmp = *s1;
secp256k1_scalar_split_lambda(s1, s2, &tmp);
secp256k1_ge_mul_lambda(p2, p1);
if (secp256k1_scalar_is_high(s1)) {
secp256k1_scalar_negate(s1, s1);
secp256k1_ge_neg(p1, p1);
}
if (secp256k1_scalar_is_high(s2)) {
secp256k1_scalar_negate(s2, s2);
secp256k1_ge_neg(p2, p2);
}
}
/**
* Returns the scratch size required for a given number of points (excluding
* base point G) without considering alignment.
*/
static size_t secp256k1_pippenger_scratch_size(size_t n_points, int bucket_window) {
size_t entries = 2*n_points + 2;
size_t entry_size = sizeof(secp256k1_ge) + sizeof(secp256k1_scalar) + sizeof(struct secp256k1_pippenger_point_state) + (WNAF_SIZE(bucket_window+1)+1)*sizeof(int);
return (sizeof(secp256k1_gej) << bucket_window) + sizeof(struct secp256k1_pippenger_state) + entries * entry_size;
}
static int secp256k1_ecmult_pippenger_batch(const secp256k1_callback* error_callback, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n_points, size_t cb_offset) {
const size_t scratch_checkpoint = secp256k1_scratch_checkpoint(error_callback, scratch);
/* Use 2(n+1) with the endomorphism, when calculating batch
* sizes. The reason for +1 is that we add the G scalar to the list of
* other scalars. */
size_t entries = 2*n_points + 2;
secp256k1_ge *points;
secp256k1_scalar *scalars;
secp256k1_gej *buckets;
struct secp256k1_pippenger_state *state_space;
size_t idx = 0;
size_t point_idx = 0;
int bucket_window;
secp256k1_gej_set_infinity(r);
if (inp_g_sc == NULL && n_points == 0) {
return 1;
}
bucket_window = secp256k1_pippenger_bucket_window(n_points);
/* We allocate PIPPENGER_SCRATCH_OBJECTS objects on the scratch space. If
* these allocations change, make sure to update the
* PIPPENGER_SCRATCH_OBJECTS constant and pippenger_scratch_size
* accordingly. */
points = (secp256k1_ge *) secp256k1_scratch_alloc(error_callback, scratch, entries * sizeof(*points));
scalars = (secp256k1_scalar *) secp256k1_scratch_alloc(error_callback, scratch, entries * sizeof(*scalars));
state_space = (struct secp256k1_pippenger_state *) secp256k1_scratch_alloc(error_callback, scratch, sizeof(*state_space));
if (points == NULL || scalars == NULL || state_space == NULL) {
secp256k1_scratch_apply_checkpoint(error_callback, scratch, scratch_checkpoint);
return 0;
}
state_space->ps = (struct secp256k1_pippenger_point_state *) secp256k1_scratch_alloc(error_callback, scratch, entries * sizeof(*state_space->ps));
state_space->wnaf_na = (int *) secp256k1_scratch_alloc(error_callback, scratch, entries*(WNAF_SIZE(bucket_window+1)) * sizeof(int));
buckets = (secp256k1_gej *) secp256k1_scratch_alloc(error_callback, scratch, ((size_t)1 << bucket_window) * sizeof(*buckets));
if (state_space->ps == NULL || state_space->wnaf_na == NULL || buckets == NULL) {
secp256k1_scratch_apply_checkpoint(error_callback, scratch, scratch_checkpoint);
return 0;
}
if (inp_g_sc != NULL) {
scalars[0] = *inp_g_sc;
points[0] = secp256k1_ge_const_g;
idx++;
secp256k1_ecmult_endo_split(&scalars[0], &scalars[1], &points[0], &points[1]);
idx++;
}
while (point_idx < n_points) {
if (!cb(&scalars[idx], &points[idx], point_idx + cb_offset, cbdata)) {
secp256k1_scratch_apply_checkpoint(error_callback, scratch, scratch_checkpoint);
return 0;
}
idx++;
secp256k1_ecmult_endo_split(&scalars[idx - 1], &scalars[idx], &points[idx - 1], &points[idx]);
idx++;
point_idx++;
}
secp256k1_ecmult_pippenger_wnaf(buckets, bucket_window, state_space, r, scalars, points, idx);
secp256k1_scratch_apply_checkpoint(error_callback, scratch, scratch_checkpoint);
return 1;
}
/* Wrapper for secp256k1_ecmult_multi_func interface */
static int secp256k1_ecmult_pippenger_batch_single(const secp256k1_callback* error_callback, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n) {
return secp256k1_ecmult_pippenger_batch(error_callback, scratch, r, inp_g_sc, cb, cbdata, n, 0);
}
/**
* Returns the maximum number of points in addition to G that can be used with
* a given scratch space. The function ensures that fewer points may also be
* used.
*/
static size_t secp256k1_pippenger_max_points(const secp256k1_callback* error_callback, secp256k1_scratch *scratch) {
size_t max_alloc = secp256k1_scratch_max_allocation(error_callback, scratch, PIPPENGER_SCRATCH_OBJECTS);
int bucket_window;
size_t res = 0;
for (bucket_window = 1; bucket_window <= PIPPENGER_MAX_BUCKET_WINDOW; bucket_window++) {
size_t n_points;
size_t max_points = secp256k1_pippenger_bucket_window_inv(bucket_window);
size_t space_for_points;
size_t space_overhead;
size_t entry_size = sizeof(secp256k1_ge) + sizeof(secp256k1_scalar) + sizeof(struct secp256k1_pippenger_point_state) + (WNAF_SIZE(bucket_window+1)+1)*sizeof(int);
entry_size = 2*entry_size;
space_overhead = (sizeof(secp256k1_gej) << bucket_window) + entry_size + sizeof(struct secp256k1_pippenger_state);
if (space_overhead > max_alloc) {
break;
}
space_for_points = max_alloc - space_overhead;
n_points = space_for_points/entry_size;
n_points = n_points > max_points ? max_points : n_points;
if (n_points > res) {
res = n_points;
}
if (n_points < max_points) {
/* A larger bucket_window may support even more points. But if we
* would choose that then the caller couldn't safely use any number
* smaller than what this function returns */
break;
}
}
return res;
}
/* Computes ecmult_multi by simply multiplying and adding each point. Does not
* require a scratch space */
static int secp256k1_ecmult_multi_simple_var(secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n_points) {
size_t point_idx;
secp256k1_gej tmpj;
secp256k1_gej_set_infinity(r);
secp256k1_gej_set_infinity(&tmpj);
/* r = inp_g_sc*G */
secp256k1_ecmult(r, &tmpj, &secp256k1_scalar_zero, inp_g_sc);
for (point_idx = 0; point_idx < n_points; point_idx++) {
secp256k1_ge point;
secp256k1_gej pointj;
secp256k1_scalar scalar;
if (!cb(&scalar, &point, point_idx, cbdata)) {
return 0;
}
/* r += scalar*point */
secp256k1_gej_set_ge(&pointj, &point);
secp256k1_ecmult(&tmpj, &pointj, &scalar, NULL);
secp256k1_gej_add_var(r, r, &tmpj, NULL);
}
return 1;
}
/* Compute the number of batches and the batch size given the maximum batch size and the
* total number of points */
static int secp256k1_ecmult_multi_batch_size_helper(size_t *n_batches, size_t *n_batch_points, size_t max_n_batch_points, size_t n) {
if (max_n_batch_points == 0) {
return 0;
}
if (max_n_batch_points > ECMULT_MAX_POINTS_PER_BATCH) {
max_n_batch_points = ECMULT_MAX_POINTS_PER_BATCH;
}
if (n == 0) {
*n_batches = 0;
*n_batch_points = 0;
return 1;
}
/* Compute ceil(n/max_n_batch_points) and ceil(n/n_batches) */
*n_batches = CEIL_DIV(n, max_n_batch_points);
*n_batch_points = CEIL_DIV(n, *n_batches);
return 1;
}
typedef int (*secp256k1_ecmult_multi_func)(const secp256k1_callback* error_callback, secp256k1_scratch*, secp256k1_gej*, const secp256k1_scalar*, secp256k1_ecmult_multi_callback cb, void*, size_t);
static int secp256k1_ecmult_multi_var(const secp256k1_callback* error_callback, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n) {
size_t i;
int (*f)(const secp256k1_callback* error_callback, secp256k1_scratch*, secp256k1_gej*, const secp256k1_scalar*, secp256k1_ecmult_multi_callback cb, void*, size_t, size_t);
size_t n_batches;
size_t n_batch_points;
secp256k1_gej_set_infinity(r);
if (inp_g_sc == NULL && n == 0) {
return 1;
} else if (n == 0) {
secp256k1_ecmult(r, r, &secp256k1_scalar_zero, inp_g_sc);
return 1;
}
if (scratch == NULL) {
return secp256k1_ecmult_multi_simple_var(r, inp_g_sc, cb, cbdata, n);
}
/* Compute the batch sizes for Pippenger's algorithm given a scratch space. If it's greater than
* a threshold use Pippenger's algorithm. Otherwise use Strauss' algorithm.
* As a first step check if there's enough space for Pippenger's algo (which requires less space
* than Strauss' algo) and if not, use the simple algorithm. */
if (!secp256k1_ecmult_multi_batch_size_helper(&n_batches, &n_batch_points, secp256k1_pippenger_max_points(error_callback, scratch), n)) {
return secp256k1_ecmult_multi_simple_var(r, inp_g_sc, cb, cbdata, n);
}
if (n_batch_points >= ECMULT_PIPPENGER_THRESHOLD) {
f = secp256k1_ecmult_pippenger_batch;
} else {
if (!secp256k1_ecmult_multi_batch_size_helper(&n_batches, &n_batch_points, secp256k1_strauss_max_points(error_callback, scratch), n)) {
return secp256k1_ecmult_multi_simple_var(r, inp_g_sc, cb, cbdata, n);
}
f = secp256k1_ecmult_strauss_batch;
}
for(i = 0; i < n_batches; i++) {
size_t nbp = n < n_batch_points ? n : n_batch_points;
size_t offset = n_batch_points*i;
secp256k1_gej tmp;
if (!f(error_callback, scratch, &tmp, i == 0 ? inp_g_sc : NULL, cb, cbdata, nbp, offset)) {
return 0;
}
secp256k1_gej_add_var(r, r, &tmp, NULL);
n -= nbp;
}
return 1;
}
#endif /* SECP256K1_ECMULT_IMPL_H */

View File

@@ -0,0 +1,351 @@
/***********************************************************************
* Copyright (c) 2013, 2014 Pieter Wuille *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or https://www.opensource.org/licenses/mit-license.php.*
***********************************************************************/
#ifndef SECP256K1_FIELD_H
#define SECP256K1_FIELD_H
#include "util.h"
/* This file defines the generic interface for working with secp256k1_fe
* objects, which represent field elements (integers modulo 2^256 - 2^32 - 977).
*
* The actual definition of the secp256k1_fe type depends on the chosen field
* implementation; see the field_5x52.h and field_10x26.h files for details.
*
* All secp256k1_fe objects have implicit properties that determine what
* operations are permitted on it. These are purely a function of what
* secp256k1_fe_ operations are applied on it, generally (implicitly) fixed at
* compile time, and do not depend on the chosen field implementation. Despite
* that, what these properties actually entail for the field representation
* values depends on the chosen field implementation. These properties are:
* - magnitude: an integer in [0,32]
* - normalized: 0 or 1; normalized=1 implies magnitude <= 1.
*
* In VERIFY mode, they are materialized explicitly as fields in the struct,
* allowing run-time verification of these properties. In that case, the field
* implementation also provides a secp256k1_fe_verify routine to verify that
* these fields match the run-time value and perform internal consistency
* checks. */
#ifdef VERIFY
# define SECP256K1_FE_VERIFY_FIELDS \
int magnitude; \
int normalized;
#else
# define SECP256K1_FE_VERIFY_FIELDS
#endif
#if defined(SECP256K1_WIDEMUL_INT128)
#include "field_5x52.h"
#elif defined(SECP256K1_WIDEMUL_INT64)
#include "field_10x26.h"
#else
#error "Please select wide multiplication implementation"
#endif
#ifdef VERIFY
/* Magnitude and normalized value for constants. */
#define SECP256K1_FE_VERIFY_CONST(d7, d6, d5, d4, d3, d2, d1, d0) \
/* Magnitude is 0 for constant 0; 1 otherwise. */ \
, (((d7) | (d6) | (d5) | (d4) | (d3) | (d2) | (d1) | (d0)) != 0) \
/* Normalized is 1 unless sum(d_i<<(32*i) for i=0..7) exceeds field modulus. */ \
, (!(((d7) & (d6) & (d5) & (d4) & (d3) & (d2)) == 0xfffffffful && ((d1) == 0xfffffffful || ((d1) == 0xfffffffe && (d0 >= 0xfffffc2f)))))
#else
#define SECP256K1_FE_VERIFY_CONST(d7, d6, d5, d4, d3, d2, d1, d0)
#endif
/** This expands to an initializer for a secp256k1_fe valued sum((i*32) * d_i, i=0..7) mod p.
*
* It has magnitude 1, unless d_i are all 0, in which case the magnitude is 0.
* It is normalized, unless sum(2^(i*32) * d_i, i=0..7) >= p.
*
* SECP256K1_FE_CONST_INNER is provided by the implementation.
*/
#define SECP256K1_FE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {SECP256K1_FE_CONST_INNER((d7), (d6), (d5), (d4), (d3), (d2), (d1), (d0)) SECP256K1_FE_VERIFY_CONST((d7), (d6), (d5), (d4), (d3), (d2), (d1), (d0)) }
static const secp256k1_fe secp256k1_fe_one = SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 1);
static const secp256k1_fe secp256k1_const_beta = SECP256K1_FE_CONST(
0x7ae96a2bul, 0x657c0710ul, 0x6e64479eul, 0xac3434e9ul,
0x9cf04975ul, 0x12f58995ul, 0xc1396c28ul, 0x719501eeul
);
#ifndef VERIFY
/* In non-VERIFY mode, we #define the fe operations to be identical to their
* internal field implementation, to avoid the potential overhead of a
* function call (even though presumably inlinable). */
# define secp256k1_fe_normalize secp256k1_fe_impl_normalize
# define secp256k1_fe_normalize_weak secp256k1_fe_impl_normalize_weak
# define secp256k1_fe_normalize_var secp256k1_fe_impl_normalize_var
# define secp256k1_fe_normalizes_to_zero secp256k1_fe_impl_normalizes_to_zero
# define secp256k1_fe_normalizes_to_zero_var secp256k1_fe_impl_normalizes_to_zero_var
# define secp256k1_fe_set_int secp256k1_fe_impl_set_int
# define secp256k1_fe_is_zero secp256k1_fe_impl_is_zero
# define secp256k1_fe_is_odd secp256k1_fe_impl_is_odd
# define secp256k1_fe_cmp_var secp256k1_fe_impl_cmp_var
# define secp256k1_fe_set_b32_mod secp256k1_fe_impl_set_b32_mod
# define secp256k1_fe_set_b32_limit secp256k1_fe_impl_set_b32_limit
# define secp256k1_fe_get_b32 secp256k1_fe_impl_get_b32
# define secp256k1_fe_negate_unchecked secp256k1_fe_impl_negate_unchecked
# define secp256k1_fe_mul_int_unchecked secp256k1_fe_impl_mul_int_unchecked
# define secp256k1_fe_add secp256k1_fe_impl_add
# define secp256k1_fe_mul secp256k1_fe_impl_mul
# define secp256k1_fe_sqr secp256k1_fe_impl_sqr
# define secp256k1_fe_cmov secp256k1_fe_impl_cmov
# define secp256k1_fe_to_storage secp256k1_fe_impl_to_storage
# define secp256k1_fe_from_storage secp256k1_fe_impl_from_storage
# define secp256k1_fe_inv secp256k1_fe_impl_inv
# define secp256k1_fe_inv_var secp256k1_fe_impl_inv_var
# define secp256k1_fe_get_bounds secp256k1_fe_impl_get_bounds
# define secp256k1_fe_half secp256k1_fe_impl_half
# define secp256k1_fe_add_int secp256k1_fe_impl_add_int
# define secp256k1_fe_is_square_var secp256k1_fe_impl_is_square_var
#endif /* !defined(VERIFY) */
/** Normalize a field element.
*
* On input, r must be a valid field element.
* On output, r represents the same value but has normalized=1 and magnitude=1.
*/
static void secp256k1_fe_normalize(secp256k1_fe *r);
/** Give a field element magnitude 1.
*
* On input, r must be a valid field element.
* On output, r represents the same value but has magnitude=1. Normalized is unchanged.
*/
static void secp256k1_fe_normalize_weak(secp256k1_fe *r);
/** Normalize a field element, without constant-time guarantee.
*
* Identical in behavior to secp256k1_fe_normalize, but not constant time in r.
*/
static void secp256k1_fe_normalize_var(secp256k1_fe *r);
/** Determine whether r represents field element 0.
*
* On input, r must be a valid field element.
* Returns whether r = 0 (mod p).
*/
static int secp256k1_fe_normalizes_to_zero(const secp256k1_fe *r);
/** Determine whether r represents field element 0, without constant-time guarantee.
*
* Identical in behavior to secp256k1_normalizes_to_zero, but not constant time in r.
*/
static int secp256k1_fe_normalizes_to_zero_var(const secp256k1_fe *r);
/** Set a field element to an integer in range [0,0x7FFF].
*
* On input, r does not need to be initialized, a must be in [0,0x7FFF].
* On output, r represents value a, is normalized and has magnitude (a!=0).
*/
static void secp256k1_fe_set_int(secp256k1_fe *r, int a);
/** Clear a field element to prevent leaking sensitive information. */
static void secp256k1_fe_clear(secp256k1_fe *a);
/** Determine whether a represents field element 0.
*
* On input, a must be a valid normalized field element.
* Returns whether a = 0 (mod p).
*
* This behaves identical to secp256k1_normalizes_to_zero{,_var}, but requires
* normalized input (and is much faster).
*/
static int secp256k1_fe_is_zero(const secp256k1_fe *a);
/** Determine whether a (mod p) is odd.
*
* On input, a must be a valid normalized field element.
* Returns (int(a) mod p) & 1.
*/
static int secp256k1_fe_is_odd(const secp256k1_fe *a);
/** Determine whether two field elements are equal.
*
* On input, a and b must be valid field elements with magnitudes not exceeding
* 1 and 31, respectively.
* Returns a = b (mod p).
*/
static int secp256k1_fe_equal(const secp256k1_fe *a, const secp256k1_fe *b);
/** Compare the values represented by 2 field elements, without constant-time guarantee.
*
* On input, a and b must be valid normalized field elements.
* Returns 1 if a > b, -1 if a < b, and 0 if a = b (comparisons are done as integers
* in range 0..p-1).
*/
static int secp256k1_fe_cmp_var(const secp256k1_fe *a, const secp256k1_fe *b);
/** Set a field element equal to the element represented by a provided 32-byte big endian value
* interpreted modulo p.
*
* On input, r does not need to be initialized. a must be a pointer to an initialized 32-byte array.
* On output, r = a (mod p). It will have magnitude 1, and not be normalized.
*/
static void secp256k1_fe_set_b32_mod(secp256k1_fe *r, const unsigned char *a);
/** Set a field element equal to a provided 32-byte big endian value, checking for overflow.
*
* On input, r does not need to be initialized. a must be a pointer to an initialized 32-byte array.
* On output, r = a if (a < p), it will be normalized with magnitude 1, and 1 is returned.
* If a >= p, 0 is returned, and r will be made invalid (and must not be used without overwriting).
*/
static int secp256k1_fe_set_b32_limit(secp256k1_fe *r, const unsigned char *a);
/** Convert a field element to 32-byte big endian byte array.
* On input, a must be a valid normalized field element, and r a pointer to a 32-byte array.
* On output, r = a (mod p).
*/
static void secp256k1_fe_get_b32(unsigned char *r, const secp256k1_fe *a);
/** Negate a field element.
*
* On input, r does not need to be initialized. a must be a valid field element with
* magnitude not exceeding m. m must be an integer constant expression in [0,31].
* Performs {r = -a}.
* On output, r will not be normalized, and will have magnitude m+1.
*/
#define secp256k1_fe_negate(r, a, m) ASSERT_INT_CONST_AND_DO(m, secp256k1_fe_negate_unchecked(r, a, m))
/** Like secp256k1_fe_negate_unchecked but m is not checked to be an integer constant expression.
*
* Should not be called directly outside of tests.
*/
static void secp256k1_fe_negate_unchecked(secp256k1_fe *r, const secp256k1_fe *a, int m);
/** Add a small integer to a field element.
*
* Performs {r += a}. The magnitude of r increases by 1, and normalized is cleared.
* a must be in range [0,0x7FFF].
*/
static void secp256k1_fe_add_int(secp256k1_fe *r, int a);
/** Multiply a field element with a small integer.
*
* On input, r must be a valid field element. a must be an integer constant expression in [0,32].
* The magnitude of r times a must not exceed 32.
* Performs {r *= a}.
* On output, r's magnitude is multiplied by a, and r will not be normalized.
*/
#define secp256k1_fe_mul_int(r, a) ASSERT_INT_CONST_AND_DO(a, secp256k1_fe_mul_int_unchecked(r, a))
/** Like secp256k1_fe_mul_int but a is not checked to be an integer constant expression.
*
* Should not be called directly outside of tests.
*/
static void secp256k1_fe_mul_int_unchecked(secp256k1_fe *r, int a);
/** Increment a field element by another.
*
* On input, r and a must be valid field elements, not necessarily normalized.
* The sum of their magnitudes must not exceed 32.
* Performs {r += a}.
* On output, r will not be normalized, and will have magnitude incremented by a's.
*/
static void secp256k1_fe_add(secp256k1_fe *r, const secp256k1_fe *a);
/** Multiply two field elements.
*
* On input, a and b must be valid field elements; r does not need to be initialized.
* r and a may point to the same object, but neither may point to the object pointed
* to by b. The magnitudes of a and b must not exceed 8.
* Performs {r = a * b}
* On output, r will have magnitude 1, but won't be normalized.
*/
static void secp256k1_fe_mul(secp256k1_fe *r, const secp256k1_fe *a, const secp256k1_fe * SECP256K1_RESTRICT b);
/** Square a field element.
*
* On input, a must be a valid field element; r does not need to be initialized. The magnitude
* of a must not exceed 8.
* Performs {r = a**2}
* On output, r will have magnitude 1, but won't be normalized.
*/
static void secp256k1_fe_sqr(secp256k1_fe *r, const secp256k1_fe *a);
/** Compute a square root of a field element.
*
* On input, a must be a valid field element with magnitude<=8; r need not be initialized.
* If sqrt(a) exists, performs {r = sqrt(a)} and returns 1.
* Otherwise, sqrt(-a) exists. The function performs {r = sqrt(-a)} and returns 0.
* The resulting value represented by r will be a square itself.
* Variables r and a must not point to the same object.
* On output, r will have magnitude 1 but will not be normalized.
*/
static int secp256k1_fe_sqrt(secp256k1_fe * SECP256K1_RESTRICT r, const secp256k1_fe * SECP256K1_RESTRICT a);
/** Compute the modular inverse of a field element.
*
* On input, a must be a valid field element; r need not be initialized.
* Performs {r = a**(p-2)} (which maps 0 to 0, and every other element to its
* inverse).
* On output, r will have magnitude (a.magnitude != 0) and be normalized.
*/
static void secp256k1_fe_inv(secp256k1_fe *r, const secp256k1_fe *a);
/** Compute the modular inverse of a field element, without constant-time guarantee.
*
* Behaves identically to secp256k1_fe_inv, but is not constant-time in a.
*/
static void secp256k1_fe_inv_var(secp256k1_fe *r, const secp256k1_fe *a);
/** Convert a field element to secp256k1_fe_storage.
*
* On input, a must be a valid normalized field element.
* Performs {r = a}.
*/
static void secp256k1_fe_to_storage(secp256k1_fe_storage *r, const secp256k1_fe *a);
/** Convert a field element back from secp256k1_fe_storage.
*
* On input, r need not be initialized.
* Performs {r = a}.
* On output, r will be normalized and will have magnitude 1.
*/
static void secp256k1_fe_from_storage(secp256k1_fe *r, const secp256k1_fe_storage *a);
/** If flag is 1, set *r equal to *a; if flag is 0, leave it. Constant-time.
* Both *r and *a must be initialized. Flag must be 0 or 1. */
static void secp256k1_fe_storage_cmov(secp256k1_fe_storage *r, const secp256k1_fe_storage *a, int flag);
/** Conditionally move a field element in constant time.
*
* On input, both r and a must be valid field elements. Flag must be 0 or 1.
* Performs {r = flag ? a : r}.
*
* On output, r's magnitude will be the maximum of both input magnitudes.
* It will be normalized if and only if both inputs were normalized.
*/
static void secp256k1_fe_cmov(secp256k1_fe *r, const secp256k1_fe *a, int flag);
/** Halve the value of a field element modulo the field prime in constant-time.
*
* On input, r must be a valid field element.
* On output, r will be normalized and have magnitude floor(m/2) + 1 where m is
* the magnitude of r on input.
*/
static void secp256k1_fe_half(secp256k1_fe *r);
/** Sets r to a field element with magnitude m, normalized if (and only if) m==0.
* The value is chosen so that it is likely to trigger edge cases related to
* internal overflows. */
static void secp256k1_fe_get_bounds(secp256k1_fe *r, int m);
/** Determine whether a is a square (modulo p).
*
* On input, a must be a valid field element.
*/
static int secp256k1_fe_is_square_var(const secp256k1_fe *a);
/** Check invariants on a field element (no-op unless VERIFY is enabled). */
static void secp256k1_fe_verify(const secp256k1_fe *a);
#define SECP256K1_FE_VERIFY(a) secp256k1_fe_verify(a)
/** Check that magnitude of a is at most m (no-op unless VERIFY is enabled). */
static void secp256k1_fe_verify_magnitude(const secp256k1_fe *a, int m);
#define SECP256K1_FE_VERIFY_MAGNITUDE(a, m) secp256k1_fe_verify_magnitude(a, m)
#endif /* SECP256K1_FIELD_H */

View File

@@ -0,0 +1,57 @@
/***********************************************************************
* Copyright (c) 2013, 2014 Pieter Wuille *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or https://www.opensource.org/licenses/mit-license.php.*
***********************************************************************/
#ifndef SECP256K1_FIELD_REPR_H
#define SECP256K1_FIELD_REPR_H
#include <stdint.h>
/** This field implementation represents the value as 10 uint32_t limbs in base
* 2^26. */
typedef struct {
/* A field element f represents the sum(i=0..9, f.n[i] << (i*26)) mod p,
* where p is the field modulus, 2^256 - 2^32 - 977.
*
* The individual limbs f.n[i] can exceed 2^26; the field's magnitude roughly
* corresponds to how much excess is allowed. The value
* sum(i=0..9, f.n[i] << (i*26)) may exceed p, unless the field element is
* normalized. */
uint32_t n[10];
/*
* Magnitude m requires:
* n[i] <= 2 * m * (2^26 - 1) for i=0..8
* n[9] <= 2 * m * (2^22 - 1)
*
* Normalized requires:
* n[i] <= (2^26 - 1) for i=0..8
* sum(i=0..9, n[i] << (i*26)) < p
* (together these imply n[9] <= 2^22 - 1)
*/
SECP256K1_FE_VERIFY_FIELDS
} secp256k1_fe;
/* Unpacks a constant into a overlapping multi-limbed FE element. */
#define SECP256K1_FE_CONST_INNER(d7, d6, d5, d4, d3, d2, d1, d0) { \
(d0) & 0x3FFFFFFUL, \
(((uint32_t)d0) >> 26) | (((uint32_t)(d1) & 0xFFFFFUL) << 6), \
(((uint32_t)d1) >> 20) | (((uint32_t)(d2) & 0x3FFFUL) << 12), \
(((uint32_t)d2) >> 14) | (((uint32_t)(d3) & 0xFFUL) << 18), \
(((uint32_t)d3) >> 8) | (((uint32_t)(d4) & 0x3UL) << 24), \
(((uint32_t)d4) >> 2) & 0x3FFFFFFUL, \
(((uint32_t)d4) >> 28) | (((uint32_t)(d5) & 0x3FFFFFUL) << 4), \
(((uint32_t)d5) >> 22) | (((uint32_t)(d6) & 0xFFFFUL) << 10), \
(((uint32_t)d6) >> 16) | (((uint32_t)(d7) & 0x3FFUL) << 16), \
(((uint32_t)d7) >> 10) \
}
typedef struct {
uint32_t n[8];
} secp256k1_fe_storage;
#define SECP256K1_FE_STORAGE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{ (d0), (d1), (d2), (d3), (d4), (d5), (d6), (d7) }}
#define SECP256K1_FE_STORAGE_CONST_GET(d) d.n[7], d.n[6], d.n[5], d.n[4],d.n[3], d.n[2], d.n[1], d.n[0]
#endif /* SECP256K1_FIELD_REPR_H */

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,62 @@
/***********************************************************************
* Copyright (c) 2013, 2014 Pieter Wuille *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or https://www.opensource.org/licenses/mit-license.php.*
***********************************************************************/
#ifndef SECP256K1_FIELD_REPR_H
#define SECP256K1_FIELD_REPR_H
#include <stdint.h>
/** This field implementation represents the value as 5 uint64_t limbs in base
* 2^52. */
typedef struct {
/* A field element f represents the sum(i=0..4, f.n[i] << (i*52)) mod p,
* where p is the field modulus, 2^256 - 2^32 - 977.
*
* The individual limbs f.n[i] can exceed 2^52; the field's magnitude roughly
* corresponds to how much excess is allowed. The value
* sum(i=0..4, f.n[i] << (i*52)) may exceed p, unless the field element is
* normalized. */
uint64_t n[5];
/*
* Magnitude m requires:
* n[i] <= 2 * m * (2^52 - 1) for i=0..3
* n[4] <= 2 * m * (2^48 - 1)
*
* Normalized requires:
* n[i] <= (2^52 - 1) for i=0..3
* sum(i=0..4, n[i] << (i*52)) < p
* (together these imply n[4] <= 2^48 - 1)
*/
SECP256K1_FE_VERIFY_FIELDS
} secp256k1_fe;
/* Unpacks a constant into a overlapping multi-limbed FE element. */
#define SECP256K1_FE_CONST_INNER(d7, d6, d5, d4, d3, d2, d1, d0) { \
(d0) | (((uint64_t)(d1) & 0xFFFFFUL) << 32), \
((uint64_t)(d1) >> 20) | (((uint64_t)(d2)) << 12) | (((uint64_t)(d3) & 0xFFUL) << 44), \
((uint64_t)(d3) >> 8) | (((uint64_t)(d4) & 0xFFFFFFFUL) << 24), \
((uint64_t)(d4) >> 28) | (((uint64_t)(d5)) << 4) | (((uint64_t)(d6) & 0xFFFFUL) << 36), \
((uint64_t)(d6) >> 16) | (((uint64_t)(d7)) << 16) \
}
typedef struct {
uint64_t n[4];
} secp256k1_fe_storage;
#define SECP256K1_FE_STORAGE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{ \
(d0) | (((uint64_t)(d1)) << 32), \
(d2) | (((uint64_t)(d3)) << 32), \
(d4) | (((uint64_t)(d5)) << 32), \
(d6) | (((uint64_t)(d7)) << 32) \
}}
#define SECP256K1_FE_STORAGE_CONST_GET(d) \
(uint32_t)(d.n[3] >> 32), (uint32_t)d.n[3], \
(uint32_t)(d.n[2] >> 32), (uint32_t)d.n[2], \
(uint32_t)(d.n[1] >> 32), (uint32_t)d.n[1], \
(uint32_t)(d.n[0] >> 32), (uint32_t)d.n[0]
#endif /* SECP256K1_FIELD_REPR_H */

View File

@@ -0,0 +1,524 @@
/***********************************************************************
* Copyright (c) 2013, 2014 Pieter Wuille *
* Distributed under the MIT software license, see the accompanying *
* file COPYING or https://www.opensource.org/licenses/mit-license.php.*
***********************************************************************/
#ifndef SECP256K1_FIELD_REPR_IMPL_H
#define SECP256K1_FIELD_REPR_IMPL_H
#include "checkmem.h"
#include "util.h"
#include "field.h"
#include "modinv64_impl.h"
#include "field_5x52_int128_impl.h"
#ifdef VERIFY
static void secp256k1_fe_impl_verify(const secp256k1_fe *a) {
const uint64_t *d = a->n;
int m = a->normalized ? 1 : 2 * a->magnitude;
/* secp256k1 'p' value defined in "Standards for Efficient Cryptography" (SEC2) 2.7.1. */
VERIFY_CHECK(d[0] <= 0xFFFFFFFFFFFFFULL * m);
VERIFY_CHECK(d[1] <= 0xFFFFFFFFFFFFFULL * m);
VERIFY_CHECK(d[2] <= 0xFFFFFFFFFFFFFULL * m);
VERIFY_CHECK(d[3] <= 0xFFFFFFFFFFFFFULL * m);
VERIFY_CHECK(d[4] <= 0x0FFFFFFFFFFFFULL * m);
if (a->normalized) {
if ((d[4] == 0x0FFFFFFFFFFFFULL) && ((d[3] & d[2] & d[1]) == 0xFFFFFFFFFFFFFULL)) {
VERIFY_CHECK(d[0] < 0xFFFFEFFFFFC2FULL);
}
}
}
#endif
static void secp256k1_fe_impl_get_bounds(secp256k1_fe *r, int m) {
r->n[0] = 0xFFFFFFFFFFFFFULL * 2 * m;
r->n[1] = 0xFFFFFFFFFFFFFULL * 2 * m;
r->n[2] = 0xFFFFFFFFFFFFFULL * 2 * m;
r->n[3] = 0xFFFFFFFFFFFFFULL * 2 * m;
r->n[4] = 0x0FFFFFFFFFFFFULL * 2 * m;
}
static void secp256k1_fe_impl_normalize(secp256k1_fe *r) {
uint64_t t0 = r->n[0], t1 = r->n[1], t2 = r->n[2], t3 = r->n[3], t4 = r->n[4];
/* Reduce t4 at the start so there will be at most a single carry from the first pass */
uint64_t m;
uint64_t x = t4 >> 48; t4 &= 0x0FFFFFFFFFFFFULL;
/* The first pass ensures the magnitude is 1, ... */
t0 += x * 0x1000003D1ULL;
t1 += (t0 >> 52); t0 &= 0xFFFFFFFFFFFFFULL;
t2 += (t1 >> 52); t1 &= 0xFFFFFFFFFFFFFULL; m = t1;
t3 += (t2 >> 52); t2 &= 0xFFFFFFFFFFFFFULL; m &= t2;
t4 += (t3 >> 52); t3 &= 0xFFFFFFFFFFFFFULL; m &= t3;
/* ... except for a possible carry at bit 48 of t4 (i.e. bit 256 of the field element) */
VERIFY_CHECK(t4 >> 49 == 0);
/* At most a single final reduction is needed; check if the value is >= the field characteristic */
x = (t4 >> 48) | ((t4 == 0x0FFFFFFFFFFFFULL) & (m == 0xFFFFFFFFFFFFFULL)
& (t0 >= 0xFFFFEFFFFFC2FULL));
/* Apply the final reduction (for constant-time behaviour, we do it always) */
t0 += x * 0x1000003D1ULL;
t1 += (t0 >> 52); t0 &= 0xFFFFFFFFFFFFFULL;
t2 += (t1 >> 52); t1 &= 0xFFFFFFFFFFFFFULL;
t3 += (t2 >> 52); t2 &= 0xFFFFFFFFFFFFFULL;
t4 += (t3 >> 52); t3 &= 0xFFFFFFFFFFFFFULL;
/* If t4 didn't carry to bit 48 already, then it should have after any final reduction */
VERIFY_CHECK(t4 >> 48 == x);
/* Mask off the possible multiple of 2^256 from the final reduction */
t4 &= 0x0FFFFFFFFFFFFULL;
r->n[0] = t0; r->n[1] = t1; r->n[2] = t2; r->n[3] = t3; r->n[4] = t4;
}
static void secp256k1_fe_impl_normalize_weak(secp256k1_fe *r) {
uint64_t t0 = r->n[0], t1 = r->n[1], t2 = r->n[2], t3 = r->n[3], t4 = r->n[4];
/* Reduce t4 at the start so there will be at most a single carry from the first pass */
uint64_t x = t4 >> 48; t4 &= 0x0FFFFFFFFFFFFULL;
/* The first pass ensures the magnitude is 1, ... */
t0 += x * 0x1000003D1ULL;
t1 += (t0 >> 52); t0 &= 0xFFFFFFFFFFFFFULL;
t2 += (t1 >> 52); t1 &= 0xFFFFFFFFFFFFFULL;
t3 += (t2 >> 52); t2 &= 0xFFFFFFFFFFFFFULL;
t4 += (t3 >> 52); t3 &= 0xFFFFFFFFFFFFFULL;
/* ... except for a possible carry at bit 48 of t4 (i.e. bit 256 of the field element) */
VERIFY_CHECK(t4 >> 49 == 0);
r->n[0] = t0; r->n[1] = t1; r->n[2] = t2; r->n[3] = t3; r->n[4] = t4;
}
static void secp256k1_fe_impl_normalize_var(secp256k1_fe *r) {
uint64_t t0 = r->n[0], t1 = r->n[1], t2 = r->n[2], t3 = r->n[3], t4 = r->n[4];
/* Reduce t4 at the start so there will be at most a single carry from the first pass */
uint64_t m;
uint64_t x = t4 >> 48; t4 &= 0x0FFFFFFFFFFFFULL;
/* The first pass ensures the magnitude is 1, ... */
t0 += x * 0x1000003D1ULL;
t1 += (t0 >> 52); t0 &= 0xFFFFFFFFFFFFFULL;
t2 += (t1 >> 52); t1 &= 0xFFFFFFFFFFFFFULL; m = t1;
t3 += (t2 >> 52); t2 &= 0xFFFFFFFFFFFFFULL; m &= t2;
t4 += (t3 >> 52); t3 &= 0xFFFFFFFFFFFFFULL; m &= t3;
/* ... except for a possible carry at bit 48 of t4 (i.e. bit 256 of the field element) */
VERIFY_CHECK(t4 >> 49 == 0);
/* At most a single final reduction is needed; check if the value is >= the field characteristic */
x = (t4 >> 48) | ((t4 == 0x0FFFFFFFFFFFFULL) & (m == 0xFFFFFFFFFFFFFULL)
& (t0 >= 0xFFFFEFFFFFC2FULL));
if (x) {
t0 += 0x1000003D1ULL;
t1 += (t0 >> 52); t0 &= 0xFFFFFFFFFFFFFULL;
t2 += (t1 >> 52); t1 &= 0xFFFFFFFFFFFFFULL;
t3 += (t2 >> 52); t2 &= 0xFFFFFFFFFFFFFULL;
t4 += (t3 >> 52); t3 &= 0xFFFFFFFFFFFFFULL;
/* If t4 didn't carry to bit 48 already, then it should have after any final reduction */
VERIFY_CHECK(t4 >> 48 == x);
/* Mask off the possible multiple of 2^256 from the final reduction */
t4 &= 0x0FFFFFFFFFFFFULL;
}
r->n[0] = t0; r->n[1] = t1; r->n[2] = t2; r->n[3] = t3; r->n[4] = t4;
}
static int secp256k1_fe_impl_normalizes_to_zero(const secp256k1_fe *r) {
uint64_t t0 = r->n[0], t1 = r->n[1], t2 = r->n[2], t3 = r->n[3], t4 = r->n[4];
/* z0 tracks a possible raw value of 0, z1 tracks a possible raw value of P */
uint64_t z0, z1;
/* Reduce t4 at the start so there will be at most a single carry from the first pass */
uint64_t x = t4 >> 48; t4 &= 0x0FFFFFFFFFFFFULL;
/* The first pass ensures the magnitude is 1, ... */
t0 += x * 0x1000003D1ULL;
t1 += (t0 >> 52); t0 &= 0xFFFFFFFFFFFFFULL; z0 = t0; z1 = t0 ^ 0x1000003D0ULL;
t2 += (t1 >> 52); t1 &= 0xFFFFFFFFFFFFFULL; z0 |= t1; z1 &= t1;
t3 += (t2 >> 52); t2 &= 0xFFFFFFFFFFFFFULL; z0 |= t2; z1 &= t2;
t4 += (t3 >> 52); t3 &= 0xFFFFFFFFFFFFFULL; z0 |= t3; z1 &= t3;
z0 |= t4; z1 &= t4 ^ 0xF000000000000ULL;
/* ... except for a possible carry at bit 48 of t4 (i.e. bit 256 of the field element) */
VERIFY_CHECK(t4 >> 49 == 0);
return (z0 == 0) | (z1 == 0xFFFFFFFFFFFFFULL);
}
static int secp256k1_fe_impl_normalizes_to_zero_var(const secp256k1_fe *r) {
uint64_t t0, t1, t2, t3, t4;
uint64_t z0, z1;
uint64_t x;
t0 = r->n[0];
t4 = r->n[4];
/* Reduce t4 at the start so there will be at most a single carry from the first pass */
x = t4 >> 48;
/* The first pass ensures the magnitude is 1, ... */
t0 += x * 0x1000003D1ULL;
/* z0 tracks a possible raw value of 0, z1 tracks a possible raw value of P */
z0 = t0 & 0xFFFFFFFFFFFFFULL;
z1 = z0 ^ 0x1000003D0ULL;
/* Fast return path should catch the majority of cases */
if ((z0 != 0ULL) & (z1 != 0xFFFFFFFFFFFFFULL)) {
return 0;
}
t1 = r->n[1];
t2 = r->n[2];
t3 = r->n[3];
t4 &= 0x0FFFFFFFFFFFFULL;
t1 += (t0 >> 52);
t2 += (t1 >> 52); t1 &= 0xFFFFFFFFFFFFFULL; z0 |= t1; z1 &= t1;
t3 += (t2 >> 52); t2 &= 0xFFFFFFFFFFFFFULL; z0 |= t2; z1 &= t2;
t4 += (t3 >> 52); t3 &= 0xFFFFFFFFFFFFFULL; z0 |= t3; z1 &= t3;
z0 |= t4; z1 &= t4 ^ 0xF000000000000ULL;
/* ... except for a possible carry at bit 48 of t4 (i.e. bit 256 of the field element) */
VERIFY_CHECK(t4 >> 49 == 0);
return (z0 == 0) | (z1 == 0xFFFFFFFFFFFFFULL);
}
SECP256K1_INLINE static void secp256k1_fe_impl_set_int(secp256k1_fe *r, int a) {
r->n[0] = a;
r->n[1] = r->n[2] = r->n[3] = r->n[4] = 0;
}
SECP256K1_INLINE static int secp256k1_fe_impl_is_zero(const secp256k1_fe *a) {
const uint64_t *t = a->n;
return (t[0] | t[1] | t[2] | t[3] | t[4]) == 0;
}
SECP256K1_INLINE static int secp256k1_fe_impl_is_odd(const secp256k1_fe *a) {
return a->n[0] & 1;
}
static int secp256k1_fe_impl_cmp_var(const secp256k1_fe *a, const secp256k1_fe *b) {
int i;
for (i = 4; i >= 0; i--) {
if (a->n[i] > b->n[i]) {
return 1;
}
if (a->n[i] < b->n[i]) {
return -1;
}
}
return 0;
}
static void secp256k1_fe_impl_set_b32_mod(secp256k1_fe *r, const unsigned char *a) {
r->n[0] = (uint64_t)a[31]
| ((uint64_t)a[30] << 8)
| ((uint64_t)a[29] << 16)
| ((uint64_t)a[28] << 24)
| ((uint64_t)a[27] << 32)
| ((uint64_t)a[26] << 40)
| ((uint64_t)(a[25] & 0xF) << 48);
r->n[1] = (uint64_t)((a[25] >> 4) & 0xF)
| ((uint64_t)a[24] << 4)
| ((uint64_t)a[23] << 12)
| ((uint64_t)a[22] << 20)
| ((uint64_t)a[21] << 28)
| ((uint64_t)a[20] << 36)
| ((uint64_t)a[19] << 44);
r->n[2] = (uint64_t)a[18]
| ((uint64_t)a[17] << 8)
| ((uint64_t)a[16] << 16)
| ((uint64_t)a[15] << 24)
| ((uint64_t)a[14] << 32)
| ((uint64_t)a[13] << 40)
| ((uint64_t)(a[12] & 0xF) << 48);
r->n[3] = (uint64_t)((a[12] >> 4) & 0xF)
| ((uint64_t)a[11] << 4)
| ((uint64_t)a[10] << 12)
| ((uint64_t)a[9] << 20)
| ((uint64_t)a[8] << 28)
| ((uint64_t)a[7] << 36)
| ((uint64_t)a[6] << 44);
r->n[4] = (uint64_t)a[5]
| ((uint64_t)a[4] << 8)
| ((uint64_t)a[3] << 16)
| ((uint64_t)a[2] << 24)
| ((uint64_t)a[1] << 32)
| ((uint64_t)a[0] << 40);
}
static int secp256k1_fe_impl_set_b32_limit(secp256k1_fe *r, const unsigned char *a) {
secp256k1_fe_impl_set_b32_mod(r, a);
return !((r->n[4] == 0x0FFFFFFFFFFFFULL) & ((r->n[3] & r->n[2] & r->n[1]) == 0xFFFFFFFFFFFFFULL) & (r->n[0] >= 0xFFFFEFFFFFC2FULL));
}
/** Convert a field element to a 32-byte big endian value. Requires the input to be normalized */
static void secp256k1_fe_impl_get_b32(unsigned char *r, const secp256k1_fe *a) {
r[0] = (a->n[4] >> 40) & 0xFF;
r[1] = (a->n[4] >> 32) & 0xFF;
r[2] = (a->n[4] >> 24) & 0xFF;
r[3] = (a->n[4] >> 16) & 0xFF;
r[4] = (a->n[4] >> 8) & 0xFF;
r[5] = a->n[4] & 0xFF;
r[6] = (a->n[3] >> 44) & 0xFF;
r[7] = (a->n[3] >> 36) & 0xFF;
r[8] = (a->n[3] >> 28) & 0xFF;
r[9] = (a->n[3] >> 20) & 0xFF;
r[10] = (a->n[3] >> 12) & 0xFF;
r[11] = (a->n[3] >> 4) & 0xFF;
r[12] = ((a->n[2] >> 48) & 0xF) | ((a->n[3] & 0xF) << 4);
r[13] = (a->n[2] >> 40) & 0xFF;
r[14] = (a->n[2] >> 32) & 0xFF;
r[15] = (a->n[2] >> 24) & 0xFF;
r[16] = (a->n[2] >> 16) & 0xFF;
r[17] = (a->n[2] >> 8) & 0xFF;
r[18] = a->n[2] & 0xFF;
r[19] = (a->n[1] >> 44) & 0xFF;
r[20] = (a->n[1] >> 36) & 0xFF;
r[21] = (a->n[1] >> 28) & 0xFF;
r[22] = (a->n[1] >> 20) & 0xFF;
r[23] = (a->n[1] >> 12) & 0xFF;
r[24] = (a->n[1] >> 4) & 0xFF;
r[25] = ((a->n[0] >> 48) & 0xF) | ((a->n[1] & 0xF) << 4);
r[26] = (a->n[0] >> 40) & 0xFF;
r[27] = (a->n[0] >> 32) & 0xFF;
r[28] = (a->n[0] >> 24) & 0xFF;
r[29] = (a->n[0] >> 16) & 0xFF;
r[30] = (a->n[0] >> 8) & 0xFF;
r[31] = a->n[0] & 0xFF;
}
SECP256K1_INLINE static void secp256k1_fe_impl_negate_unchecked(secp256k1_fe *r, const secp256k1_fe *a, int m) {
/* For all legal values of m (0..31), the following properties hold: */
VERIFY_CHECK(0xFFFFEFFFFFC2FULL * 2 * (m + 1) >= 0xFFFFFFFFFFFFFULL * 2 * m);
VERIFY_CHECK(0xFFFFFFFFFFFFFULL * 2 * (m + 1) >= 0xFFFFFFFFFFFFFULL * 2 * m);
VERIFY_CHECK(0x0FFFFFFFFFFFFULL * 2 * (m + 1) >= 0x0FFFFFFFFFFFFULL * 2 * m);
/* Due to the properties above, the left hand in the subtractions below is never less than
* the right hand. */
r->n[0] = 0xFFFFEFFFFFC2FULL * 2 * (m + 1) - a->n[0];
r->n[1] = 0xFFFFFFFFFFFFFULL * 2 * (m + 1) - a->n[1];
r->n[2] = 0xFFFFFFFFFFFFFULL * 2 * (m + 1) - a->n[2];
r->n[3] = 0xFFFFFFFFFFFFFULL * 2 * (m + 1) - a->n[3];
r->n[4] = 0x0FFFFFFFFFFFFULL * 2 * (m + 1) - a->n[4];
}
SECP256K1_INLINE static void secp256k1_fe_impl_mul_int_unchecked(secp256k1_fe *r, int a) {
r->n[0] *= a;
r->n[1] *= a;
r->n[2] *= a;
r->n[3] *= a;
r->n[4] *= a;
}
SECP256K1_INLINE static void secp256k1_fe_impl_add_int(secp256k1_fe *r, int a) {
r->n[0] += a;
}
SECP256K1_INLINE static void secp256k1_fe_impl_add(secp256k1_fe *r, const secp256k1_fe *a) {
r->n[0] += a->n[0];
r->n[1] += a->n[1];
r->n[2] += a->n[2];
r->n[3] += a->n[3];
r->n[4] += a->n[4];
}
SECP256K1_INLINE static void secp256k1_fe_impl_mul(secp256k1_fe *r, const secp256k1_fe *a, const secp256k1_fe * SECP256K1_RESTRICT b) {
secp256k1_fe_mul_inner(r->n, a->n, b->n);
}
SECP256K1_INLINE static void secp256k1_fe_impl_sqr(secp256k1_fe *r, const secp256k1_fe *a) {
secp256k1_fe_sqr_inner(r->n, a->n);
}
SECP256K1_INLINE static void secp256k1_fe_impl_cmov(secp256k1_fe *r, const secp256k1_fe *a, int flag) {
uint64_t mask0, mask1;
volatile int vflag = flag;
VERIFY_CHECK(flag == 0 || flag == 1);
SECP256K1_CHECKMEM_CHECK_VERIFY(r->n, sizeof(r->n));
mask0 = vflag + ~((uint64_t)0);
mask1 = ~mask0;
r->n[0] = (r->n[0] & mask0) | (a->n[0] & mask1);
r->n[1] = (r->n[1] & mask0) | (a->n[1] & mask1);
r->n[2] = (r->n[2] & mask0) | (a->n[2] & mask1);
r->n[3] = (r->n[3] & mask0) | (a->n[3] & mask1);
r->n[4] = (r->n[4] & mask0) | (a->n[4] & mask1);
}
static SECP256K1_INLINE void secp256k1_fe_impl_half(secp256k1_fe *r) {
uint64_t t0 = r->n[0], t1 = r->n[1], t2 = r->n[2], t3 = r->n[3], t4 = r->n[4];
uint64_t one = (uint64_t)1;
uint64_t mask = -(t0 & one) >> 12;
/* Bounds analysis (over the rationals).
*
* Let m = r->magnitude
* C = 0xFFFFFFFFFFFFFULL * 2
* D = 0x0FFFFFFFFFFFFULL * 2
*
* Initial bounds: t0..t3 <= C * m
* t4 <= D * m
*/
t0 += 0xFFFFEFFFFFC2FULL & mask;
t1 += mask;
t2 += mask;
t3 += mask;
t4 += mask >> 4;
VERIFY_CHECK((t0 & one) == 0);
/* t0..t3: added <= C/2
* t4: added <= D/2
*
* Current bounds: t0..t3 <= C * (m + 1/2)
* t4 <= D * (m + 1/2)
*/
r->n[0] = (t0 >> 1) + ((t1 & one) << 51);
r->n[1] = (t1 >> 1) + ((t2 & one) << 51);
r->n[2] = (t2 >> 1) + ((t3 & one) << 51);
r->n[3] = (t3 >> 1) + ((t4 & one) << 51);
r->n[4] = (t4 >> 1);
/* t0..t3: shifted right and added <= C/4 + 1/2
* t4: shifted right
*
* Current bounds: t0..t3 <= C * (m/2 + 1/2)
* t4 <= D * (m/2 + 1/4)
*
* Therefore the output magnitude (M) has to be set such that:
* t0..t3: C * M >= C * (m/2 + 1/2)
* t4: D * M >= D * (m/2 + 1/4)
*
* It suffices for all limbs that, for any input magnitude m:
* M >= m/2 + 1/2
*
* and since we want the smallest such integer value for M:
* M == floor(m/2) + 1
*/
}
static SECP256K1_INLINE void secp256k1_fe_storage_cmov(secp256k1_fe_storage *r, const secp256k1_fe_storage *a, int flag) {
uint64_t mask0, mask1;
volatile int vflag = flag;
VERIFY_CHECK(flag == 0 || flag == 1);
SECP256K1_CHECKMEM_CHECK_VERIFY(r->n, sizeof(r->n));
mask0 = vflag + ~((uint64_t)0);
mask1 = ~mask0;
r->n[0] = (r->n[0] & mask0) | (a->n[0] & mask1);
r->n[1] = (r->n[1] & mask0) | (a->n[1] & mask1);
r->n[2] = (r->n[2] & mask0) | (a->n[2] & mask1);
r->n[3] = (r->n[3] & mask0) | (a->n[3] & mask1);
}
static void secp256k1_fe_impl_to_storage(secp256k1_fe_storage *r, const secp256k1_fe *a) {
r->n[0] = a->n[0] | a->n[1] << 52;
r->n[1] = a->n[1] >> 12 | a->n[2] << 40;
r->n[2] = a->n[2] >> 24 | a->n[3] << 28;
r->n[3] = a->n[3] >> 36 | a->n[4] << 16;
}
static SECP256K1_INLINE void secp256k1_fe_impl_from_storage(secp256k1_fe *r, const secp256k1_fe_storage *a) {
r->n[0] = a->n[0] & 0xFFFFFFFFFFFFFULL;
r->n[1] = a->n[0] >> 52 | ((a->n[1] << 12) & 0xFFFFFFFFFFFFFULL);
r->n[2] = a->n[1] >> 40 | ((a->n[2] << 24) & 0xFFFFFFFFFFFFFULL);
r->n[3] = a->n[2] >> 28 | ((a->n[3] << 36) & 0xFFFFFFFFFFFFFULL);
r->n[4] = a->n[3] >> 16;
}
static void secp256k1_fe_from_signed62(secp256k1_fe *r, const secp256k1_modinv64_signed62 *a) {
const uint64_t M52 = UINT64_MAX >> 12;
const uint64_t a0 = a->v[0], a1 = a->v[1], a2 = a->v[2], a3 = a->v[3], a4 = a->v[4];
/* The output from secp256k1_modinv64{_var} should be normalized to range [0,modulus), and
* have limbs in [0,2^62). The modulus is < 2^256, so the top limb must be below 2^(256-62*4).
*/
VERIFY_CHECK(a0 >> 62 == 0);
VERIFY_CHECK(a1 >> 62 == 0);
VERIFY_CHECK(a2 >> 62 == 0);
VERIFY_CHECK(a3 >> 62 == 0);
VERIFY_CHECK(a4 >> 8 == 0);
r->n[0] = a0 & M52;
r->n[1] = (a0 >> 52 | a1 << 10) & M52;
r->n[2] = (a1 >> 42 | a2 << 20) & M52;
r->n[3] = (a2 >> 32 | a3 << 30) & M52;
r->n[4] = (a3 >> 22 | a4 << 40);
}
static void secp256k1_fe_to_signed62(secp256k1_modinv64_signed62 *r, const secp256k1_fe *a) {
const uint64_t M62 = UINT64_MAX >> 2;
const uint64_t a0 = a->n[0], a1 = a->n[1], a2 = a->n[2], a3 = a->n[3], a4 = a->n[4];
r->v[0] = (a0 | a1 << 52) & M62;
r->v[1] = (a1 >> 10 | a2 << 42) & M62;
r->v[2] = (a2 >> 20 | a3 << 32) & M62;
r->v[3] = (a3 >> 30 | a4 << 22) & M62;
r->v[4] = a4 >> 40;
}
static const secp256k1_modinv64_modinfo secp256k1_const_modinfo_fe = {
{{-0x1000003D1LL, 0, 0, 0, 256}},
0x27C7F6E22DDACACFLL
};
static void secp256k1_fe_impl_inv(secp256k1_fe *r, const secp256k1_fe *x) {
secp256k1_fe tmp = *x;
secp256k1_modinv64_signed62 s;
secp256k1_fe_normalize(&tmp);
secp256k1_fe_to_signed62(&s, &tmp);
secp256k1_modinv64(&s, &secp256k1_const_modinfo_fe);
secp256k1_fe_from_signed62(r, &s);
}
static void secp256k1_fe_impl_inv_var(secp256k1_fe *r, const secp256k1_fe *x) {
secp256k1_fe tmp = *x;
secp256k1_modinv64_signed62 s;
secp256k1_fe_normalize_var(&tmp);
secp256k1_fe_to_signed62(&s, &tmp);
secp256k1_modinv64_var(&s, &secp256k1_const_modinfo_fe);
secp256k1_fe_from_signed62(r, &s);
}
static int secp256k1_fe_impl_is_square_var(const secp256k1_fe *x) {
secp256k1_fe tmp;
secp256k1_modinv64_signed62 s;
int jac, ret;
tmp = *x;
secp256k1_fe_normalize_var(&tmp);
/* secp256k1_jacobi64_maybe_var cannot deal with input 0. */
if (secp256k1_fe_is_zero(&tmp)) return 1;
secp256k1_fe_to_signed62(&s, &tmp);
jac = secp256k1_jacobi64_maybe_var(&s, &secp256k1_const_modinfo_fe);
if (jac == 0) {
/* secp256k1_jacobi64_maybe_var failed to compute the Jacobi symbol. Fall back
* to computing a square root. This should be extremely rare with random
* input (except in VERIFY mode, where a lower iteration count is used). */
secp256k1_fe dummy;
ret = secp256k1_fe_sqrt(&dummy, &tmp);
} else {
ret = jac >= 0;
}
return ret;
}
#endif /* SECP256K1_FIELD_REPR_IMPL_H */

Some files were not shown because too many files have changed in this diff Show More