-
Notifications
You must be signed in to change notification settings - Fork 629
/
validator_signer.rs
380 lines (323 loc) · 12.7 KB
/
validator_signer.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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
use std::fmt::Debug;
use std::path::Path;
use std::sync::Arc;
use near_crypto::{InMemorySigner, KeyType, PublicKey, Signature, Signer};
use crate::block::{Approval, ApprovalInner, BlockHeader};
use crate::challenge::ChallengeBody;
use crate::hash::CryptoHash;
use crate::network::{AnnounceAccount, PeerId};
use crate::sharding::ChunkHash;
use crate::stateless_validation::chunk_endorsement::{
ChunkEndorsementInner, ChunkEndorsementMetadata,
};
use crate::stateless_validation::partial_witness::PartialEncodedStateWitnessInner;
use crate::stateless_validation::state_witness::EncodedChunkStateWitness;
use crate::telemetry::TelemetryInfo;
use crate::types::{AccountId, BlockHeight, EpochId};
use crate::utils::compression::CompressedData;
/// Enum for validator signer, that holds validator id and key used for signing data.
#[derive(Clone, Debug, PartialEq)]
pub enum ValidatorSigner {
/// Dummy validator signer, does not hold a key. Use for tests only!
Empty(EmptyValidatorSigner),
/// Default validator signer that holds data in memory.
InMemory(InMemoryValidatorSigner),
}
/// Validator signer that is used to sign blocks and approvals.
impl ValidatorSigner {
/// Account id of the given validator.
pub fn validator_id(&self) -> &AccountId {
match self {
ValidatorSigner::Empty(signer) => signer.validator_id(),
ValidatorSigner::InMemory(signer) => signer.validator_id(),
}
}
/// Public key that identifies this validator.
pub fn public_key(&self) -> PublicKey {
match self {
ValidatorSigner::Empty(signer) => signer.public_key(),
ValidatorSigner::InMemory(signer) => signer.public_key(),
}
}
/// Serializes telemetry info to JSON and signs it, returning JSON with "signature" field.
pub fn sign_telemetry(&self, info: &TelemetryInfo) -> serde_json::Value {
match self {
ValidatorSigner::Empty(signer) => signer.sign_telemetry(info),
ValidatorSigner::InMemory(signer) => signer.sign_telemetry(info),
}
}
/// Signs given parts of the header.
pub fn sign_block_header_parts(
&self,
prev_hash: CryptoHash,
inner_lite: &[u8],
inner_rest: &[u8],
) -> (CryptoHash, Signature) {
match self {
ValidatorSigner::Empty(signer) => {
signer.sign_block_header_parts(prev_hash, inner_lite, inner_rest)
}
ValidatorSigner::InMemory(signer) => {
signer.sign_block_header_parts(prev_hash, inner_lite, inner_rest)
}
}
}
/// Signs given inner of the chunk header.
pub fn sign_chunk_hash(&self, chunk_hash: &ChunkHash) -> Signature {
match self {
ValidatorSigner::Empty(signer) => signer.sign_chunk_hash(chunk_hash),
ValidatorSigner::InMemory(signer) => signer.sign_chunk_hash(chunk_hash),
}
}
/// Signs approval of given parent hash and reference hash.
pub fn sign_approval(&self, inner: &ApprovalInner, target_height: BlockHeight) -> Signature {
match self {
ValidatorSigner::Empty(signer) => signer.sign_approval(inner, target_height),
ValidatorSigner::InMemory(signer) => signer.sign_approval(inner, target_height),
}
}
/// Signs chunk endorsement to be sent to block producer.
pub fn sign_chunk_endorsement(&self, inner: &ChunkEndorsementInner) -> Signature {
match self {
ValidatorSigner::Empty(signer) => signer.sign_chunk_endorsement(inner),
ValidatorSigner::InMemory(signer) => signer.sign_chunk_endorsement(inner),
}
}
/// Signs chunk endorsement metadata.
pub fn sign_chunk_endorsement_metadata(&self, inner: &ChunkEndorsementMetadata) -> Signature {
match self {
ValidatorSigner::Empty(signer) => signer.sign_chunk_endorsement_metadata(inner),
ValidatorSigner::InMemory(signer) => signer.sign_chunk_endorsement_metadata(inner),
}
}
/// Signs chunk state witness to be sent to all validators.
pub fn sign_chunk_state_witness(&self, witness_bytes: &EncodedChunkStateWitness) -> Signature {
match self {
ValidatorSigner::Empty(signer) => signer.sign_chunk_state_witness(witness_bytes),
ValidatorSigner::InMemory(signer) => signer.sign_chunk_state_witness(witness_bytes),
}
}
/// Signs partial encoded state witness to be sent and forwarded to all validators.
pub fn sign_partial_encoded_state_witness(
&self,
part: &PartialEncodedStateWitnessInner,
) -> Signature {
match self {
ValidatorSigner::Empty(signer) => signer.sign_partial_encoded_state_witness(part),
ValidatorSigner::InMemory(signer) => signer.sign_partial_encoded_state_witness(part),
}
}
/// Signs challenge body.
pub fn sign_challenge(&self, challenge_body: &ChallengeBody) -> (CryptoHash, Signature) {
match self {
ValidatorSigner::Empty(signer) => signer.sign_challenge(challenge_body),
ValidatorSigner::InMemory(signer) => signer.sign_challenge(challenge_body),
}
}
/// Signs account announce.
pub fn sign_account_announce(
&self,
account_id: &AccountId,
peer_id: &PeerId,
epoch_id: &EpochId,
) -> Signature {
match self {
ValidatorSigner::Empty(signer) => {
signer.sign_account_announce(account_id, peer_id, epoch_id)
}
ValidatorSigner::InMemory(signer) => {
signer.sign_account_announce(account_id, peer_id, epoch_id)
}
}
}
pub fn sign_bytes(&self, data: &[u8]) -> Signature {
match self {
ValidatorSigner::Empty(signer) => signer.noop_signature(),
ValidatorSigner::InMemory(signer) => signer.sign_bytes(data),
}
}
pub fn compute_vrf_with_proof(
&self,
data: &[u8],
) -> (near_crypto::vrf::Value, near_crypto::vrf::Proof) {
match self {
ValidatorSigner::Empty(_) => unimplemented!(),
ValidatorSigner::InMemory(signer) => signer.compute_vrf_with_proof(data),
}
}
/// Used by test infrastructure, only implement if make sense for testing otherwise raise `unimplemented`.
pub fn write_to_file(&self, path: &Path) -> std::io::Result<()> {
match self {
ValidatorSigner::Empty(_) => unimplemented!(),
ValidatorSigner::InMemory(signer) => signer.write_to_file(path),
}
}
}
impl From<EmptyValidatorSigner> for ValidatorSigner {
fn from(signer: EmptyValidatorSigner) -> Self {
ValidatorSigner::Empty(signer)
}
}
impl From<InMemoryValidatorSigner> for ValidatorSigner {
fn from(signer: InMemoryValidatorSigner) -> Self {
ValidatorSigner::InMemory(signer)
}
}
/// Test-only signer that "signs" everything with 0s.
/// Don't use in any production or code that requires signature verification.
#[derive(smart_default::SmartDefault, Clone, Debug, PartialEq)]
pub struct EmptyValidatorSigner {
#[default("test".parse().unwrap())]
account_id: AccountId,
}
impl EmptyValidatorSigner {
pub fn new(account_id: AccountId) -> ValidatorSigner {
ValidatorSigner::Empty(Self { account_id })
}
fn validator_id(&self) -> &AccountId {
&self.account_id
}
fn public_key(&self) -> PublicKey {
PublicKey::empty(KeyType::ED25519)
}
fn noop_signature(&self) -> Signature {
Signature::default()
}
fn sign_telemetry(&self, _info: &TelemetryInfo) -> serde_json::Value {
serde_json::Value::default()
}
fn sign_block_header_parts(
&self,
prev_hash: CryptoHash,
inner_lite: &[u8],
inner_rest: &[u8],
) -> (CryptoHash, Signature) {
let hash = BlockHeader::compute_hash(prev_hash, inner_lite, inner_rest);
(hash, Signature::default())
}
fn sign_chunk_hash(&self, _chunk_hash: &ChunkHash) -> Signature {
Signature::default()
}
fn sign_approval(&self, _inner: &ApprovalInner, _target_height: BlockHeight) -> Signature {
Signature::default()
}
fn sign_chunk_endorsement(&self, _inner: &ChunkEndorsementInner) -> Signature {
Signature::default()
}
fn sign_chunk_endorsement_metadata(&self, _inner: &ChunkEndorsementMetadata) -> Signature {
Signature::default()
}
fn sign_chunk_state_witness(&self, _witness_bytes: &EncodedChunkStateWitness) -> Signature {
Signature::default()
}
fn sign_partial_encoded_state_witness(
&self,
_part: &PartialEncodedStateWitnessInner,
) -> Signature {
Signature::default()
}
fn sign_challenge(&self, challenge_body: &ChallengeBody) -> (CryptoHash, Signature) {
(CryptoHash::hash_borsh(challenge_body), Signature::default())
}
fn sign_account_announce(
&self,
_account_id: &AccountId,
_peer_id: &PeerId,
_epoch_id: &EpochId,
) -> Signature {
Signature::default()
}
}
/// Signer that keeps secret key in memory and signs locally.
#[derive(Clone, Debug, PartialEq)]
pub struct InMemoryValidatorSigner {
account_id: AccountId,
signer: Arc<Signer>,
}
impl InMemoryValidatorSigner {
#[cfg(feature = "rand")]
pub fn from_random(account_id: AccountId, key_type: KeyType) -> Self {
let signer = Arc::new(InMemorySigner::from_random(account_id.clone(), key_type).into());
Self { account_id, signer }
}
#[cfg(feature = "rand")]
pub fn from_seed(account_id: AccountId, key_type: KeyType, seed: &str) -> Self {
let signer = Arc::new(InMemorySigner::from_seed(account_id.clone(), key_type, seed).into());
Self { account_id, signer }
}
pub fn public_key(&self) -> PublicKey {
self.signer.public_key()
}
pub fn from_signer(signer: InMemorySigner) -> Self {
Self { account_id: signer.account_id.clone(), signer: Arc::new(signer.into()) }
}
pub fn from_file(path: &Path) -> std::io::Result<Self> {
let signer = InMemorySigner::from_file(path)?;
Ok(Self::from_signer(signer))
}
pub fn validator_id(&self) -> &AccountId {
&self.account_id
}
fn sign_telemetry(&self, info: &TelemetryInfo) -> serde_json::Value {
let mut value = serde_json::to_value(info).expect("Telemetry must serialize to JSON");
let content = serde_json::to_string(&value).expect("Telemetry must serialize to JSON");
value["signature"] = self.signer.sign(content.as_bytes()).to_string().into();
value
}
fn sign_block_header_parts(
&self,
prev_hash: CryptoHash,
inner_lite: &[u8],
inner_rest: &[u8],
) -> (CryptoHash, Signature) {
let hash = BlockHeader::compute_hash(prev_hash, inner_lite, inner_rest);
(hash, self.signer.sign(hash.as_ref()))
}
fn sign_chunk_hash(&self, chunk_hash: &ChunkHash) -> Signature {
self.signer.sign(chunk_hash.as_ref())
}
fn sign_approval(&self, inner: &ApprovalInner, target_height: BlockHeight) -> Signature {
self.signer.sign(&Approval::get_data_for_sig(inner, target_height))
}
fn sign_chunk_endorsement(&self, inner: &ChunkEndorsementInner) -> Signature {
self.signer.sign(&borsh::to_vec(inner).unwrap())
}
fn sign_chunk_endorsement_metadata(&self, inner: &ChunkEndorsementMetadata) -> Signature {
self.signer.sign(&borsh::to_vec(inner).unwrap())
}
fn sign_chunk_state_witness(&self, witness_bytes: &EncodedChunkStateWitness) -> Signature {
self.signer.sign(witness_bytes.as_slice())
}
fn sign_partial_encoded_state_witness(
&self,
part: &PartialEncodedStateWitnessInner,
) -> Signature {
self.signer.sign(&borsh::to_vec(part).unwrap())
}
fn sign_challenge(&self, challenge_body: &ChallengeBody) -> (CryptoHash, Signature) {
let hash = CryptoHash::hash_borsh(challenge_body);
let signature = self.signer.sign(hash.as_ref());
(hash, signature)
}
pub fn sign_account_announce(
&self,
account_id: &AccountId,
peer_id: &PeerId,
epoch_id: &EpochId,
) -> Signature {
let hash = AnnounceAccount::build_header_hash(account_id, peer_id, epoch_id);
self.signer.sign(hash.as_ref())
}
fn sign_bytes(&self, bytes: &[u8]) -> Signature {
self.signer.sign(bytes)
}
fn compute_vrf_with_proof(
&self,
data: &[u8],
) -> (near_crypto::vrf::Value, near_crypto::vrf::Proof) {
self.signer.compute_vrf_with_proof(data)
}
fn write_to_file(&self, path: &Path) -> std::io::Result<()> {
self.signer.write_to_file(path)
}
}