Skip to main content

snarkvm_console_account/graph_key/
try_from.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
18#[cfg(feature = "view_key")]
19impl<N: Network> TryFrom<ViewKey<N>> for GraphKey<N> {
20    type Error = Error;
21
22    /// Derives the account graph key from an account view key.
23    fn try_from(view_key: ViewKey<N>) -> Result<Self, Self::Error> {
24        Self::try_from(&view_key)
25    }
26}
27
28#[cfg(feature = "view_key")]
29impl<N: Network> TryFrom<&ViewKey<N>> for GraphKey<N> {
30    type Error = Error;
31
32    /// Derives the account graph key from an account view key.
33    fn try_from(view_key: &ViewKey<N>) -> Result<Self, Self::Error> {
34        // Compute sk_tag := Hash(view_key || ctr).
35        let sk_tag = N::hash_psd4(&[N::graph_key_domain(), view_key.to_field()?, Field::zero()])?;
36        // Output the graph key.
37        Self::try_from(sk_tag)
38    }
39}
40
41impl<N: Network> TryFrom<Field<N>> for GraphKey<N> {
42    type Error = Error;
43
44    /// Derives the account graph key from `sk_tag`.
45    fn try_from(sk_tag: Field<N>) -> Result<Self> {
46        // Output the graph key.
47        Ok(Self { sk_tag })
48    }
49}
50
51impl<N: Network> TryFrom<&Field<N>> for GraphKey<N> {
52    type Error = Error;
53
54    /// Derives the account graph key from `sk_tag`.
55    fn try_from(sk_tag: &Field<N>) -> Result<Self> {
56        Self::try_from(*sk_tag)
57    }
58}
59
60#[cfg(test)]
61mod tests {
62    use super::*;
63    use crate::PrivateKey;
64    use snarkvm_console_network::MainnetV0;
65
66    type CurrentNetwork = MainnetV0;
67
68    const ITERATIONS: u64 = 1000;
69
70    #[test]
71    fn test_try_from() -> Result<()> {
72        let mut rng = TestRng::default();
73
74        for _ in 0..ITERATIONS {
75            // Sample a new graph key.
76            let private_key = PrivateKey::<CurrentNetwork>::new(&mut rng)?;
77            let view_key = ViewKey::try_from(private_key)?;
78            let candidate = GraphKey::try_from(view_key)?;
79
80            // Check that graph key is derived correctly from `sk_tag`.
81            assert_eq!(candidate, GraphKey::try_from(candidate.sk_tag())?);
82        }
83        Ok(())
84    }
85}