snarkvm_synthesizer_process/stack/helpers/
sample.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> Stack<N> {
19    /// Samples a plaintext value according to the given plaintext type.
20    pub fn sample_plaintext<R: Rng + CryptoRng>(
21        &self,
22        plaintext_type: &PlaintextType<N>,
23        rng: &mut R,
24    ) -> Result<Plaintext<N>> {
25        // Sample a plaintext value.
26        let plaintext = self.sample_plaintext_internal(plaintext_type, 0, rng)?;
27        // Ensure the plaintext value matches the plaintext type.
28        self.matches_plaintext(&plaintext, plaintext_type)?;
29        // Return the plaintext value.
30        Ok(plaintext)
31    }
32
33    /// Samples a future value according to the given future type.
34    pub fn sample_future<R: Rng + CryptoRng>(&self, locator: &Locator<N>, rng: &mut R) -> Result<Future<N>> {
35        // Sample a future value.
36        let future = self.sample_future_internal(locator, 0, rng)?;
37        // Ensure the future value matches the future type.
38        self.matches_future(&future, locator)?;
39        // Return the future value.
40        Ok(future)
41    }
42
43    /// Returns a record for the given record name.
44    pub(crate) fn sample_record_internal<R: Rng + CryptoRng>(
45        &self,
46        burner_address: &Address<N>,
47        record_name: &Identifier<N>,
48        nonce: Group<N>,
49        depth: usize,
50        rng: &mut R,
51    ) -> Result<Record<N, Plaintext<N>>> {
52        // If the depth exceeds the maximum depth, then the plaintext type is invalid.
53        ensure!(depth <= N::MAX_DATA_DEPTH, "Plaintext exceeded maximum depth of {}", N::MAX_DATA_DEPTH);
54
55        // Retrieve the record type from the program.
56        let record_type = self.program.get_record(record_name)?;
57
58        // Initialize the owner based on the visibility.
59        let owner = match record_type.owner().is_public() {
60            true => RecordOwner::Public(*burner_address),
61            false => RecordOwner::Private(Plaintext::Literal(Literal::Address(*burner_address), Default::default())),
62        };
63
64        // Initialize the record data according to the defined type.
65        let data = record_type
66            .entries()
67            .iter()
68            .map(|(entry_name, entry_type)| {
69                // Sample the entry value.
70                let entry = self.sample_entry_internal(entry_type, depth + 1, rng)?;
71                // Return the entry.
72                Ok((*entry_name, entry))
73            })
74            .collect::<Result<IndexMap<_, _>>>()?;
75
76        // Return the record.
77        Record::<N, Plaintext<N>>::from_plaintext(owner, data, nonce)
78    }
79
80    /// Samples an entry according to the given entry type.
81    fn sample_entry_internal<R: Rng + CryptoRng>(
82        &self,
83        entry_type: &EntryType<N>,
84        depth: usize,
85        rng: &mut R,
86    ) -> Result<Entry<N, Plaintext<N>>> {
87        // If the depth exceeds the maximum depth, then the entry type is invalid.
88        ensure!(depth <= N::MAX_DATA_DEPTH, "Entry exceeded maximum depth of {}", N::MAX_DATA_DEPTH);
89
90        match entry_type {
91            EntryType::Constant(plaintext_type)
92            | EntryType::Public(plaintext_type)
93            | EntryType::Private(plaintext_type) => {
94                // Sample the plaintext value.
95                let plaintext = self.sample_plaintext_internal(plaintext_type, depth, rng)?;
96                // Return the entry.
97                match entry_type {
98                    EntryType::Constant(..) => Ok(Entry::Constant(plaintext)),
99                    EntryType::Public(..) => Ok(Entry::Public(plaintext)),
100                    EntryType::Private(..) => Ok(Entry::Private(plaintext)),
101                }
102            }
103        }
104    }
105
106    /// Samples a plaintext value according to the given plaintext type.
107    fn sample_plaintext_internal<R: Rng + CryptoRng>(
108        &self,
109        plaintext_type: &PlaintextType<N>,
110        depth: usize,
111        rng: &mut R,
112    ) -> Result<Plaintext<N>> {
113        // If the depth exceeds the maximum depth, then the plaintext type is invalid.
114        ensure!(depth <= N::MAX_DATA_DEPTH, "Plaintext exceeded maximum depth of {}", N::MAX_DATA_DEPTH);
115
116        // Sample the plaintext value.
117        let plaintext = match plaintext_type {
118            // Sample a literal.
119            PlaintextType::Literal(literal_type) => {
120                Plaintext::Literal(Literal::sample(*literal_type, rng), Default::default())
121            }
122            // Sample a struct.
123            PlaintextType::Struct(struct_name) => {
124                // Retrieve the struct.
125                let struct_ = self.program.get_struct(struct_name)?;
126                // Sample each member of the struct.
127                let members = struct_
128                    .members()
129                    .iter()
130                    .map(|(member_name, member_type)| {
131                        // Sample the member value.
132                        let member = self.sample_plaintext_internal(member_type, depth + 1, rng)?;
133                        // Return the member.
134                        Ok((*member_name, member))
135                    })
136                    .collect::<Result<IndexMap<_, _>>>()?;
137
138                Plaintext::Struct(members, Default::default())
139            }
140            // Sample an array.
141            PlaintextType::Array(array_type) => {
142                // Sample each element of the array.
143                let elements = (0..**array_type.length())
144                    .map(|_| {
145                        // Sample the element value.
146                        self.sample_plaintext_internal(array_type.next_element_type(), depth + 1, rng)
147                    })
148                    .collect::<Result<Vec<_>>>()?;
149
150                Plaintext::Array(elements, Default::default())
151            }
152        };
153        // Return the plaintext.
154        Ok(plaintext)
155    }
156
157    /// Samples a future value according to the given locator.
158    fn sample_future_internal<R: Rng + CryptoRng>(
159        &self,
160        locator: &Locator<N>,
161        depth: usize,
162        rng: &mut R,
163    ) -> Result<Future<N>> {
164        // Retrieve the external stack, if needed.
165        let external_stack = match locator.program_id() == self.program_id() {
166            true => None,
167            // Attention - This method must fail here and early return if the external program is missing.
168            // Otherwise, this method will proceed to look for the requested function in its own program.
169            false => Some(self.get_external_stack(locator.program_id())?),
170        };
171        // Retrieve the associated function.
172        let function = match &external_stack {
173            Some(external_stack) => external_stack.get_function_ref(locator.resource())?,
174            None => self.get_function_ref(locator.resource())?,
175        };
176
177        // Retrieve the finalize inputs.
178        let inputs = match function.finalize_logic() {
179            Some(finalize_logic) => finalize_logic.inputs(),
180            None => bail!("Function '{locator}' does not have a finalize block"),
181        };
182
183        let arguments = inputs
184            .into_iter()
185            .map(|input| {
186                match input.finalize_type() {
187                    FinalizeType::Plaintext(plaintext_type) => {
188                        // Sample the plaintext value.
189                        let plaintext = self.sample_plaintext_internal(plaintext_type, depth + 1, rng)?;
190                        // Return the argument.
191                        Ok(Argument::Plaintext(plaintext))
192                    }
193                    FinalizeType::Future(locator) => {
194                        // Sample the future value.
195                        let future = self.sample_future_internal(locator, depth + 1, rng)?;
196                        // Return the argument.
197                        Ok(Argument::Future(future))
198                    }
199                }
200            })
201            .collect::<Result<Vec<_>>>()?;
202
203        Ok(Future::new(*locator.program_id(), *locator.resource(), arguments))
204    }
205}