satsnet/crypto/
ecdsa.rs

1// SPDX-License-Identifier: CC0-1.0
2
3//! ECDSA Bitcoin signatures.
4//!
5//! This module provides ECDSA signatures used by Bitcoin that can be roundtrip (de)serialized.
6
7use core::str::FromStr;
8use core::{fmt, iter};
9
10use hex::FromHex;
11use internals::write_err;
12use io::Write;
13
14use crate::prelude::*;
15use crate::script::PushBytes;
16use crate::sighash::{EcdsaSighashType, NonStandardSighashTypeError};
17
18const MAX_SIG_LEN: usize = 73;
19
20/// An ECDSA signature with the corresponding hash type.
21#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
22#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
23#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
24pub struct Signature {
25    /// The underlying ECDSA Signature.
26    pub signature: secp256k1::ecdsa::Signature,
27    /// The corresponding hash type.
28    pub sighash_type: EcdsaSighashType,
29}
30
31impl Signature {
32    /// Constructs an ECDSA Bitcoin signature for [`EcdsaSighashType::All`].
33    pub fn sighash_all(signature: secp256k1::ecdsa::Signature) -> Signature {
34        Signature { signature, sighash_type: EcdsaSighashType::All }
35    }
36
37    /// Deserializes from slice following the standardness rules for [`EcdsaSighashType`].
38    pub fn from_slice(sl: &[u8]) -> Result<Self, Error> {
39        let (sighash_type, sig) = sl.split_last().ok_or(Error::EmptySignature)?;
40        let sighash_type = EcdsaSighashType::from_standard(*sighash_type as u32)?;
41        let signature = secp256k1::ecdsa::Signature::from_der(sig).map_err(Error::Secp256k1)?;
42        Ok(Signature { signature, sighash_type })
43    }
44
45    /// Serializes an ECDSA signature (inner secp256k1 signature in DER format).
46    ///
47    /// This does **not** perform extra heap allocation.
48    pub fn serialize(&self) -> SerializedSignature {
49        let mut buf = [0u8; MAX_SIG_LEN];
50        let signature = self.signature.serialize_der();
51        buf[..signature.len()].copy_from_slice(&signature);
52        buf[signature.len()] = self.sighash_type as u8;
53        SerializedSignature { data: buf, len: signature.len() + 1 }
54    }
55
56    /// Serializes an ECDSA signature (inner secp256k1 signature in DER format) into `Vec`.
57    ///
58    /// Note: this performs an extra heap allocation, you might prefer the
59    /// [`serialize`](Self::serialize) method instead.
60    pub fn to_vec(self) -> Vec<u8> {
61        self.signature
62            .serialize_der()
63            .iter()
64            .copied()
65            .chain(iter::once(self.sighash_type as u8))
66            .collect()
67    }
68
69    /// Serializes an ECDSA signature (inner secp256k1 signature in DER format) to a `writer`.
70    #[inline]
71    pub fn serialize_to_writer<W: Write + ?Sized>(&self, writer: &mut W) -> Result<(), io::Error> {
72        let sig = self.serialize();
73        sig.write_to(writer)
74    }
75}
76
77impl fmt::Display for Signature {
78    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79        fmt::LowerHex::fmt(&self.signature.serialize_der().as_hex(), f)?;
80        fmt::LowerHex::fmt(&[self.sighash_type as u8].as_hex(), f)
81    }
82}
83
84impl FromStr for Signature {
85    type Err = Error;
86
87    fn from_str(s: &str) -> Result<Self, Self::Err> {
88        let bytes = Vec::from_hex(s)?;
89        let (sighash_byte, signature) = bytes.split_last().ok_or(Error::EmptySignature)?;
90        Ok(Signature {
91            signature: secp256k1::ecdsa::Signature::from_der(signature)?,
92            sighash_type: EcdsaSighashType::from_standard(*sighash_byte as u32)?,
93        })
94    }
95}
96
97/// Holds signature serialized in-line (not in `Vec`).
98///
99/// This avoids allocation and allows proving maximum size of the signature (73 bytes).
100/// The type can be used largely as a byte slice. It implements all standard traits one would
101/// expect and has familiar methods.
102/// However, the usual use case is to push it into a script. This can be done directly passing it
103/// into [`push_slice`](crate::script::ScriptBuf::push_slice).
104#[derive(Copy, Clone)]
105pub struct SerializedSignature {
106    data: [u8; MAX_SIG_LEN],
107    len: usize,
108}
109
110impl SerializedSignature {
111    /// Returns an iterator over bytes of the signature.
112    #[inline]
113    pub fn iter(&self) -> core::slice::Iter<'_, u8> { self.into_iter() }
114
115    /// Writes this serialized signature to a `writer`.
116    #[inline]
117    pub fn write_to<W: Write + ?Sized>(&self, writer: &mut W) -> Result<(), io::Error> {
118        writer.write_all(self)
119    }
120}
121
122impl core::ops::Deref for SerializedSignature {
123    type Target = [u8];
124
125    #[inline]
126    fn deref(&self) -> &Self::Target { &self.data[..self.len] }
127}
128
129impl core::ops::DerefMut for SerializedSignature {
130    #[inline]
131    fn deref_mut(&mut self) -> &mut Self::Target { &mut self.data[..self.len] }
132}
133
134impl AsRef<[u8]> for SerializedSignature {
135    #[inline]
136    fn as_ref(&self) -> &[u8] { self }
137}
138
139impl AsMut<[u8]> for SerializedSignature {
140    #[inline]
141    fn as_mut(&mut self) -> &mut [u8] { self }
142}
143
144impl AsRef<PushBytes> for SerializedSignature {
145    #[inline]
146    fn as_ref(&self) -> &PushBytes { &<&PushBytes>::from(&self.data)[..self.len()] }
147}
148
149impl core::borrow::Borrow<[u8]> for SerializedSignature {
150    #[inline]
151    fn borrow(&self) -> &[u8] { self }
152}
153
154impl core::borrow::BorrowMut<[u8]> for SerializedSignature {
155    #[inline]
156    fn borrow_mut(&mut self) -> &mut [u8] { self }
157}
158
159impl fmt::Debug for SerializedSignature {
160    #[inline]
161    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self, f) }
162}
163
164impl fmt::Display for SerializedSignature {
165    #[inline]
166    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::LowerHex::fmt(self, f) }
167}
168
169impl fmt::LowerHex for SerializedSignature {
170    #[inline]
171    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
172        fmt::LowerHex::fmt(&(**self).as_hex(), f)
173    }
174}
175
176impl fmt::UpperHex for SerializedSignature {
177    #[inline]
178    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
179        fmt::UpperHex::fmt(&(**self).as_hex(), f)
180    }
181}
182
183impl PartialEq for SerializedSignature {
184    #[inline]
185    fn eq(&self, other: &SerializedSignature) -> bool { **self == **other }
186}
187
188impl Eq for SerializedSignature {}
189
190impl core::hash::Hash for SerializedSignature {
191    fn hash<H: core::hash::Hasher>(&self, state: &mut H) { core::hash::Hash::hash(&**self, state) }
192}
193
194impl<'a> IntoIterator for &'a SerializedSignature {
195    type IntoIter = core::slice::Iter<'a, u8>;
196    type Item = &'a u8;
197
198    #[inline]
199    fn into_iter(self) -> Self::IntoIter { (*self).iter() }
200}
201
202/// An ECDSA signature-related error.
203#[derive(Debug, Clone, PartialEq, Eq)]
204#[non_exhaustive]
205pub enum Error {
206    /// Hex decoding error.
207    Hex(hex::HexToBytesError),
208    /// Non-standard sighash type.
209    SighashType(NonStandardSighashTypeError),
210    /// Signature was empty.
211    EmptySignature,
212    /// A secp256k1 error.
213    Secp256k1(secp256k1::Error),
214}
215
216internals::impl_from_infallible!(Error);
217
218impl fmt::Display for Error {
219    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
220        use Error::*;
221
222        match *self {
223            Hex(ref e) => write_err!(f, "signature hex decoding error"; e),
224            SighashType(ref e) => write_err!(f, "non-standard signature hash type"; e),
225            EmptySignature => write!(f, "empty ECDSA signature"),
226            Secp256k1(ref e) => write_err!(f, "secp256k1"; e),
227        }
228    }
229}
230
231#[cfg(feature = "std")]
232impl std::error::Error for Error {
233    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
234        use Error::*;
235
236        match *self {
237            Hex(ref e) => Some(e),
238            Secp256k1(ref e) => Some(e),
239            SighashType(ref e) => Some(e),
240            EmptySignature => None,
241        }
242    }
243}
244
245impl From<secp256k1::Error> for Error {
246    fn from(e: secp256k1::Error) -> Self { Self::Secp256k1(e) }
247}
248
249impl From<NonStandardSighashTypeError> for Error {
250    fn from(e: NonStandardSighashTypeError) -> Self { Self::SighashType(e) }
251}
252
253impl From<hex::HexToBytesError> for Error {
254    fn from(e: hex::HexToBytesError) -> Self { Self::Hex(e) }
255}
256
257#[cfg(test)]
258mod tests {
259    use super::*;
260
261    #[test]
262    fn write_serialized_signature() {
263        let hex = "3046022100839c1fbc5304de944f697c9f4b1d01d1faeba32d751c0f7acb21ac8a0f436a72022100e89bd46bb3a5a62adc679f659b7ce876d83ee297c7a5587b2011c4fcc72eab45";
264        let sig = Signature {
265            signature: secp256k1::ecdsa::Signature::from_str(hex).unwrap(),
266            sighash_type: EcdsaSighashType::All,
267        };
268
269        let mut buf = vec![];
270        sig.serialize_to_writer(&mut buf).expect("write failed");
271
272        assert_eq!(sig.to_vec(), buf)
273    }
274}