error.rs 18 KB

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