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
//! secp256r1 (P-256) functions

use crate::{
    Error,
    Message,
};
use ecdsa::RecoveryId;
use fuel_types::Bytes64;
use p256::ecdsa::{
    Signature,
    VerifyingKey,
};

/// Combines recovery id with the signature bytes. See the following link for explanation.
/// https://github.com/FuelLabs/fuel-specs/blob/master/src/protocol/cryptographic_primitives.md#public-key-cryptography
/// Panics if the highest bit of byte at index 32 is set, as this indicates non-normalized
/// signature. Panics if the recovery id is in reduced-x form.
#[cfg(feature = "test-helpers")]
fn encode_signature(signature: Signature, recovery_id: RecoveryId) -> [u8; 64] {
    let mut signature: [u8; 64] = signature.to_bytes().into();
    assert!(signature[32] >> 7 == 0, "Non-normalized signature");
    assert!(!recovery_id.is_x_reduced(), "Invalid recovery id");

    let v = recovery_id.is_y_odd() as u8;

    signature[32] = (v << 7) | (signature[32] & 0x7f);
    signature
}

/// Separates recovery id from the signature bytes. See the following link for
/// explanation. https://github.com/FuelLabs/fuel-specs/blob/master/src/protocol/cryptographic_primitives.md#public-key-cryptography
fn decode_signature(mut signature: [u8; 64]) -> Option<(Signature, RecoveryId)> {
    let v = (signature[32] & 0x80) != 0;
    signature[32] &= 0x7f;

    let signature = Signature::from_slice(&signature).ok()?;

    Some((signature, RecoveryId::new(v, false)))
}

/// Sign a prehashed message. With the given key.
#[cfg(feature = "test-helpers")]
pub fn sign_prehashed(
    signing_key: &p256::ecdsa::SigningKey,
    message: &Message,
) -> Result<Bytes64, Error> {
    let (signature, _) = signing_key
        .sign_prehash_recoverable(&**message)
        .map_err(|_| Error::FailedToSign)?;

    let signature = signature.normalize_s().unwrap_or(signature);

    // TODO: this is a hack to get the recovery id. The signature should be normalized
    // before computing the recovery id, but p256 library doesn't support this, and
    // instead always computes the recovery id from non-normalized signature.
    // So instead the recovery id is determined by checking which variant matches
    // the original public key.

    let recid1 = RecoveryId::new(false, false);
    let recid2 = RecoveryId::new(true, false);

    let rec1 = VerifyingKey::recover_from_prehash(&**message, &signature, recid1);
    let rec2 = VerifyingKey::recover_from_prehash(&**message, &signature, recid2);

    let actual = signing_key.verifying_key();

    let recovery_id = if rec1.map(|r| r == *actual).unwrap_or(false) {
        recid1
    } else if rec2.map(|r| r == *actual).unwrap_or(false) {
        recid2
    } else {
        unreachable!("Invalid signature generated");
    };

    // encode_signature cannot panic as we don't generate reduced-x recovery ids.
    Ok(Bytes64::from(encode_signature(signature, recovery_id)))
}

/// Convert the publi key point to it's uncompressed non-prefixed representation,
/// i.e. 32 bytes of x coordinate and 32 bytes of y coordinate.
pub fn encode_pubkey(key: VerifyingKey) -> [u8; 64] {
    let point = key.to_encoded_point(false);
    let mut result = [0u8; 64];
    result[..32].copy_from_slice(point.x().unwrap());
    result[32..].copy_from_slice(point.y().unwrap());
    result
}

/// Recover a public key from a signature and a message digest. It assumes
/// a compacted signature
pub fn recover(signature: &Bytes64, message: &Message) -> Result<Bytes64, Error> {
    let (signature, recovery_id) =
        decode_signature(**signature).ok_or(Error::InvalidSignature)?;

    if let Ok(pub_key) =
        VerifyingKey::recover_from_prehash(&**message, &signature, recovery_id)
    {
        Ok(Bytes64::from(encode_pubkey(pub_key)))
    } else {
        Err(Error::InvalidSignature)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use p256::ecdsa::SigningKey;
    use rand::{
        rngs::StdRng,
        Rng,
        SeedableRng,
    };

    #[test]
    fn test_raw_recover() {
        let mut rng = &mut StdRng::seed_from_u64(1234);

        let signing_key = SigningKey::random(&mut rng);
        let verifying_key = signing_key.verifying_key();

        let message = Message::new([rng.gen(); 100]);

        let (signature, recovery_id) =
            signing_key.sign_prehash_recoverable(&*message).unwrap();

        let recovered =
            VerifyingKey::recover_from_prehash(&*message, &signature, recovery_id)
                .expect("Unable to recover the public key");

        assert_eq!(recovered, *verifying_key);
    }

    #[test]
    fn test_secp256r1_recover_from_msg() {
        let mut rng = &mut StdRng::seed_from_u64(1234);

        for _ in 0..100 {
            let signing_key = SigningKey::random(&mut rng);
            let verifying_key = signing_key.verifying_key();

            let message = Message::new([rng.gen(); 100]);
            let signature = crate::secp256r1::sign_prehashed(&signing_key, &message)
                .expect("Couldn't sign");

            let Ok(recovered) = recover(&signature, &message) else {
                panic!("Failed to recover public key from the message");
            };

            assert_eq!(*recovered, encode_pubkey(*verifying_key));
        }
    }

    #[test]
    fn test_signature_and_recovery_id_encoding_roundtrip() {
        let mut rng = &mut StdRng::seed_from_u64(1234);

        for _ in 0..100 {
            let message = Message::new([rng.gen(); 100]);
            let signing_key = SigningKey::random(&mut rng);
            let (signature, _) = signing_key.sign_prehash_recoverable(&*message).unwrap();
            let signature = signature.normalize_s().unwrap_or(signature);

            let recovery_id = RecoveryId::from_byte(0).unwrap();
            let encoded = encode_signature(signature, recovery_id);

            let (de_sig, de_recid) = decode_signature(encoded).unwrap();
            assert_eq!(signature, de_sig);
            assert_eq!(recovery_id, de_recid);

            let recovery_id = RecoveryId::from_byte(1).unwrap();
            let encoded = encode_signature(signature, recovery_id);

            let (de_sig, de_recid) = decode_signature(encoded).unwrap();
            assert_eq!(signature, de_sig);
            assert_eq!(recovery_id, de_recid);
        }
    }
}