entropy_protocol/
lib.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
// Copyright (C) 2023 Entropy Cryptography Inc.
//
// 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/>.

//! Protocol execution and transport logic for the Entropy signing and DKG protocols
pub mod errors;
pub mod execute_protocol;
mod listener;
mod protocol_message;
pub mod protocol_transport;
pub mod sign_and_encrypt;

pub use entropy_shared::user::ValidatorInfo;
pub use listener::Listener;
pub use protocol_message::ProtocolMessage;

extern crate alloc;
use std::{
    fmt,
    hash::{Hash, Hasher},
};

use blake2::{Blake2s256, Digest};
use errors::{ProtocolExecutionErr, VerifyingKeyError};
use serde::{Deserialize, Serialize};
use sp_core::{sr25519, Pair};
use subxt::utils::AccountId32;
use synedrion::{
    ecdsa::VerifyingKey,
    k256::{
        ecdsa::{RecoveryId, Signature},
        EncodedPoint,
    },
    signature::{self, hazmat::PrehashVerifier},
    AuxInfo, ThresholdKeyShare,
};

/// Identifies a party participating in a protocol session
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub struct PartyId(AccountId32);

impl std::hash::Hash for PartyId {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.0 .0.hash(state);
    }
}

impl PartyId {
    pub fn new(acc: AccountId32) -> Self {
        Self(acc)
    }

    fn to_public(&self) -> sr25519::Public {
        // TODO (#376): assuming that `Public` and `AccountId32` represent the same 32 bytes.
        // Ideally we should use only one of those throughout the code, probably `Public`.
        sr25519::Public(self.0 .0)
    }
}

impl From<sr25519::Public> for PartyId {
    fn from(public_key: sr25519::Public) -> Self {
        // TODO (#376): assuming that `Public` and `AccountId32` represent the same 32 bytes.
        // Ideally we should use only one of those throughout the code, probably `Public`.
        Self(AccountId32(public_key.0))
    }
}

impl PrehashVerifier<sr25519::Signature> for PartyId {
    fn verify_prehash(
        &self,
        prehash: &[u8],
        signature: &sr25519::Signature,
    ) -> Result<(), signature::Error> {
        if sr25519::Pair::verify(signature, prehash, &self.to_public()) {
            Ok(())
        } else {
            Err(signature::Error::new())
        }
    }
}

impl From<PartyId> for String {
    fn from(party_id: PartyId) -> Self {
        let bytes: &[u8] = party_id.0.as_ref();
        hex::encode(bytes)
    }
}

impl TryFrom<String> for PartyId {
    type Error = String;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        let bytes = hex::decode(s).map_err(|err| format!("{err}"))?;
        let len = bytes.len();
        let arr: [u8; 32] =
            bytes.try_into().map_err(|_err| format!("Invalid party ID length: {}", len))?;
        let acc = arr.into();
        Ok(Self(acc))
    }
}

impl fmt::Display for PartyId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        let bytes: &[u8] = self.0.as_ref();
        write!(f, "PartyId({})", hex::encode(&bytes[0..4]))
    }
}

#[cfg(not(test))]
use synedrion::ProductionParams;
/// Parameters used for the threshold signing scheme in production
#[cfg(not(test))]
pub type KeyParams = ProductionParams;

#[cfg(test)]
use synedrion::TestParams;
/// Parameters used for the threshold signing scheme in tests (faster but less secure)
#[cfg(test)]
pub type KeyParams = TestParams;

pub use synedrion::KeyShare;

/// This is the keyshare payload which gets stored by entropy-tss
pub type KeyShareWithAuxInfo = (ThresholdKeyShare<KeyParams, PartyId>, AuxInfo<KeyParams, PartyId>);

/// A secp256k1 signature from which we can recover the public key of the keypair used to create it
#[derive(Clone, Debug)]
pub struct RecoverableSignature {
    pub signature: Signature,
    pub recovery_id: RecoveryId,
}

impl RecoverableSignature {
    pub fn to_rsv_bytes(&self) -> [u8; 65] {
        let mut res = [0u8; 65];

        let rs = self.signature.to_bytes();
        res[0..64].copy_from_slice(&rs);

        res[64] = self.recovery_id.to_byte();

        res
    }
}

/// An identifier to specify and particular protocol session
#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
pub enum SessionId {
    /// A distributed key generation protocol session for initial network jumpstart
    Dkg { block_number: u32 },
    /// A proactive refresh session
    Reshare { verifying_key: Vec<u8>, block_number: u32 },
    /// A signing session
    Sign(SigningSessionInfo),
}

/// Information to identify a particular signing protocol session
#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
pub struct SigningSessionInfo {
    /// The signature request account ID
    pub signature_verifying_key: Vec<u8>,
    /// Hash of the message to be signed
    pub message_hash: [u8; 32],
    /// Account ID of the request author (in public access mode this may differ from the signature
    /// request account)
    pub request_author: AccountId32,
}

// This is needed because subxt's AccountId32 does not implement Hash
impl Hash for SessionId {
    fn hash<H: Hasher>(&self, state: &mut H) {
        match self {
            SessionId::Dkg { block_number } => {
                block_number.hash(state);
            },
            SessionId::Reshare { verifying_key, block_number } => {
                verifying_key.hash(state);
                block_number.hash(state);
            },
            SessionId::Sign(signing_session_info) => {
                signing_session_info.signature_verifying_key.hash(state);
                signing_session_info.message_hash.hash(state);
                signing_session_info.request_author.0.hash(state);
            },
        }
    }
}

impl SessionId {
    /// Take the hash of the session ID - used as uniqueness in the protocol
    /// Optionally with some extra data used to identify a sub-session
    pub fn blake2(
        &self,
        sub_session: Option<Subsession>,
    ) -> Result<[u8; 32], ProtocolExecutionErr> {
        let mut hasher = Blake2s256::new();
        hasher.update(bincode::serialize(self)?);
        if let Some(session) = sub_session {
            hasher.update(format!("{:?}", session).as_bytes());
        }
        Ok(hasher.finalize().into())
    }
}

/// A sub-protocol of the DKG or reshare protocols
#[derive(Debug)]
pub enum Subsession {
    /// The synedrion key init protocol
    KeyInit,
    /// The synedrion reshare protocol
    Reshare,
    /// The synedrion aux gen protocol
    AuxGen,
}

/// Decode a [VerifyingKey] from bytes
pub fn decode_verifying_key(
    verifying_key_encoded: &[u8; 33],
) -> Result<VerifyingKey, VerifyingKeyError> {
    let point = EncodedPoint::from_bytes(verifying_key_encoded)
        .map_err(|_| VerifyingKeyError::DecodeEncodedPoint)?;
    VerifyingKey::from_encoded_point(&point)
        .map_err(|_| VerifyingKeyError::EncodedPointToVerifyingKey)
}