cloud_code/lib.rs
1// Copyright Rivtower Technologies LLC.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use num_derive::FromPrimitive;
16
17/// The response status code
18#[derive(Debug, Clone, Copy, Eq, PartialEq, FromPrimitive)]
19pub enum StatusCode {
20 /// Success: 0
21 Success = 0,
22 /// Convert int to status Error
23 ConvertIntError,
24 /// status code is none
25 NoneStatusCode,
26 /// fate error
27 FatalError,
28
29 /// controller error, start from 100
30 /// node in misbehave list
31 MisbehaveNode = 100,
32 /// node in ban list
33 BannedNode,
34 /// address not consistent with record origin
35 AddressOriginCheckError,
36 /// provide address len is not 20
37 ProvideAddressError,
38 /// message not provide address
39 NoProvideAddress,
40 /// not get the block
41 NoBlock,
42 /// not get the proof
43 NoProof,
44 /// not get height of block which wrap tx
45 NoTxHeight,
46 /// not get tx index
47 NoTxIndex,
48 /// not get transaction
49 NoTransaction,
50 /// not get the block height base on hash
51 NoBlockHeight,
52 /// not get the block hash base on height
53 NoBlockHash,
54 /// proposal is none
55 NoneProposal,
56 /// block body is none
57 NoneBlockBody,
58 /// block header is none
59 NoneBlockHeader,
60 /// chain status is none
61 NoneChainStatus,
62 /// transaction's witness is none
63 NoneWitness,
64 /// transaction is none
65 NoneTransaction,
66 /// utxo is none
67 NoneUtxo,
68 /// raw tx is none
69 NoneRawTx,
70 /// early status received
71 EarlyStatus,
72 /// execute error
73 ExecuteError,
74 /// proto struct encode error
75 EncodeError,
76 /// proto struct encode error
77 DecodeError,
78 /// no candidate block
79 NoCandidate,
80 /// not get early status
81 NoEarlyStatus,
82 /// fork tree no block
83 NoForkTree,
84 /// find dup transaction
85 DupTransaction,
86 /// proposal too high
87 ProposalTooHigh,
88 /// proposal too low
89 ProposalTooLow,
90 /// proposal check error
91 ProposalCheckError,
92 /// consensus check proposal error
93 ConsensusProposalCheckError,
94 /// block hash check error
95 BlockCheckError,
96 /// the sig of chain status init check error
97 CSISigCheckError,
98 /// chain version or chain id check error
99 VersionOrIdCheckError,
100 /// hash check error
101 HashCheckError,
102 /// hash len is not correct
103 HashLenError,
104 /// signature len is not correct
105 SigLenError,
106 /// signature check error
107 SigCheckError,
108 /// the node in sync mode
109 NodeInSyncMode,
110 /// Dup tx in history
111 HistoryDupTx,
112 /// emergency brake
113 EmergencyBrake,
114 /// auth check tx's version error
115 InvalidVersion,
116 /// auth check tx's to error
117 InvalidTo,
118 /// auth check tx's nonce error
119 InvalidNonce,
120 /// auth check tx's valid until block error
121 InvalidValidUntilBlock,
122 /// auth check tx's value error
123 InvalidValue,
124 /// auth check tx's chain id error
125 InvalidChainId,
126 /// auth limit utxo's witness only one
127 InvalidWitness,
128 /// auth check utxo's lock id error
129 InvalidLockId,
130 /// auth check utxo's pre tx hash error
131 InvalidPreHash,
132 /// auth check send is not admin
133 AdminCheckError,
134 /// network msg's module not controller
135 ModuleNotController,
136 /// the quota use of tx has exceeded quota-limit
137 QuotaUsedExceed,
138 /// not get the state_root
139 NoStateRoot,
140 /// block state_root check error
141 StateRootCheckError,
142 /// update system-config error, wrong prehash or unallowed lockid
143 UpdateSystemConfigError,
144
145 /// Consensus from 200
146 /// check proposal proof error
147 ConsensusServerNotReady = 200,
148 /// proof of proposal error
149 ProposalProofError,
150
151 /// Crypto from 300
152 /// Crypto server not ready
153 CryptoServerNotReady = 300,
154 /// hash result is none
155 NoneHashResult,
156 /// construct signature error
157 ConstructSigError,
158 /// construct key pair error
159 ConstructKeyPairError,
160 /// sign error
161 SignError,
162
163 /// Network from 400
164 /// Network server not ready
165 NetworkServerNotReady = 400,
166 /// send message error
167 SendMsgError,
168 /// broadcast message error
169 BroadcastMsgError,
170 /// multi-addr error
171 MultiAddrParseError,
172 /// dial node failed
173 DialNodeFail,
174 // add an existed peer
175 AddExistedPeer,
176
177 /// executor from 500
178 /// Executor server not ready
179 ExecuteServerNotReady = 500,
180 /// internal channel disconnected
181 InternalChannelDisconnected,
182 /// early same block reenter
183 ReenterBlock,
184 /// invalid block reenter
185 ReenterInvalidBlock,
186
187 /// storage from 600
188 /// storage server not ready
189 StorageServerNotReady = 600,
190 /// kv not found
191 NotFound,
192 /// invalid region
193 InvalidRegion,
194 /// invalid key
195 InvalidKey,
196 /// bad region
197 BadRegion,
198 /// store data error
199 StoreError,
200 /// load data error
201 LoadError,
202 /// delete data error
203 DeleteError,
204}
205
206impl StatusCode {
207 pub fn is_success(&self) -> Result<(), StatusCode> {
208 if self != &StatusCode::Success {
209 Err(*self)
210 } else {
211 Ok(())
212 }
213 }
214}
215
216impl ::std::fmt::Display for StatusCode {
217 fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
218 write!(f, "{:?}", self)
219 }
220}
221
222impl ::std::error::Error for StatusCode {}
223
224macro_rules! impl_int_from_status {
225 ($myty : ty) => {
226 impl From<StatusCode> for $myty {
227 fn from(v: StatusCode) -> Self {
228 v as $myty
229 }
230 }
231 };
232}
233
234impl_int_from_status!(u16);
235impl_int_from_status!(u32);
236impl_int_from_status!(u64);
237impl_int_from_status!(u128);
238
239macro_rules! impl_status_from_int {
240 ($int_t : ty,$from_int :ident) => {
241 impl From<$int_t> for StatusCode {
242 fn from(v: $int_t) -> Self {
243 let s = num::FromPrimitive::$from_int(v);
244 s.unwrap_or(StatusCode::ConvertIntError)
245 }
246 }
247 };
248}
249
250impl_status_from_int!(u16, from_u16);
251impl_status_from_int!(u32, from_u32);
252impl_status_from_int!(u64, from_u64);
253impl_status_from_int!(u128, from_u128);
254
255impl From<cita_cloud_proto::common::StatusCode> for StatusCode {
256 fn from(status: cita_cloud_proto::common::StatusCode) -> Self {
257 StatusCode::from(status.code)
258 }
259}
260
261impl Into<cita_cloud_proto::common::StatusCode> for StatusCode {
262 fn into(self) -> cita_cloud_proto::common::StatusCode {
263 cita_cloud_proto::common::StatusCode { code: self.into() }
264 }
265}
266
267#[cfg(test)]
268mod tests {
269 use crate::StatusCode;
270
271 #[test]
272 fn it_works() {
273 let num: u32 = StatusCode::BannedNode.into();
274 assert_eq!(num, 101);
275
276 let s = StatusCode::from(104 as u64);
277 assert_eq!(StatusCode::NoProvideAddress, s);
278
279 let s = StatusCode::from(65535 as u16);
280 assert_eq!(StatusCode::ConvertIntError, s);
281
282 let status = cita_cloud_proto::common::StatusCode { code: 0 };
283 let s = StatusCode::from(status);
284 assert_eq!(StatusCode::Success, s);
285 }
286}