1
// Copyright (C) Moondance Labs Ltd.
2
// This file is part of Tanssi.
3

            
4
// Tanssi is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8

            
9
// Tanssi is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13

            
14
// You should have received a copy of the GNU General Public License
15
// along with Tanssi.  If not, see <http://www.gnu.org/licenses/>.
16
use {
17
    jsonrpsee::{core::RpcResult, proc_macros::rpc},
18
    sp_core::H256,
19
};
20

            
21
396
#[rpc(server)]
22
#[jsonrpsee::core::async_trait]
23
pub trait ManualRandomnessApi {
24
    /// Inject randomness
25
    #[method(name = "mock_activateRandomness")]
26
    async fn activate_randomness(&self, seed: Option<H256>) -> RpcResult<()>;
27
    #[method(name = "mock_deactivateRandomness")]
28
    async fn deactivate_randomness(&self) -> RpcResult<()>;
29
}
30

            
31
pub struct ManualRandomness {
32
    pub randomness_message_channel: flume::Sender<(bool, Option<[u8; 32]>)>,
33
}
34

            
35
#[jsonrpsee::core::async_trait]
36
impl ManualRandomnessApiServer for ManualRandomness {
37
4
    async fn activate_randomness(&self, seed: Option<H256>) -> RpcResult<()> {
38
4
        let randomness_message_channel = self.randomness_message_channel.clone();
39
4

            
40
4
        // Push the message to the shared channel where it will be queued up
41
4
        // to be injected in to an upcoming block.
42
4
        randomness_message_channel
43
4
            .send_async((true, seed.map(|x| x.into())))
44
            .await
45
4
            .map_err(|err| internal_err(err.to_string()))?;
46

            
47
4
        Ok(())
48
8
    }
49

            
50
    async fn deactivate_randomness(&self) -> RpcResult<()> {
51
        let randomness_message_channel = self.randomness_message_channel.clone();
52

            
53
        // Push the message to the shared channel where it will be queued up
54
        // to be injected in to an upcoming block.
55
        randomness_message_channel
56
            .send_async((false, None))
57
            .await
58
            .map_err(|err| internal_err(err.to_string()))?;
59

            
60
        Ok(())
61
    }
62
}
63

            
64
// This bit cribbed from frontier.
65
pub fn internal_err<T: AsRef<str>>(message: T) -> jsonrpsee::types::ErrorObjectOwned {
66
    jsonrpsee::types::error::ErrorObject::borrowed(
67
        jsonrpsee::types::error::INTERNAL_ERROR_CODE,
68
        message.as_ref(),
69
        None,
70
    )
71
    .into_owned()
72
}