error.rs 17 KB

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