Skip to main content

snarkvm_synthesizer_program/logic/command/
get.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 crate::{CallOperator, FinalizeStoreTrait, Opcode, Operand, RegistersTrait, StackTrait};
17use console::{
18    network::prelude::*,
19    program::{Register, Value},
20};
21
22/// A get command, e.g. `get accounts[r0] into r1;`.
23/// Gets the value stored at `operand` in `mapping` and stores the result in `destination`.
24#[derive(Clone, PartialEq, Eq, Hash)]
25pub struct Get<N: Network> {
26    /// The mapping.
27    mapping: CallOperator<N>,
28    /// The operands.
29    operands: [Operand<N>; 1],
30    /// The destination register.
31    destination: Register<N>,
32}
33
34impl<N: Network> Get<N> {
35    /// Returns the opcode.
36    #[inline]
37    pub const fn opcode() -> Opcode {
38        Opcode::Command("get")
39    }
40
41    /// Returns the operands in the operation.
42    #[inline]
43    pub fn operands(&self) -> &[Operand<N>] {
44        &self.operands
45    }
46
47    /// Returns the mapping.
48    #[inline]
49    pub const fn mapping(&self) -> &CallOperator<N> {
50        &self.mapping
51    }
52
53    /// Returns the operand containing the key.
54    #[inline]
55    pub const fn key(&self) -> &Operand<N> {
56        &self.operands[0]
57    }
58
59    /// Returns the destination register.
60    #[inline]
61    pub const fn destination(&self) -> &Register<N> {
62        &self.destination
63    }
64
65    /// Returns whether this command refers to an external struct.
66    #[inline]
67    pub fn contains_external_struct(&self) -> bool {
68        false
69    }
70}
71
72impl<N: Network> Get<N> {
73    /// Finalizes the command.
74    #[inline]
75    pub fn finalize(
76        &self,
77        stack: &impl StackTrait<N>,
78        store: &impl FinalizeStoreTrait<N>,
79        registers: &mut impl RegistersTrait<N>,
80    ) -> Result<()> {
81        // Determine the program ID and mapping name.
82        let (program_id, mapping_name) = match self.mapping {
83            CallOperator::Locator(locator) => (*locator.program_id(), *locator.resource()),
84            CallOperator::Resource(mapping_name) => (*stack.program_id(), mapping_name),
85        };
86
87        // Ensure the mapping exists.
88        if !store.contains_mapping_speculative(&program_id, &mapping_name)? {
89            bail!("Mapping '{program_id}/{mapping_name}' does not exist");
90        }
91
92        // Load the operand as a plaintext.
93        let key = registers.load_plaintext(stack, self.key())?;
94
95        // Retrieve the value from storage as a literal.
96        let value = match store.get_value_speculative(program_id, mapping_name, &key)? {
97            Some(Value::Plaintext(plaintext)) => Value::Plaintext(plaintext),
98            Some(Value::Record(..)) => bail!("Cannot 'get' a 'record'"),
99            Some(Value::Future(..)) => bail!("Cannot 'get' a 'future'",),
100            // If a key does not exist, then bail.
101            None => bail!("Key '{key}' does not exist in mapping '{program_id}/{mapping_name}'"),
102        };
103
104        // Assign the value to the destination register.
105        registers.store(stack, &self.destination, value)?;
106
107        Ok(())
108    }
109}
110
111impl<N: Network> Parser for Get<N> {
112    /// Parses a string into an operation.
113    #[inline]
114    fn parse(string: &str) -> ParserResult<Self> {
115        // Parse the whitespace and comments from the string.
116        let (string, _) = Sanitizer::parse(string)?;
117        // Parse the opcode from the string.
118        let (string, _) = tag(*Self::opcode())(string)?;
119        // Parse the whitespace from the string.
120        let (string, _) = Sanitizer::parse_whitespaces(string)?;
121
122        // Parse the mapping name from the string.
123        let (string, mapping) = CallOperator::parse(string)?;
124        // Parse the "[" from the string.
125        let (string, _) = tag("[")(string)?;
126        // Parse the whitespace from the string.
127        let (string, _) = Sanitizer::parse_whitespaces(string)?;
128        // Parse the key operand from the string.
129        let (string, key) = Operand::parse(string)?;
130        // Parse the whitespace from the string.
131        let (string, _) = Sanitizer::parse_whitespaces(string)?;
132        // Parse the "]" from the string.
133        let (string, _) = tag("]")(string)?;
134
135        // Parse the whitespace from the string.
136        let (string, _) = Sanitizer::parse_whitespaces(string)?;
137        // Parse the "into" keyword from the string.
138        let (string, _) = tag("into")(string)?;
139        // Parse the whitespace from the string.
140        let (string, _) = Sanitizer::parse_whitespaces(string)?;
141        // Parse the destination register from the string.
142        let (string, destination) = Register::parse(string)?;
143
144        // Parse the whitespace from the string.
145        let (string, _) = Sanitizer::parse_whitespaces(string)?;
146        // Parse the ";" from the string.
147        let (string, _) = tag(";")(string)?;
148
149        Ok((string, Self { mapping, operands: [key], destination }))
150    }
151}
152
153impl<N: Network> FromStr for Get<N> {
154    type Err = Error;
155
156    /// Parses a string into the command.
157    #[inline]
158    fn from_str(string: &str) -> Result<Self> {
159        match Self::parse(string) {
160            Ok((remainder, object)) => {
161                // Ensure the remainder is empty.
162                ensure!(remainder.is_empty(), "Failed to parse string. Found invalid character in: \"{remainder}\"");
163                // Return the object.
164                Ok(object)
165            }
166            Err(error) => bail!("Failed to parse string. {error}"),
167        }
168    }
169}
170
171impl<N: Network> Debug for Get<N> {
172    /// Prints the command as a string.
173    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
174        Display::fmt(self, f)
175    }
176}
177
178impl<N: Network> Display for Get<N> {
179    /// Prints the command to a string.
180    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
181        // Print the command.
182        write!(f, "{} ", Self::opcode())?;
183        // Print the mapping and key operand.
184        write!(f, "{}[{}] into ", self.mapping, self.key())?;
185        // Print the destination register.
186        write!(f, "{};", self.destination)
187    }
188}
189
190impl<N: Network> FromBytes for Get<N> {
191    /// Reads the command from a buffer.
192    fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
193        // Read the mapping name.
194        let mapping = CallOperator::read_le(&mut reader)?;
195        // Read the key operand.
196        let key = Operand::read_le(&mut reader)?;
197        // Read the destination register.
198        let destination = Register::read_le(&mut reader)?;
199        // Return the command.
200        Ok(Self { mapping, operands: [key], destination })
201    }
202}
203
204impl<N: Network> ToBytes for Get<N> {
205    /// Writes the command to a buffer.
206    fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
207        // Write the mapping name.
208        self.mapping.write_le(&mut writer)?;
209        // Write the key operand.
210        self.key().write_le(&mut writer)?;
211        // Write the destination register.
212        self.destination.write_le(&mut writer)
213    }
214}
215
216#[cfg(test)]
217mod tests {
218    use super::*;
219    use console::{network::MainnetV0, program::Register};
220
221    type CurrentNetwork = MainnetV0;
222
223    #[test]
224    fn test_parse() {
225        let (string, get) = Get::<CurrentNetwork>::parse("get account[r0] into r1;").unwrap();
226        assert!(string.is_empty(), "Parser did not consume all of the string: '{string}'");
227        assert_eq!(get.mapping, CallOperator::from_str("account").unwrap());
228        assert_eq!(get.operands().len(), 1, "The number of operands is incorrect");
229        assert_eq!(get.key(), &Operand::Register(Register::Locator(0)), "The first operand is incorrect");
230        assert_eq!(get.destination, Register::Locator(1), "The second operand is incorrect");
231
232        let (string, get) = Get::<CurrentNetwork>::parse("get token.aleo/balances[r0] into r1;").unwrap();
233        assert!(string.is_empty(), "Parser did not consume all of the string: '{string}'");
234        assert_eq!(get.mapping, CallOperator::from_str("token.aleo/balances").unwrap());
235        assert_eq!(get.operands().len(), 1, "The number of operands is incorrect");
236        assert_eq!(get.key(), &Operand::Register(Register::Locator(0)), "The first operand is incorrect");
237        assert_eq!(get.destination, Register::Locator(1), "The second operand is incorrect");
238    }
239
240    #[test]
241    fn test_from_bytes() {
242        let (string, get) = Get::<CurrentNetwork>::parse("get account[r0] into r1;").unwrap();
243        assert!(string.is_empty());
244        let bytes_le = get.to_bytes_le().unwrap();
245        let result = Get::<CurrentNetwork>::from_bytes_le(&bytes_le[..]);
246        assert!(result.is_ok())
247    }
248}