error.rs 18 KB

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