error.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  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 SecretKey")]
  131. SecretKeyFromBytes,
  132. #[error("Failed converting b58 string to PublicKey")]
  133. PublicKeyFromStr,
  134. #[error("Failed converting bs58 string to SecretKey")]
  135. SecretKeyFromStr,
  136. #[error("Invalid DarkFi address")]
  137. InvalidAddress,
  138. #[cfg(feature = "futures-rustls")]
  139. #[error(transparent)]
  140. RustlsError(#[from] futures_rustls::rustls::Error),
  141. #[cfg(feature = "futures-rustls")]
  142. #[error("Invalid DNS Name {0}")]
  143. RustlsInvalidDns(String),
  144. // =======================
  145. // Protocol-related errors
  146. // =======================
  147. #[error("Unsupported chain")]
  148. UnsupportedChain,
  149. #[error("Unsupported token")]
  150. UnsupportedToken,
  151. #[error("Unsupported coin network")]
  152. UnsupportedCoinNetwork,
  153. #[error("Raft error: {0}")]
  154. RaftError(String),
  155. #[error("JSON-RPC error: {0}")]
  156. JsonRpcError(String),
  157. #[error("Received proposal from unknown node")]
  158. UnknownNodeError,
  159. #[error("Public inputs are invalid")]
  160. InvalidPublicInputsError,
  161. #[error("Error during leader proof verification")]
  162. LeaderProofVerificationError,
  163. #[error("Signature could not be verified")]
  164. InvalidSignatureError,
  165. #[error("State transition failed")]
  166. StateTransitionError,
  167. #[error("Check if proposal extends any existing fork chains failed")]
  168. ExtendedChainIndexNotFoundError,
  169. // ===============
  170. // Database errors
  171. // ===============
  172. #[cfg(feature = "sqlx")]
  173. #[error("Sqlx error: {0}")]
  174. SqlxError(String),
  175. #[cfg(feature = "sled")]
  176. #[error(transparent)]
  177. SledError(#[from] sled::Error),
  178. #[error("Transaction {0} not found in database")]
  179. TransactionNotFound(String),
  180. #[error("Header {0} not found in database")]
  181. HeaderNotFound(String),
  182. #[error("Block {0} not found in database")]
  183. BlockNotFound(String),
  184. #[error("Block in slot {0} not found in database")]
  185. SlotNotFound(u64),
  186. #[error("Block {0} metadata not found in database")]
  187. BlockMetadataNotFound(String),
  188. #[error("Contract {0} not found in database")]
  189. ContractNotFound(String),
  190. #[error("Contract state tree not found")]
  191. ContractStateNotFound,
  192. #[error("Contract already initialized")]
  193. ContractAlreadyInitialized,
  194. // =============
  195. // Wallet errors
  196. // =============
  197. #[error("Wallet password is empty")]
  198. WalletEmptyPassword,
  199. #[error("Merkle tree already exists in wallet")]
  200. WalletTreeExists,
  201. #[error("Wallet insufficient balance")]
  202. WalletInsufficientBalance,
  203. // ===================
  204. // wasm runtime errors
  205. // ===================
  206. #[cfg(feature = "wasm-runtime")]
  207. #[error("Wasmer compile error: {0}")]
  208. WasmerCompileError(String),
  209. #[cfg(feature = "wasm-runtime")]
  210. #[error("Wasmer export error: {0}")]
  211. WasmerExportError(String),
  212. #[cfg(feature = "wasm-runtime")]
  213. #[error("Wasmer runtime error: {0}")]
  214. WasmerRuntimeError(String),
  215. #[cfg(feature = "wasm-runtime")]
  216. #[error("Wasmer instantiation error: {0}")]
  217. WasmerInstantiationError(String),
  218. #[cfg(feature = "wasm-runtime")]
  219. #[error("wasm memory error")]
  220. WasmerMemoryError(String),
  221. #[cfg(feature = "wasm-runtime")]
  222. #[error("wasm runtime out of memory")]
  223. WasmerOomError(String),
  224. // TODO: FIXME: The strings are wrong
  225. #[cfg(feature = "darkfi-sdk")]
  226. #[error("contract initialize error")]
  227. ContractError(darkfi_sdk::error::ContractError),
  228. #[cfg(feature = "wasm-runtime")]
  229. #[error("contract initialize error")]
  230. ContractInitError(u64),
  231. #[cfg(feature = "wasm-runtime")]
  232. #[error("contract execution error")]
  233. ContractExecError(u64),
  234. // ====================
  235. // Miscellaneous errors
  236. // ====================
  237. #[error("IO error: {0}")]
  238. Io(std::io::ErrorKind),
  239. #[error("Infallible error: {0}")]
  240. InfallibleError(String),
  241. #[cfg(feature = "smol")]
  242. #[error("async_channel sender error: {0}")]
  243. AsyncChannelSendError(String),
  244. #[cfg(feature = "smol")]
  245. #[error("async_channel receiver error: {0}")]
  246. AsyncChannelRecvError(String),
  247. #[error("SetLogger (log crate) failed: {0}")]
  248. SetLoggerError(String),
  249. #[error("ValueIsNotObject")]
  250. ValueIsNotObject,
  251. #[error("No config file detected")]
  252. ConfigNotFound,
  253. #[error("Invalid config file detected")]
  254. ConfigInvalid,
  255. #[error("Failed decoding bincode: {0}")]
  256. ZkasDecoderError(String),
  257. #[cfg(feature = "util")]
  258. #[error("System clock is not correct!")]
  259. InvalidClock,
  260. #[error("Unsupported OS")]
  261. UnsupportedOS,
  262. #[error("System clock went backwards")]
  263. BackwardsTime(std::time::SystemTimeError),
  264. // ==============================================
  265. // Wrappers for other error types in this library
  266. // ==============================================
  267. #[error(transparent)]
  268. VerifyFailed(#[from] VerifyFailed),
  269. #[error(transparent)]
  270. ClientFailed(#[from] ClientFailed),
  271. //=============
  272. // clock
  273. //=============
  274. #[error("clock out of sync with peers: {0}")]
  275. ClockOutOfSync(String),
  276. // ==============
  277. // DHT errors
  278. // ==============
  279. // FIXME: This is out of context, be specific when writing errors.
  280. #[error("Did not find key")]
  281. UnknownKey,
  282. // Catch-all
  283. #[error("{0}")]
  284. Custom(String),
  285. }
  286. /// Transaction verification errors
  287. #[derive(Debug, Clone, thiserror::Error)]
  288. pub enum VerifyFailed {
  289. #[error("Transaction has no inputs")]
  290. LackingInputs,
  291. #[error("Transaction has no outputs")]
  292. LackingOutputs,
  293. #[error("Invalid cashier/faucet public key for clear input {0}")]
  294. InvalidCashierOrFaucetKey(usize),
  295. #[error("Invalid Merkle root for input {0}")]
  296. InvalidMerkle(usize),
  297. #[error("Nullifier already exists for input {0}")]
  298. NullifierExists(usize),
  299. #[error("Invalid signature for input {0}")]
  300. InputSignature(usize),
  301. #[error("Invalid signature for clear input {0}")]
  302. ClearInputSignature(usize),
  303. #[error("Token commitments in inputs or outputs to not match")]
  304. TokenMismatch,
  305. #[error("Money in does not match money out (value commitments)")]
  306. MissingFunds,
  307. #[error("Mint proof verification failure for input {0}")]
  308. MintProof(usize),
  309. #[error("Burn proof verification failure for input {0}")]
  310. BurnProof(usize),
  311. #[error("Failed verifying zk proofs: {0}")]
  312. ProofVerifyFailed(String),
  313. #[error("Internal error: {0}")]
  314. InternalError(String),
  315. }
  316. /// Client module errors
  317. #[derive(Debug, Clone, thiserror::Error)]
  318. pub enum ClientFailed {
  319. #[error("IO error: {0}")]
  320. Io(std::io::ErrorKind),
  321. #[error("Not enough value: {0}")]
  322. NotEnoughValue(u64),
  323. #[error("Invalid address: {0}")]
  324. InvalidAddress(String),
  325. #[error("Invalid amount: {0}")]
  326. InvalidAmount(u64),
  327. #[error("Internal error: {0}")]
  328. InternalError(String),
  329. #[error("Verify error: {0}")]
  330. VerifyError(String),
  331. }
  332. impl From<Error> for VerifyFailed {
  333. fn from(err: Error) -> Self {
  334. Self::InternalError(err.to_string())
  335. }
  336. }
  337. impl From<Error> for ClientFailed {
  338. fn from(err: Error) -> Self {
  339. Self::InternalError(err.to_string())
  340. }
  341. }
  342. impl From<VerifyFailed> for ClientFailed {
  343. fn from(err: VerifyFailed) -> Self {
  344. Self::VerifyError(err.to_string())
  345. }
  346. }
  347. impl From<std::io::Error> for ClientFailed {
  348. fn from(err: std::io::Error) -> Self {
  349. Self::Io(err.kind())
  350. }
  351. }
  352. #[cfg(feature = "async-std")]
  353. impl From<async_std::future::TimeoutError> for Error {
  354. fn from(_err: async_std::future::TimeoutError) -> Self {
  355. Self::TimeoutError
  356. }
  357. }
  358. impl From<std::io::Error> for Error {
  359. fn from(err: std::io::Error) -> Self {
  360. Self::Io(err.kind())
  361. }
  362. }
  363. impl From<std::time::SystemTimeError> for Error {
  364. fn from(err: std::time::SystemTimeError) -> Self {
  365. Self::BackwardsTime(err)
  366. }
  367. }
  368. impl From<std::convert::Infallible> for Error {
  369. fn from(err: std::convert::Infallible) -> Self {
  370. Self::InfallibleError(err.to_string())
  371. }
  372. }
  373. impl From<()> for Error {
  374. fn from(_err: ()) -> Self {
  375. Self::InfallibleError("Infallible".into())
  376. }
  377. }
  378. #[cfg(feature = "smol")]
  379. impl<T> From<smol::channel::SendError<T>> for Error {
  380. fn from(err: smol::channel::SendError<T>) -> Self {
  381. Self::AsyncChannelSendError(err.to_string())
  382. }
  383. }
  384. #[cfg(feature = "smol")]
  385. impl From<smol::channel::RecvError> for Error {
  386. fn from(err: smol::channel::RecvError) -> Self {
  387. Self::AsyncChannelRecvError(err.to_string())
  388. }
  389. }
  390. impl From<log::SetLoggerError> for Error {
  391. fn from(err: log::SetLoggerError) -> Self {
  392. Self::SetLoggerError(err.to_string())
  393. }
  394. }
  395. #[cfg(feature = "sqlx")]
  396. impl From<sqlx::error::Error> for Error {
  397. fn from(err: sqlx::error::Error) -> Self {
  398. Self::SqlxError(err.to_string())
  399. }
  400. }
  401. #[cfg(feature = "halo2_proofs")]
  402. impl From<halo2_proofs::plonk::Error> for Error {
  403. fn from(err: halo2_proofs::plonk::Error) -> Self {
  404. Self::PlonkError(err.to_string())
  405. }
  406. }
  407. #[cfg(feature = "tungstenite")]
  408. impl From<tungstenite::Error> for Error {
  409. fn from(err: tungstenite::Error) -> Self {
  410. Self::TungsteniteError(err.to_string())
  411. }
  412. }
  413. #[cfg(feature = "futures-rustls")]
  414. impl From<futures_rustls::rustls::client::InvalidDnsNameError> for Error {
  415. fn from(err: futures_rustls::rustls::client::InvalidDnsNameError) -> Self {
  416. Self::RustlsInvalidDns(err.to_string())
  417. }
  418. }
  419. #[cfg(feature = "serde_json")]
  420. impl From<serde_json::Error> for Error {
  421. fn from(err: serde_json::Error) -> Self {
  422. Self::SerdeJsonError(err.to_string())
  423. }
  424. }
  425. #[cfg(feature = "fast-socks5")]
  426. impl From<fast_socks5::SocksError> for Error {
  427. fn from(err: fast_socks5::SocksError) -> Self {
  428. Self::SocksError(err.to_string())
  429. }
  430. }
  431. #[cfg(feature = "wasm-runtime")]
  432. impl From<wasmer::CompileError> for Error {
  433. fn from(err: wasmer::CompileError) -> Self {
  434. Self::WasmerCompileError(err.to_string())
  435. }
  436. }
  437. #[cfg(feature = "wasm-runtime")]
  438. impl From<wasmer::ExportError> for Error {
  439. fn from(err: wasmer::ExportError) -> Self {
  440. Self::WasmerExportError(err.to_string())
  441. }
  442. }
  443. #[cfg(feature = "wasm-runtime")]
  444. impl From<wasmer::RuntimeError> for Error {
  445. fn from(err: wasmer::RuntimeError) -> Self {
  446. Self::WasmerRuntimeError(err.to_string())
  447. }
  448. }
  449. #[cfg(feature = "wasm-runtime")]
  450. impl From<wasmer::InstantiationError> for Error {
  451. fn from(err: wasmer::InstantiationError) -> Self {
  452. Self::WasmerInstantiationError(err.to_string())
  453. }
  454. }
  455. #[cfg(feature = "wasm-runtime")]
  456. impl From<wasmer::MemoryAccessError> for Error {
  457. fn from(err: wasmer::MemoryAccessError) -> Self {
  458. Self::WasmerMemoryError(err.to_string())
  459. }
  460. }
  461. #[cfg(feature = "wasm-runtime")]
  462. impl From<wasmer::MemoryError> for Error {
  463. fn from(err: wasmer::MemoryError) -> Self {
  464. Self::WasmerOomError(err.to_string())
  465. }
  466. }
  467. #[cfg(feature = "darkfi-sdk")]
  468. impl From<darkfi_sdk::error::ContractError> for Error {
  469. fn from(err: darkfi_sdk::error::ContractError) -> Self {
  470. Self::ContractError(err)
  471. }
  472. }