Merge pull request #732 from Foundation-Devices/sft-8545-native-taproot-key-signing
What changed, and why it matters
This commit adds a new, dedicated way for the Passport hardware wallet to sign Bitcoin Taproot transactions. It moves the cryptographic 'tweak' calculation from Python code into a Rust library and adds unit tests. There is nothing in the commit message or code changes that suggests a security bug was fixed; it reads as a normal feature/refactoring improvement.
No security action required; treat as a routine feature/refactor commit. Continue normal code review and testing.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The change introduces foundation_secp256k1_sign_schnorr_taproot(), a native Rust function that performs BIP-341 TapTweak on the internal secret key and then produces a Schnorr signature in one call. The MicroPython binding validates input lengths (32-byte data, 32-byte secret key, optional 32-byte Merkle root). Python taproot.py is updated to call the new native function instead of its own pure-Python taproot_tweak_seckey() + sign_schnorr() sequence. Unit tests are added/updated to verify BIP-341 test vectors and script-tree tweaking. No vulnerability indicators are present in the diff.
Changed components
extmod/foundation-rust/src/secp256k1.rsextmod/foundation-rust/include/foundation.hextmod/foundation/modfoundation-secp56k1.hports/stm32/boards/Passport/modules/taproot.pyports/stm32/boards/Passport/modules/tests/unit/psbt_sighash.pyInspect captured patch +234 / −18
### extmod/foundation-rust/include/foundation.h
@@ -567,6 +567,24 @@ void foundation_secp256k1_sign_schnorr(const uint8_t (*data)[32],
const uint8_t (*secret_key)[32],
uint8_t (*signature)[64]);
+/**
+ * Computes a BIP-341 Taproot key path signature over the message `data`.
+ *
+ * - `data` is the message hash.
+ * - `secret_key` is the internal secret key, before the Taproot tweak.
+ * - `merkle_root` is the Merkle root of the script tree, or null when the
+ * output key commits to no script tree.
+ * - `signature` is the output of the resulting signature.
+ *
+ * See also:
+ *
+ * - https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#constructing-and-spending-taproot-outputs
+ */
+void foundation_secp256k1_sign_schnorr_taproot(const uint8_t (*data)[32],
+ const uint8_t (*secret_key)[32],
+ const uint8_t (*merkle_root)[32],
+ uint8_t (*signature)[64]);
+
/**
* Receive a Uniform Resource part.
*
### extmod/foundation-rust/src/secp256k1.rs
@@ -1,11 +1,12 @@
// SPDX-FileCopyrightText: © 2023 Foundation Devices, Inc. <hello@foundation.xyz>
// SPDX-License-Identifier: GPL-3.0-or-later
+use bitcoin_hashes::{sha256, HashEngine};
use core::ptr;
use once_cell::sync::Lazy;
use secp256k1::{
- ffi::types::AlignedType, AllPreallocated, Keypair, Message, Secp256k1,
- SecretKey,
+ ffi::types::AlignedType, AllPreallocated, Keypair, Message, Scalar,
+ Secp256k1, SecretKey,
};
/// cbindgen:ignore
@@ -79,6 +80,58 @@ pub extern "C" fn secp256k1_sign_schnorr(
signature.copy_from_slice(sig.as_ref());
}
+/// Computes a BIP-341 Taproot key path signature over the message `data`.
+///
+/// - `data` is the message hash.
+/// - `secret_key` is the internal secret key, before the Taproot tweak.
+/// - `merkle_root` is the Merkle root of the script tree, or null when the
+/// output key commits to no script tree.
+/// - `signature` is the output of the resulting signature.
+///
+/// See also:
+///
+/// - https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#constructing-and-spending-taproot-outputs
+#[export_name = "foundation_secp256k1_sign_schnorr_taproot"]
+pub extern "C" fn secp256k1_sign_schnorr_taproot(
+ data: &[u8; 32],
+ secret_key: &[u8; 32],
+ merkle_root: Option<&[u8; 32]>,
+ signature: &mut [u8; 64],
+) {
+ let mut keypair = taproot_tweak(secret_key, merkle_root);
+
+ let sig =
+ PRE_ALLOCATED_CTX.sign_schnorr_with_rng(data, &keypair, &mut rng());
+ keypair.non_secure_erase();
+ signature.copy_from_slice(sig.as_ref());
+}
+
+/// Applies the BIP-341 `TapTweak` to `secret_key`, negating it first when its
+/// public key has an odd Y coordinate.
+fn taproot_tweak(
+ secret_key: &[u8; 32],
+ merkle_root: Option<&[u8; 32]>,
+) -> Keypair {
+ let keypair = Keypair::from_seckey_slice(&PRE_ALLOCATED_CTX, secret_key)
+ .expect("invalid secret key");
+ let (internal_key, _) = keypair.x_only_public_key();
+
+ let tag = sha256::Hash::hash(b"TapTweak");
+ let mut engine = sha256::Hash::engine();
+ engine.input(tag.as_ref());
+ engine.input(tag.as_ref());
+ engine.input(&internal_key.serialize());
+ if let Some(merkle_root) = merkle_root {
+ engine.input(merkle_root);
+ }
+ let tweak = sha256::Hash::from_engine(engine).to_byte_array();
+
+ let tweak = Scalar::from_be_bytes(tweak).expect("tweak is out of range");
+ keypair
+ .add_xonly_tweak(&PRE_ALLOCATED_CTX, &tweak)
+ .expect("tweak produced an invalid key")
+}
+
#[cfg(target_arch = "arm")]
fn rng() -> crate::rand::PassportRng {
crate::rand::PassportRng
@@ -88,3 +141,92 @@ fn rng() -> crate::rand::PassportRng {
fn rng() -> rand::rngs::ThreadRng {
rand::thread_rng()
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use secp256k1::schnorr::Signature;
+
+ /// BIP-341 wallet test vectors, `keyPathSpending`: internal secret key,
+ /// Merkle root, and the expected tweaked secret key.
+ const KEY_PATH_VECTORS: &[(&str, Option<&str>, &str)] = &[
+ (
+ "6b973d88838f27366ed61c9ad6367663045cb456e28335c109e30717ae0c6baa",
+ None,
+ "2405b971772ad26915c8dcdf10f238753a9b837e5f8e6a86fd7c0cce5b7296d9",
+ ),
+ (
+ "1e4da49f6aaf4e5cd175fe08a32bb5cb4863d963921255f33d3bc31e1343907f",
+ Some("5b75adecf53548f3ec6ad7d78383bf84cc57b55a3127c72b9a2481752dd88b21"),
+ "ea260c3b10e60f6de018455cd0278f2f5b7e454be1999572789e6a9565d26080",
+ ),
+ (
+ "d3c7af07da2d54f7a7735d3d0fc4f0a73164db638b2f2f7c43f711f6d4aa7e64",
+ Some("c525714a7f49c28aedbbba78c005931a81c234b2f6c99a73e4d06082adc8bf2b"),
+ "97323385e57015b75b0339a549c56a948eb961555973f0951f555ae6039ef00d",
+ ),
+ (
+ "f36bb07a11e469ce941d16b63b11b9b9120a84d9d87cff2c84a8d4affb438f4e",
+ Some("ccbd66c6f7e8fdab47b3a486f59d28262be857f30d4773f2d5ea47f7761ce0e2"),
+ "a8e7aa924f0d58854185a490e6c41f6efb7b675c0f3331b7f14b549400b4d501",
+ ),
+ (
+ "415cfe9c15d9cea27d8104d5517c06e9de48e2f986b695e4f5ffebf230e725d8",
+ Some("2f6b2c5397b6d68ca18e09a3f05161668ffe93a988582d55c6f07bd5b3329def"),
+ "241c14f2639d0d7139282aa6abde28dd8a067baa9d633e4e7230287ec2d02901",
+ ),
+ (
+ "c7b0e81f0a9a0b0499e112279d718cca98e79a12e2f137c72ae5b213aad0d103",
+ Some("6c2dc106ab816b73f9d07e3cd1ef2c8c1256f519748e0813e4edd2405d277bef"),
+ "65b6000cd2bfa6b7cf736767a8955760e62b6649058cbc970b7c0871d786346b",
+ ),
+ (
+ "77863416be0d0665e517e1c375fd6f75839544eca553675ef7fdf4949518ebaa",
+ Some("ab179431c28d3b68fb798957faf5497d69c883c6fb1e1cd9f81483d87bac90cc"),
+ "ec18ce6af99f43815db543f47b8af5ff5df3b2cb7315c955aa4a86e8143d2bf5",
+ ),
+ ];
+
+ fn hex32(text: &str) -> [u8; 32] {
+ let mut bytes = [0; 32];
+ for (byte, pair) in bytes.iter_mut().zip(text.as_bytes().chunks(2)) {
+ let pair = core::str::from_utf8(pair).unwrap();
+ *byte = u8::from_str_radix(pair, 16).unwrap();
+ }
+ bytes
+ }
+
+ #[test]
+ fn taproot_tweak_matches_bip341_vectors() {
+ for (internal, merkle_root, tweaked) in KEY_PATH_VECTORS {
+ let merkle_root = merkle_root.map(hex32);
+ let keypair = taproot_tweak(&hex32(internal), merkle_root.as_ref());
+ assert_eq!(keypair.secret_bytes(), hex32(tweaked));
+ }
+ }
+
+ #[test]
+ fn taproot_signature_verifies_against_the_output_key() {
+ let data = [0x42; 32];
+ for (internal, merkle_root, tweaked) in KEY_PATH_VECTORS {
+ let merkle_root = merkle_root.map(hex32);
+ let mut signature = [0; 64];
+ secp256k1_sign_schnorr_taproot(
+ &data,
+ &hex32(internal),
+ merkle_root.as_ref(),
+ &mut signature,
+ );
+
+ let output_key =
+ Keypair::from_seckey_slice(&PRE_ALLOCATED_CTX, &hex32(tweaked))
+ .unwrap()
+ .x_only_public_key()
+ .0;
+ let signature = Signature::from_slice(&signature).unwrap();
+ PRE_ALLOCATED_CTX
+ .verify_schnorr(&signature, &data, &output_key)
+ .unwrap();
+ }
+ }
+}
### extmod/foundation/modfoundation-secp56k1.h
@@ -78,10 +78,56 @@ STATIC mp_obj_t mod_foundation_secp256k1_sign_schnorr(mp_obj_t data_obj,
STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_foundation_secp256k1_sign_schnorr_obj,
mod_foundation_secp256k1_sign_schnorr);
+/// def sign_schnorr_taproot(data, secret_key, merkle_root) -> bytes:
+/// """
+/// BIP-341 key path signature. secret_key is the internal key, before the
+/// Taproot tweak. merkle_root is the script tree root, or None when the
+/// output key commits to no script tree.
+/// """
+STATIC mp_obj_t mod_foundation_secp256k1_sign_schnorr_taproot(mp_obj_t data_obj,
+ mp_obj_t secret_key_obj,
+ mp_obj_t merkle_root_obj)
+{
+ mp_buffer_info_t data;
+ mp_buffer_info_t secret_key;
+ mp_buffer_info_t merkle_root;
+ const uint8_t (*merkle_root_ptr)[32] = NULL;
+ uint8_t signature[64];
+
+ mp_get_buffer_raise(data_obj, &data, MP_BUFFER_READ);
+ mp_get_buffer_raise(secret_key_obj, &secret_key, MP_BUFFER_READ);
+
+ if (data.len != 32) {
+ mp_raise_msg(&mp_type_ValueError, MP_ERROR_TEXT("data should be 32 bytes"));
+ }
+
+ if (secret_key.len != 32) {
+ mp_raise_msg(&mp_type_ValueError, MP_ERROR_TEXT("secret key should be 32 bytes"));
+ }
+
+ if (merkle_root_obj != mp_const_none) {
+ mp_get_buffer_raise(merkle_root_obj, &merkle_root, MP_BUFFER_READ);
+ if (merkle_root.len != 32) {
+ mp_raise_msg(&mp_type_ValueError, MP_ERROR_TEXT("merkle root should be 32 bytes"));
+ }
+ merkle_root_ptr = merkle_root.buf;
+ }
+
+ foundation_secp256k1_sign_schnorr_taproot(data.buf,
+ secret_key.buf,
+ merkle_root_ptr,
+ &signature);
+
+ return mp_obj_new_bytes(signature, sizeof(signature));
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_3(mod_foundation_secp256k1_sign_schnorr_taproot_obj,
+ mod_foundation_secp256k1_sign_schnorr_taproot);
+
STATIC const mp_rom_map_elem_t mod_foundation_secp256k1_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR_public_key_schnorr), MP_ROM_PTR(&mod_foundation_secp256k1_public_key_schnorr_obj) },
{ MP_ROM_QSTR(MP_QSTR_sign_ecdsa), MP_ROM_PTR(&mod_foundation_secp256k1_sign_ecdsa_obj) },
{ MP_ROM_QSTR(MP_QSTR_sign_schnorr), MP_ROM_PTR(&mod_foundation_secp256k1_sign_schnorr_obj) },
+ { MP_ROM_QSTR(MP_QSTR_sign_schnorr_taproot), MP_ROM_PTR(&mod_foundation_secp256k1_sign_schnorr_taproot_obj) },
};
STATIC MP_DEFINE_CONST_DICT(mod_foundation_secp256k1_globals, mod_foundation_secp256k1_globals_table);
### ports/stm32/boards/Passport/modules/taproot.py
@@ -122,16 +122,6 @@ def tweak_internal_key(internal_key, h):
return 0 if has_even_y(Q) else 1, bytes_from_int(x(Q))
-def taproot_tweak_seckey(seckey0, h):
- seckey0 = int_from_bytes(seckey0)
- P = scalar_multiply(seckey0)
- seckey = seckey0 if has_even_y(P) else SECP256K1_ORDER - seckey0
- t = int_from_bytes(hash_tap_tweak(bytes_from_int(x(P)) + h))
- if t >= SECP256K1_ORDER:
- raise ValueError
- return bytes_from_int((seckey + t) % SECP256K1_ORDER)
-
-
def taproot_tree_helper(script_tree):
from serializations import ser_string
@@ -166,11 +156,10 @@ def taproot_sign_key(script_tree, internal_seckey, hash_type, sighash):
from foundation import secp256k1
if script_tree is None:
- h = bytes()
+ merkle_root = None
else:
- _, h = taproot_tree_helper(script_tree)
- output_seckey = taproot_tweak_seckey(internal_seckey, h)
- sig = secp256k1.sign_schnorr(sighash, output_seckey)
+ _, merkle_root = taproot_tree_helper(script_tree)
+ sig = secp256k1.sign_schnorr_taproot(sighash, internal_seckey, merkle_root)
if hash_type != 0:
sig += bytes([hash_type])
return sig
### ports/stm32/boards/Passport/modules/tests/unit/psbt_sighash.py
@@ -11,11 +11,12 @@
from ustruct import pack
from exceptions import FatalPSBTIssue
+from foundation import secp256k1
from psbt import psbtInputProxy, psbtObject
from serializations import (COutPoint, CTxIn, CTxOut, SIGHASH_ALL, SIGHASH_DEFAULT,
ser_compact_size, ser_string, sha256)
from taproot import (bytes_from_int, int_from_bytes, output_script, scalar_multiply,
- tagged_hash, taproot_sign_key, taproot_tweak_seckey,
+ tagged_hash, taproot_sign_key, taproot_tree_helper,
tweak_internal_key, x)
# secp256k1, written out here rather than imported, so verification below does not
@@ -268,7 +269,6 @@ def ref_taproot_sighash(spec, input_idx, hash_type):
# Key path signing uses the tweaked key, so the two must differ to begin with.
assert TWEAKED_PUBKEY != INTERNAL_PUBKEY
-assert taproot_tweak_seckey(SECKEY, b'') != SECKEY
signatures = {}
for hash_type in (SIGHASH_DEFAULT, SIGHASH_ALL):
@@ -292,6 +292,27 @@ def ref_taproot_sighash(spec, input_idx, hash_type):
assert not bip340_verify(INTERNAL_PUBKEY, digests[(SIGHASH_DEFAULT, 0)], sig)
assert not bip340_verify(TWEAKED_PUBKEY, digests[(SIGHASH_ALL, 0)], sig)
+# With a script tree, the key is tweaked by the tree's Merkle root, so the signature
+# verifies under that output key and not under the key-only one.
+SCRIPT_TREE = [(0xc0, b'\x51'), (0xc0, b'\x52')]
+_, MERKLE_ROOT = taproot_tree_helper(SCRIPT_TREE)
+TREE_PUBKEY = tweak_internal_key(INTERNAL_PUBKEY, MERKLE_ROOT)[1]
+assert output_script(INTERNAL_PUBKEY, SCRIPT_TREE)[2:] == TREE_PUBKEY
+
+digest = digests[(SIGHASH_DEFAULT, 0)]
+sig = taproot_sign_key(SCRIPT_TREE, SECKEY, SIGHASH_DEFAULT, digest)
+assert bip340_verify(TREE_PUBKEY, digest, sig)
+assert not bip340_verify(TWEAKED_PUBKEY, digest, sig)
+
+# A Merkle root must be exactly 32 bytes.
+for merkle_root in (b'', MERKLE_ROOT[:31], MERKLE_ROOT + b'\x00'):
+ try:
+ secp256k1.sign_schnorr_taproot(digest, SECKEY, merkle_root)
+ except ValueError:
+ pass
+ else:
+ raise AssertionError('accepted a {} byte Merkle root'.format(len(merkle_root)))
+
# -------------------------------------------------------------------- legacy digest
Why this scored 15/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.