bytes.rs
1 // Copyright (c) 2019-2025 Alpha-Delta Network Inc. 2 // This file is part of the deltavm 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 16 use super::*; 17 18 impl<N: Network> FromBytes for PartialSolution<N> { 19 /// Reads the partial solution from the buffer. 20 fn read_le<R: Read>(mut reader: R) -> IoResult<Self> { 21 let epoch_hash = N::BlockHash::read_le(&mut reader)?; 22 let address = Address::<N>::read_le(&mut reader)?; 23 let counter = u64::read_le(&mut reader)?; 24 25 Self::new(epoch_hash, address, counter).map_err(error) 26 } 27 } 28 29 impl<N: Network> ToBytes for PartialSolution<N> { 30 /// Writes the partial solution to the buffer. 31 fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> { 32 self.epoch_hash.write_le(&mut writer)?; 33 self.address.write_le(&mut writer)?; 34 self.counter.write_le(&mut writer) 35 } 36 } 37 38 #[cfg(test)] 39 mod tests { 40 use super::*; 41 use console::{account::PrivateKey, network::MainnetV0}; 42 43 type CurrentNetwork = MainnetV0; 44 45 #[test] 46 fn test_bytes() -> Result<()> { 47 let mut rng = TestRng::default(); 48 let private_key = PrivateKey::<CurrentNetwork>::new(&mut rng)?; 49 let address = Address::try_from(private_key)?; 50 51 // Sample a new partial solution. 52 let expected = PartialSolution::new(rng.r#gen(), address, u64::rand(&mut rng)).unwrap(); 53 54 // Check the byte representation. 55 let expected_bytes = expected.to_bytes_le()?; 56 assert_eq!(expected, PartialSolution::read_le(&expected_bytes[..])?); 57 assert!(PartialSolution::<CurrentNetwork>::read_le(&expected_bytes[1..]).is_err()); 58 59 Ok(()) 60 } 61 }