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
use std::time::Duration;

use lifeline::{Bus, Lifeline, Receiver, Sender, Service, Task};
use tokio::time::sleep;

use client_pangolin::client::PangolinClient;
use client_pangolin::component::PangolinClientComponent;
use client_pangolin::types::runtime_types::darwinia_bridge_ethereum::EthereumRelayHeaderParcel;
use component_state::state::BridgeState;
use lifeline::dyn_bus::DynBus;
use microkv::namespace::NamespaceMicroKV;
use shadow_liketh::component::ShadowComponent;
use shadow_liketh::shadow::Shadow;
use shadow_liketh::types::BridgeName;
use support_common::config::{Config, Names};
use support_lifeline::service::BridgeService;

use crate::bridge::PangolinRopstenBus;
use crate::bridge::PangolinRopstenTask;
use crate::bridge::{Extrinsic, PangolinRopstenConfig, ToExtrinsicsMessage, ToGuardMessage};

#[derive(Debug)]
pub struct GuardService {
    _greet: Lifeline,
}

impl BridgeService for GuardService {}

impl Service for GuardService {
    type Bus = PangolinRopstenBus;
    type Lifeline = color_eyre::Result<Self>;

    fn spawn(bus: &Self::Bus) -> Self::Lifeline {
        // Receiver & Sender
        let mut rx = bus.rx::<ToGuardMessage>()?;
        let state = bus.storage().clone_resource::<BridgeState>()?;
        let microkv = state.microkv_with_namespace(PangolinRopstenTask::name());

        let sender_to_extrinsics = bus.tx::<ToExtrinsicsMessage>()?;

        let _greet = Self::try_task(
            &format!("{}-service-guard", PangolinRopstenTask::name()),
            async move {
                //
                tokio::spawn(async move { start(sender_to_extrinsics, &microkv).await });

                while let Some(recv) = rx.recv().await {
                    match recv {
                        ToGuardMessage::StartGuard => {}
                    }
                }

                Ok(())
            },
        );
        Ok(Self { _greet })
    }
}

async fn start(
    mut sender_to_extrinsics: impl Sender<ToExtrinsicsMessage>,
    microkv: &NamespaceMicroKV,
) {
    while let Err(err) = run(&mut sender_to_extrinsics, microkv).await {
        tracing::error!(target: "pangolin-ropsten", "[pangolin] [guard] guard err {:#?}", err);
        sleep(Duration::from_secs(10)).await;
    }
}

async fn run(
    sender_to_extrinsics: &mut impl Sender<ToExtrinsicsMessage>,
    microkv: &NamespaceMicroKV,
) -> color_eyre::Result<()> {
    tracing::info!(target: "pangolin-ropsten", "SERVICE RESTARTING...");

    let bridge_config: PangolinRopstenConfig = Config::restore(Names::BridgePangolinRopsten)?;

    // Config
    let config_darwinia = bridge_config.darwinia;
    let servce_config = bridge_config.task;

    // Darwinia client & account
    let client = PangolinClientComponent::component(config_darwinia).await?;
    let is_tech_comm_member = client.is_tech_comm_member(None, None).await?;
    if !is_tech_comm_member {
        return Ok(());
    }

    // Shadow client
    let shadow = ShadowComponent::component(
        bridge_config.shadow,
        bridge_config.ethereum,
        bridge_config.web3,
        BridgeName::PangolinRopsten,
    )?;

    tracing::info!(
        target: "pangolin-ropsten",
        "✨ SERVICE STARTED: ETHEREUM <> DARWINIA GUARD"
    );

    loop {
        GuardService::guard(&client, &shadow, sender_to_extrinsics, microkv).await?;
        sleep(Duration::from_secs(servce_config.interval_guard)).await;
    }
}

impl GuardService {
    pub async fn extrinsics(
        client: &PangolinClient,
        shadow: &Shadow,
    ) -> color_eyre::Result<Vec<Extrinsic>> {
        tracing::trace!(
            target: "pangolin-ropsten",
            "[pangolin] [guard] Checking pending headers..."
        );

        let mut extrinsics = Vec::new();

        let last_confirmed = client.ethereum().last_confirmed().await?;
        let pending_headers = client
            .runtime()
            .storage()
            .ethereum_relay()
            .pending_relay_header_parcels(None)
            .await?;

        if !pending_headers.is_empty() {
            tracing::trace!(
                target: "pangolin-ropsten",
                "[pangolin] [guard] pending headers: {:?}",
                pending_headers
                    .clone()
                    .iter()
                    .map(|p| p.1.header.number.to_string())
                    .collect::<Vec<_>>()
                    .join(", ")
            );
        }
        for pending in pending_headers {
            let pending_parcel = pending.1;
            let voting_state = pending.2;
            let pending_block_number: u64 = pending_parcel.header.number;

            // high than last_confirmed(https://github.com/darwinia-network/bridger/issues/33),
            // and,
            // have not voted
            if pending_block_number <= last_confirmed {
                continue;
            }
            let real_account = client.account().real_account();
            let has_voted = voting_state.ayes.contains(real_account)
                || voting_state.nays.contains(real_account);
            if has_voted {
                continue;
            }

            match shadow.parcel(pending_block_number).await {
                Ok(parcel_from_shadow) => {
                    let parcel_from_shadow: EthereumRelayHeaderParcel =
                        parcel_from_shadow.try_into()?;
                    let ex = if is_same_as(&pending_parcel, &parcel_from_shadow) {
                        Extrinsic::GuardVote(pending_block_number, true)
                    } else {
                        Extrinsic::GuardVote(pending_block_number, false)
                    };
                    extrinsics.push(ex);
                }
                Err(err) => {
                    // todo: the ethereum component not return color error
                    // if let Some(BizError::BlankEthereumMmrRoot(block, msg)) =
                    //     err.downcast_ref::<BizError>()
                    // {
                    //     tracing::warn!(
                    //         target: "pangolin-ropsten",
                    //         "[pangolin] [guard] The parcel of ethereum block {} from Shadow service is blank, the err msg is {}",
                    //         block,
                    //         msg
                    //     );
                    //     return Ok(extrinsics);
                    // }
                    return Err(err.into());
                }
            }
        }

        Ok(extrinsics)
    }

    async fn guard(
        client: &PangolinClient,
        shadow: &Shadow,
        sender_to_extrinsics: &mut impl Sender<ToExtrinsicsMessage>,
        microkv: &NamespaceMicroKV,
    ) -> color_eyre::Result<()> {
        let extrinsics = Self::extrinsics(client, shadow).await?;

        if extrinsics.is_empty() {
            return Ok(());
        }

        let max_block = *extrinsics
            .iter()
            .map(|ex| {
                if let Extrinsic::GuardVote(block_num, _) = ex {
                    block_num
                } else {
                    &0u64
                }
            })
            .max()
            .unwrap();

        let latest: u64 = microkv
            .get_as_unwrap("latest_guard_vote_block_num")
            .unwrap_or(0u64);
        for extrinsic in extrinsics {
            if let Extrinsic::GuardVote(block_num, _) = extrinsic {
                if block_num > latest {
                    let message = ToExtrinsicsMessage::Extrinsic(extrinsic);
                    sender_to_extrinsics.send(message).await?;
                } else {
                    tracing::info!(
                        target: "pangolin-ropsten",
                        "[pangolin] [guard] Skip guard vote for block: {}",
                        &block_num
                    );
                }
            }
        }
        if max_block > latest {
            microkv.put("latest_guard_vote_block_num", &max_block)?;
        }

        Ok(())
    }
}

fn is_same_as(a: &EthereumRelayHeaderParcel, b: &EthereumRelayHeaderParcel) -> bool {
    a.header.hash == b.header.hash && a.parent_mmr_root == b.parent_mmr_root
}