z4_types/
lib.rs

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
18/// Z4 main Result with Z4 error
19pub type Result<T> = core::result::Result<T, Error>;
20
21/// The result when after handling the message or task.
22#[derive(Default)]
23pub struct HandleResult<P: Param> {
24    /// Need broadcast the msg in the room
25    pub all: Vec<P>,
26    /// Need send to someone msg
27    pub one: Vec<(PeerId, P)>,
28    /// When game over, need prove the operations & states
29    pub over: bool,
30    /// When need waiting others, can use started = false (for PoZK)
31    pub started: bool,
32}
33
34impl<P: Param> HandleResult<P> {
35    /// Broadcast message to all players in the room
36    pub fn add_all(&mut self, param: P) {
37        self.all.push(param);
38    }
39
40    /// Send message to player in the room
41    pub fn add_one(&mut self, account: PeerId, param: P) {
42        self.one.push((account, param));
43    }
44
45    /// Over the room/game
46    pub fn over(&mut self) {
47        self.over = true;
48    }
49
50    /// Start the room/game, no other players can join
51    pub fn started(&mut self) {
52        self.started = true;
53    }
54}
55
56/// Serialize & deserialize for params
57pub trait Param: Sized + Send + Default {
58    /// To json value
59    fn to_string(&self) -> String;
60
61    /// From json value
62    fn from_string(s: String) -> Result<Self>;
63
64    /// To bytes
65    fn to_bytes(&self) -> Vec<u8>;
66
67    /// From bytes
68    fn from_bytes(bytes: Vec<u8>) -> Result<Self>;
69
70    /// To json value
71    fn to_value(&self) -> Value;
72
73    /// From json value
74    fn from_value(v: Value) -> Result<Self>;
75}
76
77/// Timer tasks when game room started
78#[async_trait::async_trait]
79pub trait Task: Send + Sync {
80    /// Game logic Handler
81    type H: Handler;
82
83    /// Next time for execute the task
84    fn timer(&self) -> u64;
85
86    /// Execute the task
87    async fn run(
88        &mut self,
89        state: &mut Self::H,
90    ) -> Result<HandleResult<<Self::H as Handler>::Param>>;
91}
92
93/// Type helper for tasks
94pub type Tasks<H> = Vec<Box<dyn Task<H = H>>>;
95
96/// Standard player from chain & pozk
97#[derive(Copy, Clone, Debug)]
98pub struct Player {
99    pub account: Address,
100    pub peer: PeerId,
101    pub signer: [u8; 32],
102}
103
104/// Player bytes length
105pub const PLAYER_BYTES_LEN: usize = 72;
106
107impl Player {
108    /// deserialize Player from bytes
109    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    /// serialize Player to bytes
129    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/// Handle message received from players
138#[async_trait::async_trait]
139pub trait Handler: Send + Sized + 'static {
140    /// Request/Response params
141    type Param: Param;
142
143    /// Viewable for game
144    fn viewable() -> bool {
145        false
146    }
147
148    /// Accept params when submit to chain
149    async fn chain_accept(_players: &[Player]) -> Vec<u8> {
150        vec![]
151    }
152
153    /// Create new room scan from chain
154    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    /// Create new room from PoZK
164    async fn pozk_create(
165        _player: Player,
166        _params: Vec<u8>,
167        _rid: RoomId,
168    ) -> Option<(Self, Tasks<Self>)> {
169        None
170    }
171
172    /// New player join from PoZK
173    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    /// New Viewer online if viewable is true
182    async fn viewer_online(&mut self, _peer: PeerId) -> Result<HandleResult<Self::Param>> {
183        Ok(HandleResult::default())
184    }
185
186    /// New Viewer offline if viewable is true
187    async fn viewer_offline(&mut self, _peer: PeerId) -> Result<HandleResult<Self::Param>> {
188        Ok(HandleResult::default())
189    }
190
191    /// When player online
192    async fn online(&mut self, _peer: PeerId) -> Result<HandleResult<Self::Param>> {
193        Ok(HandleResult::default())
194    }
195
196    /// When player offline
197    async fn offline(&mut self, _peer: PeerId) -> Result<HandleResult<Self::Param>> {
198        Ok(HandleResult::default())
199    }
200
201    /// Handle message in a room
202    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    /// Generate proof for this game result, when find game is over
211    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/// method & multiple values for Param, compatible with jsonrpc
294#[derive(Default, Debug, Clone, Serialize, Deserialize)]
295pub struct MethodValues {
296    pub method: String,
297    pub params: Vec<Value>,
298}
299
300impl MethodValues {
301    /// new a method with values params
302    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}