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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
/* This file is part of DarkFi (https://dark.fi)
 *
 * Copyright (C) 2020-2024 Dyne.org foundation
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

use darkfi_serial::deserialize_async;
use log::{error, warn};
use tinyjson::JsonValue;

use darkfi::{
    rpc::jsonrpc::{
        ErrorCode::{InternalError, InvalidParams},
        JsonError, JsonResponse, JsonResult,
    },
    tx::Transaction,
    util::encoding::base64,
};

use super::Darkfid;
use crate::{server_error, RpcError};

impl Darkfid {
    // RPCAPI:
    // Simulate a network state transition with the given transaction.
    // Returns `true` if the transaction is valid, otherwise, a corresponding
    // error.
    //
    // --> {"jsonrpc": "2.0", "method": "tx.simulate", "params": ["base64encodedTX"], "id": 1}
    // <-- {"jsonrpc": "2.0", "result": true, "id": 1}
    pub async fn tx_simulate(&self, id: u16, params: JsonValue) -> JsonResult {
        let params = params.get::<Vec<JsonValue>>().unwrap();
        if params.len() != 1 || !params[0].is_string() {
            return JsonError::new(InvalidParams, None, id).into()
        }

        if !*self.validator.synced.read().await {
            error!(target: "darkfid::rpc::tx_simulate", "Blockchain is not synced");
            return server_error(RpcError::NotSynced, id, None)
        }

        // Try to deserialize the transaction
        let tx_enc = params[0].get::<String>().unwrap().trim();
        let tx_bytes = match base64::decode(tx_enc) {
            Some(v) => v,
            None => {
                error!(target: "darkfid::rpc::tx_simulate", "Failed decoding base64 transaction");
                return server_error(RpcError::ParseError, id, None)
            }
        };

        let tx: Transaction = match deserialize_async(&tx_bytes).await {
            Ok(v) => v,
            Err(e) => {
                error!(target: "darkfid::rpc::tx_simulate", "Failed deserializing bytes into Transaction: {}", e);
                return server_error(RpcError::ParseError, id, None)
            }
        };

        // Simulate state transition
        let result = self.validator.append_tx(&tx, false).await;
        if result.is_err() {
            error!(
                target: "darkfid::rpc::tx_simulate", "Failed to validate state transition: {}",
                result.err().unwrap()
            );
            return server_error(RpcError::TxSimulationFail, id, None)
        };

        JsonResponse::new(JsonValue::Boolean(true), id).into()
    }

    // RPCAPI:
    // Broadcast a given transaction to the P2P network.
    // The function will first simulate the state transition in order to see
    // if the transaction is actually valid, and in turn it will return an
    // error if this is the case. Otherwise, a transaction ID will be returned.
    //
    // --> {"jsonrpc": "2.0", "method": "tx.broadcast", "params": ["base64encodedTX"], "id": 1}
    // <-- {"jsonrpc": "2.0", "result": "txID...", "id": 1}
    pub async fn tx_broadcast(&self, id: u16, params: JsonValue) -> JsonResult {
        let params = params.get::<Vec<JsonValue>>().unwrap();
        if params.len() != 1 || !params[0].is_string() {
            return JsonError::new(InvalidParams, None, id).into()
        }

        if !*self.validator.synced.read().await {
            error!(target: "darkfid::rpc::tx_broadcast", "Blockchain is not synced");
            return server_error(RpcError::NotSynced, id, None)
        }

        // Try to deserialize the transaction
        let tx_enc = params[0].get::<String>().unwrap().trim();
        let tx_bytes = match base64::decode(tx_enc) {
            Some(v) => v,
            None => {
                error!(target: "darkfid::rpc::tx_broadcast", "Failed decoding base64 transaction");
                return server_error(RpcError::ParseError, id, None)
            }
        };

        let tx: Transaction = match deserialize_async(&tx_bytes).await {
            Ok(v) => v,
            Err(e) => {
                error!(target: "darkfid::rpc::tx_broadcast", "Failed deserializing bytes into Transaction: {}", e);
                return server_error(RpcError::ParseError, id, None)
            }
        };

        // Block production participants can directly perform
        // the state transition check and append to their
        // pending transactions store.
        let error_message = if self.miner {
            "Failed to append transaction to mempool"
        } else {
            "Failed to validate state transition"
        };
        // We'll perform the state transition check here.
        if let Err(e) = self.validator.append_tx(&tx, self.miner).await {
            error!(target: "darkfid::rpc::tx_broadcast", "{}: {}", error_message, e);
            return server_error(RpcError::TxSimulationFail, id, None)
        };

        self.p2p.broadcast(&tx).await;
        if self.p2p.hosts().channels().await.is_empty() {
            warn!(target: "darkfid::rpc::tx_broadcast", "No connected channels to broadcast tx");
        }

        let tx_hash = tx.hash().to_string();
        JsonResponse::new(JsonValue::String(tx_hash), id).into()
    }

    // RPCAPI:
    // Queries the node pending transactions store to retrieve all transactions.
    // Returns a vector of hex-encoded transaction hashes.
    //
    // --> {"jsonrpc": "2.0", "method": "tx.pending", "params": [], "id": 1}
    // <-- {"jsonrpc": "2.0", "result": "[TxHash,...]", "id": 1}
    pub async fn tx_pending(&self, id: u16, params: JsonValue) -> JsonResult {
        let params = params.get::<Vec<JsonValue>>().unwrap();
        if !params.is_empty() {
            return JsonError::new(InvalidParams, None, id).into()
        }

        if !*self.validator.synced.read().await {
            error!(target: "darkfid::rpc::tx_pending", "Blockchain is not synced");
            return server_error(RpcError::NotSynced, id, None)
        }

        let pending_txs = match self.validator.blockchain.get_pending_txs() {
            Ok(v) => v,
            Err(e) => {
                error!(target: "darkfid::rpc::tx_pending", "Failed fetching pending txs: {}", e);
                return JsonError::new(InternalError, None, id).into()
            }
        };

        let pending_txs: Vec<JsonValue> =
            pending_txs.iter().map(|x| JsonValue::String(x.hash().to_string())).collect();

        JsonResponse::new(JsonValue::Array(pending_txs), id).into()
    }

    // RPCAPI:
    // Queries the node pending transactions store to remove all transactions.
    // Returns a vector of hex-encoded transaction hashes.
    //
    // --> {"jsonrpc": "2.0", "method": "tx.clean_pending", "params": [], "id": 1}
    // <-- {"jsonrpc": "2.0", "result": "[TxHash,...]", "id": 1}
    pub async fn tx_clean_pending(&self, id: u16, params: JsonValue) -> JsonResult {
        let params = params.get::<Vec<JsonValue>>().unwrap();
        if !params.is_empty() {
            return JsonError::new(InvalidParams, None, id).into()
        }

        if !*self.validator.synced.read().await {
            error!(target: "darkfid::rpc::tx_clean_pending", "Blockchain is not synced");
            return server_error(RpcError::NotSynced, id, None)
        }

        let pending_txs = match self.validator.blockchain.get_pending_txs() {
            Ok(v) => v,
            Err(e) => {
                error!(target: "darkfid::rpc::tx_clean_pending", "Failed fetching pending txs: {}", e);
                return JsonError::new(InternalError, None, id).into()
            }
        };

        if let Err(e) = self.validator.blockchain.remove_pending_txs(&pending_txs) {
            error!(target: "darkfid::rpc::tx_clean_pending", "Failed fetching pending txs: {}", e);
            return JsonError::new(InternalError, None, id).into()
        };

        let pending_txs: Vec<JsonValue> =
            pending_txs.iter().map(|x| JsonValue::String(x.hash().to_string())).collect();

        JsonResponse::new(JsonValue::Array(pending_txs), id).into()
    }

    // RPCAPI:
    // Compute provided transaction's total gas, against current best fork.
    // Returns the gas value if the transaction is valid, otherwise, a corresponding
    // error.
    //
    // --> {"jsonrpc": "2.0", "method": "tx.calculate_gas", "params": ["base64encodedTX", "include_fee"], "id": 1}
    // <-- {"jsonrpc": "2.0", "result": true, "id": 1}
    pub async fn tx_calculate_gas(&self, id: u16, params: JsonValue) -> JsonResult {
        let params = params.get::<Vec<JsonValue>>().unwrap();
        if params.len() != 2 || !params[0].is_string() || !params[1].is_bool() {
            return JsonError::new(InvalidParams, None, id).into()
        }

        if !*self.validator.synced.read().await {
            error!(target: "darkfid::rpc::tx_calculate_gas", "Blockchain is not synced");
            return server_error(RpcError::NotSynced, id, None)
        }

        // Try to deserialize the transaction
        let tx_enc = params[0].get::<String>().unwrap().trim();
        let tx_bytes = match base64::decode(tx_enc) {
            Some(v) => v,
            None => {
                error!(target: "darkfid::rpc::tx_calculate_gas", "Failed decoding base64 transaction");
                return server_error(RpcError::ParseError, id, None)
            }
        };

        let tx: Transaction = match deserialize_async(&tx_bytes).await {
            Ok(v) => v,
            Err(e) => {
                error!(target: "darkfid::rpc::tx_calculate_gas", "Failed deserializing bytes into Transaction: {}", e);
                return server_error(RpcError::ParseError, id, None)
            }
        };

        // Parse the include fee flag
        let include_fee = params[1].get::<bool>().unwrap();

        // Simulate state transition
        let result = self.validator.calculate_gas(&tx, *include_fee).await;
        if result.is_err() {
            error!(
                target: "darkfid::rpc::tx_calculate_gas", "Failed to validate state transition: {}",
                result.err().unwrap()
            );
            return server_error(RpcError::TxGasCalculationFail, id, None)
        };

        JsonResponse::new(JsonValue::Number(result.unwrap() as f64), id).into()
    }
}