Skip to main content

amaru_kernel/cardano/
nonce.rs

1// Copyright 2026 PRAGMA
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::{Hash, size::NONCE};
16
17pub type Nonce = Hash<NONCE>;
18
19/// Utility function to parse a nonce (i.e. a blake2b-256 hash digest) from an hex-encoded string.
20pub fn parse_nonce(hex_str: &str) -> Result<Nonce, String> {
21    hex::decode(hex_str)
22        .map_err(|e| format!("invalid hex encoding: {e}"))
23        .and_then(|bytes| <[u8; 32]>::try_from(bytes).map_err(|_| "expected 32-byte nonce".to_string()))
24        .map(Nonce::from)
25}
26
27#[cfg(test)]
28mod tests {
29    use super::*;
30
31    #[test]
32    fn test_parse_nonce() {
33        assert!(matches!(parse_nonce("d6fe6439aed8bddc10eec22c1575bf0648e4a76125387d9e985e9a3f8342870d"), Ok(..)));
34    }
35
36    #[test]
37    fn test_parse_nonce_not_hex() {
38        assert!(matches!(parse_nonce("patate"), Err(..)));
39    }
40
41    #[test]
42    fn test_parse_nonce_too_long() {
43        assert!(matches!(parse_nonce("d6fe6439aed8bddc10eec22c1575bf0648e4a76125387d9e985e9a3f8342870d1234"), Err(..)));
44    }
45
46    #[test]
47    fn test_parse_nonce_too_short() {
48        assert!(matches!(parse_nonce("d6fe6439aed8bddc10eec22c1575bf0648e4a76125387d9e985e9a"), Err(..)));
49    }
50}