Skip to content

Commit

Permalink
crypto: Rederive pubkey for encode/decode (MystenLabs#6989)
Browse files Browse the repository at this point in the history
MystenLabs#6940

## What
This changes the serialization of a `SuiKeyPair` from base64 encoded
`flag || pubkey || privkey` to `flag || privkey`. This is to never trust
the pubkey bytes inputs when but to always derive it from privkey when
bootstrapping from read/write from files.

This impact the `sui keytool generate` and `sui client new-address`. 

## Notes for breaking change

If you see the following error, 
```
target/debug/sui keytool generate ed25519
Invalid Keypair file InvalidInput "/Users/joy/.sui/sui_config/sui.keystore"
```
This is because the old serialization cannot be parsed anymore. Run: `rm
/Users/joy/.sui/sui_config/sui.keystore` If you would like to keep the
existing keys, please reimport from mnemonics using `keytool import`

## Test
```
target/debug/sui client new-address ed25519
Created new keypair for address with scheme ED25519: [0x25142b365037715dae989375ac2b74b2517edd62]
Secret Recovery Phrase : [original rent brick leader middle target cheap rather choose elephant system abstract despair math pudding music garment young syrup foam core try good market]

target/debug/sui client new-address secp256k1
Created new keypair for address with scheme Secp256k1: [0x049045049bbcd071609e0caf88b0542ed791aa3e]
Secret Recovery Phrase : [enroll field short hurry unique morning glad can bridge immune sorry blood badge collect gesture math gallery rifle lens surge nasty hurt couch delay]

target/debug/sui client new-address secp256r1 
Created new keypair for address with scheme Secp256r1: [0xa76b0f7b5e19b86c768486b1ffb757b9952f8d61]
Secret Recovery Phrase : [witness stuff sorry try chuckle cliff moon share purchase person runway online usual exit lunar same limit act walk spread abandon cradle basic coin]

target/debug/sui keytool list
                Sui Address                 |              Public Key (Base64)              | Scheme
----------------------------------------------------------------------------------------------------
 0x049045049bbcd071609e0caf88b0542ed791aa3e | AQKxLzhpin3HwLzcjscgPGzrcdRvCX6vZT0xTH5X6PDKRA== | secp256k1
 0x25142b365037715dae989375ac2b74b2517edd62 | AOBT/yUKPQuCNh8eiLaGyyIoUTa3HbWpxwYxM/1dNdoV  | ed25519
 0xa76b0f7b5e19b86c768486b1ffb757b9952f8d61 | AgNy9UEXhU/K1aro4vY/QxssR6pfw9K6NmNLsUDi0VydSg== | secp256r1

cat /Users/joy/.sui/sui_config/sui.keystore
[
  "ATWhXWl/zlrENWnc2AIbjChwAB5FGMsBp3RBcKUCUe90",
  "AOhFYQNpqLgJyYmfg975nwQmQ8YCPXCnTw/l8ZjIBEqy",
  "ArYljv5d6NQWahm8/oDF7xa+E5f6XpyMdDxTfPuxhLzD"
]%
  • Loading branch information
joyqvq authored Jan 5, 2023
1 parent 48c447b commit 28c4823
Show file tree
Hide file tree
Showing 10 changed files with 267 additions and 320 deletions.
339 changes: 163 additions & 176 deletions Cargo.lock

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,8 @@ move-prover-boogie-backend = { git = "https://github.com/move-language/move", re
move-stackless-bytecode = { git = "https://github.com/move-language/move", rev = "a8e95cbae69564d8928c9873b8acfabc50e642cf" }
move-symbol-pool = { git = "https://github.com/move-language/move", rev = "a8e95cbae69564d8928c9873b8acfabc50e642cf" }

fastcrypto = { git = "https://github.com/MystenLabs/fastcrypto", rev = "f64e36ceed674ccd46938cfd9645a2d32a923656" }
fastcrypto-zkp = { git = "https://github.com/MystenLabs/fastcrypto", rev = "f64e36ceed674ccd46938cfd9645a2d32a923656", package = "fastcrypto-zkp" }
fastcrypto = { git = "https://github.com/MystenLabs/fastcrypto", rev = "4886087c10be9b9a7a4cf40c4b87428458c1fce5" }
fastcrypto-zkp = { git = "https://github.com/MystenLabs/fastcrypto", rev = "4886087c10be9b9a7a4cf40c4b87428458c1fce5", package = "fastcrypto-zkp" }

# anemo dependencies
anemo = { git = "https://github.com/mystenlabs/anemo.git", rev = "ccfb77628ec1883121079f1ae9c65e9c716709c8" }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,13 @@ expression: network_config
---
validator_configs:
- protocol-key-pair:
value:
name: mfJe9h+AMrkUY2RgmCxcxvE07x3a52ZX8sv+wev8jQlzdAgN9vzw3Li8Sw2OCvXYDrv/K0xZn1T0LWMS38MUJ2B4wcw0fru+xRmL4lhRPzhrkw0CwnSagD4jMJVevRoQ
secret: VTDx4HjVmRBqdqBWg2zN+zcFE20io3CrBchGy/iV1lo=
value: VTDx4HjVmRBqdqBWg2zN+zcFE20io3CrBchGy/iV1lo=
worker-key-pair:
value: AB8qeQGoQuTTYjvGHOHBcX0udo4P1y34NBr1ZhW5FvA4fsz863qJR38mPjuvloaZBE4vbibFPgrwQXUa+OGTTNM=
value: AH7M/Ot6iUd/Jj47r5aGmQROL24mxT4K8EF1Gvjhk0zT
account-key-pair:
value: AJTkqEkxROnmliCMvtACWebdtW+Xm5HDKWdWCYW+YZCbZeUwqtiSP4IuiO1U/Br2sTVBQpkckD5caF+BanumitE=
value: AGXlMKrYkj+CLojtVPwa9rE1QUKZHJA+XGhfgWp7porR
network-key-pair:
value: AL44MMsMV12FoZiE5Sg5asNvkOHbsTLAOvoDWFoxKhmAKUrb+C2JL5zKk+XaKXpgLj08mCQegCCekpnR0SLAhTA=
value: AClK2/gtiS+cypPl2il6YC49PJgkHoAgnpKZ0dEiwIUw
db-path: /tmp/foo/
network-address: ""
json-rpc-address: "0.0.0.0:1"
Expand Down Expand Up @@ -66,15 +64,13 @@ validator_configs:
end-of-epoch-broadcast-channel-capacity: 128
local-execution-timeout-sec: 10
- protocol-key-pair:
value:
name: jc/20VUECmVvSBmxMRG1LFdGqGunLzlfuv4uw4R9HoFA5iSnUf32tfIFC8cgXPnTAATJCwx0Cv/TJs5nPMKyOi0k1T4q/rKG38Zo/UBgCJ1tKxe3md02+Q0zLlSnozjU
secret: avYcyVgYMXTyaUYh9IRwLK0gSzl7YF6ZQDAbrS1Bhvo=
value: avYcyVgYMXTyaUYh9IRwLK0gSzl7YF6ZQDAbrS1Bhvo=
worker-key-pair:
value: ANSWQQYBVmLJ14dt+EH2BgvuTMMGCQNb4W0ooIJ2QomvpPBKumCrkESEmAiG/7UfSMyIlAyKCQaysBb0RA9oxIg=
value: AKTwSrpgq5BEhJgIhv+1H0jMiJQMigkGsrAW9EQPaMSI
account-key-pair:
value: ACxHMS0iupHOTDgHm2HYa+f/ft9OjvxBk5+C7f/APsXUezeV+HwuWFqdYT/NOM6oMWQ2IMvai7GOMn5YNPn+FWA=
value: AHs3lfh8LlhanWE/zTjOqDFkNiDL2ouxjjJ+WDT5/hVg
network-key-pair:
value: ADZBr90s2BQK6vOoAlQE0lfeXjWWwRBJzgFTsdYoFwHD25MXKYkbDqXWtIZXl27gbhE44t3hp1Qi3HFWHLfWWc0=
value: ANuTFymJGw6l1rSGV5du4G4ROOLd4adUItxxVhy31lnN
db-path: /tmp/foo/
network-address: ""
json-rpc-address: "0.0.0.0:1"
Expand Down Expand Up @@ -128,15 +124,13 @@ validator_configs:
end-of-epoch-broadcast-channel-capacity: 128
local-execution-timeout-sec: 10
- protocol-key-pair:
value:
name: rd7vlNiYyI5A297/kcXxBfnPLHR/tvK8N+wD1ske2y4aV4z1RL6LCTHiXyQ9WbDDDZihbOO6HWzx1/UEJpkusK2zE0sFW+gUDS218l+wDYP45CIr8B/WrJOh/0152ljy
secret: OXnx3yM1C/ppgnDMx/o1d49fJs7E05kq11mXNae/O+I=
value: OXnx3yM1C/ppgnDMx/o1d49fJs7E05kq11mXNae/O+I=
worker-key-pair:
value: ALVWB00uJAL5Za9FJP5LLyje/D/cqGQPouQqBIjdwDbU1Dh27FOw52h9QAd9IijyRq42PtJGYtmCZ2RvXYPDEXo=
value: ANQ4duxTsOdofUAHfSIo8kauNj7SRmLZgmdkb12DwxF6
account-key-pair:
value: ANoED1MVNxaUbvcp8K7QXQLx/JQAamix308cQdCKwKu2YYJojLU7C+8u2vatwd7CUkkEgsvOGsRqjhCYXQPZRPM=
value: AGGCaIy1OwvvLtr2rcHewlJJBILLzhrEao4QmF0D2UTz
network-key-pair:
value: APcMoNRxXoAwhpg+kkOBUEbkqKeqxCPCZy7Ej7VtIc9eoUiBY+hNlv3/NS7/U/zAW3EMNi45uTXGv9BrFnYfjyI=
value: AKFIgWPoTZb9/zUu/1P8wFtxDDYuObk1xr/QaxZ2H48i
db-path: /tmp/foo/
network-address: ""
json-rpc-address: "0.0.0.0:1"
Expand Down Expand Up @@ -190,15 +184,13 @@ validator_configs:
end-of-epoch-broadcast-channel-capacity: 128
local-execution-timeout-sec: 10
- protocol-key-pair:
value:
name: s/1e+1yHJAOkrRPxGZUTYG0jNUqEUkmuoVdWTCP/PBXGyeZSty10DoysuTy8wGhrDsDMDBx2C/tCtDZRn8WoBUt2UzqXqfI5h9CX75ax8lJrsgc/oQp3GZQXcjR+8nT0
secret: CyNkjqNVr3HrHTH7f/NLs7u5lUHJzuPAw0PqMTD2y2s=
value: CyNkjqNVr3HrHTH7f/NLs7u5lUHJzuPAw0PqMTD2y2s=
worker-key-pair:
value: APHAGQX7Q8ru1I3xIpXIXPE4/+sy3F3653KVP/SEEGE8EHX7HidEWjJgbesq5yxWacBkHUx/wALB90Mm8SiaEZY=
value: ABB1+x4nRFoyYG3rKucsVmnAZB1Mf8ACwfdDJvEomhGW
account-key-pair:
value: AEgi5sKIaNYxb+8Vr0MKLUWpdrRfjLPiCeYy4hQTtSBHkXLa5CsQhIUzlhFBEFTP1eKxJ6lBGRYzNkOjrDamlU8=
value: AJFy2uQrEISFM5YRQRBUz9XisSepQRkWMzZDo6w2ppVP
network-key-pair:
value: AKhAJDLu7QoRDl/OHYaKpoedNK6/nwK1KTnNInegI/AIjQ5isfeCs5cO8kQfRoNiE6Ex250niEtXCH7U4Y3Khd4=
value: AI0OYrH3grOXDvJEH0aDYhOhMdudJ4hLVwh+1OGNyoXe
db-path: /tmp/foo/
network-address: ""
json-rpc-address: "0.0.0.0:1"
Expand Down Expand Up @@ -252,15 +244,13 @@ validator_configs:
end-of-epoch-broadcast-channel-capacity: 128
local-execution-timeout-sec: 10
- protocol-key-pair:
value:
name: iykapXF0PID5jtwjt7N3ZdJa6lpWaL4SqcxDafLvaXwbAcFKyHdC4ooqkJj+YZRiFV6exojtsF/QKVaqOne/52TWAd4Tl+TWnopwHw8TeEOlc0rWTcUEt2zfwoihd/4h
secret: X/I/kM+KvHcxAKEf2UU6Sr7SpN3bhiE9nP5CuM/iIY0=
value: X/I/kM+KvHcxAKEf2UU6Sr7SpN3bhiE9nP5CuM/iIY0=
worker-key-pair:
value: AAu5FA71j6mrLj53XwefJvFxwEnQ96jHXA2e1QLDzeO2UkqY1k2SrJLzldSoAqzDZp1vudV6MzAZqojam0XY2ZM=
value: AFJKmNZNkqyS85XUqAKsw2adb7nVejMwGaqI2ptF2NmT
account-key-pair:
value: AB86G1ccGVVMFPrc3src2g3fB3NMyEcsS5pzI+Yr6cyKJ0hDQggulPK2ZTpGNWrch+vg73OQ9lWfRXu9uN+Qo88=
value: ACdIQ0IILpTytmU6RjVq3Ifr4O9zkPZVn0V7vbjfkKPP
network-key-pair:
value: AAr1m714uM0Q8gG5dcq+WtV+G7BZZ+9mjxEhNTP6gaLgUqrQzLuBAdMMbnxVAxgiaFTXz6PaV70e0XTyeF6Fu8o=
value: AFKq0My7gQHTDG58VQMYImhU18+j2le9HtF08nhehbvK
db-path: /tmp/foo/
network-address: ""
json-rpc-address: "0.0.0.0:1"
Expand Down Expand Up @@ -314,15 +304,13 @@ validator_configs:
end-of-epoch-broadcast-channel-capacity: 128
local-execution-timeout-sec: 10
- protocol-key-pair:
value:
name: hDG9yW+2b1MVu6dC9eQPfjcvI3xeIg2B3zYYOwYmU154R+z0ao40SlohrbXlOIuVARpZPG30Ei9/4q1+gCipawnqvYQ3aSXqUBVj1YYnli1dMMIKrtMCG8TQ59v9HhyV
secret: N272EiFDyKtxRbDKbyN6ujenJ+skPcRoc/XolpOLGnU=
value: N272EiFDyKtxRbDKbyN6ujenJ+skPcRoc/XolpOLGnU=
worker-key-pair:
value: APAynrz31Ch7RE8FdCwb4IO3ngw+n/EiYwDIqRXdko9tHloy4pnf8pWEHGP+4OFsXz56bLdIJhkD2O+OdKMqCA4=
value: AB5aMuKZ3/KVhBxj/uDhbF8+emy3SCYZA9jvjnSjKggO
account-key-pair:
value: AHH6sQEDMUJH0Spm5nDLrKbFAUcBHYL/VIORf2ervCbbpvMScjoMR/DaN0M5IOxS2VpGC59N6kv6gDm63ufLQ5w=
value: AKbzEnI6DEfw2jdDOSDsUtlaRgufTepL+oA5ut7ny0Oc
network-key-pair:
value: AN/lvly8qQKGpl49Z6HXdwC+D7ULK+u08HVxA4GHDHi/tPu3gzoWoFbHbnuaUp1whWKFV7mtDVfOtTHDWWR2ZoU=
value: ALT7t4M6FqBWx257mlKdcIVihVe5rQ1XzrUxw1lkdmaF
db-path: /tmp/foo/
network-address: ""
json-rpc-address: "0.0.0.0:1"
Expand Down Expand Up @@ -376,15 +364,13 @@ validator_configs:
end-of-epoch-broadcast-channel-capacity: 128
local-execution-timeout-sec: 10
- protocol-key-pair:
value:
name: lamelKkm5XZeTAwR14xd1R0/fXugoGU7kl6RQkUn8PhjGFbkBMDtPVlWPOddZqEWE7hYH0edddPDSgk/K3vqaSorqorcW+AZTjWLIOAmr5YiVwlqLGsHCmQ3Hmuw+hXt
secret: a74f03IOjL8ZFSWFChFVEi+wiMwHNwNCPDGIYkGfgjs=
value: a74f03IOjL8ZFSWFChFVEi+wiMwHNwNCPDGIYkGfgjs=
worker-key-pair:
value: AH3cM/tEnyOv0j05eb8x/efG9GjMFlCdFSg9jy2+EwIY5RWlYF22jS9i76zLl8jP2D3D8GC5ht+IP1dWUBGZxi8=
value: AOUVpWBdto0vYu+sy5fIz9g9w/BguYbfiD9XVlARmcYv
account-key-pair:
value: AKHC3Gr1i6u+zAK1Yj1vys0hB83qha4jRCfzoHqLAo6FQ5EkvCcy5cw1JKStwSs0v/QByW0I8JXCqdnagoupCMg=
value: AEORJLwnMuXMNSSkrcErNL/0AcltCPCVwqnZ2oKLqQjI
network-key-pair:
value: ALhZgk9n2c3J7x/45tQsL/CdHhfzu0gAfjC9exnw4pbB+EEIX4hOQB79xqDr8Cp0UGNNC4sEE849/ORTGY1iwxc=
value: APhBCF+ITkAe/cag6/AqdFBjTQuLBBPOPfzkUxmNYsMX
db-path: /tmp/foo/
network-address: ""
json-rpc-address: "0.0.0.0:1"
Expand Down Expand Up @@ -438,10 +424,10 @@ validator_configs:
end-of-epoch-broadcast-channel-capacity: 128
local-execution-timeout-sec: 10
account_keys:
- 10wECHkYvXqL5/CY6WhjbfFPotZb5tjEbpmumqbRxul6/9LaD95rkXfiBEoGJR8u81q9fCiP+O7nXOsprVTPUQ==
- ZTWBfKEmFOyYM9oBU9dNfREBuAU5fm2OBhg/vPtI00ee91o4Td1upRqxdMC/5khQi58pBG83ZvbMUnI2shFOvw==
- +0LdRe35y6TgXPz6qcArpf0T8/Hh7zkjJL0yT19jbjdWZVO3wT0uCs8sHK38p5+DiwNKSfKm/iqb6R7vmIsYNg==
- cHifntmjxd4QLaC71WRMoOeCpvicyDJMbTKRuo2v3R9UjI8DXP6RwO6c5B70OPjZEdiV0XB+RVfcjX6/JKfZeg==
- mTzV/JVz4RdheOnQVFF3xuCPFF4AYAPyShHQCUizJX9pHbCeXB5wKAz9LCwtuoC4PCML0v4vko2/c16HlmPrbQ==
- 10wECHkYvXqL5/CY6WhjbfFPotZb5tjEbpmumqbRxuk=
- ZTWBfKEmFOyYM9oBU9dNfREBuAU5fm2OBhg/vPtI00c=
- +0LdRe35y6TgXPz6qcArpf0T8/Hh7zkjJL0yT19jbjc=
- cHifntmjxd4QLaC71WRMoOeCpvicyDJMbTKRuo2v3R8=
- mTzV/JVz4RdheOnQVFF3xuCPFF4AYAPyShHQCUizJX8=
genesis: "[fake genesis]"

13 changes: 4 additions & 9 deletions crates/sui-core/tests/staged/sui.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,12 @@ AccountAddress:
SIZE: 20
AuthorityPublicKeyBytes:
NEWTYPESTRUCT: BYTES
BLS12381KeyPair:
STRUCT:
- name: STR
- secret: STR
BLS12381Signature:
STRUCT:
- sig: BYTES
- sig:
TUPLEARRAY:
CONTENT: U8
SIZE: 48
CallArg:
ENUM:
0:
Expand Down Expand Up @@ -64,10 +63,6 @@ DeleteKind:
UnwrapThenDelete: UNIT
2:
Wrap: UNIT
Ed25519KeyPair:
STRUCT:
- name: STR
- secret: STR
EntryArgumentError:
STRUCT:
- argument_idx: U8
Expand Down
2 changes: 1 addition & 1 deletion crates/sui-keys/src/key_derive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ pub fn derive_key_pair_from_path(
let derived = derive_ed25519_private_key(seed, &indexes);
let sk = Ed25519PrivateKey::from_bytes(&derived)
.map_err(|e| SuiError::SignatureKeyGenError(e.to_string()))?;
let kp = Ed25519KeyPair::from(sk);
let kp: Ed25519KeyPair = sk.into();
Ok((kp.public().into(), SuiKeyPair::Ed25519(kp)))
}
SignatureScheme::Secp256k1 => {
Expand Down
110 changes: 42 additions & 68 deletions crates/sui-types/src/crypto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,14 @@
// SPDX-License-Identifier: Apache-2.0
use anyhow::{anyhow, Error};
use derive_more::From;
use eyre::eyre;
use fastcrypto::bls12381::min_sig::{
BLS12381AggregateSignature, BLS12381KeyPair, BLS12381PrivateKey, BLS12381PublicKey,
BLS12381Signature,
};
use fastcrypto::ed25519::{Ed25519KeyPair, Ed25519PrivateKey, Ed25519PublicKey, Ed25519Signature};
use fastcrypto::secp256k1::{
Secp256k1KeyPair, Secp256k1PrivateKey, Secp256k1PublicKey, Secp256k1Signature,
};
use fastcrypto::secp256r1::{
Secp256r1KeyPair, Secp256r1PrivateKey, Secp256r1PublicKey, Secp256r1Signature,
};
use fastcrypto::secp256k1::{Secp256k1KeyPair, Secp256k1PublicKey, Secp256k1Signature};
use fastcrypto::secp256r1::{Secp256r1KeyPair, Secp256r1PublicKey, Secp256r1Signature};
pub use fastcrypto::traits::KeyPair as KeypairTraits;
pub use fastcrypto::traits::{
AggregateAuthenticator, Authenticator, EncodeDecodeBase64, SigningKey, ToFromBytes,
Expand Down Expand Up @@ -130,72 +127,54 @@ impl FromStr for SuiKeyPair {
type Err = eyre::Report;

fn from_str(s: &str) -> Result<Self, Self::Err> {
let kp = Self::decode_base64(s).map_err(|e| eyre::eyre!("{}", e.to_string()))?;
let kp = Self::decode_base64(s).map_err(|e| eyre!("{}", e.to_string()))?;
Ok(kp)
}
}

impl EncodeDecodeBase64 for SuiKeyPair {
/// Encode a SuiKeyPair as `flag || privkey` in Base64. Note that the pubkey is not encoded.
fn encode_base64(&self) -> String {
let mut bytes: Vec<u8> = Vec::new();
match self {
SuiKeyPair::Ed25519(kp) => {
let kp1 = kp.copy();
bytes.extend_from_slice(&[self.public().flag()]);
bytes.extend_from_slice(kp.public().as_ref());
bytes.extend_from_slice(kp1.private().as_ref());
bytes.push(self.public().flag());
bytes.extend_from_slice(kp.as_bytes());
}
SuiKeyPair::Secp256k1(kp) => {
let kp1 = kp.copy();
bytes.extend_from_slice(&[self.public().flag()]);
bytes.extend_from_slice(kp.public().as_ref());
bytes.extend_from_slice(kp1.private().as_ref());
bytes.push(self.public().flag());
bytes.extend_from_slice(kp.as_bytes());
}
SuiKeyPair::Secp256r1(kp) => {
let kp1 = kp.copy();
bytes.extend_from_slice(&[self.public().flag()]);
bytes.extend_from_slice(kp.public().as_ref());
bytes.extend_from_slice(kp1.private().as_ref());
bytes.push(self.public().flag());
bytes.extend_from_slice(kp.as_bytes());
}
}
Base64::encode(&bytes[..])
}

/// Decode a SuiKeyPair from `flag || privkey` in Base64. The public key is computed directly from the private key bytes.
fn decode_base64(value: &str) -> Result<Self, eyre::Report> {
let bytes = Base64::decode(value).map_err(|e| eyre::eyre!("{}", e.to_string()))?;
match bytes.first() {
Some(x) => {
if x == &Ed25519SuiSignature::SCHEME.flag() {
let priv_key_bytes = bytes
.get(1 + Ed25519PublicKey::LENGTH..)
.ok_or_else(|| eyre::eyre!("Invalid length"))?;
let sk = Ed25519PrivateKey::from_bytes(priv_key_bytes)?;
Ok(SuiKeyPair::Ed25519(<Ed25519KeyPair as From<
Ed25519PrivateKey,
>>::from(sk)))
} else if x == &Secp256k1SuiSignature::SCHEME.flag() {
let sk = Secp256k1PrivateKey::from_bytes(
bytes
.get(1 + Secp256k1PublicKey::LENGTH..)
.ok_or_else(|| eyre::eyre!("Invalid length"))?,
)?;
Ok(SuiKeyPair::Secp256k1(<Secp256k1KeyPair as From<
Secp256k1PrivateKey,
>>::from(sk)))
} else if x == &Secp256r1SuiSignature::SCHEME.flag() {
let sk = Secp256r1PrivateKey::from_bytes(
bytes
.get(1 + Secp256r1PublicKey::LENGTH..)
.ok_or_else(|| eyre::eyre!("Invalid length"))?,
)?;
Ok(SuiKeyPair::Secp256r1(<Secp256r1KeyPair as From<
Secp256r1PrivateKey,
>>::from(sk)))
} else {
Err(eyre::eyre!("Invalid flag byte"))
let bytes = Base64::decode(value).map_err(|e| eyre!("{}", e.to_string()))?;
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"))?,
)?))
}
}
_ => Err(eyre::eyre!("Invalid bytes")),
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")),
}
}
}
Expand Down Expand Up @@ -241,35 +220,29 @@ impl EncodeDecodeBase64 for PublicKey {
}

fn decode_base64(value: &str) -> Result<Self, eyre::Report> {
let bytes = Base64::decode(value).map_err(|e| eyre::eyre!("{}", e.to_string()))?;
let bytes = Base64::decode(value).map_err(|e| eyre!("{}", e.to_string()))?;
match bytes.first() {
Some(x) => {
if x == &<Ed25519PublicKey as SuiPublicKey>::SIGNATURE_SCHEME.flag() {
let pk = Ed25519PublicKey::from_bytes(
bytes
.get(1..)
.ok_or_else(|| eyre::eyre!("Invalid length"))?,
bytes.get(1..).ok_or_else(|| eyre!("Invalid length"))?,
)?;
Ok(PublicKey::Ed25519(pk))
} else if x == &<Secp256k1PublicKey as SuiPublicKey>::SIGNATURE_SCHEME.flag() {
let pk = Secp256k1PublicKey::from_bytes(
bytes
.get(1..)
.ok_or_else(|| eyre::eyre!("Invalid length"))?,
bytes.get(1..).ok_or_else(|| eyre!("Invalid length"))?,
)?;
Ok(PublicKey::Secp256k1(pk))
} else if x == &<Secp256r1PublicKey as SuiPublicKey>::SIGNATURE_SCHEME.flag() {
let pk = Secp256r1PublicKey::from_bytes(
bytes
.get(1..)
.ok_or_else(|| eyre::eyre!("Invalid length"))?,
bytes.get(1..).ok_or_else(|| eyre!("Invalid length"))?,
)?;
Ok(PublicKey::Secp256r1(pk))
} else {
Err(eyre::eyre!("Invalid flag byte"))
Err(eyre!("Invalid flag byte"))
}
}
_ => Err(eyre::eyre!("Invalid bytes")),
_ => Err(eyre!("Invalid bytes")),
}
}
}
Expand Down Expand Up @@ -319,7 +292,7 @@ impl PublicKey {
SignatureScheme::Secp256r1 => Ok(PublicKey::Secp256r1(Secp256r1PublicKey::from_bytes(
key_bytes,
)?)),
_ => Err(eyre::eyre!("Unsupported curve")),
_ => Err(eyre!("Unsupported curve")),
}
}
pub fn scheme(&self) -> SignatureScheme {
Expand Down Expand Up @@ -633,9 +606,6 @@ where
)
.map_err(|_| SuiError::InvalidPrivateKey)?;
let kp: KP = sk.into();
if kp.public().as_ref() != &bytes[priv_length..] {
return Err(SuiError::InvalidAddress);
}
Ok((kp.public().into(), kp))
}

Expand Down Expand Up @@ -1539,6 +1509,10 @@ impl SignatureScheme {
let byte_int = flag
.parse::<u8>()
.map_err(|_| SuiError::KeyConversionError("Invalid key scheme".to_string()))?;
Self::from_flag_byte(&byte_int)
}

pub fn from_flag_byte(byte_int: &u8) -> Result<SignatureScheme, SuiError> {
match byte_int {
0x00 => Ok(SignatureScheme::ED25519),
0x01 => Ok(SignatureScheme::Secp256k1),
Expand Down
Loading

0 comments on commit 28c4823

Please sign in to comment.