error.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. // Hello developer. Please add your error to the according subsection
  2. // that is commented, or make a new subsection. Keep it clean.
  3. /// Main result type used throughout the codebase.
  4. pub type Result<T> = std::result::Result<T, Error>;
  5. /// Result type used in transaction verifications
  6. pub type VerifyResult<T> = std::result::Result<T, VerifyFailed>;
  7. /// Result type used in the Client module
  8. pub type ClientResult<T> = std::result::Result<T, ClientFailed>;
  9. /// General library errors used throughout the codebase.
  10. #[derive(Debug, Clone, thiserror::Error)]
  11. pub enum Error {
  12. // ==============
  13. // Parsing errors
  14. // ==============
  15. #[error("Parse failed: {0}")]
  16. ParseFailed(&'static str),
  17. #[error(transparent)]
  18. ParseIntError(#[from] std::num::ParseIntError),
  19. #[error(transparent)]
  20. ParseFloatError(#[from] std::num::ParseFloatError),
  21. #[cfg(feature = "url")]
  22. #[error(transparent)]
  23. UrlParseError(#[from] url::ParseError),
  24. #[error("URL parse error: {0}")]
  25. UrlParse(String),
  26. #[error(transparent)]
  27. AddrParseError(#[from] std::net::AddrParseError),
  28. #[error("Could not parse token parameter")]
  29. TokenParseError,
  30. #[error(transparent)]
  31. TryFromSliceError(#[from] std::array::TryFromSliceError),
  32. // ===============
  33. // Encoding errors
  34. // ===============
  35. #[error("decode failed: {0}")]
  36. DecodeError(&'static str),
  37. #[error("encode failed: {0}")]
  38. EncodeError(&'static str),
  39. #[error("VarInt was encoded in a non-minimal way")]
  40. NonMinimalVarInt,
  41. #[error(transparent)]
  42. Utf8Error(#[from] std::string::FromUtf8Error),
  43. #[error(transparent)]
  44. StrUtf8Error(#[from] std::str::Utf8Error),
  45. #[cfg(feature = "serde_json")]
  46. #[error("serde_json error: {0}")]
  47. SerdeJsonError(String),
  48. #[cfg(feature = "toml")]
  49. #[error(transparent)]
  50. TomlDeserializeError(#[from] toml::de::Error),
  51. #[cfg(feature = "bs58")]
  52. #[error(transparent)]
  53. Bs58DecodeError(#[from] bs58::decode::Error),
  54. #[cfg(feature = "hex")]
  55. #[error(transparent)]
  56. HexDecodeError(#[from] hex::FromHexError),
  57. #[error("Bad operation type byte")]
  58. BadOperationType,
  59. // ======================
  60. // Network-related errors
  61. // ======================
  62. #[error("Unsupported network transport: {0}")]
  63. UnsupportedTransport(String),
  64. #[error("Unsupported network transport upgrade: {0}")]
  65. UnsupportedTransportUpgrade(String),
  66. #[error("Connection failed")]
  67. ConnectFailed,
  68. #[error("Timeout Error")]
  69. TimeoutError,
  70. #[error("Connection timed out")]
  71. ConnectTimeout,
  72. #[error("Channel stopped")]
  73. ChannelStopped,
  74. #[error("Channel timed out")]
  75. ChannelTimeout,
  76. #[error("Network service stopped")]
  77. NetworkServiceStopped,
  78. #[error("Create listener bound to {0} failed")]
  79. BindFailed(String),
  80. #[error("Accept a new incoming connection from the listener {0} failed")]
  81. AcceptConnectionFailed(String),
  82. #[error("Accept a new tls connection from the listener {0} failed")]
  83. AcceptTlsConnectionFailed(String),
  84. #[error("Network operation failed")]
  85. NetworkOperationFailed,
  86. #[error("Malformed packet")]
  87. MalformedPacket,
  88. #[error("Socks proxy error: {0}")]
  89. SocksError(String),
  90. #[error("No Socks5 URL found")]
  91. NoSocks5UrlFound,
  92. #[error("No URL found")]
  93. NoUrlFound,
  94. #[cfg(feature = "tungstenite")]
  95. #[error("tungstenite error: {0}")]
  96. TungsteniteError(String),
  97. #[error("Tor error: {0}")]
  98. TorError(String),
  99. #[error("Node is not connected to other nodes.")]
  100. NetworkNotConnected,
  101. // =============
  102. // Crypto errors
  103. // =============
  104. #[cfg(feature = "halo2_proofs")]
  105. #[error("halo2 plonk error: {0}")]
  106. PlonkError(String),
  107. #[error("Unable to decrypt mint note: {0}")]
  108. NoteDecryptionFailed(String),
  109. #[error("No keypair file detected")]
  110. KeypairPathNotFound,
  111. #[error("Failed converting bytes to PublicKey")]
  112. PublicKeyFromBytes,
  113. #[error("Failed converting bytes to SecretKey")]
  114. SecretKeyFromBytes,
  115. #[error("Failed converting b58 string to PublicKey")]
  116. PublicKeyFromStr,
  117. #[error("Failed converting bs58 string to SecretKey")]
  118. SecretKeyFromStr,
  119. #[error("Invalid DarkFi address")]
  120. InvalidAddress,
  121. #[cfg(feature = "futures-rustls")]
  122. #[error(transparent)]
  123. RustlsError(#[from] futures_rustls::rustls::Error),
  124. #[cfg(feature = "futures-rustls")]
  125. #[error("Invalid DNS Name {0}")]
  126. RustlsInvalidDns(String),
  127. // =======================
  128. // Protocol-related errors
  129. // =======================
  130. #[error("Unsupported chain")]
  131. UnsupportedChain,
  132. #[error("Unsupported token")]
  133. UnsupportedToken,
  134. #[error("Unsupported coin network")]
  135. UnsupportedCoinNetwork,
  136. #[error("Raft error: {0}")]
  137. RaftError(String),
  138. #[error("JSON-RPC error: {0}")]
  139. JsonRpcError(String),
  140. #[error("Received proposal from unknown node")]
  141. UnknownNodeError,
  142. #[error("Public inputs are invalid")]
  143. InvalidPublicInputsError,
  144. #[error("Error during leader proof verification")]
  145. LeaderProofVerificationError,
  146. #[error("Signature could not be verified")]
  147. InvalidSignatureError,
  148. #[error("State transition failed")]
  149. StateTransitionError,
  150. // ===============
  151. // Database errors
  152. // ===============
  153. #[cfg(feature = "sqlx")]
  154. #[error("Sqlx error: {0}")]
  155. SqlxError(String),
  156. #[cfg(feature = "sled")]
  157. #[error(transparent)]
  158. SledError(#[from] sled::Error),
  159. #[error("Transaction {0} not found in database")]
  160. TransactionNotFound(String),
  161. #[error("Header {0} not found in database")]
  162. HeaderNotFound(String),
  163. #[error("Block {0} not found in database")]
  164. BlockNotFound(String),
  165. #[error("Block in slot {0} not found in database")]
  166. SlotNotFound(u64),
  167. #[error("Block {0} metadata not found in database")]
  168. BlockMetadataNotFound(String),
  169. // =============
  170. // Wallet errors
  171. // =============
  172. #[error("Wallet password is empty")]
  173. WalletEmptyPassword,
  174. #[error("Merkle tree already exists in wallet")]
  175. WalletTreeExists,
  176. #[error("Wallet insufficient balance")]
  177. WalletInsufficientBalance,
  178. // ===================
  179. // wasm runtime errors
  180. // ===================
  181. #[cfg(feature = "wasm-runtime")]
  182. #[error("Wasmer compile error: {0}")]
  183. WasmerCompileError(String),
  184. #[cfg(feature = "wasm-runtime")]
  185. #[error("Wasmer export error: {0}")]
  186. WasmerExportError(String),
  187. #[cfg(feature = "wasm-runtime")]
  188. #[error("Wasmer runtime error: {0}")]
  189. WasmerRuntimeError(String),
  190. #[cfg(feature = "wasm-runtime")]
  191. #[error("Wasmer instantiation error: {0}")]
  192. WasmerInstantiationError(String),
  193. #[cfg(feature = "wasm-runtime")]
  194. #[error("wasm runtime out of memory")]
  195. WasmerOomError,
  196. // ====================
  197. // Miscellaneous errors
  198. // ====================
  199. #[error("IO error: {0}")]
  200. Io(std::io::ErrorKind),
  201. #[error("Infallible error: {0}")]
  202. InfallibleError(String),
  203. #[cfg(feature = "smol")]
  204. #[error("async_channel sender error: {0}")]
  205. AsyncChannelSendError(String),
  206. #[cfg(feature = "smol")]
  207. #[error("async_channel receiver error: {0}")]
  208. AsyncChannelRecvError(String),
  209. #[error("SetLogger (log crate) failed: {0}")]
  210. SetLoggerError(String),
  211. #[error("ValueIsNotObject")]
  212. ValueIsNotObject,
  213. #[error("No config file detected")]
  214. ConfigNotFound,
  215. #[error("Invalid config file detected")]
  216. ConfigInvalid,
  217. #[error("Failed decoding bincode: {0}")]
  218. ZkasDecoderError(String),
  219. #[cfg(feature = "util")]
  220. #[error("System clock is not correct!")]
  221. InvalidClock,
  222. #[error("Unsupported OS")]
  223. UnsupportedOS,
  224. #[error("System clock went backwards")]
  225. BackwardsTime(std::time::SystemTimeError),
  226. // ==============================================
  227. // Wrappers for other error types in this library
  228. // ==============================================
  229. #[error(transparent)]
  230. VerifyFailed(#[from] VerifyFailed),
  231. #[error(transparent)]
  232. ClientFailed(#[from] ClientFailed),
  233. //=============
  234. // clock
  235. //=============
  236. #[error("clock out of sync with peers: {0}")]
  237. ClockOutOfSync(String),
  238. // ==============
  239. // DHT errors
  240. // ==============
  241. // FIXME: This is out of context, be specific when writing errors.
  242. #[error("Did not find key")]
  243. UnknownKey,
  244. // Catch-all
  245. #[error("{0}")]
  246. Custom(String),
  247. }
  248. /// Transaction verification errors
  249. #[derive(Debug, Clone, thiserror::Error)]
  250. pub enum VerifyFailed {
  251. #[error("Transaction has no inputs")]
  252. LackingInputs,
  253. #[error("Transaction has no outputs")]
  254. LackingOutputs,
  255. #[error("Invalid cashier/faucet public key for clear input {0}")]
  256. InvalidCashierOrFaucetKey(usize),
  257. #[error("Invalid Merkle root for input {0}")]
  258. InvalidMerkle(usize),
  259. #[error("Nullifier already exists for input {0}")]
  260. NullifierExists(usize),
  261. #[error("Invalid signature for input {0}")]
  262. InputSignature(usize),
  263. #[error("Invalid signature for clear input {0}")]
  264. ClearInputSignature(usize),
  265. #[error("Token commitments in inputs or outputs to not match")]
  266. TokenMismatch,
  267. #[error("Money in does not match money out (value commitments)")]
  268. MissingFunds,
  269. #[error("Mint proof verification failure for input {0}")]
  270. MintProof(usize),
  271. #[error("Burn proof verification failure for input {0}")]
  272. BurnProof(usize),
  273. #[error("Failed verifying zk proofs: {0}")]
  274. ProofVerifyFailed(String),
  275. #[error("Internal error: {0}")]
  276. InternalError(String),
  277. }
  278. /// Client module errors
  279. #[derive(Debug, Clone, thiserror::Error)]
  280. pub enum ClientFailed {
  281. #[error("IO error: {0}")]
  282. Io(std::io::ErrorKind),
  283. #[error("Not enough value: {0}")]
  284. NotEnoughValue(u64),
  285. #[error("Invalid address: {0}")]
  286. InvalidAddress(String),
  287. #[error("Invalid amount: {0}")]
  288. InvalidAmount(u64),
  289. #[error("Internal error: {0}")]
  290. InternalError(String),
  291. #[error("Verify error: {0}")]
  292. VerifyError(String),
  293. }
  294. impl From<Error> for VerifyFailed {
  295. fn from(err: Error) -> Self {
  296. Self::InternalError(err.to_string())
  297. }
  298. }
  299. impl From<Error> for ClientFailed {
  300. fn from(err: Error) -> Self {
  301. Self::InternalError(err.to_string())
  302. }
  303. }
  304. impl From<VerifyFailed> for ClientFailed {
  305. fn from(err: VerifyFailed) -> Self {
  306. Self::VerifyError(err.to_string())
  307. }
  308. }
  309. impl From<std::io::Error> for ClientFailed {
  310. fn from(err: std::io::Error) -> Self {
  311. Self::Io(err.kind())
  312. }
  313. }
  314. #[cfg(feature = "async-std")]
  315. impl From<async_std::future::TimeoutError> for Error {
  316. fn from(_err: async_std::future::TimeoutError) -> Self {
  317. Self::TimeoutError
  318. }
  319. }
  320. impl From<std::io::Error> for Error {
  321. fn from(err: std::io::Error) -> Self {
  322. Self::Io(err.kind())
  323. }
  324. }
  325. impl From<std::time::SystemTimeError> for Error {
  326. fn from(err: std::time::SystemTimeError) -> Self {
  327. Self::BackwardsTime(err)
  328. }
  329. }
  330. impl From<std::convert::Infallible> for Error {
  331. fn from(err: std::convert::Infallible) -> Self {
  332. Self::InfallibleError(err.to_string())
  333. }
  334. }
  335. impl From<()> for Error {
  336. fn from(_err: ()) -> Self {
  337. Self::InfallibleError("Infallible".into())
  338. }
  339. }
  340. #[cfg(feature = "smol")]
  341. impl<T> From<smol::channel::SendError<T>> for Error {
  342. fn from(err: smol::channel::SendError<T>) -> Self {
  343. Self::AsyncChannelSendError(err.to_string())
  344. }
  345. }
  346. #[cfg(feature = "smol")]
  347. impl From<smol::channel::RecvError> for Error {
  348. fn from(err: smol::channel::RecvError) -> Self {
  349. Self::AsyncChannelRecvError(err.to_string())
  350. }
  351. }
  352. impl From<log::SetLoggerError> for Error {
  353. fn from(err: log::SetLoggerError) -> Self {
  354. Self::SetLoggerError(err.to_string())
  355. }
  356. }
  357. #[cfg(feature = "sqlx")]
  358. impl From<sqlx::error::Error> for Error {
  359. fn from(err: sqlx::error::Error) -> Self {
  360. Self::SqlxError(err.to_string())
  361. }
  362. }
  363. #[cfg(feature = "halo2_proofs")]
  364. impl From<halo2_proofs::plonk::Error> for Error {
  365. fn from(err: halo2_proofs::plonk::Error) -> Self {
  366. Self::PlonkError(err.to_string())
  367. }
  368. }
  369. #[cfg(feature = "tungstenite")]
  370. impl From<tungstenite::Error> for Error {
  371. fn from(err: tungstenite::Error) -> Self {
  372. Self::TungsteniteError(err.to_string())
  373. }
  374. }
  375. #[cfg(feature = "futures-rustls")]
  376. impl From<futures_rustls::rustls::client::InvalidDnsNameError> for Error {
  377. fn from(err: futures_rustls::rustls::client::InvalidDnsNameError) -> Self {
  378. Self::RustlsInvalidDns(err.to_string())
  379. }
  380. }
  381. #[cfg(feature = "serde_json")]
  382. impl From<serde_json::Error> for Error {
  383. fn from(err: serde_json::Error) -> Self {
  384. Self::SerdeJsonError(err.to_string())
  385. }
  386. }
  387. #[cfg(feature = "fast-socks5")]
  388. impl From<fast_socks5::SocksError> for Error {
  389. fn from(err: fast_socks5::SocksError) -> Self {
  390. Self::SocksError(err.to_string())
  391. }
  392. }
  393. #[cfg(feature = "wasm-runtime")]
  394. impl From<wasmer::CompileError> for Error {
  395. fn from(err: wasmer::CompileError) -> Self {
  396. Self::WasmerCompileError(err.to_string())
  397. }
  398. }
  399. #[cfg(feature = "wasm-runtime")]
  400. impl From<wasmer::ExportError> for Error {
  401. fn from(err: wasmer::ExportError) -> Self {
  402. Self::WasmerExportError(err.to_string())
  403. }
  404. }
  405. #[cfg(feature = "wasm-runtime")]
  406. impl From<wasmer::RuntimeError> for Error {
  407. fn from(err: wasmer::RuntimeError) -> Self {
  408. Self::WasmerRuntimeError(err.to_string())
  409. }
  410. }
  411. #[cfg(feature = "wasm-runtime")]
  412. impl From<wasmer::InstantiationError> for Error {
  413. fn from(err: wasmer::InstantiationError) -> Self {
  414. Self::WasmerInstantiationError(err.to_string())
  415. }
  416. }