diem_types/
mempool_status.rs

1// Copyright (c) The Diem Core Contributors
2// SPDX-License-Identifier: Apache-2.0
3
4// Copyright 2021 Conflux Foundation. All rights reserved.
5// Conflux is free software and distributed under GNU General Public License.
6// See http://www.gnu.org/licenses/
7
8#![allow(clippy::unit_arg)]
9
10use anyhow::Result;
11#[cfg(any(test, feature = "fuzzing"))]
12use proptest::prelude::*;
13#[cfg(any(test, feature = "fuzzing"))]
14use proptest_derive::Arbitrary;
15use std::{convert::TryFrom, fmt};
16
17/// A `MempoolStatus` is represented as a required status code that is semantic
18/// coupled with an optional sub status and message.
19#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
20#[cfg_attr(any(test, feature = "fuzzing"), derive(Arbitrary))]
21#[cfg_attr(any(test, feature = "fuzzing"), proptest(no_params))]
22pub struct MempoolStatus {
23    /// insertion status code
24    pub code: MempoolStatusCode,
25    /// optional message
26    pub message: String,
27}
28
29impl MempoolStatus {
30    pub fn new(code: MempoolStatusCode) -> Self {
31        Self {
32            code,
33            message: "".to_string(),
34        }
35    }
36
37    /// Adds a message to the Mempool status.
38    pub fn with_message(mut self, message: String) -> Self {
39        self.message = message;
40        self
41    }
42}
43
44#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
45#[cfg_attr(any(test, feature = "fuzzing"), derive(Arbitrary))]
46#[repr(u64)]
47pub enum MempoolStatusCode {
48    // Transaction was accepted by Mempool
49    Accepted = 0,
50    // Sequence number is old, etc.
51    InvalidSeqNumber = 1,
52    // Mempool is full (reached max global capacity)
53    MempoolIsFull = 2,
54    // Account reached max capacity per account
55    TooManyTransactions = 3,
56    // Invalid update. Only gas price increase is allowed
57    InvalidUpdate = 4,
58    // transaction didn't pass vm_validation
59    VmError = 5,
60    UnknownStatus = 6,
61}
62
63impl TryFrom<u64> for MempoolStatusCode {
64    type Error = &'static str;
65
66    fn try_from(value: u64) -> Result<Self, Self::Error> {
67        match value {
68            0 => Ok(MempoolStatusCode::Accepted),
69            1 => Ok(MempoolStatusCode::InvalidSeqNumber),
70            2 => Ok(MempoolStatusCode::MempoolIsFull),
71            3 => Ok(MempoolStatusCode::TooManyTransactions),
72            4 => Ok(MempoolStatusCode::InvalidUpdate),
73            5 => Ok(MempoolStatusCode::VmError),
74            6 => Ok(MempoolStatusCode::UnknownStatus),
75            _ => Err("invalid StatusCode"),
76        }
77    }
78}
79
80impl From<MempoolStatusCode> for u64 {
81    fn from(status: MempoolStatusCode) -> u64 { status as u64 }
82}
83
84impl fmt::Display for MempoolStatusCode {
85    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86        write!(f, "{:?}", self)
87    }
88}