1mod error;
2mod key;
3mod network;
4mod task;
5mod utils;
6
7use serde::{Deserialize, Serialize};
8pub use serde_json::{json, Value};
9
10pub use error::Error;
11pub use ethereum_types::{Address, H160};
12pub use key::*;
13pub use network::*;
14pub use task::*;
15pub use tdn_types::primitives::PeerId;
16pub use utils::*;
17
18pub type Result<T> = core::result::Result<T, Error>;
20
21#[derive(Default)]
23pub struct HandleResult<P: Param> {
24 pub all: Vec<P>,
26 pub one: Vec<(PeerId, P)>,
28 pub over: bool,
30 pub started: bool,
32}
33
34impl<P: Param> HandleResult<P> {
35 pub fn add_all(&mut self, param: P) {
37 self.all.push(param);
38 }
39
40 pub fn add_one(&mut self, account: PeerId, param: P) {
42 self.one.push((account, param));
43 }
44
45 pub fn over(&mut self) {
47 self.over = true;
48 }
49
50 pub fn started(&mut self) {
52 self.started = true;
53 }
54}
55
56pub trait Param: Sized + Send + Default {
58 fn to_string(&self) -> String;
60
61 fn from_string(s: String) -> Result<Self>;
63
64 fn to_bytes(&self) -> Vec<u8>;
66
67 fn from_bytes(bytes: Vec<u8>) -> Result<Self>;
69
70 fn to_value(&self) -> Value;
72
73 fn from_value(v: Value) -> Result<Self>;
75}
76
77#[async_trait::async_trait]
79pub trait Task: Send + Sync {
80 type H: Handler;
82
83 fn timer(&self) -> u64;
85
86 async fn run(
88 &mut self,
89 state: &mut Self::H,
90 ) -> Result<HandleResult<<Self::H as Handler>::Param>>;
91}
92
93pub type Tasks<H> = Vec<Box<dyn Task<H = H>>>;
95
96#[derive(Copy, Clone, Debug)]
98pub struct Player {
99 pub account: Address,
100 pub peer: PeerId,
101 pub signer: [u8; 32],
102}
103
104pub const PLAYER_BYTES_LEN: usize = 72;
106
107impl Player {
108 pub fn from_bytes(bytes: &[u8]) -> Result<Player> {
110 if bytes.len() < PLAYER_BYTES_LEN {
111 return Err(Error::Serialize);
112 }
113
114 let mut account_bytes = [0u8; 20];
115 let mut peer_bytes = [0u8; 20];
116 let mut signer_bytes = [0u8; 32];
117 account_bytes.copy_from_slice(&bytes[0..20]);
118 peer_bytes.copy_from_slice(&bytes[20..40]);
119 signer_bytes.copy_from_slice(&bytes[40..72]);
120
121 Ok(Player {
122 account: H160(account_bytes),
123 peer: PeerId(peer_bytes),
124 signer: signer_bytes,
125 })
126 }
127
128 pub fn to_bytes(&self) -> Vec<u8> {
130 let mut bytes = self.account.0.to_vec();
131 bytes.extend(self.peer.0.to_vec());
132 bytes.extend(self.signer.to_vec());
133 bytes
134 }
135}
136
137#[async_trait::async_trait]
139pub trait Handler: Send + Sized + 'static {
140 type Param: Param;
142
143 fn viewable() -> bool {
145 false
146 }
147
148 async fn chain_accept(_players: &[Player]) -> Vec<u8> {
150 vec![]
151 }
152
153 async fn chain_create(
155 _players: &[Player],
156 _params: Vec<u8>,
157 _rid: RoomId,
158 _seed: [u8; 32],
159 ) -> Option<(Self, Tasks<Self>)> {
160 None
161 }
162
163 async fn pozk_create(
165 _player: Player,
166 _params: Vec<u8>,
167 _rid: RoomId,
168 ) -> Option<(Self, Tasks<Self>)> {
169 None
170 }
171
172 async fn pozk_join(
174 &mut self,
175 _player: Player,
176 _params: Vec<u8>,
177 ) -> Result<HandleResult<Self::Param>> {
178 Ok(HandleResult::default())
179 }
180
181 async fn viewer_online(&mut self, _peer: PeerId) -> Result<HandleResult<Self::Param>> {
183 Ok(HandleResult::default())
184 }
185
186 async fn viewer_offline(&mut self, _peer: PeerId) -> Result<HandleResult<Self::Param>> {
188 Ok(HandleResult::default())
189 }
190
191 async fn online(&mut self, _peer: PeerId) -> Result<HandleResult<Self::Param>> {
193 Ok(HandleResult::default())
194 }
195
196 async fn offline(&mut self, _peer: PeerId) -> Result<HandleResult<Self::Param>> {
198 Ok(HandleResult::default())
199 }
200
201 async fn handle(
203 &mut self,
204 _peer: PeerId,
205 _param: Self::Param,
206 ) -> Result<HandleResult<Self::Param>> {
207 Ok(HandleResult::default())
208 }
209
210 async fn prove(&mut self) -> Result<(Vec<u8>, Vec<u8>)>;
212}
213
214impl Param for Value {
215 fn to_string(&self) -> String {
216 serde_json::to_string(&self).unwrap_or("".to_owned())
217 }
218
219 fn from_string(s: String) -> Result<Self> {
220 Ok(serde_json::from_str(&s)?)
221 }
222
223 fn to_bytes(&self) -> Vec<u8> {
224 serde_json::to_vec(&self).unwrap_or(vec![])
225 }
226
227 fn from_bytes(bytes: Vec<u8>) -> Result<Self> {
228 Ok(serde_json::from_slice(&bytes)?)
229 }
230
231 fn to_value(&self) -> Value {
232 self.clone()
233 }
234
235 fn from_value(v: Value) -> Result<Self> {
236 Ok(v)
237 }
238}
239
240impl Param for String {
241 fn to_string(&self) -> String {
242 self.clone()
243 }
244
245 fn from_string(s: String) -> Result<Self> {
246 Ok(s)
247 }
248
249 fn to_bytes(&self) -> Vec<u8> {
250 self.as_bytes().to_vec()
251 }
252
253 fn from_bytes(bytes: Vec<u8>) -> Result<Self> {
254 String::from_utf8(bytes).map_err(|_| Error::Serialize)
255 }
256
257 fn to_value(&self) -> Value {
258 Value::String(self.clone())
259 }
260
261 fn from_value(v: Value) -> Result<Self> {
262 v.as_str().map(|v| v.to_owned()).ok_or(Error::Serialize)
263 }
264}
265
266impl Param for Vec<u8> {
267 fn to_string(&self) -> String {
268 hex::encode(&self)
269 }
270
271 fn from_string(s: String) -> Result<Self> {
272 Ok(hex::decode(s)?)
273 }
274
275 fn to_bytes(&self) -> Vec<u8> {
276 self.clone()
277 }
278
279 fn from_bytes(bytes: Vec<u8>) -> Result<Self> {
280 Ok(bytes)
281 }
282
283 fn to_value(&self) -> Value {
284 Value::String(self.to_string())
285 }
286
287 fn from_value(v: Value) -> Result<Self> {
288 let s = v.as_str().map(|v| v.to_owned()).ok_or(Error::Serialize)?;
289 Self::from_string(s)
290 }
291}
292
293#[derive(Default, Debug, Clone, Serialize, Deserialize)]
295pub struct MethodValues {
296 pub method: String,
297 pub params: Vec<Value>,
298}
299
300impl MethodValues {
301 pub fn new(method: &str, params: Vec<Value>) -> Self {
303 Self {
304 method: method.to_owned(),
305 params,
306 }
307 }
308}
309
310impl Param for MethodValues {
311 fn to_string(&self) -> String {
312 serde_json::to_string(&self).unwrap_or("".to_owned())
313 }
314
315 fn from_string(s: String) -> Result<Self> {
316 Ok(serde_json::from_str(&s)?)
317 }
318
319 fn to_bytes(&self) -> Vec<u8> {
320 serde_json::to_vec(&self).unwrap_or(vec![])
321 }
322
323 fn from_bytes(bytes: Vec<u8>) -> Result<Self> {
324 Ok(serde_json::from_slice(&bytes)?)
325 }
326
327 fn to_value(&self) -> Value {
328 json!({
329 "method": self.method,
330 "params": self.params,
331 })
332 }
333
334 fn from_value(v: Value) -> Result<Self> {
335 Ok(serde_json::from_value(v)?)
336 }
337}