summaryrefslogtreecommitdiff
path: root/src/ui.rs
blob: df181f5ae4b46a0853e9ff928cd29879a4e381fd (plain)
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
use std::sync::{Arc, Weak};

use bitcoin::{
    blocks::BlockChain,
    client::Client,
    network::{Network, Request},
    transaction::Transaction,
};
use tokio::sync::Mutex;

pub struct Ui {
    network: Weak<Mutex<Network>>,
    me: Client,
}

impl Ui {
    pub fn new(network: Weak<Mutex<Network>>, me: Client) -> Self {
        Self {
            network,
            me,
        }
    }

    // TODO: typed command and result propagation
    pub async fn cmd(&mut self, cmd: &str) -> Option<Request> {
        let cmd: Vec<&str> = cmd
            .split_whitespace()
            .collect();
        if cmd[0] == "trans" {
            let trans = Transaction::new(
                self.me,
                Client::new(
                    cmd[1]
                        .parse()
                        .unwrap(),
                ),
                cmd[2]
                    .parse()
                    .unwrap(),
            );
            return Some(Request::Block(
                self.network
                    .upgrade()
                    .unwrap()
                    .lock()
                    .await
                    .get_blockchain()
                    .lock()
                    .await
                    .new_block(trans),
            ));
        }

        if cmd[0] == "bc" {
            println!(
                "{:#?}",
                self.network
                    .upgrade()
                    .unwrap()
                    .lock()
                    .await
                    .get_blockchain()
                    .lock()
                    .await
            );
        }

        if cmd[0] == "peer" {
            if cmd[1] == "add" {
                Network::try_peer(
                    self.network
                        .clone(),
                    cmd[2],
                )
                .await;
            }
        }

        if cmd[0] == "fetch" {
            self.network
                .upgrade()
                .unwrap()
                .lock()
                .await
                .get_idb();
        }

        None
    }
}