error.rs 17 KB

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