error.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  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. // Hello developer. Please add your error to the according subsection
  19. // that is commented, or make a new subsection. Keep it clean.
  20. /// Main result type used throughout the codebase.
  21. pub type Result<T> = std::result::Result<T, Error>;
  22. /// Result type used in the Client module
  23. pub type ClientResult<T> = std::result::Result<T, ClientFailed>;
  24. /// General library errors used throughout the codebase.
  25. #[derive(Debug, Clone, thiserror::Error)]
  26. pub enum Error {
  27. // ==============
  28. // Parsing errors
  29. // ==============
  30. #[error("Parse failed: {0}")]
  31. ParseFailed(&'static str),
  32. #[error(transparent)]
  33. ParseIntError(#[from] std::num::ParseIntError),
  34. #[error(transparent)]
  35. ParseFloatError(#[from] std::num::ParseFloatError),
  36. #[cfg(feature = "url")]
  37. #[error(transparent)]
  38. UrlParseError(#[from] url::ParseError),
  39. #[error("URL parse error: {0}")]
  40. UrlParse(String),
  41. #[error(transparent)]
  42. AddrParseError(#[from] std::net::AddrParseError),
  43. #[error("Could not parse token parameter")]
  44. TokenParseError,
  45. #[error(transparent)]
  46. TryFromSliceError(#[from] std::array::TryFromSliceError),
  47. #[cfg(feature = "dashu")]
  48. #[error(transparent)]
  49. DashuParseError(#[from] dashu::base::error::ParseError),
  50. // ===============
  51. // Encoding errors
  52. // ===============
  53. #[error("decode failed: {0}")]
  54. DecodeError(&'static str),
  55. #[error("encode failed: {0}")]
  56. EncodeError(&'static str),
  57. #[error("VarInt was encoded in a non-minimal way")]
  58. NonMinimalVarInt,
  59. #[error(transparent)]
  60. Utf8Error(#[from] std::string::FromUtf8Error),
  61. #[error(transparent)]
  62. StrUtf8Error(#[from] std::str::Utf8Error),
  63. #[cfg(feature = "serde_json")]
  64. #[error("serde_json error: {0}")]
  65. SerdeJsonError(String),
  66. #[cfg(feature = "toml")]
  67. #[error(transparent)]
  68. TomlDeserializeError(#[from] toml::de::Error),
  69. #[cfg(feature = "bs58")]
  70. #[error(transparent)]
  71. Bs58DecodeError(#[from] bs58::decode::Error),
  72. #[cfg(feature = "hex")]
  73. #[error(transparent)]
  74. HexDecodeError(#[from] hex::FromHexError),
  75. #[error("Bad operation type byte")]
  76. BadOperationType,
  77. // ======================
  78. // Network-related errors
  79. // ======================
  80. #[error("Unsupported network transport: {0}")]
  81. UnsupportedTransport(String),
  82. #[error("Unsupported network transport upgrade: {0}")]
  83. UnsupportedTransportUpgrade(String),
  84. #[error("Connection failed")]
  85. ConnectFailed,
  86. #[error("Timeout Error")]
  87. TimeoutError,
  88. #[error("Connection timed out")]
  89. ConnectTimeout,
  90. #[error("Channel stopped")]
  91. ChannelStopped,
  92. #[error("Channel timed out")]
  93. ChannelTimeout,
  94. #[error("Network service stopped")]
  95. NetworkServiceStopped,
  96. #[error("Create listener bound to {0} failed")]
  97. BindFailed(String),
  98. #[error("Accept a new incoming connection from the listener {0} failed")]
  99. AcceptConnectionFailed(String),
  100. #[error("Accept a new tls connection from the listener {0} failed")]
  101. AcceptTlsConnectionFailed(String),
  102. #[error("Network operation failed")]
  103. NetworkOperationFailed,
  104. #[error("Malformed packet")]
  105. MalformedPacket,
  106. #[error("Socks proxy error: {0}")]
  107. SocksError(String),
  108. #[error("No Socks5 URL found")]
  109. NoSocks5UrlFound,
  110. #[error("No URL found")]
  111. NoUrlFound,
  112. #[cfg(feature = "async-tungstenite")]
  113. #[error("tungstenite error: {0}")]
  114. TungsteniteError(String),
  115. #[error("Tor error: {0}")]
  116. TorError(String),
  117. #[error("Node is not connected to other nodes.")]
  118. NetworkNotConnected,
  119. // =============
  120. // Crypto errors
  121. // =============
  122. #[cfg(feature = "halo2_proofs")]
  123. #[error("halo2 plonk error: {0}")]
  124. PlonkError(String),
  125. #[error("Unable to decrypt mint note: {0}")]
  126. NoteDecryptionFailed(String),
  127. #[error("No keypair file detected")]
  128. KeypairPathNotFound,
  129. #[error("Failed converting bytes to PublicKey")]
  130. PublicKeyFromBytes,
  131. #[error("Failed converting bytes to Coin")]
  132. CoinFromBytes,
  133. #[error("Failed converting bytes to SecretKey")]
  134. SecretKeyFromBytes,
  135. #[error("Failed converting b58 string to PublicKey")]
  136. PublicKeyFromStr,
  137. #[error("Failed converting bs58 string to SecretKey")]
  138. SecretKeyFromStr,
  139. #[error("Invalid DarkFi address")]
  140. InvalidAddress,
  141. #[cfg(feature = "futures-rustls")]
  142. #[error(transparent)]
  143. RustlsError(#[from] futures_rustls::rustls::Error),
  144. #[cfg(feature = "futures-rustls")]
  145. #[error("Invalid DNS Name {0}")]
  146. RustlsInvalidDns(String),
  147. #[error("unable to decrypt rcpt")]
  148. TxRcptDecryptionError,
  149. #[cfg(feature = "blake3")]
  150. #[error(transparent)]
  151. Blake3FromHexError(#[from] blake3::HexError),
  152. // =======================
  153. // Protocol-related errors
  154. // =======================
  155. #[error("Unsupported chain")]
  156. UnsupportedChain,
  157. #[error("Unsupported token")]
  158. UnsupportedToken,
  159. #[error("Unsupported coin network")]
  160. UnsupportedCoinNetwork,
  161. #[error("Raft error: {0}")]
  162. RaftError(String),
  163. #[error("JSON-RPC error: {0}")]
  164. JsonRpcError(String),
  165. #[error("Unexpected JSON-RPC data received: {0}")]
  166. UnexpectedJsonRpc(String),
  167. #[error("Received proposal from unknown node")]
  168. UnknownNodeError,
  169. #[error("Public inputs are invalid")]
  170. InvalidPublicInputsError,
  171. #[error("Error during leader proof verification")]
  172. LeaderProofVerification,
  173. #[error("Signature could not be verified")]
  174. InvalidSignature,
  175. #[error("State transition failed")]
  176. StateTransitionError,
  177. #[error("Check if proposal extends any existing fork chains failed")]
  178. ExtendedChainIndexNotFound,
  179. #[error("Proposal received after finalization sync period")]
  180. ProposalAfterFinalizationError,
  181. #[error("Proposal received not for current slot")]
  182. ProposalNotForCurrentSlotError,
  183. #[error("Proposal contains missmatched hashes")]
  184. ProposalHashesMissmatchError,
  185. #[error("Proposal contains missmatched headers")]
  186. ProposalHeadersMissmatchError,
  187. #[error("Proposal contains different coin creation eta")]
  188. ProposalDifferentCoinEtaError,
  189. #[error("Proposal contains spent coin")]
  190. ProposalIsSpent,
  191. #[error("Proposal contains more transactions than configured cap")]
  192. ProposalTxsExceedCapError,
  193. #[error("Unable to verify transfer transaction")]
  194. TransferTxVerification,
  195. #[error("Unable to verify proposed mu values")]
  196. ProposalPublicValuesMismatched,
  197. #[error("Proposer is not eligible to produce proposals")]
  198. ProposalProposerNotEligible,
  199. #[error("Erroneous transactions detected")]
  200. ErroneousTxsDetected,
  201. // ===============
  202. // Database errors
  203. // ===============
  204. #[cfg(feature = "sqlx")]
  205. #[error("Sqlx error: {0}")]
  206. SqlxError(String),
  207. #[cfg(feature = "sled")]
  208. #[error(transparent)]
  209. SledError(#[from] sled::Error),
  210. #[cfg(feature = "sled")]
  211. #[error(transparent)]
  212. SledTransactionError(#[from] sled::transaction::TransactionError),
  213. #[error("Transaction {0} not found in database")]
  214. TransactionNotFound(String),
  215. #[error("Transaction already seen")]
  216. TransactionAlreadySeen,
  217. #[error("Input vectors have different length")]
  218. InvalidInputLengths,
  219. #[error("Header {0} not found in database")]
  220. HeaderNotFound(String),
  221. #[error("Block {0} is invalid")]
  222. BlockIsInvalid(String),
  223. #[error("Block {0} already in database")]
  224. BlockAlreadyExists(String),
  225. #[error("Block {0} not found in database")]
  226. BlockNotFound(String),
  227. #[error("Block in slot {0} not found in database")]
  228. BlockSlotNotFound(u64),
  229. #[error("Slot {0} not found in database")]
  230. SlotNotFound(u64),
  231. #[error("Future slot {0} was received")]
  232. FutureSlotReceived(u64),
  233. #[error("Contract {0} not found in database")]
  234. ContractNotFound(String),
  235. #[error("Contract state tree not found")]
  236. ContractStateNotFound,
  237. #[error("Contract already initialized")]
  238. ContractAlreadyInitialized,
  239. #[error("zkas bincode not found in sled database")]
  240. ZkasBincodeNotFound,
  241. // =============
  242. // Wallet errors
  243. // =============
  244. #[error("Wallet password is empty")]
  245. WalletEmptyPassword,
  246. #[error("Merkle tree already exists in wallet")]
  247. WalletTreeExists,
  248. #[error("Wallet insufficient balance")]
  249. WalletInsufficientBalance,
  250. // ===================
  251. // wasm runtime errors
  252. // ===================
  253. #[cfg(feature = "wasm-runtime")]
  254. #[error("Wasmer compile error: {0}")]
  255. WasmerCompileError(String),
  256. #[cfg(feature = "wasm-runtime")]
  257. #[error("Wasmer export error: {0}")]
  258. WasmerExportError(String),
  259. #[cfg(feature = "wasm-runtime")]
  260. #[error("Wasmer runtime error: {0}")]
  261. WasmerRuntimeError(String),
  262. #[cfg(feature = "wasm-runtime")]
  263. #[error("Wasmer instantiation error: {0}")]
  264. WasmerInstantiationError(String),
  265. #[cfg(feature = "wasm-runtime")]
  266. #[error("wasm memory error")]
  267. WasmerMemoryError(String),
  268. #[cfg(feature = "wasm-runtime")]
  269. #[error("wasm runtime out of memory")]
  270. WasmerOomError(String),
  271. #[cfg(feature = "darkfi-sdk")]
  272. #[error("Contract execution failed")]
  273. ContractError(darkfi_sdk::error::ContractError),
  274. #[cfg(feature = "wasm-runtime")]
  275. #[error("contract wasm bincode not found")]
  276. WasmBincodeNotFound,
  277. #[cfg(feature = "wasm-runtime")]
  278. #[error("contract initialize error")]
  279. ContractInitError(u64),
  280. #[cfg(feature = "wasm-runtime")]
  281. #[error("contract execution error")]
  282. ContractExecError(u64),
  283. // ====================
  284. // Miscellaneous errors
  285. // ====================
  286. #[error("IO error: {0}")]
  287. Io(std::io::ErrorKind),
  288. #[error("Infallible error: {0}")]
  289. InfallibleError(String),
  290. #[cfg(feature = "smol")]
  291. #[error("async_channel sender error: {0}")]
  292. AsyncChannelSendError(String),
  293. #[cfg(feature = "smol")]
  294. #[error("async_channel receiver error: {0}")]
  295. AsyncChannelRecvError(String),
  296. #[error("SetLogger (log crate) failed: {0}")]
  297. SetLoggerError(String),
  298. #[error("ValueIsNotObject")]
  299. ValueIsNotObject,
  300. #[error("No config file detected")]
  301. ConfigNotFound,
  302. #[error("Invalid config file detected")]
  303. ConfigInvalid,
  304. #[error("Failed decoding bincode: {0}")]
  305. ZkasDecoderError(String),
  306. #[cfg(feature = "util")]
  307. #[error("System clock is not correct!")]
  308. InvalidClock,
  309. #[error("Unsupported OS")]
  310. UnsupportedOS,
  311. #[error("System clock went backwards")]
  312. BackwardsTime(std::time::SystemTimeError),
  313. // ==============================================
  314. // Wrappers for other error types in this library
  315. // ==============================================
  316. #[error(transparent)]
  317. ClientFailed(#[from] ClientFailed),
  318. #[cfg(feature = "tx")]
  319. #[error(transparent)]
  320. TxVerifyFailed(#[from] TxVerifyFailed),
  321. //=============
  322. // clock
  323. //=============
  324. #[error("clock out of sync with peers: {0}")]
  325. ClockOutOfSync(String),
  326. // ==============
  327. // DHT errors
  328. // ==============
  329. #[error("Chunk not found")]
  330. DhtChunkNotFound,
  331. #[error("File metadata not found")]
  332. DhtFileMetadataNotFound,
  333. // FIXME: This is out of context, be specific when writing errors.
  334. #[error("Did not find key")]
  335. UnknownKey,
  336. // Catch-all
  337. #[error("{0}")]
  338. Custom(String),
  339. }
  340. #[cfg(feature = "tx")]
  341. impl Error {
  342. /// Auxiliary function to retrieve the vector of erroneous
  343. /// transactions from a TxVerifyFailed error.
  344. /// In any other case, we return the error itself.
  345. pub fn retrieve_erroneous_txs(&self) -> Result<Vec<crate::tx::Transaction>> {
  346. if let Self::TxVerifyFailed(TxVerifyFailed::ErroneousTxs(erroneous_txs)) = self {
  347. return Ok(erroneous_txs.clone())
  348. };
  349. Err(self.clone())
  350. }
  351. }
  352. #[cfg(feature = "tx")]
  353. /// Transaction verification errors
  354. #[derive(Debug, Clone, thiserror::Error)]
  355. pub enum TxVerifyFailed {
  356. #[error("Invalid transaction signature")]
  357. InvalidSignature,
  358. #[error("Missing signatures in transaction")]
  359. MissingSignatures,
  360. #[error("Missing contract calls in transaction")]
  361. MissingCalls,
  362. #[error("Missing Money::Fee call in transaction")]
  363. MissingFee,
  364. #[error("Invalid ZK proof in transaction")]
  365. InvalidZkProof,
  366. #[error("Erroneous transactions found")]
  367. ErroneousTxs(Vec<crate::tx::Transaction>),
  368. }
  369. /// Client module errors
  370. #[derive(Debug, Clone, thiserror::Error)]
  371. pub enum ClientFailed {
  372. #[error("IO error: {0}")]
  373. Io(std::io::ErrorKind),
  374. #[error("Not enough value: {0}")]
  375. NotEnoughValue(u64),
  376. #[error("Invalid address: {0}")]
  377. InvalidAddress(String),
  378. #[error("Invalid amount: {0}")]
  379. InvalidAmount(u64),
  380. #[error("Invalid token ID: {0}")]
  381. InvalidTokenId(String),
  382. #[error("Internal error: {0}")]
  383. InternalError(String),
  384. #[error("Verify error: {0}")]
  385. VerifyError(String),
  386. }
  387. impl From<Error> for ClientFailed {
  388. fn from(err: Error) -> Self {
  389. Self::InternalError(err.to_string())
  390. }
  391. }
  392. impl From<std::io::Error> for ClientFailed {
  393. fn from(err: std::io::Error) -> Self {
  394. Self::Io(err.kind())
  395. }
  396. }
  397. #[cfg(feature = "async-std")]
  398. impl From<async_std::future::TimeoutError> for Error {
  399. fn from(_err: async_std::future::TimeoutError) -> Self {
  400. Self::TimeoutError
  401. }
  402. }
  403. impl From<std::io::Error> for Error {
  404. fn from(err: std::io::Error) -> Self {
  405. Self::Io(err.kind())
  406. }
  407. }
  408. impl From<std::time::SystemTimeError> for Error {
  409. fn from(err: std::time::SystemTimeError) -> Self {
  410. Self::BackwardsTime(err)
  411. }
  412. }
  413. impl From<std::convert::Infallible> for Error {
  414. fn from(err: std::convert::Infallible) -> Self {
  415. Self::InfallibleError(err.to_string())
  416. }
  417. }
  418. impl From<()> for Error {
  419. fn from(_err: ()) -> Self {
  420. Self::InfallibleError("Infallible".into())
  421. }
  422. }
  423. #[cfg(feature = "smol")]
  424. impl<T> From<smol::channel::SendError<T>> for Error {
  425. fn from(err: smol::channel::SendError<T>) -> Self {
  426. Self::AsyncChannelSendError(err.to_string())
  427. }
  428. }
  429. #[cfg(feature = "smol")]
  430. impl From<smol::channel::RecvError> for Error {
  431. fn from(err: smol::channel::RecvError) -> Self {
  432. Self::AsyncChannelRecvError(err.to_string())
  433. }
  434. }
  435. impl From<log::SetLoggerError> for Error {
  436. fn from(err: log::SetLoggerError) -> Self {
  437. Self::SetLoggerError(err.to_string())
  438. }
  439. }
  440. #[cfg(feature = "sqlx")]
  441. impl From<sqlx::error::Error> for Error {
  442. fn from(err: sqlx::error::Error) -> Self {
  443. Self::SqlxError(err.to_string())
  444. }
  445. }
  446. #[cfg(feature = "halo2_proofs")]
  447. impl From<halo2_proofs::plonk::Error> for Error {
  448. fn from(err: halo2_proofs::plonk::Error) -> Self {
  449. Self::PlonkError(err.to_string())
  450. }
  451. }
  452. /*
  453. #[cfg(feature = "tungstenite")]
  454. impl From<tungstenite::Error> for Error {
  455. fn from(err: tungstenite::Error) -> Self {
  456. Self::TungsteniteError(err.to_string())
  457. }
  458. }
  459. */
  460. #[cfg(feature = "async-tungstenite")]
  461. impl From<async_tungstenite::tungstenite::Error> for Error {
  462. fn from(err: async_tungstenite::tungstenite::Error) -> Self {
  463. Self::TungsteniteError(err.to_string())
  464. }
  465. }
  466. #[cfg(feature = "futures-rustls")]
  467. impl From<futures_rustls::rustls::client::InvalidDnsNameError> for Error {
  468. fn from(err: futures_rustls::rustls::client::InvalidDnsNameError) -> Self {
  469. Self::RustlsInvalidDns(err.to_string())
  470. }
  471. }
  472. #[cfg(feature = "serde_json")]
  473. impl From<serde_json::Error> for Error {
  474. fn from(err: serde_json::Error) -> Self {
  475. Self::SerdeJsonError(err.to_string())
  476. }
  477. }
  478. #[cfg(feature = "fast-socks5")]
  479. impl From<fast_socks5::SocksError> for Error {
  480. fn from(err: fast_socks5::SocksError) -> Self {
  481. Self::SocksError(err.to_string())
  482. }
  483. }
  484. #[cfg(feature = "wasm-runtime")]
  485. impl From<wasmer::CompileError> for Error {
  486. fn from(err: wasmer::CompileError) -> Self {
  487. Self::WasmerCompileError(err.to_string())
  488. }
  489. }
  490. #[cfg(feature = "wasm-runtime")]
  491. impl From<wasmer::ExportError> for Error {
  492. fn from(err: wasmer::ExportError) -> Self {
  493. Self::WasmerExportError(err.to_string())
  494. }
  495. }
  496. #[cfg(feature = "wasm-runtime")]
  497. impl From<wasmer::RuntimeError> for Error {
  498. fn from(err: wasmer::RuntimeError) -> Self {
  499. Self::WasmerRuntimeError(err.to_string())
  500. }
  501. }
  502. #[cfg(feature = "wasm-runtime")]
  503. impl From<wasmer::InstantiationError> for Error {
  504. fn from(err: wasmer::InstantiationError) -> Self {
  505. Self::WasmerInstantiationError(err.to_string())
  506. }
  507. }
  508. #[cfg(feature = "wasm-runtime")]
  509. impl From<wasmer::MemoryAccessError> for Error {
  510. fn from(err: wasmer::MemoryAccessError) -> Self {
  511. Self::WasmerMemoryError(err.to_string())
  512. }
  513. }
  514. #[cfg(feature = "wasm-runtime")]
  515. impl From<wasmer::MemoryError> for Error {
  516. fn from(err: wasmer::MemoryError) -> Self {
  517. Self::WasmerOomError(err.to_string())
  518. }
  519. }
  520. #[cfg(feature = "darkfi-sdk")]
  521. impl From<darkfi_sdk::error::ContractError> for Error {
  522. fn from(err: darkfi_sdk::error::ContractError) -> Self {
  523. Self::ContractError(err)
  524. }
  525. }