casper_node/components/consensus/
cl_context.rs1use std::sync::Arc;
2
3use datasize::DataSize;
4use serde::{Deserialize, Serialize};
5use tracing::info;
6
7use casper_types::{crypto, Digest, PublicKey, SecretKey, Signature};
8
9use crate::{
10 components::consensus::traits::{ConsensusValueT, Context, ValidatorSecret},
11 types::BlockPayload,
12};
13
14#[derive(DataSize)]
15pub struct Keypair {
16 secret_key: Arc<SecretKey>,
17 public_key: PublicKey,
18}
19
20impl Keypair {
21 pub(crate) fn new(secret_key: Arc<SecretKey>, public_key: PublicKey) -> Self {
22 Self {
23 secret_key,
24 public_key,
25 }
26 }
27
28 #[cfg(test)]
29 pub(crate) fn public_key(&self) -> &PublicKey {
30 &self.public_key
31 }
32}
33
34impl From<Arc<SecretKey>> for Keypair {
35 fn from(secret_key: Arc<SecretKey>) -> Self {
36 let public_key: PublicKey = secret_key.as_ref().into();
37 Self::new(secret_key, public_key)
38 }
39}
40
41impl ValidatorSecret for Keypair {
42 type Hash = Digest;
43 type Signature = Signature;
44
45 fn sign(&self, hash: &Digest) -> Signature {
46 crypto::sign(hash, self.secret_key.as_ref(), &self.public_key)
47 }
48}
49
50impl ConsensusValueT for Arc<BlockPayload> {
51 fn needs_validation(&self) -> bool {
52 self.all_transactions().next().is_some()
53 || !self.accusations().is_empty()
54 || self.rewarded_signatures().has_some()
55 }
56}
57
58#[derive(Clone, DataSize, Debug, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
60pub struct ClContext;
61
62impl Context for ClContext {
63 type ConsensusValue = Arc<BlockPayload>;
64 type ValidatorId = PublicKey;
65 type ValidatorSecret = Keypair;
66 type Signature = Signature;
67 type Hash = Digest;
68 type InstanceId = Digest;
69
70 fn hash(data: &[u8]) -> Digest {
71 Digest::hash(data)
72 }
73
74 fn verify_signature(hash: &Digest, public_key: &PublicKey, signature: &Signature) -> bool {
75 if let Err(error) = crypto::verify(hash, signature, public_key) {
76 info!(%error, %signature, %public_key, %hash, "failed to validate signature");
77 return false;
78 }
79 true
80 }
81}
82
83mod specimen_support {
84 use super::Keypair;
85 use crate::utils::specimen::{Cache, LargestSpecimen, SizeEstimator};
86 use casper_types::{PublicKey, SecretKey};
87 use std::sync::Arc;
88
89 impl LargestSpecimen for Keypair {
90 fn largest_specimen<E: SizeEstimator>(estimator: &E, cache: &mut Cache) -> Self {
91 let secret_key = SecretKey::largest_specimen(estimator, cache);
92 let public_key = PublicKey::from(&secret_key);
93 Keypair {
94 secret_key: Arc::new(secret_key),
95 public_key,
96 }
97 }
98 }
99}