Skip to main content

dpp/util/ecdsa/verify_hash_signature/
mod.rs

1use crate::util::ecdsa::verify_hash_signature::v0::verify_hash_signature_v0;
2use crate::util::ecdsa::verify_hash_signature::v1::verify_hash_signature_v1;
3use crate::ProtocolError;
4use platform_version::version::PlatformVersion;
5
6mod v0;
7mod v1;
8
9/// Checks that `signature`, a 65-byte compact recoverable ECDSA signature over `data_hash`, was
10/// made by the key whose HASH160 is `public_key_hash`, by recovering the key: an ECDSA_HASH160
11/// identity key, a P2PKH address witness, an asset lock's one-time key.
12///
13/// Recovery alone leaves a third party two ways to turn a valid signature into another valid
14/// one, and so to change the hash of the transition carrying it:
15///
16/// - it takes any S, so the signature stays valid with S replaced by `n - S` and the recovery
17///   id's parity flipped;
18/// - it hashes the recovered key in its compressed form whatever the header says, so the
19///   signature stays valid with its header rewritten from `31 + id` (a compressed key) to
20///   `27 + id` (an uncompressed one).
21///
22/// # Parameters
23///
24/// - `data_hash`: the 32-byte digest that was signed.
25/// - `signature`: the compact recoverable signature.
26/// - `public_key_hash`: the HASH160 of the compressed public key expected to have signed.
27/// - `platform_version`: selects the rule through
28///   `dpp.state_transition_method_versions.verify_hash_signature`. 0 is
29///   `dashcore::signer::verify_hash_signature`, which accepts both rewrites (protocol versions
30///   1 to 14); 1 also refuses a high-S signature and a header that does not name a compressed
31///   key.
32///
33/// # Returns
34///
35/// `Ok(Ok(()))` when the signature is valid, `Ok(Err(_))` with the reason when it is not, and
36/// `Err(ProtocolError::UnknownVersionMismatch)` for a version this build does not know.
37pub fn verify_hash_signature(
38    data_hash: &[u8],
39    signature: &[u8],
40    public_key_hash: &[u8],
41    platform_version: &PlatformVersion,
42) -> Result<Result<(), anyhow::Error>, ProtocolError> {
43    match platform_version
44        .dpp
45        .state_transition_method_versions
46        .verify_hash_signature
47    {
48        0 => Ok(verify_hash_signature_v0(
49            data_hash,
50            signature,
51            public_key_hash,
52        )),
53        1 => Ok(verify_hash_signature_v1(
54            data_hash,
55            signature,
56            public_key_hash,
57        )),
58        version => Err(ProtocolError::UnknownVersionMismatch {
59            method: "verify_hash_signature".to_string(),
60            known_versions: vec![0, 1],
61            received: version,
62        }),
63    }
64}
65
66#[cfg(test)]
67mod tests {
68    use super::*;
69    use crate::tests::utils::{high_s_twin, uncompressed_header_twin};
70    use dashcore::crypto::ecdsa::{EcdsaError, EcdsaSignature};
71    use dashcore::signer::{double_sha, sign_hash};
72    use dashcore::{sign_message, signer, PrivateKey};
73
74    /// Half the curve order, `n / 2`, the largest low S.
75    const HALF_ORDER: [u8; 32] = [
76        0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
77        0xff, 0x5d, 0x57, 0x6e, 0x73, 0x57, 0xa4, 0x50, 0x1d, 0xdf, 0xe9, 0x2f, 0x46, 0x68, 0x1b,
78        0x20, 0xa0,
79    ];
80    /// The curve order `n`.
81    const ORDER: [u8; 32] = [
82        0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
83        0xfe, 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36,
84        0x41, 0x41,
85    ];
86
87    fn signature_s_is_low(signature: &[u8]) -> bool {
88        sign_message::from_slice(signature)
89            .expect("a compact recoverable signature")
90            .signature()
91            .expect("a valid signature")
92            .is_low_s()
93    }
94
95    /// A low-S signature over a digest, the digest, and the signing key's HASH160.
96    fn fixture() -> (Vec<u8>, Vec<u8>, Vec<u8>) {
97        let secret = [0x11; 32];
98        let key_hash = PrivateKey::from_byte_array(&secret, dashcore::Network::Testnet)
99            .expect("a valid key")
100            .public_key()
101            .pubkey_hash();
102        let digest = double_sha(b"a message");
103        let signature = sign_hash(&digest, &secret).expect("signs").to_vec();
104        (digest, signature, key_hash.to_byte_array().to_vec())
105    }
106
107    /// `signature` with its S replaced by `s`.
108    fn with_s(signature: &[u8], s: [u8; 32]) -> Vec<u8> {
109        let mut changed = signature.to_vec();
110        changed[33..].copy_from_slice(&s);
111        changed
112    }
113
114    /// `signature` with its header byte replaced by `header`.
115    fn with_header(signature: &[u8], header: u8) -> Vec<u8> {
116        let mut changed = signature.to_vec();
117        changed[0] = header;
118        changed
119    }
120
121    fn protocol_version(version: u32) -> &'static PlatformVersion {
122        PlatformVersion::get(version).expect("a known protocol version")
123    }
124
125    #[test]
126    fn should_hold_s_equal_to_half_the_order_low_and_one_more_high() {
127        let mut compact = [1u8; 64];
128        compact[32..].copy_from_slice(&HALF_ORDER);
129        assert!(EcdsaSignature::from_bytes(&compact)
130            .expect("a valid signature")
131            .is_low_s());
132        compact[63] += 1;
133        assert!(!EcdsaSignature::from_bytes(&compact)
134            .expect("a valid signature")
135            .is_low_s());
136    }
137
138    #[test]
139    fn should_build_a_high_s_twin_that_recovery_alone_accepts() {
140        let (digest, signature, key_hash) = fixture();
141        let twin = high_s_twin(&signature);
142        assert!(signature_s_is_low(&signature));
143        assert!(!signature_s_is_low(&twin));
144        signer::verify_hash_signature(&digest, &twin, &key_hash)
145            .expect("recovery alone accepts the twin");
146    }
147
148    #[test]
149    fn should_build_an_uncompressed_header_twin_that_recovery_alone_accepts() {
150        let (digest, signature, key_hash) = fixture();
151        let twin = uncompressed_header_twin(&signature);
152        assert_eq!(twin[0] + 4, signature[0]);
153        assert_eq!(twin[1..], signature[1..]);
154        assert!(signature_s_is_low(&twin));
155        signer::verify_hash_signature(&digest, &twin, &key_hash)
156            .expect("recovery alone accepts the twin");
157    }
158
159    #[test]
160    fn should_accept_the_high_s_twin_up_to_protocol_version_14() {
161        let (digest, signature, key_hash) = fixture();
162        let twin = high_s_twin(&signature);
163        for version in [1, 13, 14] {
164            let platform_version = protocol_version(version);
165            verify_hash_signature(&digest, &signature, &key_hash, platform_version)
166                .expect("a known version")
167                .expect("the low-S signature is valid");
168            verify_hash_signature(&digest, &twin, &key_hash, platform_version)
169                .expect("a known version")
170                .expect("protocol version 14 and earlier accept the high-S twin");
171        }
172    }
173
174    #[test]
175    fn should_refuse_the_high_s_twin_at_the_latest_protocol_version() {
176        let (digest, signature, key_hash) = fixture();
177        let platform_version = PlatformVersion::latest();
178        verify_hash_signature(&digest, &signature, &key_hash, platform_version)
179            .expect("a known version")
180            .expect("the low-S signature is valid");
181        let error = verify_hash_signature(
182            &digest,
183            &high_s_twin(&signature),
184            &key_hash,
185            platform_version,
186        )
187        .expect("a known version")
188        .expect_err("the high-S twin is refused");
189        assert_eq!(error.to_string(), EcdsaError::VerifyFailed.to_string());
190    }
191
192    #[test]
193    fn should_accept_the_uncompressed_header_twin_up_to_protocol_version_14() {
194        let (digest, signature, key_hash) = fixture();
195        let twin = uncompressed_header_twin(&signature);
196        for version in [1, 13, 14] {
197            verify_hash_signature(&digest, &twin, &key_hash, protocol_version(version))
198                .expect("a known version")
199                .expect("protocol version 14 and earlier accept the uncompressed header");
200        }
201    }
202
203    #[test]
204    fn should_refuse_the_uncompressed_header_twin_at_the_latest_protocol_version() {
205        let (digest, signature, key_hash) = fixture();
206        let platform_version = PlatformVersion::latest();
207        // The twin, and the twin of the high-S twin: neither rewrite hides the other.
208        for twin in [
209            uncompressed_header_twin(&signature),
210            uncompressed_header_twin(&high_s_twin(&signature)),
211        ] {
212            let error = verify_hash_signature(&digest, &twin, &key_hash, platform_version)
213                .expect("a known version")
214                .expect_err("the uncompressed header is refused");
215            assert_eq!(error.to_string(), EcdsaError::VerifyFailed.to_string());
216        }
217    }
218
219    /// Of the eight headers recovery parses, 27 to 34, the latest protocol version accepts one:
220    /// the compressed-key header carrying the recovery id that recovers the signing key.
221    #[test]
222    fn should_accept_a_single_header_at_the_latest_protocol_version() {
223        let (digest, signature, key_hash) = fixture();
224        let accepted: Vec<u8> = (27..=34)
225            .filter(|header| {
226                let mut candidate = signature.clone();
227                candidate[0] = *header;
228                verify_hash_signature(&digest, &candidate, &key_hash, PlatformVersion::latest())
229                    .expect("a known version")
230                    .is_ok()
231            })
232            .collect();
233        assert_eq!(accepted, vec![signature[0]]);
234    }
235
236    /// A signature recovery already refuses (another key, a wrong length, S zero or not below the
237    /// curve order, a header outside 27 to 34) fails with the library's own error at both
238    /// versions.
239    #[test]
240    fn should_fail_an_invalid_signature_with_the_same_error_at_both_versions() {
241        let (digest, signature, key_hash) = fixture();
242        let wrong_key_hash = [7u8; 20];
243        let cases = [
244            (signature.clone(), wrong_key_hash.to_vec(), "another key"),
245            (signature[..64].to_vec(), key_hash.clone(), "a wrong length"),
246            (with_s(&signature, [0; 32]), key_hash.clone(), "S zero"),
247            (with_s(&signature, ORDER), key_hash.clone(), "S equal to n"),
248            (
249                with_s(&signature, [0xff; 32]),
250                key_hash.clone(),
251                "S above n",
252            ),
253            (with_header(&signature, 26), key_hash.clone(), "header 26"),
254            (with_header(&signature, 35), key_hash.clone(), "header 35"),
255        ];
256        for (signature, key_hash, label) in cases {
257            let legacy =
258                verify_hash_signature(&digest, &signature, &key_hash, protocol_version(14))
259                    .expect("a known version")
260                    .expect_err(label);
261            let latest =
262                verify_hash_signature(&digest, &signature, &key_hash, PlatformVersion::latest())
263                    .expect("a known version")
264                    .expect_err(label);
265            assert_eq!(legacy.to_string(), latest.to_string(), "{label}");
266        }
267    }
268}