1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
use super::{Block0Error, Error};
use crate::certificate;
use crate::transaction::*;
use crate::value::Value;
use chain_addr::Address;
use thiserror::Error;

pub const CHECK_TX_MAXIMUM_INPUTS: u8 = 255;
pub const CHECK_TX_MAXIMUM_OUTPUTS: u8 = 254;
pub const CHECK_POOL_REG_MAXIMUM_OWNERS: usize = 31;
pub const CHECK_POOL_REG_MAXIMUM_OPERATORS: usize = 3;

// if condition, then fail_with
//
// `if_cond_fail_with(a == b, MyError)`
//
// `if a == b { Err(MyError) } else { Ok() }`
macro_rules! if_cond_fail_with(
    ($cond: expr, $err: expr) => {
        if $cond {
            Err($err)
        } else {
            Ok(())
        }
    };
);
#[allow(clippy::large_enum_variant)]
type LedgerCheck = Result<(), Error>;

// Check that a specific block0 transaction has no inputs and no witnesses
pub(super) fn valid_block0_transaction_no_inputs<Extra>(
    tx: &TransactionSlice<Extra>,
) -> LedgerCheck {
    if_cond_fail_with!(
        tx.nb_inputs() != 0,
        Error::Block0(Block0Error::TransactionHasInput)
    )
}

// Check that a specific block0 transaction has no outputs
pub(super) fn valid_block0_cert_transaction<Extra>(tx: &TransactionSlice<Extra>) -> LedgerCheck {
    if_cond_fail_with!(
        tx.nb_inputs() != 0,
        Error::Block0(Block0Error::CertTransactionHasInput)
    )?;
    if_cond_fail_with!(
        tx.nb_outputs() != 0,
        Error::Block0(Block0Error::CertTransactionHasOutput)
    )
}

/// Check that the output value is valid
pub(super) fn valid_output_value(output: &Output<Address>) -> LedgerCheck {
    if_cond_fail_with!(
        output.value == Value::zero(),
        Error::ZeroOutput {
            output: output.clone()
        }
    )
}

/// check that the transaction input/outputs/witnesses is valid for stake_owner_delegation
///
/// * Only 1 input (subsequently 1 witness), no output
pub(super) fn valid_stake_owner_delegation_transaction(
    tx: &TransactionSlice<certificate::OwnerStakeDelegation>,
) -> LedgerCheck {
    if_cond_fail_with!(
        tx.inputs().nb_inputs() != 1
            || tx.witnesses().nb_witnesses() != 1
            || tx.outputs().nb_outputs() != 0,
        Error::OwnerStakeDelegationInvalidTransaction
    )
}

/// check that the transaction input/outputs/witnesses is valid for the ballot
///
/// * Only 1 input (subsequently 1 witness), no output
pub(super) fn valid_vote_cast_tx_slice(
    tx: &TransactionSlice<certificate::VoteCast>,
) -> LedgerCheck {
    if_cond_fail_with!(
        tx.inputs().nb_inputs() != 1
            || tx.witnesses().nb_witnesses() != 1
            || tx.outputs().nb_outputs() != 0,
        Error::VoteCastInvalidTransaction
    )
}

/// check that the pool registration certificate is valid
///
/// * management threshold T is valid: 0 < T <= #owners
/// * there is no more than MAXIMUM_OWNERS
pub(super) fn valid_pool_registration_certificate(
    auth_cert: &certificate::PoolRegistration,
) -> LedgerCheck {
    if_cond_fail_with!(
        auth_cert.management_threshold() == 0,
        Error::PoolRegistrationManagementThresholdZero
    )?;
    if_cond_fail_with!(
        auth_cert.management_threshold() as usize > auth_cert.owners.len(),
        Error::PoolRegistrationManagementThresholdAbove
    )?;
    if_cond_fail_with!(
        auth_cert.owners.is_empty(),
        Error::PoolRegistrationHasNoOwner
    )?;
    if_cond_fail_with!(
        auth_cert.owners.len() > CHECK_POOL_REG_MAXIMUM_OWNERS,
        Error::PoolRegistrationHasTooManyOwners
    )?;
    if_cond_fail_with!(
        auth_cert.operators.len() > CHECK_POOL_REG_MAXIMUM_OPERATORS,
        Error::PoolRegistrationHasTooManyOperators
    )?;
    Ok(())
}

pub(super) fn valid_pool_owner_signature(pos: &certificate::PoolOwnersSigned) -> LedgerCheck {
    if_cond_fail_with!(
        pos.signatures.is_empty(),
        Error::CertificateInvalidSignature
    )?;
    if_cond_fail_with!(
        pos.signatures.len() > CHECK_POOL_REG_MAXIMUM_OWNERS,
        Error::CertificateInvalidSignature
    )?;
    Ok(())
}

pub(super) fn valid_pool_signature(ps: &certificate::PoolSignature) -> LedgerCheck {
    match ps {
        certificate::PoolSignature::Operator(_) => Ok(()),
        certificate::PoolSignature::Owners(pos) => valid_pool_owner_signature(pos),
    }
}

pub(super) fn valid_pool_update_certificate(reg: &certificate::PoolUpdate) -> LedgerCheck {
    valid_pool_registration_certificate(&reg.new_pool_reg)
}

#[derive(Debug, Error, Clone, PartialEq, Eq)]
pub enum TxVerifyError {
    #[error("too many outputs, expected maximum of {expected}, but received {actual}")]
    TooManyOutputs { expected: u8, actual: u8 },
}

// #[derive(Debug, Error, Clone, PartialEq, Eq)]
// pub enum TxValidityError {
//     #[error("Transaction validity expired")]
//     TransactionExpired,
//     #[error("Transaction validity is too far in the future")]
//     TransactionValidForTooLong,
// }

#[allow(clippy::absurd_extreme_comparisons)]
pub(super) fn valid_transaction_ios_number<P>(
    tx: &TransactionSlice<P>,
) -> Result<(), TxVerifyError> {
    // note this is always false at the moment, but just in case we change the maximum inputs.
    if tx.nb_inputs() > CHECK_TX_MAXIMUM_INPUTS {
        return Err(TxVerifyError::TooManyOutputs {
            expected: CHECK_TX_MAXIMUM_INPUTS,
            actual: tx.nb_outputs(),
        });
    }
    if tx.nb_outputs() > CHECK_TX_MAXIMUM_OUTPUTS {
        return Err(TxVerifyError::TooManyOutputs {
            expected: CHECK_TX_MAXIMUM_OUTPUTS,
            actual: tx.nb_outputs(),
        });
    }
    Ok(())
}

#[cfg(test)]
mod tests {

    use super::*;
    use quickcheck::TestResult;
    use quickcheck_macros::quickcheck;

    fn test_valid_block0_transaction_no_inputs_for<P: Payload>(tx: Transaction<P>) -> TestResult {
        let has_valid_inputs = tx.nb_inputs() == 0 && tx.nb_witnesses() == 0;
        let result = valid_block0_transaction_no_inputs(&tx.as_slice());
        to_quickchek_result(result, has_valid_inputs)
    }

    #[quickcheck]
    pub fn test_valid_block0_transaction_no_inputs(
        tx: Transaction<certificate::OwnerStakeDelegation>,
    ) -> TestResult {
        test_valid_block0_transaction_no_inputs_for(tx)
    }

    #[quickcheck]
    pub fn test_valid_block0_transaction_outputs(
        tx: Transaction<certificate::OwnerStakeDelegation>,
    ) -> TestResult {
        let has_valid_ios = tx.nb_inputs() == 0 && tx.nb_outputs() == 0;

        let result = valid_block0_cert_transaction(&tx.as_slice());
        to_quickchek_result(result, has_valid_ios)
    }

    #[quickcheck]
    pub fn test_valid_output_value(output: Output<Address>) -> TestResult {
        let is_valid_output = output.value != Value::zero();
        let result = valid_output_value(&output);
        to_quickchek_result(result, is_valid_output)
    }

    #[quickcheck]
    pub fn test_valid_pool_registration_certificate(
        pool_registration: certificate::PoolRegistration,
    ) -> TestResult {
        let is_valid = pool_registration.management_threshold() > 0
            && (pool_registration.management_threshold() as usize)
                <= pool_registration.owners.len()
            && pool_registration.owners.len() <= CHECK_POOL_REG_MAXIMUM_OWNERS
            && pool_registration.operators.len() <= CHECK_POOL_REG_MAXIMUM_OPERATORS;
        let result = valid_pool_registration_certificate(&pool_registration);
        to_quickchek_result(result, is_valid)
    }

    #[quickcheck]
    pub fn test_valid_stake_owner_delegation_transaction(
        tx: Transaction<certificate::OwnerStakeDelegation>,
    ) -> TestResult {
        let is_valid = tx.nb_witnesses() == 1 && tx.nb_inputs() == 1 && tx.nb_outputs() == 0;
        let result = valid_stake_owner_delegation_transaction(&tx.as_slice());
        to_quickchek_result(result, is_valid)
    }

    /*
    #[quickcheck]
    pub fn test_valid_pool_retirement_certificate(
        cert: certificate::PoolOwnersSigned<T>,
    ) -> TestResult {
        let is_valid = cert.signatures.len() > 0 && cert.signatures.len() < 256;
        let result = valid_pool_retirement_certificate(&cert);
        to_quickchek_result(result, is_valid)
    }
    #[quickcheck]
    pub fn test_valid_pool_update_certificate(
        cert: certificate::PoolOwnersSigned<certificate::PoolUpdate>,
    ) -> TestResult {
        let is_valid = cert.signatures.len() > 0 && cert.signatures.len() < 256;
        let result = valid_pool_update_certificate(&cert);
        to_quickchek_result(result, is_valid)
    }
    */

    fn to_quickchek_result(result: LedgerCheck, should_succeed: bool) -> TestResult {
        match (result, should_succeed) {
            (Ok(_), true) => TestResult::passed(),
            (Ok(_), false) => TestResult::failed(),
            (Err(_), true) => TestResult::failed(),
            (Err(_), false) => TestResult::passed(),
        }
    }
}