snarkvm_console_account/private_key/
serialize.rs

1// Copyright (c) 2019-2025 Provable Inc.
2// This file is part of the snarkVM library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use super::*;
17
18impl<N: Network> Serialize for PrivateKey<N> {
19    /// Serializes an account private key into string or bytes.
20    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
21        match serializer.is_human_readable() {
22            true => serializer.collect_str(self),
23            false => ToBytesSerializer::serialize(self, serializer),
24        }
25    }
26}
27
28impl<'de, N: Network> Deserialize<'de> for PrivateKey<N> {
29    /// Deserializes an account private key from a string or bytes.
30    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
31        match deserializer.is_human_readable() {
32            true => FromStr::from_str(&String::deserialize(deserializer)?).map_err(de::Error::custom),
33            false => FromBytesDeserializer::<Self>::deserialize(
34                deserializer,
35                "private key",
36                N::Scalar::size_in_bits().div_ceil(8),
37            ),
38        }
39    }
40}
41
42#[cfg(test)]
43mod tests {
44    use super::*;
45    use snarkvm_console_network::MainnetV0;
46
47    type CurrentNetwork = MainnetV0;
48
49    const ITERATIONS: u64 = 1000;
50
51    #[test]
52    fn test_serde_json() -> Result<()> {
53        let mut rng = TestRng::default();
54
55        for _ in 0..ITERATIONS {
56            // Sample a new private key.
57            let expected = PrivateKey::<CurrentNetwork>::new(&mut rng)?;
58
59            // Serialize
60            let expected_string = &expected.to_string();
61            let candidate_string = serde_json::to_string(&expected)?;
62            assert_eq!(expected_string, serde_json::Value::from_str(&candidate_string)?.as_str().unwrap());
63
64            // Deserialize
65            assert_eq!(expected, PrivateKey::from_str(expected_string)?);
66            assert_eq!(expected, serde_json::from_str(&candidate_string)?);
67        }
68        Ok(())
69    }
70
71    #[test]
72    fn test_bincode() -> Result<()> {
73        let mut rng = TestRng::default();
74
75        for _ in 0..ITERATIONS {
76            // Sample a new private key.
77            let expected = PrivateKey::<CurrentNetwork>::new(&mut rng)?;
78
79            // Serialize
80            let expected_bytes = expected.to_bytes_le()?;
81            assert_eq!(&expected_bytes[..], &bincode::serialize(&expected)?[..]);
82
83            // Deserialize
84            assert_eq!(expected, PrivateKey::read_le(&expected_bytes[..])?);
85            assert_eq!(expected, bincode::deserialize(&expected_bytes[..])?);
86        }
87        Ok(())
88    }
89}