1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
// Rust Bitcoin Library
// Written in 2014 by
//     Andrew Poelstra <apoelstra@wpsoftware.net>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication
// along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
//

//! ECDSA Bitcoin signatures.
//!
//! This module provides ECDSA signatures used Bitcoin that can be roundtrip (de)serialized.

use prelude::*;
use core::str::FromStr;
use core::{fmt, iter};
use hashes::hex::{self, FromHex};
use blockdata::transaction::NonStandardSighashType;
use secp256k1;
use EcdsaSighashType;

/// An ECDSA signature with the corresponding hash type.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct EcdsaSig {
    /// The underlying ECDSA Signature
    pub sig: secp256k1::ecdsa::Signature,
    /// The corresponding hash type
    pub hash_ty: EcdsaSighashType,
}

impl EcdsaSig {
    /// Constructs ECDSA bitcoin signature for [`EcdsaSighashType::All`]
    pub fn sighash_all(sig: secp256k1::ecdsa::Signature) -> EcdsaSig {
        EcdsaSig {
            sig,
            hash_ty: EcdsaSighashType::All
        }
    }

    /// Deserialize from slice following the standardness rules for [`EcdsaSighashType`]
    pub fn from_slice(sl: &[u8]) -> Result<Self, EcdsaSigError> {
        let (hash_ty, sig) = sl.split_last()
            .ok_or(EcdsaSigError::EmptySignature)?;
        let hash_ty = EcdsaSighashType::from_standard(*hash_ty as u32)
            .map_err(|_| EcdsaSigError::NonStandardSighashType(*hash_ty as u32))?;
        let sig = secp256k1::ecdsa::Signature::from_der(sig)
            .map_err(EcdsaSigError::Secp256k1)?;
        Ok(EcdsaSig { sig, hash_ty })
    }

    /// Serialize EcdsaSig
    pub fn to_vec(&self) -> Vec<u8> {
        // TODO: add support to serialize to a writer to SerializedSig
        self.sig.serialize_der()
            .iter().map(|x| *x)
            .chain(iter::once(self.hash_ty as u8))
            .collect()
    }
}

impl fmt::Display for EcdsaSig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        hex::format_hex(&self.sig.serialize_der(), f)?;
        hex::format_hex(&[self.hash_ty as u8], f)
    }
}

impl FromStr for EcdsaSig {
    type Err = EcdsaSigError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let bytes = Vec::from_hex(s)?;
        let (sighash_byte, signature) = bytes.split_last()
            .ok_or(EcdsaSigError::EmptySignature)?;
        Ok(EcdsaSig {
            sig: secp256k1::ecdsa::Signature::from_der(signature)?,
            hash_ty: EcdsaSighashType::from_standard(*sighash_byte as u32)?
        })
    }
}

/// A key-related error.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum EcdsaSigError {
    /// Hex encoding error
    HexEncoding(hex::Error),
    /// Base58 encoding error
    NonStandardSighashType(u32),
    /// Empty Signature
    EmptySignature,
    /// secp256k1-related error
    Secp256k1(secp256k1::Error),
}


impl fmt::Display for EcdsaSigError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            EcdsaSigError::NonStandardSighashType(hash_ty) =>
                write!(f, "Non standard signature hash type {}", hash_ty),
            EcdsaSigError::Secp256k1(ref e) =>
                write!(f, "Invalid Ecdsa signature: {}", e),
            EcdsaSigError::EmptySignature =>
                write!(f, "Empty ECDSA signature"),
            EcdsaSigError::HexEncoding(e) => write!(f, "EcdsaSig hex encoding error: {}", e)
        }
    }
}

#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl ::std::error::Error for EcdsaSigError {}

impl From<secp256k1::Error> for EcdsaSigError {
    fn from(e: secp256k1::Error) -> EcdsaSigError {
        EcdsaSigError::Secp256k1(e)
    }
}

impl From<NonStandardSighashType> for EcdsaSigError {
    fn from(err: NonStandardSighashType) -> Self {
        EcdsaSigError::NonStandardSighashType(err.0)
    }
}

impl From<hex::Error> for EcdsaSigError {
    fn from(err: hex::Error) -> Self {
        EcdsaSigError::HexEncoding(err)
    }
}