error.rs 18 KB

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