-
Notifications
You must be signed in to change notification settings - Fork 11.3k
/
Copy pathcrypto.rs
1810 lines (1614 loc) · 58.9 KB
/
crypto.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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
use crate::base_types::{AuthorityName, ConciseableName, SuiAddress};
use crate::committee::CommitteeTrait;
use crate::committee::{Committee, EpochId, StakeUnit};
use crate::error::{SuiError, SuiResult};
use crate::signature::GenericSignature;
use crate::sui_serde::{Readable, SuiBitmap};
use anyhow::{anyhow, Error};
use derive_more::{AsMut, AsRef, From};
pub use enum_dispatch::enum_dispatch;
use eyre::eyre;
use fastcrypto::bls12381::min_sig::{
BLS12381AggregateSignature, BLS12381AggregateSignatureAsBytes, BLS12381KeyPair,
BLS12381PrivateKey, BLS12381PublicKey, BLS12381Signature,
};
use fastcrypto::ed25519::{
Ed25519KeyPair, Ed25519PrivateKey, Ed25519PublicKey, Ed25519PublicKeyAsBytes, Ed25519Signature,
Ed25519SignatureAsBytes,
};
use fastcrypto::encoding::{Base64, Bech32, Encoding, Hex};
use fastcrypto::error::{FastCryptoError, FastCryptoResult};
use fastcrypto::hash::{Blake2b256, HashFunction};
use fastcrypto::secp256k1::{
Secp256k1KeyPair, Secp256k1PublicKey, Secp256k1PublicKeyAsBytes, Secp256k1Signature,
Secp256k1SignatureAsBytes,
};
use fastcrypto::secp256r1::{
Secp256r1KeyPair, Secp256r1PublicKey, Secp256r1PublicKeyAsBytes, Secp256r1Signature,
Secp256r1SignatureAsBytes,
};
pub use fastcrypto::traits::KeyPair as KeypairTraits;
pub use fastcrypto::traits::Signer;
pub use fastcrypto::traits::{
AggregateAuthenticator, Authenticator, EncodeDecodeBase64, SigningKey, ToFromBytes,
VerifyingKey,
};
use fastcrypto_zkp::bn254::zk_login::ZkLoginInputs;
use fastcrypto_zkp::zk_login_utils::Bn254FrElement;
use rand::rngs::{OsRng, StdRng};
use rand::SeedableRng;
use roaring::RoaringBitmap;
use schemars::JsonSchema;
use serde::ser::Serializer;
use serde::{Deserialize, Deserializer, Serialize};
use serde_with::{serde_as, Bytes};
use shared_crypto::intent::{Intent, IntentMessage, IntentScope};
use std::collections::BTreeMap;
use std::fmt::Debug;
use std::fmt::{self, Display, Formatter};
use std::hash::{Hash, Hasher};
use std::str::FromStr;
use strum::EnumString;
use tracing::{instrument, warn};
#[cfg(test)]
#[path = "unit_tests/crypto_tests.rs"]
mod crypto_tests;
#[cfg(test)]
#[path = "unit_tests/intent_tests.rs"]
mod intent_tests;
// Authority Objects
pub type AuthorityKeyPair = BLS12381KeyPair;
pub type AuthorityPublicKey = BLS12381PublicKey;
pub type AuthorityPrivateKey = BLS12381PrivateKey;
pub type AuthoritySignature = BLS12381Signature;
pub type AggregateAuthoritySignature = BLS12381AggregateSignature;
pub type AggregateAuthoritySignatureAsBytes = BLS12381AggregateSignatureAsBytes;
// TODO(joyqvq): prefix these types with Default, DefaultAccountKeyPair etc
pub type AccountKeyPair = Ed25519KeyPair;
pub type AccountPublicKey = Ed25519PublicKey;
pub type AccountPrivateKey = Ed25519PrivateKey;
pub type NetworkKeyPair = Ed25519KeyPair;
pub type NetworkPublicKey = Ed25519PublicKey;
pub type NetworkPrivateKey = Ed25519PrivateKey;
pub type DefaultHash = Blake2b256;
pub const DEFAULT_EPOCH_ID: EpochId = 0;
pub const SUI_PRIV_KEY_PREFIX: &str = "suiprivkey";
/// Creates a proof of that the authority account address is owned by the
/// holder of authority protocol key, and also ensures that the authority
/// protocol public key exists. A proof of possession is an authority
/// signature committed over the intent message `intent || message || epoch` (See
/// more at [struct IntentMessage] and [struct Intent]) where the message is
/// constructed as `authority_pubkey_bytes || authority_account_address`.
pub fn generate_proof_of_possession(
keypair: &AuthorityKeyPair,
address: SuiAddress,
) -> AuthoritySignature {
let mut msg: Vec<u8> = Vec::new();
msg.extend_from_slice(keypair.public().as_bytes());
msg.extend_from_slice(address.as_ref());
AuthoritySignature::new_secure(
&IntentMessage::new(Intent::sui_app(IntentScope::ProofOfPossession), msg),
&DEFAULT_EPOCH_ID,
keypair,
)
}
/// Verify proof of possession against the expected intent message,
/// consisting of the protocol pubkey and the authority account address.
pub fn verify_proof_of_possession(
pop: &AuthoritySignature,
protocol_pubkey: &AuthorityPublicKey,
sui_address: SuiAddress,
) -> Result<(), SuiError> {
protocol_pubkey
.validate()
.map_err(|_| SuiError::InvalidSignature {
error: "Fail to validate pubkey".to_string(),
})?;
let mut msg = protocol_pubkey.as_bytes().to_vec();
msg.extend_from_slice(sui_address.as_ref());
pop.verify_secure(
&IntentMessage::new(Intent::sui_app(IntentScope::ProofOfPossession), msg),
DEFAULT_EPOCH_ID,
protocol_pubkey.into(),
)
}
///////////////////////////////////////////////
/// Account Keys
///
/// * The following section defines the keypairs that are used by
/// * accounts to interact with Sui.
/// * Currently we support eddsa and ecdsa on Sui.
///
#[allow(clippy::large_enum_variant)]
#[derive(Debug, From, PartialEq, Eq)]
pub enum SuiKeyPair {
Ed25519(Ed25519KeyPair),
Secp256k1(Secp256k1KeyPair),
Secp256r1(Secp256r1KeyPair),
}
impl SuiKeyPair {
pub fn public(&self) -> PublicKey {
match self {
SuiKeyPair::Ed25519(kp) => PublicKey::Ed25519(kp.public().into()),
SuiKeyPair::Secp256k1(kp) => PublicKey::Secp256k1(kp.public().into()),
SuiKeyPair::Secp256r1(kp) => PublicKey::Secp256r1(kp.public().into()),
}
}
pub fn copy(&self) -> Self {
match self {
SuiKeyPair::Ed25519(kp) => kp.copy().into(),
SuiKeyPair::Secp256k1(kp) => kp.copy().into(),
SuiKeyPair::Secp256r1(kp) => kp.copy().into(),
}
}
}
impl Signer<Signature> for SuiKeyPair {
fn sign(&self, msg: &[u8]) -> Signature {
match self {
SuiKeyPair::Ed25519(kp) => kp.sign(msg),
SuiKeyPair::Secp256k1(kp) => kp.sign(msg),
SuiKeyPair::Secp256r1(kp) => kp.sign(msg),
}
}
}
impl EncodeDecodeBase64 for SuiKeyPair {
fn encode_base64(&self) -> String {
Base64::encode(self.to_bytes())
}
fn decode_base64(value: &str) -> FastCryptoResult<Self> {
let bytes = Base64::decode(value)?;
Self::from_bytes(&bytes).map_err(|_| FastCryptoError::InvalidInput)
}
}
impl SuiKeyPair {
pub fn to_bytes(&self) -> Vec<u8> {
let mut bytes: Vec<u8> = Vec::new();
bytes.push(self.public().flag());
match self {
SuiKeyPair::Ed25519(kp) => {
bytes.extend_from_slice(kp.as_bytes());
}
SuiKeyPair::Secp256k1(kp) => {
bytes.extend_from_slice(kp.as_bytes());
}
SuiKeyPair::Secp256r1(kp) => {
bytes.extend_from_slice(kp.as_bytes());
}
}
bytes
}
pub fn from_bytes(bytes: &[u8]) -> Result<Self, eyre::Report> {
match SignatureScheme::from_flag_byte(bytes.first().ok_or_else(|| eyre!("Invalid length"))?)
{
Ok(x) => match x {
SignatureScheme::ED25519 => Ok(SuiKeyPair::Ed25519(Ed25519KeyPair::from_bytes(
bytes.get(1..).ok_or_else(|| eyre!("Invalid length"))?,
)?)),
SignatureScheme::Secp256k1 => {
Ok(SuiKeyPair::Secp256k1(Secp256k1KeyPair::from_bytes(
bytes.get(1..).ok_or_else(|| eyre!("Invalid length"))?,
)?))
}
SignatureScheme::Secp256r1 => {
Ok(SuiKeyPair::Secp256r1(Secp256r1KeyPair::from_bytes(
bytes.get(1..).ok_or_else(|| eyre!("Invalid length"))?,
)?))
}
_ => Err(eyre!("Invalid flag byte")),
},
_ => Err(eyre!("Invalid bytes")),
}
}
pub fn to_bytes_no_flag(&self) -> Vec<u8> {
match self {
SuiKeyPair::Ed25519(kp) => kp.as_bytes().to_vec(),
SuiKeyPair::Secp256k1(kp) => kp.as_bytes().to_vec(),
SuiKeyPair::Secp256r1(kp) => kp.as_bytes().to_vec(),
}
}
/// Encode a SuiKeyPair as `flag || privkey` in Bech32 starting with "suiprivkey" to a string. Note that the pubkey is not encoded.
pub fn encode(&self) -> Result<String, eyre::Report> {
Bech32::encode(self.to_bytes(), SUI_PRIV_KEY_PREFIX).map_err(|e| eyre!(e))
}
/// Decode a SuiKeyPair from `flag || privkey` in Bech32 starting with "suiprivkey" to SuiKeyPair. The public key is computed directly from the private key bytes.
pub fn decode(value: &str) -> Result<Self, eyre::Report> {
let bytes = Bech32::decode(value, SUI_PRIV_KEY_PREFIX)?;
Self::from_bytes(&bytes)
}
}
impl Serialize for SuiKeyPair {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let s = self.encode_base64();
serializer.serialize_str(&s)
}
}
impl<'de> Deserialize<'de> for SuiKeyPair {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
use serde::de::Error;
let s = String::deserialize(deserializer)?;
SuiKeyPair::decode_base64(&s).map_err(|e| Error::custom(e.to_string()))
}
}
#[derive(Clone, Debug, PartialEq, Eq, JsonSchema, Serialize, Deserialize)]
pub enum PublicKey {
Ed25519(Ed25519PublicKeyAsBytes),
Secp256k1(Secp256k1PublicKeyAsBytes),
Secp256r1(Secp256r1PublicKeyAsBytes),
ZkLogin(ZkLoginPublicIdentifier),
Passkey(Secp256r1PublicKeyAsBytes),
}
/// A wrapper struct to retrofit in [enum PublicKey] for zkLogin.
/// Useful to construct [struct MultiSigPublicKey].
#[derive(Clone, Debug, PartialEq, Eq, JsonSchema, Serialize, Deserialize)]
pub struct ZkLoginPublicIdentifier(#[schemars(with = "Base64")] pub Vec<u8>);
impl ZkLoginPublicIdentifier {
/// Consists of iss_bytes_len || iss_bytes || padded_32_byte_address_seed.
pub fn new(iss: &str, address_seed: &Bn254FrElement) -> SuiResult<Self> {
let mut bytes = Vec::new();
let iss_bytes = iss.as_bytes();
bytes.extend([iss_bytes.len() as u8]);
bytes.extend(iss_bytes);
bytes.extend(address_seed.padded());
Ok(Self(bytes))
}
}
impl AsRef<[u8]> for PublicKey {
fn as_ref(&self) -> &[u8] {
match self {
PublicKey::Ed25519(pk) => &pk.0,
PublicKey::Secp256k1(pk) => &pk.0,
PublicKey::Secp256r1(pk) => &pk.0,
PublicKey::ZkLogin(z) => &z.0,
PublicKey::Passkey(pk) => &pk.0,
}
}
}
impl EncodeDecodeBase64 for PublicKey {
fn encode_base64(&self) -> String {
let mut bytes: Vec<u8> = Vec::new();
bytes.extend_from_slice(&[self.flag()]);
bytes.extend_from_slice(self.as_ref());
Base64::encode(&bytes[..])
}
fn decode_base64(value: &str) -> FastCryptoResult<Self> {
let bytes = Base64::decode(value)?;
match bytes.first() {
Some(x) => {
if x == &SignatureScheme::ED25519.flag() {
let pk: Ed25519PublicKey =
Ed25519PublicKey::from_bytes(bytes.get(1..).ok_or(
FastCryptoError::InputLengthWrong(Ed25519PublicKey::LENGTH + 1),
)?)?;
Ok(PublicKey::Ed25519((&pk).into()))
} else if x == &SignatureScheme::Secp256k1.flag() {
let pk = Secp256k1PublicKey::from_bytes(bytes.get(1..).ok_or(
FastCryptoError::InputLengthWrong(Secp256k1PublicKey::LENGTH + 1),
)?)?;
Ok(PublicKey::Secp256k1((&pk).into()))
} else if x == &SignatureScheme::Secp256r1.flag() {
let pk = Secp256r1PublicKey::from_bytes(bytes.get(1..).ok_or(
FastCryptoError::InputLengthWrong(Secp256r1PublicKey::LENGTH + 1),
)?)?;
Ok(PublicKey::Secp256r1((&pk).into()))
} else if x == &SignatureScheme::PasskeyAuthenticator.flag() {
let pk = Secp256r1PublicKey::from_bytes(bytes.get(1..).ok_or(
FastCryptoError::InputLengthWrong(Secp256r1PublicKey::LENGTH + 1),
)?)?;
Ok(PublicKey::Passkey((&pk).into()))
} else {
Err(FastCryptoError::InvalidInput)
}
}
_ => Err(FastCryptoError::InvalidInput),
}
}
}
impl PublicKey {
pub fn flag(&self) -> u8 {
self.scheme().flag()
}
pub fn try_from_bytes(
curve: SignatureScheme,
key_bytes: &[u8],
) -> Result<PublicKey, eyre::Report> {
match curve {
SignatureScheme::ED25519 => Ok(PublicKey::Ed25519(
(&Ed25519PublicKey::from_bytes(key_bytes)?).into(),
)),
SignatureScheme::Secp256k1 => Ok(PublicKey::Secp256k1(
(&Secp256k1PublicKey::from_bytes(key_bytes)?).into(),
)),
SignatureScheme::Secp256r1 => Ok(PublicKey::Secp256r1(
(&Secp256r1PublicKey::from_bytes(key_bytes)?).into(),
)),
SignatureScheme::PasskeyAuthenticator => Ok(PublicKey::Passkey(
(&Secp256r1PublicKey::from_bytes(key_bytes)?).into(),
)),
_ => Err(eyre!("Unsupported curve")),
}
}
pub fn scheme(&self) -> SignatureScheme {
match self {
PublicKey::Ed25519(_) => Ed25519SuiSignature::SCHEME,
PublicKey::Secp256k1(_) => Secp256k1SuiSignature::SCHEME,
PublicKey::Secp256r1(_) => Secp256r1SuiSignature::SCHEME,
PublicKey::ZkLogin(_) => SignatureScheme::ZkLoginAuthenticator,
PublicKey::Passkey(_) => SignatureScheme::PasskeyAuthenticator,
}
}
pub fn from_zklogin_inputs(inputs: &ZkLoginInputs) -> SuiResult<Self> {
Ok(PublicKey::ZkLogin(ZkLoginPublicIdentifier::new(
inputs.get_iss(),
inputs.get_address_seed(),
)?))
}
}
/// Defines the compressed version of the public key that we pass around
/// in Sui
#[serde_as]
#[derive(
Copy,
Clone,
PartialEq,
Eq,
Hash,
PartialOrd,
Ord,
Serialize,
Deserialize,
schemars::JsonSchema,
AsRef,
)]
#[as_ref(forward)]
pub struct AuthorityPublicKeyBytes(
#[schemars(with = "Base64")]
#[serde_as(as = "Readable<Base64, Bytes>")]
pub [u8; AuthorityPublicKey::LENGTH],
);
impl AuthorityPublicKeyBytes {
fn fmt_impl(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
let s = Hex::encode(self.0);
write!(f, "k#{}", s)?;
Ok(())
}
}
impl<'a> ConciseableName<'a> for AuthorityPublicKeyBytes {
type ConciseTypeRef = ConciseAuthorityPublicKeyBytesRef<'a>;
type ConciseType = ConciseAuthorityPublicKeyBytes;
/// Get a ConciseAuthorityPublicKeyBytesRef. Usage:
///
/// debug!(name = ?authority.concise());
/// format!("{:?}", authority.concise());
fn concise(&'a self) -> ConciseAuthorityPublicKeyBytesRef<'a> {
ConciseAuthorityPublicKeyBytesRef(self)
}
fn concise_owned(&self) -> ConciseAuthorityPublicKeyBytes {
ConciseAuthorityPublicKeyBytes(*self)
}
}
/// A wrapper around AuthorityPublicKeyBytes that provides a concise Debug impl.
pub struct ConciseAuthorityPublicKeyBytesRef<'a>(&'a AuthorityPublicKeyBytes);
impl Debug for ConciseAuthorityPublicKeyBytesRef<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
let s = Hex::encode(self.0 .0.get(0..4).ok_or(std::fmt::Error)?);
write!(f, "k#{}..", s)
}
}
impl Display for ConciseAuthorityPublicKeyBytesRef<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
Debug::fmt(self, f)
}
}
/// A wrapper around AuthorityPublicKeyBytes but owns it.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
pub struct ConciseAuthorityPublicKeyBytes(AuthorityPublicKeyBytes);
impl Debug for ConciseAuthorityPublicKeyBytes {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
let s = Hex::encode(self.0 .0.get(0..4).ok_or(std::fmt::Error)?);
write!(f, "k#{}..", s)
}
}
impl Display for ConciseAuthorityPublicKeyBytes {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
Debug::fmt(self, f)
}
}
impl TryFrom<AuthorityPublicKeyBytes> for AuthorityPublicKey {
type Error = FastCryptoError;
fn try_from(bytes: AuthorityPublicKeyBytes) -> Result<AuthorityPublicKey, Self::Error> {
AuthorityPublicKey::from_bytes(bytes.as_ref())
}
}
impl From<&AuthorityPublicKey> for AuthorityPublicKeyBytes {
fn from(pk: &AuthorityPublicKey) -> AuthorityPublicKeyBytes {
AuthorityPublicKeyBytes::from_bytes(pk.as_ref()).unwrap()
}
}
impl Debug for AuthorityPublicKeyBytes {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
self.fmt_impl(f)
}
}
impl Display for AuthorityPublicKeyBytes {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
self.fmt_impl(f)
}
}
impl ToFromBytes for AuthorityPublicKeyBytes {
fn from_bytes(bytes: &[u8]) -> Result<Self, fastcrypto::error::FastCryptoError> {
let bytes: [u8; AuthorityPublicKey::LENGTH] = bytes
.try_into()
.map_err(|_| fastcrypto::error::FastCryptoError::InvalidInput)?;
Ok(AuthorityPublicKeyBytes(bytes))
}
}
impl AuthorityPublicKeyBytes {
pub const ZERO: Self = Self::new([0u8; AuthorityPublicKey::LENGTH]);
/// This ensures it's impossible to construct an instance with other than registered lengths
pub const fn new(bytes: [u8; AuthorityPublicKey::LENGTH]) -> AuthorityPublicKeyBytes
where {
AuthorityPublicKeyBytes(bytes)
}
}
impl FromStr for AuthorityPublicKeyBytes {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let value = Hex::decode(s).map_err(|e| anyhow!(e))?;
Self::from_bytes(&value[..]).map_err(|e| anyhow!(e))
}
}
impl Default for AuthorityPublicKeyBytes {
fn default() -> Self {
Self::ZERO
}
}
//
// Add helper calls for Authority Signature
//
pub trait SuiAuthoritySignature {
fn verify_secure<T>(
&self,
value: &IntentMessage<T>,
epoch_id: EpochId,
author: AuthorityPublicKeyBytes,
) -> Result<(), SuiError>
where
T: Serialize;
fn new_secure<T>(
value: &IntentMessage<T>,
epoch_id: &EpochId,
secret: &dyn Signer<Self>,
) -> Self
where
T: Serialize;
}
impl SuiAuthoritySignature for AuthoritySignature {
#[instrument(level = "trace", skip_all)]
fn new_secure<T>(value: &IntentMessage<T>, epoch: &EpochId, secret: &dyn Signer<Self>) -> Self
where
T: Serialize,
{
let mut intent_msg_bytes =
bcs::to_bytes(&value).expect("Message serialization should not fail");
epoch.write(&mut intent_msg_bytes);
secret.sign(&intent_msg_bytes)
}
#[instrument(level = "trace", skip_all)]
fn verify_secure<T>(
&self,
value: &IntentMessage<T>,
epoch: EpochId,
author: AuthorityPublicKeyBytes,
) -> Result<(), SuiError>
where
T: Serialize,
{
let mut message = bcs::to_bytes(&value).expect("Message serialization should not fail");
epoch.write(&mut message);
let public_key = AuthorityPublicKey::try_from(author).map_err(|_| {
SuiError::KeyConversionError(
"Failed to serialize public key bytes to valid public key".to_string(),
)
})?;
public_key
.verify(&message[..], self)
.map_err(|e| SuiError::InvalidSignature {
error: format!(
"Fail to verify auth sig {} epoch: {} author: {}",
e,
epoch,
author.concise()
),
})
}
}
// TODO: get_key_pair() and get_key_pair_from_bytes() should return KeyPair only.
// TODO: rename to random_key_pair
pub fn get_key_pair<KP: KeypairTraits>() -> (SuiAddress, KP)
where
<KP as KeypairTraits>::PubKey: SuiPublicKey,
{
get_key_pair_from_rng(&mut OsRng)
}
/// Generate a random committee key pairs with a given committee size
pub fn random_committee_key_pairs_of_size(size: usize) -> Vec<AuthorityKeyPair> {
let mut rng = StdRng::from_seed([0; 32]);
(0..size)
.map(|_| {
// TODO: We are generating the keys 4 times to match exactly as how we generate
// keys in ConfigBuilder::build (sui-config/src/network_config_builder). This is because
// we are using these key generation functions as fixtures and we call them
// independently in different paths and exact the results to be the same.
// We should eliminate them.
let key_pair = get_key_pair_from_rng::<AuthorityKeyPair, _>(&mut rng);
get_key_pair_from_rng::<AuthorityKeyPair, _>(&mut rng);
get_key_pair_from_rng::<AccountKeyPair, _>(&mut rng);
get_key_pair_from_rng::<AccountKeyPair, _>(&mut rng);
key_pair.1
})
.collect()
}
pub fn deterministic_random_account_key() -> (SuiAddress, AccountKeyPair) {
let mut rng = StdRng::from_seed([0; 32]);
get_key_pair_from_rng(&mut rng)
}
pub fn get_account_key_pair() -> (SuiAddress, AccountKeyPair) {
get_key_pair()
}
pub fn get_authority_key_pair() -> (SuiAddress, AuthorityKeyPair) {
get_key_pair()
}
/// Generate a keypair from the specified RNG (useful for testing with seedable rngs).
pub fn get_key_pair_from_rng<KP: KeypairTraits, R>(csprng: &mut R) -> (SuiAddress, KP)
where
R: rand::CryptoRng + rand::RngCore,
<KP as KeypairTraits>::PubKey: SuiPublicKey,
{
let kp = KP::generate(&mut StdRng::from_rng(csprng).unwrap());
(kp.public().into(), kp)
}
// TODO: C-GETTER
pub fn get_key_pair_from_bytes<KP: KeypairTraits>(bytes: &[u8]) -> SuiResult<(SuiAddress, KP)>
where
<KP as KeypairTraits>::PubKey: SuiPublicKey,
{
let priv_length = <KP as KeypairTraits>::PrivKey::LENGTH;
let pub_key_length = <KP as KeypairTraits>::PubKey::LENGTH;
if bytes.len() != priv_length + pub_key_length {
return Err(SuiError::KeyConversionError(format!(
"Invalid input byte length, expected {}: {}",
priv_length,
bytes.len()
)));
}
let sk = <KP as KeypairTraits>::PrivKey::from_bytes(
bytes
.get(..priv_length)
.ok_or(SuiError::InvalidPrivateKey)?,
)
.map_err(|_| SuiError::InvalidPrivateKey)?;
let kp: KP = sk.into();
Ok((kp.public().into(), kp))
}
//
// Account Signatures
//
// Enums for signature scheme signatures
#[enum_dispatch]
#[derive(Clone, JsonSchema, Debug, PartialEq, Eq, Hash)]
pub enum Signature {
Ed25519SuiSignature,
Secp256k1SuiSignature,
Secp256r1SuiSignature,
}
impl Serialize for Signature {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let bytes = self.as_ref();
if serializer.is_human_readable() {
let s = Base64::encode(bytes);
serializer.serialize_str(&s)
} else {
serializer.serialize_bytes(bytes)
}
}
}
impl<'de> Deserialize<'de> for Signature {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
use serde::de::Error;
let bytes = if deserializer.is_human_readable() {
let s = String::deserialize(deserializer)?;
Base64::decode(&s).map_err(|e| Error::custom(e.to_string()))?
} else {
let data: Vec<u8> = Vec::deserialize(deserializer)?;
data
};
Self::from_bytes(&bytes).map_err(|e| Error::custom(e.to_string()))
}
}
impl Signature {
/// The messaged passed in is already hashed form.
pub fn new_hashed(hashed_msg: &[u8], secret: &dyn Signer<Signature>) -> Self {
Signer::sign(secret, hashed_msg)
}
pub fn new_secure<T>(value: &IntentMessage<T>, secret: &dyn Signer<Signature>) -> Self
where
T: Serialize,
{
// Compute the BCS hash of the value in intent message. In the case of transaction data,
// this is the BCS hash of `struct TransactionData`, different from the transaction digest
// itself that computes the BCS hash of the Rust type prefix and `struct TransactionData`.
// (See `fn digest` in `impl Message for SenderSignedData`).
let mut hasher = DefaultHash::default();
hasher.update(bcs::to_bytes(&value).expect("Message serialization should not fail"));
Signer::sign(secret, &hasher.finalize().digest)
}
}
impl AsRef<[u8]> for Signature {
fn as_ref(&self) -> &[u8] {
match self {
Signature::Ed25519SuiSignature(sig) => sig.as_ref(),
Signature::Secp256k1SuiSignature(sig) => sig.as_ref(),
Signature::Secp256r1SuiSignature(sig) => sig.as_ref(),
}
}
}
impl AsMut<[u8]> for Signature {
fn as_mut(&mut self) -> &mut [u8] {
match self {
Signature::Ed25519SuiSignature(sig) => sig.as_mut(),
Signature::Secp256k1SuiSignature(sig) => sig.as_mut(),
Signature::Secp256r1SuiSignature(sig) => sig.as_mut(),
}
}
}
impl ToFromBytes for Signature {
fn from_bytes(bytes: &[u8]) -> Result<Self, FastCryptoError> {
match bytes.first() {
Some(x) => {
if x == &Ed25519SuiSignature::SCHEME.flag() {
Ok(<Ed25519SuiSignature as ToFromBytes>::from_bytes(bytes)?.into())
} else if x == &Secp256k1SuiSignature::SCHEME.flag() {
Ok(<Secp256k1SuiSignature as ToFromBytes>::from_bytes(bytes)?.into())
} else if x == &Secp256r1SuiSignature::SCHEME.flag() {
Ok(<Secp256r1SuiSignature as ToFromBytes>::from_bytes(bytes)?.into())
} else {
Err(FastCryptoError::InvalidInput)
}
}
_ => Err(FastCryptoError::InvalidInput),
}
}
}
//
// BLS Port
//
impl SuiPublicKey for BLS12381PublicKey {
const SIGNATURE_SCHEME: SignatureScheme = SignatureScheme::BLS12381;
}
//
// Ed25519 Sui Signature port
//
#[serde_as]
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Hash, AsRef, AsMut)]
#[as_ref(forward)]
#[as_mut(forward)]
pub struct Ed25519SuiSignature(
#[schemars(with = "Base64")]
#[serde_as(as = "Readable<Base64, Bytes>")]
[u8; Ed25519PublicKey::LENGTH + Ed25519Signature::LENGTH + 1],
);
// Implementation useful for simplify testing when mock signature is needed
impl Default for Ed25519SuiSignature {
fn default() -> Self {
Self([0; Ed25519PublicKey::LENGTH + Ed25519Signature::LENGTH + 1])
}
}
impl SuiSignatureInner for Ed25519SuiSignature {
type Sig = Ed25519Signature;
type PubKey = Ed25519PublicKey;
type KeyPair = Ed25519KeyPair;
const LENGTH: usize = Ed25519PublicKey::LENGTH + Ed25519Signature::LENGTH + 1;
}
impl SuiPublicKey for Ed25519PublicKey {
const SIGNATURE_SCHEME: SignatureScheme = SignatureScheme::ED25519;
}
impl ToFromBytes for Ed25519SuiSignature {
fn from_bytes(bytes: &[u8]) -> Result<Self, FastCryptoError> {
if bytes.len() != Self::LENGTH {
return Err(FastCryptoError::InputLengthWrong(Self::LENGTH));
}
let mut sig_bytes = [0; Self::LENGTH];
sig_bytes.copy_from_slice(bytes);
Ok(Self(sig_bytes))
}
}
impl Signer<Signature> for Ed25519KeyPair {
fn sign(&self, msg: &[u8]) -> Signature {
Ed25519SuiSignature::new(self, msg).into()
}
}
//
// Secp256k1 Sui Signature port
//
#[serde_as]
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Hash, AsRef, AsMut)]
#[as_ref(forward)]
#[as_mut(forward)]
pub struct Secp256k1SuiSignature(
#[schemars(with = "Base64")]
#[serde_as(as = "Readable<Base64, Bytes>")]
[u8; Secp256k1PublicKey::LENGTH + Secp256k1Signature::LENGTH + 1],
);
impl SuiSignatureInner for Secp256k1SuiSignature {
type Sig = Secp256k1Signature;
type PubKey = Secp256k1PublicKey;
type KeyPair = Secp256k1KeyPair;
const LENGTH: usize = Secp256k1PublicKey::LENGTH + Secp256k1Signature::LENGTH + 1;
}
impl SuiPublicKey for Secp256k1PublicKey {
const SIGNATURE_SCHEME: SignatureScheme = SignatureScheme::Secp256k1;
}
impl ToFromBytes for Secp256k1SuiSignature {
fn from_bytes(bytes: &[u8]) -> Result<Self, FastCryptoError> {
if bytes.len() != Self::LENGTH {
return Err(FastCryptoError::InputLengthWrong(Self::LENGTH));
}
let mut sig_bytes = [0; Self::LENGTH];
sig_bytes.copy_from_slice(bytes);
Ok(Self(sig_bytes))
}
}
impl Signer<Signature> for Secp256k1KeyPair {
fn sign(&self, msg: &[u8]) -> Signature {
Secp256k1SuiSignature::new(self, msg).into()
}
}
//
// Secp256r1 Sui Signature port
//
#[serde_as]
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Hash, AsRef, AsMut)]
#[as_ref(forward)]
#[as_mut(forward)]
pub struct Secp256r1SuiSignature(
#[schemars(with = "Base64")]
#[serde_as(as = "Readable<Base64, Bytes>")]
[u8; Secp256r1PublicKey::LENGTH + Secp256r1Signature::LENGTH + 1],
);
impl SuiSignatureInner for Secp256r1SuiSignature {
type Sig = Secp256r1Signature;
type PubKey = Secp256r1PublicKey;
type KeyPair = Secp256r1KeyPair;
const LENGTH: usize = Secp256r1PublicKey::LENGTH + Secp256r1Signature::LENGTH + 1;
}
impl SuiPublicKey for Secp256r1PublicKey {
const SIGNATURE_SCHEME: SignatureScheme = SignatureScheme::Secp256r1;
}
impl ToFromBytes for Secp256r1SuiSignature {
fn from_bytes(bytes: &[u8]) -> Result<Self, FastCryptoError> {
if bytes.len() != Self::LENGTH {
return Err(FastCryptoError::InputLengthWrong(Self::LENGTH));
}
let mut sig_bytes = [0; Self::LENGTH];
sig_bytes.copy_from_slice(bytes);
Ok(Self(sig_bytes))
}
}
impl Signer<Signature> for Secp256r1KeyPair {
fn sign(&self, msg: &[u8]) -> Signature {
Secp256r1SuiSignature::new(self, msg).into()
}
}
//
// This struct exists due to the limitations of the `enum_dispatch` library.
//
pub trait SuiSignatureInner: Sized + ToFromBytes + PartialEq + Eq + Hash {
type Sig: Authenticator<PubKey = Self::PubKey>;
type PubKey: VerifyingKey<Sig = Self::Sig> + SuiPublicKey;
type KeyPair: KeypairTraits<PubKey = Self::PubKey, Sig = Self::Sig>;
const LENGTH: usize = Self::Sig::LENGTH + Self::PubKey::LENGTH + 1;
const SCHEME: SignatureScheme = Self::PubKey::SIGNATURE_SCHEME;
/// Returns the deserialized signature and deserialized pubkey.
fn get_verification_inputs(&self) -> SuiResult<(Self::Sig, Self::PubKey)> {
let pk = Self::PubKey::from_bytes(self.public_key_bytes())
.map_err(|_| SuiError::KeyConversionError("Invalid public key".to_string()))?;
// deserialize the signature
let signature = Self::Sig::from_bytes(self.signature_bytes()).map_err(|_| {
SuiError::InvalidSignature {
error: "Fail to get pubkey and sig".to_string(),
}
})?;
Ok((signature, pk))
}
fn new(kp: &Self::KeyPair, message: &[u8]) -> Self {
let sig = Signer::sign(kp, message);
let mut signature_bytes: Vec<u8> = Vec::new();
signature_bytes
.extend_from_slice(&[<Self::PubKey as SuiPublicKey>::SIGNATURE_SCHEME.flag()]);
signature_bytes.extend_from_slice(sig.as_ref());
signature_bytes.extend_from_slice(kp.public().as_ref());
Self::from_bytes(&signature_bytes[..])
.expect("Serialized signature did not have expected size")
}
}
pub trait SuiPublicKey: VerifyingKey {
const SIGNATURE_SCHEME: SignatureScheme;
}
#[enum_dispatch(Signature)]
pub trait SuiSignature: Sized + ToFromBytes {
fn signature_bytes(&self) -> &[u8];
fn public_key_bytes(&self) -> &[u8];
fn scheme(&self) -> SignatureScheme;
fn verify_secure<T>(
&self,
value: &IntentMessage<T>,
author: SuiAddress,
scheme: SignatureScheme,
) -> SuiResult<()>
where
T: Serialize;
}
impl<S: SuiSignatureInner + Sized> SuiSignature for S {
fn signature_bytes(&self) -> &[u8] {
// Access array slice is safe because the array bytes is initialized as
// flag || signature || pubkey with its defined length.
&self.as_ref()[1..1 + S::Sig::LENGTH]
}
fn public_key_bytes(&self) -> &[u8] {
// Access array slice is safe because the array bytes is initialized as
// flag || signature || pubkey with its defined length.
&self.as_ref()[S::Sig::LENGTH + 1..]
}
fn scheme(&self) -> SignatureScheme {
S::PubKey::SIGNATURE_SCHEME
}
fn verify_secure<T>(
&self,
value: &IntentMessage<T>,
author: SuiAddress,
scheme: SignatureScheme,
) -> Result<(), SuiError>
where
T: Serialize,
{
let mut hasher = DefaultHash::default();