aboutsummaryrefslogtreecommitdiffstats
path: root/src/handlers.rs
blob: 07986f5d4aaeeba3fbb14b6eafd4a4023e09b5a7 (plain)
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
use blake2::{Blake2s, Digest};
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
/// API handlers, the ends of each filter chain
use log::debug;
use md5::Md5;
use parking_lot::RwLockUpgradableReadGuard;
use serde::{Deserialize, Serialize};
use serde_json;
use serde_json::json;
use std::convert::Infallible;
use std::fs;
use warp::{http::Response, http::StatusCode, reject, reply};

use gradecoin::schema::{
    AuthRequest, Block, Db, MetuId, NakedBlock, PublicKeySignature, Transaction, User,
};

const BEARER: &str = "Bearer ";

/// tha: Transaction Hash, String
/// iat: Issued At, Unix Time, epoch
#[derive(Debug, Serialize, Deserialize)]
pub struct Claims {
    pub tha: String,
    pub iat: usize,
}

/// POST /register
/// Enables a student to introduce themselves to the system
/// Can fail
pub async fn authenticate_user(
    request: AuthRequest,
    db: Db,
) -> Result<impl warp::Reply, warp::Rejection> {
    let given_id = request.student_id.clone();

    if let Some(priv_student_id) = MetuId::new(request.student_id) {
        let userlist = db.users.upgradable_read();

        if userlist.contains_key(&given_id) {
            let res = Response::builder()
                .status(StatusCode::BAD_REQUEST)
                .body("This user is already authenticated");

            Ok(res)
        } else {
            let new_user = User {
                user_id: priv_student_id,
                public_key: request.public_key,
                balance: 0,
            };

            let user_json = serde_json::to_string(&new_user).unwrap();

            fs::write(format!("users/{}.guy", new_user.user_id), user_json).unwrap();

            let mut userlist = RwLockUpgradableReadGuard::upgrade(userlist);
            userlist.insert(given_id, new_user);
            // TODO: signature of the public key, please <11-04-21, yigit> //

            let res = Response::builder()
                .status(StatusCode::CREATED)
                .body("Ready to use Gradecoin");

            Ok(res)
        }
    } else {
        let res = Response::builder()
            .status(StatusCode::BAD_REQUEST)
            .body("This user cannot have a gradecoin account");

        Ok(res)
    }
}

/// GET /transaction
/// Returns JSON array of transactions
/// Cannot fail
pub async fn list_transactions(db: Db) -> Result<impl warp::Reply, Infallible> {
    debug!("list all transactions");
    let mut result = Vec::new();

    let transactions = db.pending_transactions.read();
    // let transactions = transactions.clone().into_iter().collect();

    for (_, value) in transactions.iter() {
        result.push(value)
    }

    Ok(reply::with_status(reply::json(&result), StatusCode::OK))
}

/// GET /block
/// Returns JSON array of blocks
/// Cannot fail
/// Mostly around for debug purposes
pub async fn list_blocks(db: Db) -> Result<impl warp::Reply, Infallible> {
    debug!("list all block");

    let block = db.blockchain.read();

    Ok(reply::with_status(reply::json(&*block), StatusCode::OK))
}

/// POST /transaction
/// Pushes a new transaction for pending transaction pool
/// Can reject the transaction proposal
/// TODO: when is a new transaction rejected <07-04-21, yigit> //
pub async fn propose_transaction(
    new_transaction: Transaction,
    db: Db,
) -> Result<impl warp::Reply, warp::Rejection> {
    debug!("new transaction request {:?}", new_transaction);

    // let mut transactions = db.lock().await;
    let mut transactions = db.pending_transactions.write();

    transactions.insert(new_transaction.source.to_owned(), new_transaction);

    Ok(StatusCode::CREATED)
}

/// POST /block
/// Proposes a new block for the next round
/// Can reject the block
pub async fn propose_block(new_block: Block, db: Db) -> Result<impl warp::Reply, warp::Rejection> {
    debug!("new block request {:?}", new_block);

    // https://blog.logrocket.com/create-an-async-crud-web-service-in-rust-with-warp/ (this has
    // error.rs, error struct, looks very clean)

    let pending_transactions = db.pending_transactions.upgradable_read();
    let blockchain = db.blockchain.upgradable_read();

    // check 1, new_block.transaction_list from pending_transactions pool? <07-04-21, yigit> //
    for transaction_hash in new_block.transaction_list.iter() {
        if !pending_transactions.contains_key(transaction_hash) {
            return Ok(StatusCode::BAD_REQUEST);
        }
    }

    let naked_block = NakedBlock {
        transaction_list: new_block.transaction_list.clone(),
        nonce: new_block.nonce.clone(),
        timestamp: new_block.timestamp.clone(),
    };

    let naked_block_flat = serde_json::to_vec(&naked_block).unwrap();

    let hashvalue = Blake2s::digest(&naked_block_flat);
    let hash_string = format!("{:x}", hashvalue);

    // 6 rightmost bits are zero
    let should_zero = hashvalue[31] as i32 + hashvalue[30] as i32 + hashvalue[29] as i32;

    if should_zero == 0 {
        // one last check to see if block is telling the truth
        if hash_string == new_block.hash {
            let mut blockchain = RwLockUpgradableReadGuard::upgrade(blockchain);

            let block_json = serde_json::to_string(&new_block).unwrap();

            fs::write(
                format!("blocks/{}.block", new_block.timestamp.timestamp()),
                block_json,
            )
            .unwrap();

            *blockchain = new_block;

            let mut pending_transactions = RwLockUpgradableReadGuard::upgrade(pending_transactions);
            pending_transactions.clear();

            Ok(StatusCode::CREATED)
        } else {
            Ok(StatusCode::BAD_REQUEST)
        }
    } else {
        // reject
        Ok(StatusCode::BAD_REQUEST)
    }
}

pub async fn auth_propose_transaction(
    new_transaction: Transaction,
    token: String,
    db: Db,
) -> Result<impl warp::Reply, warp::Rejection> {
    debug!("new transaction request {:?}", new_transaction);
    let raw_jwt = token.trim_start_matches(BEARER).to_owned();

    let decoded = jsonwebtoken::decode::<Claims>(
        &token,
        &DecodingKey::from_rsa_pem(
            db.users
                .read()
                .get(&new_transaction.by)
                .unwrap()
                .public_key
                .as_bytes(),
        )
        .unwrap(),
        // todo@keles: If user is not found return user not found error
        &Validation::new(Algorithm::PS256),
    )
    .unwrap();
    // todo: If user is found but header is not validated, return header not valid

    let hashed_transaction = Md5::digest(&serde_json::to_vec(&new_transaction).unwrap());

    // let mut transactions = db.lock().await;
    if decoded.claims.tha == format!("{:x}", hashed_transaction) {
        let mut transactions = db.pending_transactions.write();

        transactions.insert(new_transaction.source.to_owned(), new_transaction);

        Ok(StatusCode::CREATED)
    } else {
        Ok(StatusCode::BAD_REQUEST)
    }
}