snarkvm_console_account/view_key/
mod.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
16mod bytes;
17mod serialize;
18mod string;
19mod to_address;
20mod try_from;
21
22#[cfg(feature = "compute_key")]
23use crate::ComputeKey;
24#[cfg(feature = "private_key")]
25use crate::PrivateKey;
26
27use snarkvm_console_network::prelude::*;
28use snarkvm_console_types::{Address, Scalar};
29
30use zeroize::Zeroize;
31
32/// The account view key used to decrypt records and ciphertext.
33#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Zeroize)]
34pub struct ViewKey<N: Network>(Scalar<N>);
35
36impl<N: Network> ViewKey<N> {
37    /// Initializes the account view key from a scalar.
38    pub const fn from_scalar(view_key: Scalar<N>) -> Self {
39        Self(view_key)
40    }
41}
42
43impl<N: Network> Deref for ViewKey<N> {
44    type Target = Scalar<N>;
45
46    /// Returns the account view key as a scalar.
47    fn deref(&self) -> &Self::Target {
48        &self.0
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55    use snarkvm_console_network::MainnetV0;
56
57    type CurrentNetwork = MainnetV0;
58
59    const ITERATIONS: u64 = 1000;
60
61    #[test]
62    fn test_from_scalar() -> Result<()> {
63        let rng = &mut TestRng::default();
64
65        for _ in 0..ITERATIONS {
66            // Sample a new address.
67            let private_key = PrivateKey::<CurrentNetwork>::new(rng)?;
68            let expected = ViewKey::try_from(private_key)?;
69
70            // Check the scalar representation.
71            let candidate = *expected;
72            assert_eq!(expected, ViewKey::from_scalar(candidate));
73        }
74        Ok(())
75    }
76}