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 jsonrpsee::{core::RpcResult, proc_macros::rpc};
17
use sp_core::H256;
18

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

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

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

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

            
45
4
        Ok(())
46
8
    }
47

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

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

            
58
        Ok(())
59
    }
60
}
61

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