1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
/*
 * Copyright 2018 Bitwise IO, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * -----------------------------------------------------------------------------
 */

mod game;
mod payload;
mod state;

cfg_if! {
    if #[cfg(target_arch = "wasm32")] {
        use sabre_sdk::{ApplyError, TpProcessRequest, TransactionContext, TransactionHandler,};
    } else {
        use sawtooth_sdk::messages::processor::TpProcessRequest;
        use sawtooth_sdk::processor::handler::{ApplyError, TransactionContext, TransactionHandler};
    }
}

use crate::handler::game::Game;
use crate::handler::payload::XoPayload;
use crate::handler::state::{get_xo_prefix, XoState};

pub struct XoTransactionHandler {
    family_name: String,
    family_versions: Vec<String>,
    namespaces: Vec<String>,
}

impl XoTransactionHandler {
    pub fn new() -> XoTransactionHandler {
        XoTransactionHandler {
            family_name: "xo".into(),
            family_versions: vec!["1.0".into()],
            namespaces: vec![get_xo_prefix()],
        }
    }
}

impl TransactionHandler for XoTransactionHandler {
    fn family_name(&self) -> String {
        self.family_name.clone()
    }

    fn family_versions(&self) -> Vec<String> {
        self.family_versions.clone()
    }

    fn namespaces(&self) -> Vec<String> {
        self.namespaces.clone()
    }

    fn apply(
        &self,
        request: &TpProcessRequest,
        context: &mut dyn TransactionContext,
    ) -> Result<(), ApplyError> {
        let signer = request.get_header().get_signer_public_key();

        let payload = XoPayload::new(request.get_payload())?;

        let mut state = XoState::new(context);

        info!(
            "Payload: {} {} {}",
            payload.get_name(),
            payload.get_action(),
            payload.get_space(),
        );

        let game = state.get_game(payload.get_name().as_str())?;

        match payload.get_action().as_str() {
            "delete" => {
                if game.is_none() {
                    return Err(ApplyError::InvalidTransaction(String::from(
                        "Invalid action: game does not exist",
                    )));
                }
                state.delete_game(payload.get_name().as_str())?;
            }
            "create" => {
                if game.is_none() {
                    let game = Game::new(payload.get_name());
                    state.set_game(payload.get_name().as_str(), game)?;
                    info!("Created game: {}", payload.get_name().as_str());
                } else {
                    return Err(ApplyError::InvalidTransaction(String::from(
                        "Invalid action: Game already exists",
                    )));
                }
            }
            "take" => {
                if let Some(mut g) = game {
                    match g.get_state().as_str() {
                        "P1-WIN" | "P2-WIN" | "TIE" => {
                            return Err(ApplyError::InvalidTransaction(String::from(
                                "Invalid action: Game has ended",
                            )));
                        }
                        "P1-NEXT" => {
                            let p1 = g.get_player1();
                            if !p1.is_empty() && p1.as_str() != signer {
                                return Err(ApplyError::InvalidTransaction(String::from(
                                    "Not player 2's turn",
                                )));
                            }
                        }
                        "P2-NEXT" => {
                            let p2 = g.get_player2();
                            if !p2.is_empty() && p2.as_str() != signer {
                                return Err(ApplyError::InvalidTransaction(String::from(
                                    "Not player 1's turn",
                                )));
                            }
                        }
                        _ => {
                            return Err(ApplyError::InvalidTransaction(String::from(
                                "Invalid state",
                            )));
                        }
                    }

                    let board_chars: Vec<char> = g.get_board().chars().collect();
                    if board_chars[payload.get_space() - 1] != '-' {
                        return Err(ApplyError::InvalidTransaction(format!(
                            "Space {} is already taken",
                            payload.get_space()
                        )));
                    }

                    if g.get_player1().is_empty() {
                        g.set_player1(signer);
                    } else if g.get_player2().is_empty() {
                        g.set_player2(signer)
                    }

                    g.mark_space(payload.get_space())?;
                    g.update_state()?;

                    g.display();

                    state.set_game(payload.get_name().as_str(), g)?;
                } else {
                    return Err(ApplyError::InvalidTransaction(String::from(
                        "Invalid action: Take requires an existing game",
                    )));
                }
            }
            other_action => {
                return Err(ApplyError::InvalidTransaction(format!(
                    "Invalid action: '{}'",
                    other_action
                )));
            }
        }

        Ok(())
    }
}

#[cfg(target_arch = "wasm32")]
// Sabre apply must return a bool
pub fn apply(
    request: &TpProcessRequest,
    context: &mut dyn TransactionContext,
) -> Result<bool, ApplyError> {
    let handler = XoTransactionHandler::new();
    match handler.apply(request, context) {
        Ok(_) => Ok(true),
        Err(err) => {
            info!("{}", err);
            Err(err)
        }
    }
}