Skip to main content

amaru_kernel/cardano/
stake_credential.rs

1// Copyright 2025 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
15pub use pallas_primitives::conway::StakeCredential;
16
17use crate::{
18    Address, HasOwnership, Hash,
19    size::{KEY, SCRIPT},
20};
21
22// This function shouldn't exist and pallas should provide a RewardAccount = (Network,
23// StakeCredential) out of the box instead of row bytes.
24pub fn stake_credential_from_reward_account(bytes: &[u8]) -> Option<StakeCredential> {
25    if let Ok(Address::Stake(address)) = Address::from_bytes(bytes) { Some(address.owner()) } else { None }
26}
27
28#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
29pub enum BorrowedStakeCredential<'a> {
30    KeyHash(&'a Hash<KEY>),
31    ScriptHash(&'a Hash<SCRIPT>),
32}
33
34impl<'a> From<&'a StakeCredential> for BorrowedStakeCredential<'a> {
35    fn from(value: &'a StakeCredential) -> Self {
36        match value {
37            StakeCredential::AddrKeyhash(hash) => Self::KeyHash(hash),
38            StakeCredential::ScriptHash(hash) => Self::ScriptHash(hash),
39        }
40    }
41}
42
43impl From<BorrowedStakeCredential<'_>> for StakeCredential {
44    fn from(value: BorrowedStakeCredential<'_>) -> Self {
45        match value {
46            BorrowedStakeCredential::KeyHash(hash) => Self::AddrKeyhash(*hash),
47            BorrowedStakeCredential::ScriptHash(hash) => Self::ScriptHash(*hash),
48        }
49    }
50}
51
52#[cfg(any(test, feature = "test-utils"))]
53pub use tests::*;
54
55#[cfg(any(test, feature = "test-utils"))]
56mod tests {
57    use proptest::prelude::*;
58
59    use crate::{Hash, StakeCredential};
60
61    pub fn any_stake_credential() -> impl Strategy<Value = StakeCredential> {
62        prop_oneof![
63            any::<[u8; 28]>().prop_map(|hash| StakeCredential::AddrKeyhash(Hash::new(hash))),
64            any::<[u8; 28]>().prop_map(|hash| StakeCredential::ScriptHash(Hash::new(hash))),
65        ]
66    }
67}