miden_stdlib/handlers/
ecdsa.rs

1//! ECDSA signature verification precompile for the Miden VM.
2//!
3//! This module provides both execution-time and verification-time support for ECDSA signature
4//! verification using the secp256k1 curve with Keccak256 hashing.
5//!
6//! ## Architecture
7//!
8//! ### Event Handler (Execution-Time)
9//! When the VM emits an ECDSA verification event requesting signature validation, the processor
10//! calls [`EcdsaPrecompile`] which reads the public key, message digest, and signature from
11//! memory, performs the verification, provides the boolean result via the advice stack, and logs
12//! the request data for deferred verification.
13//!
14//! ### Precompile Verifier (Verification-Time)
15//! During verification, the [`PrecompileVerifier`] receives the stored request data (public key,
16//! digest, signature), re-performs the ECDSA verification, and generates a commitment
17//! `Rpo256(Rpo256(Rpo256(pk) || Rpo256(digest)) || Rpo256(sig))` with a tag containing the
18//! verification result that validates the computation was performed correctly. Here `pk`,
19//! `digest`, and `sig` are hashed as u32‑packed field elements before being merged.
20//!
21//! ### Commitment Tag Format
22//! Each request is tagged as `[event_id, result, 0, 0]` where `result` is 1 for valid signatures
23//! and 0 for invalid ones. This allows the verifier to check that the execution-time result
24//! matches the verification-time result.
25//!
26//! ## Data Format
27//! - **Public Key**: 33 bytes (compressed secp256k1 point)
28//! - **Message Digest**: 32 bytes (Keccak256 hash of the message)
29//! - **Signature**: 66 bytes (implementation‑defined serialization used by
30//!   `miden_crypto::dsa::ecdsa_k256_keccak::Signature`). When packed into u32 elements for VM
31//!   memory, the final word contains 2 zero padding bytes (since 66 ≡ 2 mod 4).
32
33use alloc::{vec, vec::Vec};
34
35use miden_core::{
36    EventName,
37    precompile::{PrecompileCommitment, PrecompileError, PrecompileRequest, PrecompileVerifier},
38    utils::{ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable},
39};
40use miden_crypto::{
41    ZERO,
42    dsa::ecdsa_k256_keccak::{PublicKey, Signature},
43    hash::rpo::Rpo256,
44};
45use miden_processor::{AdviceMutation, EventError, EventHandler, ProcessState};
46
47use crate::handlers::{bytes_to_packed_u32_felts, read_memory_packed_u32};
48
49/// Qualified event name for the ECDSA signature verification event.
50pub const ECDSA_VERIFY_EVENT_NAME: EventName = EventName::new("stdlib::crypto::dsa::ecdsa::verify");
51
52const PUBLIC_KEY_LEN_BYTES: usize = 33;
53const MESSAGE_DIGEST_LEN_BYTES: usize = 32;
54const SIGNATURE_LEN_BYTES: usize = 66; // r (32) + s (32) + v (1) + padding (1)
55
56const PRECOMPILE_REQUEST_LEN: usize =
57    PUBLIC_KEY_LEN_BYTES + MESSAGE_DIGEST_LEN_BYTES + SIGNATURE_LEN_BYTES;
58
59/// ECDSA signature verification precompile handler.
60pub struct EcdsaPrecompile;
61
62impl EventHandler for EcdsaPrecompile {
63    /// ECDSA verification event handler called by the processor when the VM emits a signature
64    /// verification request event.
65    ///
66    /// Reads the public key, signature, and message digest from memory, performs ECDSA signature
67    /// verification, provides the result via the advice stack, and stores the request data for
68    /// verification (see [`PrecompileVerifier`]).
69    ///
70    /// ## Input Format
71    /// - **Stack**: `[event_id, ptr_pk, ptr_digest, ptr_sig, ...]` where all pointers are
72    ///   word-aligned (divisible by 4)
73    /// - **Memory**: Data stored as packed u32 field elements (4 bytes per element, little-endian)
74    ///   with unused bytes in the final u32 set to zero
75    ///
76    /// ## Output Format
77    /// - **Advice Stack**: Extended with verification result (1 for valid, 0 for invalid)
78    /// - **Precompile Request**: Stores tag `[event_id, result, 0, 0]` and serialized request data
79    ///   (pk || digest || sig) for verification time
80    fn on_event(&self, process: &ProcessState) -> Result<Vec<AdviceMutation>, EventError> {
81        // Stack: [event_id, ptr_pk, ptr_digest, ptr_sig, ...]
82        let ptr_pk = process.get_stack_item(1).as_int();
83        let ptr_digest = process.get_stack_item(2).as_int();
84        let ptr_sig = process.get_stack_item(3).as_int();
85
86        let pk = {
87            let data_type = DataType::PublicKey;
88            let bytes = read_memory_packed_u32(process, ptr_pk, PUBLIC_KEY_LEN_BYTES)
89                .map_err(|source| EcdsaError::ReadError { data_type, source })?;
90            PublicKey::read_from_bytes(&bytes)
91                .map_err(|source| EcdsaError::DeserializeError { data_type, source })?
92        };
93
94        let sig = {
95            let data_type = DataType::Signature;
96            let bytes = read_memory_packed_u32(process, ptr_sig, SIGNATURE_LEN_BYTES)
97                .map_err(|source| EcdsaError::ReadError { data_type, source })?;
98            Signature::read_from_bytes(&bytes)
99                .map_err(|source| EcdsaError::DeserializeError { data_type, source })?
100        };
101
102        let digest = read_memory_packed_u32(process, ptr_digest, MESSAGE_DIGEST_LEN_BYTES)
103            .map_err(|source| EcdsaError::ReadError { data_type: DataType::Digest, source })?
104            .try_into()
105            .expect("digest is exactly 32 bytes");
106
107        let request = EcdsaRequest::new(pk, digest, sig);
108        let result = request.result();
109
110        Ok(vec![
111            AdviceMutation::extend_stack([result.into()]),
112            AdviceMutation::extend_precompile_requests([request.into()]),
113        ])
114    }
115}
116
117impl PrecompileVerifier for EcdsaPrecompile {
118    /// Verifier for ECDSA signature verification at verification time.
119    ///
120    /// Receives the serialized request data (public key || digest || signature) stored during
121    /// execution (see [`EventHandler::on_event`]), re-performs the ECDSA verification, and
122    /// generates a commitment `RPO(RPO(RPO(pk) || RPO(digest)) || RPO(sig))` with tag
123    /// `[event_id, result, 0, 0]` that validates against the execution trace. Each of `pk`,
124    /// `digest`, and `sig` is first converted to u32‑packed field elements before hashing.
125    fn verify(&self, calldata: &[u8]) -> Result<PrecompileCommitment, PrecompileError> {
126        let request = EcdsaRequest::read_from_bytes(calldata)?;
127        Ok(request.as_precompile_commitment())
128    }
129}
130
131/// ECDSA signature verification request containing all data needed to verify a signature.
132///
133/// This structure encapsulates a complete ECDSA verification request including the public key,
134/// message digest, and signature. It is used during both execution (via the event handler) and
135/// verification (via the precompile verifier).
136pub struct EcdsaRequest {
137    /// secp256k1 public key (33 bytes, compressed)
138    pk: PublicKey,
139    /// Message digest (32 bytes, typically Keccak256 hash)
140    digest: [u8; MESSAGE_DIGEST_LEN_BYTES],
141    /// ECDSA signature (serialized by the implementation; 66 bytes in this crate)
142    sig: Signature,
143}
144
145impl EcdsaRequest {
146    /// Creates a new ECDSA verification request.
147    ///
148    /// # Arguments
149    /// * `pk` - The secp256k1 public key (33 bytes, compressed)
150    /// * `digest` - The message digest (32 bytes)
151    /// * `sig` - The ECDSA signature
152    pub fn new(pk: PublicKey, digest: [u8; MESSAGE_DIGEST_LEN_BYTES], sig: Signature) -> Self {
153        Self { pk, digest, sig }
154    }
155
156    /// Returns a reference to the public key.
157    pub fn pk(&self) -> &PublicKey {
158        &self.pk
159    }
160
161    /// Returns a reference to the digest.
162    pub fn digest(&self) -> &[u8; MESSAGE_DIGEST_LEN_BYTES] {
163        &self.digest
164    }
165
166    /// Returns a reference to the signature.
167    pub fn sig(&self) -> &Signature {
168        &self.sig
169    }
170
171    /// Converts this request into a [`PrecompileRequest`] for deferred verification.
172    ///
173    /// Serializes the request data (public key || digest || signature) and wraps it in a
174    /// PrecompileRequest with the ECDSA event ID.
175    pub fn as_precompile_request(&self) -> PrecompileRequest {
176        let mut calldata = Vec::with_capacity(PRECOMPILE_REQUEST_LEN);
177        self.write_into(&mut calldata);
178        PrecompileRequest::new(ECDSA_VERIFY_EVENT_NAME.to_event_id(), calldata)
179    }
180
181    /// Performs ECDSA signature verification and returns the result.
182    ///
183    /// Returns `true` if the signature is valid for the given public key and digest,
184    /// `false` otherwise.
185    pub fn result(&self) -> bool {
186        self.pk.verify_prehash(self.digest, &self.sig)
187    }
188
189    /// Computes the precompile commitment for this request.
190    ///
191    /// The commitment is `RPO(RPO(RPO(pk) || RPO(digest)) || RPO(sig))` with tag
192    /// `[event_id, result, 0, 0]`, where `result` is 1 for valid signatures and 0 for
193    /// invalid ones. Each component is hashed over u32‑packed field elements.
194    ///
195    /// This is called by the [`PrecompileVerifier`] at verification time and must match
196    /// the commitment generated during execution.
197    pub fn as_precompile_commitment(&self) -> PrecompileCommitment {
198        // Compute tag: [event_id, result, 0, 0]
199        let result = self.result().into();
200        let tag = [ECDSA_VERIFY_EVENT_NAME.to_event_id().as_felt(), result, ZERO, ZERO].into();
201
202        // Convert serialized bytes to field elements and hash
203        let pk_comm = {
204            let felts = bytes_to_packed_u32_felts(&self.pk.to_bytes());
205            Rpo256::hash_elements(&felts)
206        };
207        let digest_comm = {
208            // `digest` is a 32‑byte array; hash its u32‑packed representation
209            let felts = bytes_to_packed_u32_felts(&self.digest);
210            Rpo256::hash_elements(&felts)
211        };
212        let sig_comm = {
213            let felts = bytes_to_packed_u32_felts(&self.sig.to_bytes());
214            Rpo256::hash_elements(&felts)
215        };
216
217        let commitment = Rpo256::merge(&[Rpo256::merge(&[pk_comm, digest_comm]), sig_comm]);
218
219        PrecompileCommitment::new(tag, commitment)
220    }
221}
222
223impl Serializable for EcdsaRequest {
224    fn write_into<W: ByteWriter>(&self, target: &mut W) {
225        self.pk.write_into(target);
226        self.digest.write_into(target);
227        self.sig.write_into(target);
228    }
229}
230
231impl Deserializable for EcdsaRequest {
232    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
233        let pk = PublicKey::read_from(source)?;
234        let digest = source.read_array()?;
235        let sig = Signature::read_from(source)?;
236        Ok(Self { pk, digest, sig })
237    }
238}
239
240impl From<EcdsaRequest> for PrecompileRequest {
241    fn from(request: EcdsaRequest) -> Self {
242        request.as_precompile_request()
243    }
244}
245
246// ERROR TYPES
247// ================================================================================================
248
249/// Type of data being read/processed during ECDSA verification.
250#[derive(Debug, Clone, Copy)]
251pub(crate) enum DataType {
252    PublicKey,
253    Signature,
254    Digest,
255}
256
257impl core::fmt::Display for DataType {
258    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
259        match self {
260            DataType::PublicKey => write!(f, "public key"),
261            DataType::Signature => write!(f, "signature"),
262            DataType::Digest => write!(f, "digest"),
263        }
264    }
265}
266
267/// Error types that can occur during ECDSA signature verification operations.
268#[derive(Debug, thiserror::Error)]
269pub(crate) enum EcdsaError {
270    /// Failed to read data from memory.
271    #[error("failed to read {data_type} from memory")]
272    ReadError {
273        data_type: DataType,
274        #[source]
275        source: crate::handlers::MemoryReadError,
276    },
277
278    /// Failed to deserialize data.
279    #[error("failed to deserialize {data_type}")]
280    DeserializeError {
281        data_type: DataType,
282        #[source]
283        source: DeserializationError,
284    },
285}