arnaucube
arnaucube/phantom-zonePublic Self-hosted repository
phantom-zone/examples/bomberman.rs
examples/bomberman.rsRaw
  1use std::fmt::Debug;
  2
  3use bin_rs::*;
  4use itertools::Itertools;
  5use rand::{thread_rng, Rng, RngCore};
  6
  7struct Coordinates<T>(T, T);
  8impl<T> Coordinates<T> {
  9    fn new(x: T, y: T) -> Self {
 10        Coordinates(x, y)
 11    }
 12    fn x(&self) -> &T {
 13        &self.0
 14    }
 15
 16    fn y(&self) -> &T {
 17        &self.1
 18    }
 19}
 20
 21impl<T> Debug for Coordinates<T>
 22where
 23    T: Debug,
 24{
 25    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 26        f.debug_struct("Coordinates")
 27            .field("x", self.x())
 28            .field("y", self.y())
 29            .finish()
 30    }
 31}
 32
 33fn coordinates_is_equal(a: &Coordinates<FheUint8>, b: &Coordinates<FheUint8>) -> FheBool {
 34    &(a.x().eq(b.x())) & &(a.y().eq(b.y()))
 35}
 36
 37/// Traverse the map with `p0` moves and check whether any of the moves equal
 38/// bomb coordinates (in encrypted domain)
 39fn traverse_map(p0: &[Coordinates<FheUint8>], bomb_coords: &[Coordinates<FheUint8>]) -> FheBool {
 40    // First move
 41    let mut out = coordinates_is_equal(&p0[0], &bomb_coords[0]);
 42    bomb_coords.iter().skip(1).for_each(|b_coord| {
 43        out |= coordinates_is_equal(&p0[0], &b_coord);
 44    });
 45
 46    // rest of the moves
 47    p0.iter().skip(1).for_each(|m_coord| {
 48        bomb_coords.iter().for_each(|b_coord| {
 49            out |= coordinates_is_equal(m_coord, b_coord);
 50        });
 51    });
 52
 53    out
 54}
 55
 56// Do you recall bomberman? It's an interesting game where the bomberman has to
 57// cross the map without stepping on strategically placed bombs all over the
 58// map. Below we implement a very basic prototype of bomberman with 4 players.
 59//
 60// The map has 256 tiles with bottom left-most tile labelled with coordinates
 61// (0,0) and top right-most tile labelled with coordinates (255, 255). There are
 62// 4 players: Player 0, Player 1, Player 2, Player 3. Player 0's task is to walk
 63// across the map with fixed no. of moves while preventing itself from stepping
 64// on any of the bombs placed on the map by Player 1, 2, and 3.
 65//
 66// The twist is that Player 0's moves and the locations of bombs placed by other
 67// players are encrypted. Player 0 moves across the map in encrypted domain.
 68// Only a boolean output indicating whether player 0 survived after all the
 69// moves or killed itself by stepping onto a bomb is revealed at the end. If
 70// player 0 survives, Player 1, 2, 3 never learn what moves did Player 0 make.
 71// If Player 0 kills itself by stepping onto a bomb, it only learns that bomb
 72// was placed on one of the coordinates it moved to. Moreover, Player 1, 2, 3
 73// never learn locations of each other bombs or whose bomb killed Player 0.
 74fn main() {
 75    set_parameter_set(ParameterSelector::NonInteractiveLTE4Party);
 76
 77    // set application's common reference seed
 78    let mut seed = [0; 32];
 79    thread_rng().fill_bytes(&mut seed);
 80    set_common_reference_seed(seed);
 81
 82    let no_of_parties = 4;
 83
 84    // Client side //
 85
 86    // Players generate client keys
 87    let cks = (0..no_of_parties).map(|_| gen_client_key()).collect_vec();
 88
 89    // Players generate server keys
 90    let server_key_shares = cks
 91        .iter()
 92        .enumerate()
 93        .map(|(index, k)| gen_server_key_share(index, no_of_parties, k))
 94        .collect_vec();
 95
 96    // Player 0 describes its moves as sequence of coordinates on the map
 97    let no_of_moves = 10;
 98    let player_0_moves = (0..no_of_moves)
 99        .map(|_| Coordinates::new(thread_rng().gen::<u8>(), thread_rng().gen()))
100        .collect_vec();
101    // Coordinates of bomb placed by Player 1
102    let player_1_bomb = Coordinates::new(thread_rng().gen::<u8>(), thread_rng().gen());
103    // Coordinates of bomb placed by Player 2
104    let player_2_bomb = Coordinates::new(thread_rng().gen::<u8>(), thread_rng().gen());
105    // Coordinates of bomb placed by Player 3
106    let player_3_bomb = Coordinates::new(thread_rng().gen::<u8>(), thread_rng().gen());
107
108    println!("P0 moves coordinates: {:?}", &player_0_moves);
109    println!("P1 bomb coordinates : {:?}", &player_1_bomb);
110    println!("P2 bomb coordinates : {:?}", &player_2_bomb);
111    println!("P3 bomb coordinates : {:?}", &player_3_bomb);
112
113    // Players encrypt their private inputs
114    let player_0_enc = cks[0].encrypt(
115        player_0_moves
116            .iter()
117            .flat_map(|c| vec![*c.x(), *c.y()])
118            .collect_vec()
119            .as_slice(),
120    );
121    let player_1_enc = cks[1].encrypt(vec![*player_1_bomb.x(), *player_1_bomb.y()].as_slice());
122    let player_2_enc = cks[2].encrypt(vec![*player_2_bomb.x(), *player_2_bomb.y()].as_slice());
123    let player_3_enc = cks[3].encrypt(vec![*player_3_bomb.x(), *player_3_bomb.y()].as_slice());
124
125    // Players upload the encrypted inputs and server key shares to the server
126
127    // Server side //
128
129    let server_key = aggregate_server_key_shares(&server_key_shares);
130    server_key.set_server_key();
131
132    // server parses Player inputs
133    let player_0_moves_enc = {
134        let c = player_0_enc
135            .unseed::<Vec<Vec<u64>>>()
136            .key_switch(0)
137            .extract_all();
138        c.into_iter()
139            .chunks(2)
140            .into_iter()
141            .map(|mut x_y| Coordinates::new(x_y.next().unwrap(), x_y.next().unwrap()))
142            .collect_vec()
143    };
144    let player_1_bomb_enc = {
145        let c = player_1_enc.unseed::<Vec<Vec<u64>>>().key_switch(1);
146        Coordinates::new(c.extract_at(0), c.extract_at(1))
147    };
148    let player_2_bomb_enc = {
149        let c = player_2_enc.unseed::<Vec<Vec<u64>>>().key_switch(2);
150        Coordinates::new(c.extract_at(0), c.extract_at(1))
151    };
152    let player_3_bomb_enc = {
153        let c = player_3_enc.unseed::<Vec<Vec<u64>>>().key_switch(3);
154        Coordinates::new(c.extract_at(0), c.extract_at(1))
155    };
156
157    // Server runs the game
158    let player_0_dead_ct = traverse_map(
159        &player_0_moves_enc,
160        &vec![player_1_bomb_enc, player_2_bomb_enc, player_3_bomb_enc],
161    );
162
163    // Client side //
164
165    // Players generate decryption shares and send them to each other
166    let decryption_shares = cks
167        .iter()
168        .map(|k| k.gen_decryption_share(&player_0_dead_ct))
169        .collect_vec();
170    // Players decrypt to find whether Player 0 survived
171    let player_0_dead = cks[0].aggregate_decryption_shares(&player_0_dead_ct, &decryption_shares);
172
173    if player_0_dead {
174        println!("Oops! Player 0 dead");
175    } else {
176        println!("Wohoo! Player 0 survived");
177    }
178}