net_name.rs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{io, str::FromStr};
  19. use darkfi_serial::{Decodable, Encodable};
  20. use serde::{Deserialize, Serialize};
  21. #[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
  22. pub enum NetworkName {
  23. DarkFi,
  24. Solana,
  25. Bitcoin,
  26. Ethereum,
  27. }
  28. impl core::fmt::Display for NetworkName {
  29. fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
  30. match self {
  31. Self::DarkFi => {
  32. write!(f, "DarkFi")
  33. }
  34. Self::Solana => {
  35. write!(f, "Solana")
  36. }
  37. Self::Bitcoin => {
  38. write!(f, "Bitcoin")
  39. }
  40. Self::Ethereum => {
  41. write!(f, "Ethereum")
  42. }
  43. }
  44. }
  45. }
  46. impl FromStr for NetworkName {
  47. type Err = crate::Error;
  48. fn from_str(s: &str) -> core::result::Result<Self, Self::Err> {
  49. match s.to_lowercase().as_str() {
  50. "drk" | "darkfi" => Ok(NetworkName::DarkFi),
  51. "sol" | "solana" => Ok(NetworkName::Solana),
  52. "btc" | "bitcoin" => Ok(NetworkName::Bitcoin),
  53. "eth" | "ethereum" => Ok(NetworkName::Ethereum),
  54. _ => Err(crate::Error::UnsupportedCoinNetwork),
  55. }
  56. }
  57. }
  58. impl Encodable for NetworkName {
  59. fn encode<S: io::Write>(&self, s: S) -> core::result::Result<usize, io::Error> {
  60. let name = self.to_string();
  61. let len = name.encode(s)?;
  62. Ok(len)
  63. }
  64. }
  65. impl Decodable for NetworkName {
  66. fn decode<D: io::Read>(mut d: D) -> core::result::Result<Self, io::Error> {
  67. let name: String = Decodable::decode(&mut d)?;
  68. match NetworkName::from_str(&name) {
  69. Ok(v) => Ok(v),
  70. Err(e) => Err(io::Error::new(io::ErrorKind::Other, e)),
  71. }
  72. }
  73. }