darkfid/proto/
protocol_tx.rs

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
/* 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 std::sync::Arc;

use log::{debug, error};
use tinyjson::JsonValue;

use darkfi::{
    net::{
        protocol::protocol_generic::{
            ProtocolGenericAction, ProtocolGenericHandler, ProtocolGenericHandlerPtr,
        },
        session::SESSION_DEFAULT,
        P2pPtr,
    },
    rpc::jsonrpc::JsonSubscriber,
    system::ExecutorPtr,
    tx::Transaction,
    util::encoding::base64,
    validator::ValidatorPtr,
    Error, Result,
};
use darkfi_serial::serialize_async;

/// Atomic pointer to the `ProtocolTx` handler.
pub type ProtocolTxHandlerPtr = Arc<ProtocolTxHandler>;

/// Handler managing [`Transaction`] messages, over a generic P2P protocol.
pub struct ProtocolTxHandler {
    /// The generic handler for [`Transaction`] messages.
    handler: ProtocolGenericHandlerPtr<Transaction, Transaction>,
}

impl ProtocolTxHandler {
    /// Initialize a generic prototocol handler for [`Transaction`] messages
    /// and registers it to the provided P2P network, using the default session flag.
    pub async fn init(p2p: &P2pPtr) -> ProtocolTxHandlerPtr {
        debug!(
            target: "darkfid::proto::protocol_tx::init",
            "Adding ProtocolTx to the protocol registry"
        );

        let handler = ProtocolGenericHandler::new(p2p, "ProtocolTx", SESSION_DEFAULT).await;

        Arc::new(Self { handler })
    }

    /// Start the `ProtocolTx` background task.
    pub async fn start(
        &self,
        executor: &ExecutorPtr,
        validator: &ValidatorPtr,
        subscriber: JsonSubscriber,
    ) -> Result<()> {
        debug!(
            target: "darkfid::proto::protocol_tx::start",
            "Starting ProtocolTx handler task..."
        );

        self.handler.task.clone().start(
            handle_receive_tx(self.handler.clone(), validator.clone(), subscriber),
            |res| async move {
                match res {
                    Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
                    Err(e) => error!(target: "darkfid::proto::protocol_tx::start", "Failed starting ProtocolTx handler task: {e}"),
                }
            },
            Error::DetachedTaskStopped,
            executor.clone(),
        );

        debug!(
            target: "darkfid::proto::protocol_tx::start",
            "ProtocolTx handler task started!"
        );

        Ok(())
    }

    /// Stop the `ProtocolTx` background task.
    pub async fn stop(&self) {
        debug!(target: "darkfid::proto::protocol_tx::stop", "Terminating ProtocolTx handler task...");
        self.handler.task.stop().await;
        debug!(target: "darkfid::proto::protocol_tx::stop", "ProtocolTx handler task terminated!");
    }
}

/// Background handler function for ProtocolTx.
async fn handle_receive_tx(
    handler: ProtocolGenericHandlerPtr<Transaction, Transaction>,
    validator: ValidatorPtr,
    subscriber: JsonSubscriber,
) -> Result<()> {
    debug!(target: "darkfid::proto::protocol_tx::handle_receive_tx", "START");
    loop {
        // Wait for a new transaction message
        let (channel, tx) = match handler.receiver.recv().await {
            Ok(r) => r,
            Err(e) => {
                debug!(
                    target: "darkfid::proto::protocol_tx::handle_receive_tx",
                    "recv fail: {e}"
                );
                continue
            }
        };

        // Check if node has finished syncing its blockchain
        if !*validator.synced.read().await {
            debug!(
                target: "darkfid::proto::protocol_tx::handle_receive_tx",
                "Node still syncing blockchain, skipping..."
            );
            handler.send_action(channel, ProtocolGenericAction::Skip).await;
            continue
        }

        // Append transaction
        if let Err(e) = validator.append_tx(&tx, true).await {
            debug!(
                target: "darkfid::proto::protocol_tx::handle_receive_tx",
                "append_tx fail: {e}"
            );
            handler.send_action(channel, ProtocolGenericAction::Skip).await;
            continue
        }

        // Signal handler to broadcast the valid transaction to rest nodes
        handler.send_action(channel, ProtocolGenericAction::Broadcast).await;

        // Notify subscriber
        let encoded_tx = JsonValue::String(base64::encode(&serialize_async(&tx).await));
        subscriber.notify(vec![encoded_tx].into()).await;
    }
}