forked from CodeChain-io/codechain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathecdsa.rs
320 lines (270 loc) · 9.83 KB
/
ecdsa.rs
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
// Copyright 2018 Kodebox, Inc.
// This file is part of CodeChain.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use std::cmp::PartialEq;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::ops::{Deref, DerefMut};
use std::str::FromStr;
use primitives::{H256, H520};
use rlp::{Decodable, DecoderError, Encodable, RlpStream, UntrustedRlp};
use rustc_hex::{FromHex, ToHex};
use secp256k1::{key, Error as SecpError, Message as SecpMessage, RecoverableSignature, RecoveryId};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use super::{public_to_address, Address, Error, Message, Private, Public, SECP256K1};
pub const ECDSA_SIGNATURE_LENGTH: usize = 65;
/// Signature encoded as RSV components
#[repr(C)]
#[derive(Copy)]
pub struct ECDSASignature([u8; 65]);
impl ECDSASignature {
/// Get a slice into the 'r' portion of the data.
pub fn r(&self) -> &[u8] {
&self.0[0..32]
}
/// Get a slice into the 's' portion of the data.
pub fn s(&self) -> &[u8] {
&self.0[32..64]
}
/// Get the recovery byte.
pub fn v(&self) -> u8 {
self.0[64]
}
/// Check if this is a "low" signature.
pub fn is_low_s(&self) -> bool {
H256::from_slice(self.s()) <= "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0".into()
}
/// Check if each component of the signature is in range.
pub fn is_valid(&self) -> bool {
self.v() <= 1
&& H256::from_slice(self.r()) < "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141".into()
&& H256::from_slice(self.r()) >= 1.into()
&& H256::from_slice(self.s()) < "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141".into()
&& H256::from_slice(self.s()) >= 1.into()
}
pub fn random() -> Self {
let r = H520::random();
ECDSASignature::from(r)
}
}
// manual implementation large arrays don't have trait impls by default.
// remove when integer generics exist
impl PartialEq for ECDSASignature {
fn eq(&self, other: &Self) -> bool {
&self.0[..] == &other.0[..]
}
}
// manual implementation required in Rust 1.13+, see `std::cmp::AssertParamIsEq`.
impl Eq for ECDSASignature {}
// also manual for the same reason, but the pretty printing might be useful.
impl fmt::Debug for ECDSASignature {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
f.debug_struct("Signature")
.field("r", &self.0[0..32].to_hex())
.field("s", &self.0[32..64].to_hex())
.field("v", &self.0[64..65].to_hex())
.finish()
}
}
impl fmt::Display for ECDSASignature {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{}", self.to_hex())
}
}
impl FromStr for ECDSASignature {
type Err = SecpError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.from_hex() {
Ok(ref hex) if hex.len() == 65 => {
let mut data = [0; 65];
data.copy_from_slice(&hex[0..65]);
Ok(ECDSASignature(data))
}
_ => Err(SecpError::InvalidSignature),
}
}
}
impl Default for ECDSASignature {
fn default() -> Self {
ECDSASignature([0; 65])
}
}
impl Hash for ECDSASignature {
fn hash<H: Hasher>(&self, state: &mut H) {
H520::from(self.0).hash(state);
}
}
impl Clone for ECDSASignature {
fn clone(&self) -> Self {
ECDSASignature(self.0)
}
}
impl From<[u8; 65]> for ECDSASignature {
fn from(s: [u8; 65]) -> Self {
ECDSASignature(s)
}
}
impl<'a> From<&'a [u8]> for ECDSASignature {
fn from(s: &'a [u8]) -> Self {
let mut array = [0; 65];
array.copy_from_slice(s);
ECDSASignature(array)
}
}
impl Into<[u8; 65]> for ECDSASignature {
fn into(self) -> [u8; 65] {
self.0
}
}
impl From<ECDSASignature> for H520 {
fn from(s: ECDSASignature) -> Self {
H520::from(s.0)
}
}
impl From<H520> for ECDSASignature {
fn from(bytes: H520) -> Self {
ECDSASignature(bytes.into())
}
}
impl Deref for ECDSASignature {
type Target = [u8; 65];
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for ECDSASignature {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl Serialize for ECDSASignature {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer, {
let data: H520 = self.0.into();
data.serialize(serializer)
}
}
impl<'a> Deserialize<'a> for ECDSASignature {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'a>, {
let data = H520::deserialize(deserializer)?;
Ok(Self::from(data))
}
}
impl Encodable for ECDSASignature {
fn rlp_append(&self, s: &mut RlpStream) {
let data: H520 = self.0.into();
data.rlp_append(s);
}
}
impl Decodable for ECDSASignature {
fn decode(rlp: &UntrustedRlp) -> Result<Self, DecoderError> {
let data = H520::decode(rlp)?;
Ok(Self::from(data))
}
}
pub fn sign_ecdsa(private: &Private, message: &Message) -> Result<ECDSASignature, Error> {
let context = &SECP256K1;
let sec = key::SecretKey::from_slice(context, &private)?;
let s = context.sign_recoverable(&SecpMessage::from_slice(&message[..])?, &sec)?;
let (rec_id, data) = s.serialize_compact(context);
let mut data_arr = [0; 65];
// no need to check if s is low, it always is
data_arr[0..64].copy_from_slice(&data[0..64]);
data_arr[64] = rec_id.to_i32() as u8;
Ok(ECDSASignature(data_arr))
}
pub fn verify_ecdsa(public: &Public, signature: &ECDSASignature, message: &Message) -> Result<bool, Error> {
let context = &SECP256K1;
let rsig =
RecoverableSignature::from_compact(context, &signature[0..64], RecoveryId::from_i32(signature[64] as i32)?)?;
let sig = rsig.to_standard(context);
let pdata: [u8; 65] = {
let mut temp = [4u8; 65];
temp[1..65].copy_from_slice(&**public);
temp
};
let publ = key::PublicKey::from_slice(context, &pdata)?;
match context.verify(&SecpMessage::from_slice(&message[..])?, &sig, &publ) {
Ok(_) => Ok(true),
Err(SecpError::IncorrectSignature) => Ok(false),
Err(x) => Err(Error::from(x)),
}
}
pub fn verify_ecdsa_address(address: &Address, signature: &ECDSASignature, message: &Message) -> Result<bool, Error> {
let public = recover_ecdsa(signature, message)?;
let recovered_address = public_to_address(&public);
Ok(address == &recovered_address)
}
pub fn recover_ecdsa(signature: &ECDSASignature, message: &Message) -> Result<Public, Error> {
let context = &SECP256K1;
let rsig =
RecoverableSignature::from_compact(context, &signature[0..64], RecoveryId::from_i32(signature[64] as i32)?)?;
let pubkey = context.recover(&SecpMessage::from_slice(&message[..])?, &rsig)?;
let serialized = pubkey.serialize_vec(context, false);
let mut public = Public::default();
public.copy_from_slice(&serialized[1..65]);
Ok(public)
}
#[cfg(test)]
mod tests {
use super::super::{Generator, Message, Random};
use super::{recover_ecdsa, sign_ecdsa, verify_ecdsa, verify_ecdsa_address, ECDSASignature};
use std::str::FromStr;
#[test]
fn signature_to_and_from_str() {
let keypair = Random.generate().unwrap();
let message = Message::default();
let signature = sign_ecdsa(keypair.private(), &message).unwrap();
let string = format!("{}", signature);
let deserialized = ECDSASignature::from_str(&string).unwrap();
assert_eq!(signature, deserialized);
}
#[test]
fn sign_and_recover_public() {
let keypair = Random.generate().unwrap();
let message = Message::default();
let signature = sign_ecdsa(keypair.private(), &message).unwrap();
assert_eq!(keypair.public(), &recover_ecdsa(&signature, &message).unwrap());
}
#[test]
fn sign_and_verify_public() {
let keypair = Random.generate().unwrap();
let message = Message::default();
let signature = sign_ecdsa(keypair.private(), &message).unwrap();
assert!(verify_ecdsa(keypair.public(), &signature, &message).unwrap());
}
#[test]
fn sign_and_verify_address() {
let keypair = Random.generate().unwrap();
let message = Message::default();
let signature = sign_ecdsa(keypair.private(), &message).unwrap();
assert!(verify_ecdsa_address(&keypair.address(), &signature, &message).unwrap());
}
}