error.rs 16 KB

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