waffles_solana_program/
secp256k1_recover.rs

1//! Public key recovery from [secp256k1] ECDSA signatures.
2//!
3//! [secp256k1]: https://en.bitcoin.it/wiki/Secp256k1
4//!
5//! _This module provides low-level cryptographic building blocks that must be
6//! used carefully to ensure proper security. Read this documentation and
7//! accompanying links thoroughly._
8//!
9//! The [`secp256k1_recover`] syscall allows a secp256k1 public key that has
10//! previously signed a message to be recovered from the combination of the
11//! message, the signature, and a recovery ID. The recovery ID is generated
12//! during signing.
13//!
14//! Use cases for `secp256k1_recover` include:
15//!
16//! - Implementing the Ethereum [`ecrecover`] builtin contract.
17//! - Performing secp256k1 public key recovery generally.
18//! - Verifying a single secp256k1 signature.
19//!
20//! While `secp256k1_recover` can be used to verify secp256k1 signatures, Solana
21//! also provides the [secp256k1 program][sp], which is more flexible, has lower CPU
22//! cost, and can validate many signatures at once.
23//!
24//! [sp]: crate::secp256k1_program
25//! [`ecrecover`]: https://docs.soliditylang.org/en/v0.8.14/units-and-global-variables.html?highlight=ecrecover#mathematical-and-cryptographic-functions
26
27use {
28    borsh::{BorshDeserialize, BorshSchema, BorshSerialize},
29    core::convert::TryFrom,
30    thiserror::Error,
31};
32
33#[derive(Debug, Clone, PartialEq, Eq, Error)]
34pub enum Secp256k1RecoverError {
35    #[error("The hash provided to a secp256k1_recover is invalid")]
36    InvalidHash,
37    #[error("The recovery_id provided to a secp256k1_recover is invalid")]
38    InvalidRecoveryId,
39    #[error("The signature provided to a secp256k1_recover is invalid")]
40    InvalidSignature,
41}
42
43impl From<u64> for Secp256k1RecoverError {
44    fn from(v: u64) -> Secp256k1RecoverError {
45        match v {
46            1 => Secp256k1RecoverError::InvalidHash,
47            2 => Secp256k1RecoverError::InvalidRecoveryId,
48            3 => Secp256k1RecoverError::InvalidSignature,
49            _ => panic!("Unsupported Secp256k1RecoverError"),
50        }
51    }
52}
53
54impl From<Secp256k1RecoverError> for u64 {
55    fn from(v: Secp256k1RecoverError) -> u64 {
56        match v {
57            Secp256k1RecoverError::InvalidHash => 1,
58            Secp256k1RecoverError::InvalidRecoveryId => 2,
59            Secp256k1RecoverError::InvalidSignature => 3,
60        }
61    }
62}
63
64pub const SECP256K1_SIGNATURE_LENGTH: usize = 64;
65pub const SECP256K1_PUBLIC_KEY_LENGTH: usize = 64;
66
67#[repr(transparent)]
68#[derive(
69    BorshSerialize,
70    BorshDeserialize,
71    BorshSchema,
72    Clone,
73    Copy,
74    Eq,
75    PartialEq,
76    Ord,
77    PartialOrd,
78    Hash,
79    AbiExample,
80)]
81pub struct Secp256k1Pubkey(pub [u8; SECP256K1_PUBLIC_KEY_LENGTH]);
82
83impl Secp256k1Pubkey {
84    pub fn new(pubkey_vec: &[u8]) -> Self {
85        Self(
86            <[u8; SECP256K1_PUBLIC_KEY_LENGTH]>::try_from(<&[u8]>::clone(&pubkey_vec))
87                .expect("Slice must be the same length as a Pubkey"),
88        )
89    }
90
91    pub fn to_bytes(self) -> [u8; 64] {
92        self.0
93    }
94}
95
96/// Recover the public key from a [secp256k1] ECDSA signature and
97/// cryptographically-hashed message.
98///
99/// [secp256k1]: https://en.bitcoin.it/wiki/Secp256k1
100///
101/// This function is specifically intended for efficiently implementing
102/// Ethereum's [`ecrecover`] builtin contract, for use by Ethereum integrators.
103/// It may be useful for other purposes.
104///
105/// [`ecrecover`]: https://docs.soliditylang.org/en/v0.8.14/units-and-global-variables.html?highlight=ecrecover#mathematical-and-cryptographic-functions
106///
107/// `hash` is the 32-byte cryptographic hash (typically [`keccak`]) of an
108/// arbitrary message, signed by some public key.
109///
110/// The recovery ID is a value in the range [0, 3] that is generated during
111/// signing, and allows the recovery process to be more efficent. Note that the
112/// `recovery_id` here does not directly correspond to an Ethereum recovery ID
113/// as used in `ecrecover`. This function accepts recovery IDs in the range of
114/// [0, 3], while Ethereum's recovery IDs have a value of 27 or 28. To convert
115/// an Ethereum recovery ID to a value this function will accept subtract 27
116/// from it, checking for underflow. In practice this function will not succeed
117/// if given a recovery ID of 2 or 3, as these values represent an
118/// "overflowing" signature, and this function returns an error when parsing
119/// overflowing signatures.
120///
121/// [`keccak`]: crate::keccak
122/// [`wrapping_sub`]: https://doc.rust-lang.org/std/primitive.u8.html#method.wrapping_sub
123///
124/// On success this function returns a [`Secp256k1Pubkey`], a wrapper around a
125/// 64-byte secp256k1 public key. This public key corresponds to the secret key
126/// that previously signed the message `hash` to produce the provided
127/// `signature`.
128///
129/// While `secp256k1_recover` can be used to verify secp256k1 signatures by
130/// comparing the recovered key against an expected key, Solana also provides
131/// the [secp256k1 program][sp], which is more flexible, has lower CPU cost, and
132/// can validate many signatures at once.
133///
134/// [sp]: crate::secp256k1_program
135///
136/// The `secp256k1_recover` syscall is implemented with the [`libsecp256k1`]
137/// crate, which clients may also want to use.
138///
139/// [`libsecp256k1`]: https://docs.rs/libsecp256k1/latest/libsecp256k1
140///
141/// # Hashing messages
142///
143/// In ECDSA signing and key recovery the signed "message" is always a
144/// crytographic hash, not the original message itself. If not a cryptographic
145/// hash, then an adversary can craft signatures that recover to arbitrary
146/// public keys. This means the caller of this function generally must hash the
147/// original message themselves and not rely on another party to provide the
148/// hash.
149///
150/// Ethereum uses the [`keccak`] hash.
151///
152/// # Signature malleability
153///
154/// With the ECDSA signature algorithm it is possible for any party, given a
155/// valid signature of some message, to create a second signature that is
156/// equally valid. This is known as _signature malleability_. In many cases this
157/// is not a concern, but in cases where applications rely on signatures to have
158/// a unique representation this can be the source of bugs, potentially with
159/// security implications.
160///
161/// **The solana `secp256k1_recover` function does not prevent signature
162/// malleability**. This is in contrast to the Bitcoin secp256k1 library, which
163/// does prevent malleability by default. Solana accepts signatures with `S`
164/// values that are either in the _high order_ or in the _low order_, and it
165/// is trivial to produce one from the other.
166///
167/// To prevent signature malleability, it is common for secp256k1 signature
168/// validators to only accept signatures with low-order `S` values, and reject
169/// signatures with high-order `S` values. The following code will accomplish
170/// this:
171///
172/// ```rust
173/// # use solana_program::program_error::ProgramError;
174/// # let signature_bytes = [
175/// #     0x83, 0x55, 0x81, 0xDF, 0xB1, 0x02, 0xA7, 0xD2,
176/// #     0x2D, 0x33, 0xA4, 0x07, 0xDD, 0x7E, 0xFA, 0x9A,
177/// #     0xE8, 0x5F, 0x42, 0x6B, 0x2A, 0x05, 0xBB, 0xFB,
178/// #     0xA1, 0xAE, 0x93, 0x84, 0x46, 0x48, 0xE3, 0x35,
179/// #     0x74, 0xE1, 0x6D, 0xB4, 0xD0, 0x2D, 0xB2, 0x0B,
180/// #     0x3C, 0x89, 0x8D, 0x0A, 0x44, 0xDF, 0x73, 0x9C,
181/// #     0x1E, 0xBF, 0x06, 0x8E, 0x8A, 0x9F, 0xA9, 0xC3,
182/// #     0xA5, 0xEA, 0x21, 0xAC, 0xED, 0x5B, 0x22, 0x13,
183/// # ];
184/// let signature = libsecp256k1::Signature::parse_standard_slice(&signature_bytes)
185///     .map_err(|_| ProgramError::InvalidArgument)?;
186///
187/// if signature.s.is_high() {
188///     return Err(ProgramError::InvalidArgument);
189/// }
190/// # Ok::<_, ProgramError>(())
191/// ```
192///
193/// This has the downside that the program must link to the [`libsecp256k1`]
194/// crate and parse the signature just for this check. Note that `libsecp256k1`
195/// version 0.7.0 or greater is required for running on the Solana SBF target.
196///
197/// [`libsecp256k1`]: https://docs.rs/libsecp256k1/latest/libsecp256k1
198///
199/// For the most accurate description of signature malleability, and its
200/// prevention in secp256k1, refer to comments in [`secp256k1.h`] in the Bitcoin
201/// Core secp256k1 library, the documentation of the [OpenZeppelin `recover`
202/// method for Solidity][ozr], and [this description of the problem on
203/// StackExchange][sxr].
204///
205/// [`secp256k1.h`]: https://github.com/bitcoin-core/secp256k1/blob/44c2452fd387f7ca604ab42d73746e7d3a44d8a2/include/secp256k1.h
206/// [ozr]: https://docs.openzeppelin.com/contracts/2.x/api/cryptography#ECDSA-recover-bytes32-bytes-
207/// [sxr]: https://bitcoin.stackexchange.com/questions/81115/if-someone-wanted-to-pretend-to-be-satoshi-by-posting-a-fake-signature-to-defrau/81116#81116
208///
209/// # Errors
210///
211/// If `hash` is not 32 bytes in length this function returns
212/// [`Secp256k1RecoverError::InvalidHash`], though see notes
213/// on SBF-specific behavior below.
214///
215/// If `recovery_id` is not in the range [0, 3] this function returns
216/// [`Secp256k1RecoverError::InvalidRecoveryId`].
217///
218/// If `signature` is not 64 bytes in length this function returns
219/// [`Secp256k1RecoverError::InvalidSignature`], though see notes
220/// on SBF-specific behavior below.
221///
222/// If `signature` represents an "overflowing" signature this function returns
223/// [`Secp256k1RecoverError::InvalidSignature`]. Overflowing signatures are
224/// non-standard and should not be encountered in practice.
225///
226/// If `signature` is otherwise invalid this function returns
227/// [`Secp256k1RecoverError::InvalidSignature`].
228///
229/// # SBF-specific behavior
230///
231/// When calling this function on-chain the caller must verify the correct
232/// lengths of `hash` and `signature` beforehand.
233///
234/// When run on-chain this function will not directly validate the lengths of
235/// `hash` and `signature`. It will assume they are the the correct lengths and
236/// pass their pointers to the runtime, which will interpret them as 32-byte and
237/// 64-byte buffers. If the provided slices are too short, the runtime will read
238/// invalid data and attempt to interpret it, most likely returning an error,
239/// though in some scenarios it may be possible to incorrectly return
240/// successfully, or the transaction will abort if the syscall reads data
241/// outside of the program's memory space. If the provided slices are too long
242/// then they may be used to "smuggle" uninterpreted data.
243///
244/// # Examples
245///
246/// This example demonstrates recovering a public key and using it to very a
247/// signature with the `secp256k1_recover` syscall. It has three parts: a Solana
248/// program, an RPC client to call the program, and common definitions shared
249/// between the two.
250///
251/// Common definitions:
252///
253/// ```
254/// use borsh::{BorshDeserialize, BorshSerialize};
255///
256/// #[derive(BorshSerialize, BorshDeserialize, Debug)]
257/// pub struct DemoSecp256k1RecoverInstruction {
258///     pub message: Vec<u8>,
259///     pub signature: [u8; 64],
260///     pub recovery_id: u8,
261/// }
262/// ```
263///
264/// The Solana program. Note that it uses `libsecp256k1` version 0.7.0 to parse
265/// the secp256k1 signature to prevent malleability.
266///
267/// ```no_run
268/// use solana_program::{
269///     entrypoint::ProgramResult,
270///     keccak, msg,
271///     program_error::ProgramError,
272///     secp256k1_recover::secp256k1_recover,
273/// };
274///
275/// /// The key we expect to sign secp256k1 messages,
276/// /// as serialized by `libsecp256k1::PublicKey::serialize`.
277/// const AUTHORIZED_PUBLIC_KEY: [u8; 64] = [
278///     0x8C, 0xD6, 0x47, 0xF8, 0xA5, 0xBF, 0x59, 0xA0, 0x4F, 0x77, 0xFA, 0xFA, 0x6C, 0xA0, 0xE6, 0x4D,
279///     0x94, 0x5B, 0x46, 0x55, 0xA6, 0x2B, 0xB0, 0x6F, 0x10, 0x4C, 0x9E, 0x2C, 0x6F, 0x42, 0x0A, 0xBE,
280///     0x18, 0xDF, 0x0B, 0xF0, 0x87, 0x42, 0xBA, 0x88, 0xB4, 0xCF, 0x87, 0x5A, 0x35, 0x27, 0xBE, 0x0F,
281///     0x45, 0xAE, 0xFC, 0x66, 0x9C, 0x2C, 0x6B, 0xF3, 0xEF, 0xCA, 0x5C, 0x32, 0x11, 0xF7, 0x2A, 0xC7,
282/// ];
283/// # pub struct DemoSecp256k1RecoverInstruction {
284/// #     pub message: Vec<u8>,
285/// #     pub signature: [u8; 64],
286/// #     pub recovery_id: u8,
287/// # }
288///
289/// pub fn process_secp256k1_recover(
290///     instruction: DemoSecp256k1RecoverInstruction,
291/// ) -> ProgramResult {
292///     // The secp256k1 recovery operation accepts a cryptographically-hashed
293///     // message only. Passing it anything else is insecure and allows signatures
294///     // to be forged.
295///     //
296///     // This means that the code calling `secp256k1_recover` must perform the hash
297///     // itself, and not assume that data passed to it has been properly hashed.
298///     let message_hash = {
299///         let mut hasher = keccak::Hasher::default();
300///         hasher.hash(&instruction.message);
301///         hasher.result()
302///     };
303///
304///     // Reject high-s value signatures to prevent malleability.
305///     // Solana does not do this itself.
306///     // This may or may not be necessary depending on use case.
307///     {
308///         let signature = libsecp256k1::Signature::parse_standard_slice(&instruction.signature)
309///             .map_err(|_| ProgramError::InvalidArgument)?;
310///
311///         if signature.s.is_high() {
312///             msg!("signature with high-s value");
313///             return Err(ProgramError::InvalidArgument);
314///         }
315///     }
316///
317///     let recovered_pubkey = secp256k1_recover(
318///         &message_hash.0,
319///         instruction.recovery_id,
320///         &instruction.signature,
321///     )
322///     .map_err(|_| ProgramError::InvalidArgument)?;
323///
324///     // If we're using this function for signature verification then we
325///     // need to check the pubkey is an expected value.
326///     // Here we are checking the secp256k1 pubkey against a known authorized pubkey.
327///     if recovered_pubkey.0 != AUTHORIZED_PUBLIC_KEY {
328///         return Err(ProgramError::InvalidArgument);
329///     }
330///
331///     Ok(())
332/// }
333/// ```
334///
335/// The RPC client program:
336///
337/// ```no_run
338/// # use solana_program::example_mocks::solana_rpc_client;
339/// # use solana_program::example_mocks::solana_sdk;
340/// use anyhow::Result;
341/// use solana_rpc_client::rpc_client::RpcClient;
342/// use solana_sdk::{
343///     instruction::Instruction,
344///     keccak,
345///     pubkey::Pubkey,
346///     signature::{Keypair, Signer},
347///     transaction::Transaction,
348/// };
349/// # use borsh::{BorshDeserialize, BorshSerialize};
350/// # #[derive(BorshSerialize, BorshDeserialize, Debug)]
351/// # pub struct DemoSecp256k1RecoverInstruction {
352/// #     pub message: Vec<u8>,
353/// #     pub signature: [u8; 64],
354/// #     pub recovery_id: u8,
355/// # }
356///
357/// pub fn demo_secp256k1_recover(
358///     payer_keypair: &Keypair,
359///     secp256k1_secret_key: &libsecp256k1::SecretKey,
360///     client: &RpcClient,
361///     program_keypair: &Keypair,
362/// ) -> Result<()> {
363///     let message = b"hello world";
364///     let message_hash = {
365///         let mut hasher = keccak::Hasher::default();
366///         hasher.hash(message);
367///         hasher.result()
368///     };
369///
370///     let secp_message = libsecp256k1::Message::parse(&message_hash.0);
371///     let (signature, recovery_id) = libsecp256k1::sign(&secp_message, &secp256k1_secret_key);
372///
373///     let signature = signature.serialize();
374///
375///     let instr = DemoSecp256k1RecoverInstruction {
376///         message: message.to_vec(),
377///         signature,
378///         recovery_id: recovery_id.serialize(),
379///     };
380///     let instr = Instruction::new_with_borsh(
381///         program_keypair.pubkey(),
382///         &instr,
383///         vec![],
384///     );
385///
386///     let blockhash = client.get_latest_blockhash()?;
387///     let tx = Transaction::new_signed_with_payer(
388///         &[instr],
389///         Some(&payer_keypair.pubkey()),
390///         &[payer_keypair],
391///         blockhash,
392///     );
393///
394///     client.send_and_confirm_transaction(&tx)?;
395///
396///     Ok(())
397/// }
398/// ```
399pub fn secp256k1_recover(
400    hash: &[u8],
401    recovery_id: u8,
402    signature: &[u8],
403) -> Result<Secp256k1Pubkey, Secp256k1RecoverError> {
404    #[cfg(target_os = "solana")]
405    {
406        let mut pubkey_buffer = [0u8; SECP256K1_PUBLIC_KEY_LENGTH];
407        let result = unsafe {
408            crate::syscalls::sol_secp256k1_recover(
409                hash.as_ptr(),
410                recovery_id as u64,
411                signature.as_ptr(),
412                pubkey_buffer.as_mut_ptr(),
413            )
414        };
415
416        match result {
417            0 => Ok(Secp256k1Pubkey::new(&pubkey_buffer)),
418            error => Err(Secp256k1RecoverError::from(error)),
419        }
420    }
421
422    #[cfg(not(target_os = "solana"))]
423    {
424        let message = libsecp256k1::Message::parse_slice(hash)
425            .map_err(|_| Secp256k1RecoverError::InvalidHash)?;
426        let recovery_id = libsecp256k1::RecoveryId::parse(recovery_id)
427            .map_err(|_| Secp256k1RecoverError::InvalidRecoveryId)?;
428        let signature = libsecp256k1::Signature::parse_standard_slice(signature)
429            .map_err(|_| Secp256k1RecoverError::InvalidSignature)?;
430        let secp256k1_key = libsecp256k1::recover(&message, &signature, &recovery_id)
431            .map_err(|_| Secp256k1RecoverError::InvalidSignature)?;
432        Ok(Secp256k1Pubkey::new(&secp256k1_key.serialize()[1..65]))
433    }
434}