error.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  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. // =======================
  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. #[cfg(feature = "sled")]
  208. #[error(transparent)]
  209. SledTransactionError(#[from] sled::transaction::TransactionError),
  210. #[error("Transaction {0} not found in database")]
  211. TransactionNotFound(String),
  212. #[error("Header {0} not found in database")]
  213. HeaderNotFound(String),
  214. #[error("Block {0} not found in database")]
  215. BlockNotFound(String),
  216. #[error("Block in slot {0} not found in database")]
  217. SlotNotFound(u64),
  218. #[error("Slot checkpoint {0} not found in database")]
  219. SlotCheckpointNotFound(u64),
  220. #[error("Contract {0} not found in database")]
  221. ContractNotFound(String),
  222. #[error("Contract state tree not found")]
  223. ContractStateNotFound,
  224. #[error("Contract already initialized")]
  225. ContractAlreadyInitialized,
  226. #[error("zkas bincode not found in sled database")]
  227. ZkasBincodeNotFound,
  228. // =============
  229. // Wallet errors
  230. // =============
  231. #[error("Wallet password is empty")]
  232. WalletEmptyPassword,
  233. #[error("Merkle tree already exists in wallet")]
  234. WalletTreeExists,
  235. #[error("Wallet insufficient balance")]
  236. WalletInsufficientBalance,
  237. // ===================
  238. // wasm runtime errors
  239. // ===================
  240. #[cfg(feature = "wasm-runtime")]
  241. #[error("Wasmer compile error: {0}")]
  242. WasmerCompileError(String),
  243. #[cfg(feature = "wasm-runtime")]
  244. #[error("Wasmer export error: {0}")]
  245. WasmerExportError(String),
  246. #[cfg(feature = "wasm-runtime")]
  247. #[error("Wasmer runtime error: {0}")]
  248. WasmerRuntimeError(String),
  249. #[cfg(feature = "wasm-runtime")]
  250. #[error("Wasmer instantiation error: {0}")]
  251. WasmerInstantiationError(String),
  252. #[cfg(feature = "wasm-runtime")]
  253. #[error("wasm memory error")]
  254. WasmerMemoryError(String),
  255. #[cfg(feature = "wasm-runtime")]
  256. #[error("wasm runtime out of memory")]
  257. WasmerOomError(String),
  258. // TODO: FIXME: The strings are wrong
  259. #[cfg(feature = "darkfi-sdk")]
  260. #[error("contract initialize error")]
  261. ContractError(darkfi_sdk::error::ContractError),
  262. #[cfg(feature = "wasm-runtime")]
  263. #[error("contract wasm bincode not found")]
  264. WasmBincodeNotFound,
  265. #[cfg(feature = "wasm-runtime")]
  266. #[error("contract initialize error")]
  267. ContractInitError(u64),
  268. #[cfg(feature = "wasm-runtime")]
  269. #[error("contract execution error")]
  270. ContractExecError(u64),
  271. // ====================
  272. // Miscellaneous errors
  273. // ====================
  274. #[error("IO error: {0}")]
  275. Io(std::io::ErrorKind),
  276. #[error("Infallible error: {0}")]
  277. InfallibleError(String),
  278. #[cfg(feature = "smol")]
  279. #[error("async_channel sender error: {0}")]
  280. AsyncChannelSendError(String),
  281. #[cfg(feature = "smol")]
  282. #[error("async_channel receiver error: {0}")]
  283. AsyncChannelRecvError(String),
  284. #[error("SetLogger (log crate) failed: {0}")]
  285. SetLoggerError(String),
  286. #[error("ValueIsNotObject")]
  287. ValueIsNotObject,
  288. #[error("No config file detected")]
  289. ConfigNotFound,
  290. #[error("Invalid config file detected")]
  291. ConfigInvalid,
  292. #[error("Failed decoding bincode: {0}")]
  293. ZkasDecoderError(String),
  294. #[cfg(feature = "util")]
  295. #[error("System clock is not correct!")]
  296. InvalidClock,
  297. #[error("Unsupported OS")]
  298. UnsupportedOS,
  299. #[error("System clock went backwards")]
  300. BackwardsTime(std::time::SystemTimeError),
  301. // ==============================================
  302. // Wrappers for other error types in this library
  303. // ==============================================
  304. #[error(transparent)]
  305. VerifyFailed(#[from] VerifyFailed),
  306. #[error(transparent)]
  307. ClientFailed(#[from] ClientFailed),
  308. //=============
  309. // clock
  310. //=============
  311. #[error("clock out of sync with peers: {0}")]
  312. ClockOutOfSync(String),
  313. // ==============
  314. // DHT errors
  315. // ==============
  316. // FIXME: This is out of context, be specific when writing errors.
  317. #[error("Did not find key")]
  318. UnknownKey,
  319. // Catch-all
  320. #[error("{0}")]
  321. Custom(String),
  322. }
  323. /// Transaction verification errors
  324. #[derive(Debug, Clone, thiserror::Error)]
  325. pub enum VerifyFailed {
  326. #[error("Transaction has no inputs")]
  327. LackingInputs,
  328. #[error("Transaction has no outputs")]
  329. LackingOutputs,
  330. #[error("Invalid cashier/faucet public key for clear input {0}")]
  331. InvalidCashierOrFaucetKey(usize),
  332. #[error("Invalid Merkle root for input {0}")]
  333. InvalidMerkle(usize),
  334. #[error("Nullifier already exists for input {0}")]
  335. NullifierExists(usize),
  336. #[error("Invalid signature for input {0}")]
  337. InputSignature(usize),
  338. #[error("Invalid signature for clear input {0}")]
  339. ClearInputSignature(usize),
  340. #[error("Token commitments in inputs or outputs to not match")]
  341. TokenMismatch,
  342. #[error("Money in does not match money out (value commitments)")]
  343. MissingFunds,
  344. #[error("Mint proof verification failure for input {0}")]
  345. MintProof(usize),
  346. #[error("Burn proof verification failure for input {0}")]
  347. BurnProof(usize),
  348. #[error("Failed verifying zk proofs: {0}")]
  349. ProofVerifyFailed(String),
  350. #[error("Internal error: {0}")]
  351. InternalError(String),
  352. }
  353. /// Client module errors
  354. #[derive(Debug, Clone, thiserror::Error)]
  355. pub enum ClientFailed {
  356. #[error("IO error: {0}")]
  357. Io(std::io::ErrorKind),
  358. #[error("Not enough value: {0}")]
  359. NotEnoughValue(u64),
  360. #[error("Invalid address: {0}")]
  361. InvalidAddress(String),
  362. #[error("Invalid amount: {0}")]
  363. InvalidAmount(u64),
  364. #[error("Invalid token ID: {0}")]
  365. InvalidTokenId(String),
  366. #[error("Internal error: {0}")]
  367. InternalError(String),
  368. #[error("Verify error: {0}")]
  369. VerifyError(String),
  370. }
  371. impl From<Error> for VerifyFailed {
  372. fn from(err: Error) -> Self {
  373. Self::InternalError(err.to_string())
  374. }
  375. }
  376. impl From<Error> for ClientFailed {
  377. fn from(err: Error) -> Self {
  378. Self::InternalError(err.to_string())
  379. }
  380. }
  381. impl From<VerifyFailed> for ClientFailed {
  382. fn from(err: VerifyFailed) -> Self {
  383. Self::VerifyError(err.to_string())
  384. }
  385. }
  386. impl From<std::io::Error> for ClientFailed {
  387. fn from(err: std::io::Error) -> Self {
  388. Self::Io(err.kind())
  389. }
  390. }
  391. #[cfg(feature = "async-std")]
  392. impl From<async_std::future::TimeoutError> for Error {
  393. fn from(_err: async_std::future::TimeoutError) -> Self {
  394. Self::TimeoutError
  395. }
  396. }
  397. impl From<std::io::Error> for Error {
  398. fn from(err: std::io::Error) -> Self {
  399. Self::Io(err.kind())
  400. }
  401. }
  402. impl From<std::time::SystemTimeError> for Error {
  403. fn from(err: std::time::SystemTimeError) -> Self {
  404. Self::BackwardsTime(err)
  405. }
  406. }
  407. impl From<std::convert::Infallible> for Error {
  408. fn from(err: std::convert::Infallible) -> Self {
  409. Self::InfallibleError(err.to_string())
  410. }
  411. }
  412. impl From<()> for Error {
  413. fn from(_err: ()) -> Self {
  414. Self::InfallibleError("Infallible".into())
  415. }
  416. }
  417. #[cfg(feature = "smol")]
  418. impl<T> From<smol::channel::SendError<T>> for Error {
  419. fn from(err: smol::channel::SendError<T>) -> Self {
  420. Self::AsyncChannelSendError(err.to_string())
  421. }
  422. }
  423. #[cfg(feature = "smol")]
  424. impl From<smol::channel::RecvError> for Error {
  425. fn from(err: smol::channel::RecvError) -> Self {
  426. Self::AsyncChannelRecvError(err.to_string())
  427. }
  428. }
  429. impl From<log::SetLoggerError> for Error {
  430. fn from(err: log::SetLoggerError) -> Self {
  431. Self::SetLoggerError(err.to_string())
  432. }
  433. }
  434. #[cfg(feature = "sqlx")]
  435. impl From<sqlx::error::Error> for Error {
  436. fn from(err: sqlx::error::Error) -> Self {
  437. Self::SqlxError(err.to_string())
  438. }
  439. }
  440. #[cfg(feature = "halo2_proofs")]
  441. impl From<halo2_proofs::plonk::Error> for Error {
  442. fn from(err: halo2_proofs::plonk::Error) -> Self {
  443. Self::PlonkError(err.to_string())
  444. }
  445. }
  446. /*
  447. #[cfg(feature = "tungstenite")]
  448. impl From<tungstenite::Error> for Error {
  449. fn from(err: tungstenite::Error) -> Self {
  450. Self::TungsteniteError(err.to_string())
  451. }
  452. }
  453. */
  454. #[cfg(feature = "async-tungstenite")]
  455. impl From<async_tungstenite::tungstenite::Error> for Error {
  456. fn from(err: async_tungstenite::tungstenite::Error) -> Self {
  457. Self::TungsteniteError(err.to_string())
  458. }
  459. }
  460. #[cfg(feature = "futures-rustls")]
  461. impl From<futures_rustls::rustls::client::InvalidDnsNameError> for Error {
  462. fn from(err: futures_rustls::rustls::client::InvalidDnsNameError) -> Self {
  463. Self::RustlsInvalidDns(err.to_string())
  464. }
  465. }
  466. #[cfg(feature = "serde_json")]
  467. impl From<serde_json::Error> for Error {
  468. fn from(err: serde_json::Error) -> Self {
  469. Self::SerdeJsonError(err.to_string())
  470. }
  471. }
  472. #[cfg(feature = "fast-socks5")]
  473. impl From<fast_socks5::SocksError> for Error {
  474. fn from(err: fast_socks5::SocksError) -> Self {
  475. Self::SocksError(err.to_string())
  476. }
  477. }
  478. #[cfg(feature = "wasm-runtime")]
  479. impl From<wasmer::CompileError> for Error {
  480. fn from(err: wasmer::CompileError) -> Self {
  481. Self::WasmerCompileError(err.to_string())
  482. }
  483. }
  484. #[cfg(feature = "wasm-runtime")]
  485. impl From<wasmer::ExportError> for Error {
  486. fn from(err: wasmer::ExportError) -> Self {
  487. Self::WasmerExportError(err.to_string())
  488. }
  489. }
  490. #[cfg(feature = "wasm-runtime")]
  491. impl From<wasmer::RuntimeError> for Error {
  492. fn from(err: wasmer::RuntimeError) -> Self {
  493. Self::WasmerRuntimeError(err.to_string())
  494. }
  495. }
  496. #[cfg(feature = "wasm-runtime")]
  497. impl From<wasmer::InstantiationError> for Error {
  498. fn from(err: wasmer::InstantiationError) -> Self {
  499. Self::WasmerInstantiationError(err.to_string())
  500. }
  501. }
  502. #[cfg(feature = "wasm-runtime")]
  503. impl From<wasmer::MemoryAccessError> for Error {
  504. fn from(err: wasmer::MemoryAccessError) -> Self {
  505. Self::WasmerMemoryError(err.to_string())
  506. }
  507. }
  508. #[cfg(feature = "wasm-runtime")]
  509. impl From<wasmer::MemoryError> for Error {
  510. fn from(err: wasmer::MemoryError) -> Self {
  511. Self::WasmerOomError(err.to_string())
  512. }
  513. }
  514. #[cfg(feature = "darkfi-sdk")]
  515. impl From<darkfi_sdk::error::ContractError> for Error {
  516. fn from(err: darkfi_sdk::error::ContractError) -> Self {
  517. Self::ContractError(err)
  518. }
  519. }