9cc5cd5839258e581887cb3715ca1abf1f71b6ea
[electrum-server.git] / backends / libbitcoin / history.cpp
1 #include <system_error>
2
3 #include <bitcoin/bitcoin.hpp>
4 using namespace libbitcoin;
5
6 #include <boost/python.hpp>
7 namespace python = boost::python;
8
9 #include "/home/genjix/python-bitcoin/src/primitive.h"
10
11 typedef std::function<void (const std::error_code&)> finish_handler;
12
13 namespace ph = std::placeholders;
14
15 class query_history
16   : public std::enable_shared_from_this<query_history>
17 {
18 public:
19     query_history(async_service& service,
20         blockchain_ptr chain, transaction_pool_ptr txpool)
21       : strand_(service.get_service()), chain_(chain),
22         txpool_(txpool), stopped_(false)
23     {
24     }
25
26     void start(const std::string& address, finish_handler handle_finish)
27     {
28         address_.set_encoded(address);
29         handle_finish_ = handle_finish;
30         chain_->fetch_outputs(address_,
31             strand_.wrap(std::bind(&query_history::start_loading,
32                 shared_from_this(), ph::_1, ph::_2)));
33     }
34
35 private:
36     // Not thread-safe
37     void stop()
38     {
39         BITCOIN_ASSERT(stopped_ == false);
40         stopped_ = true;
41     }
42
43     void start_loading(const std::error_code& ec,
44         const message::output_point_list& outpoints)
45     {
46         handle_finish_(ec);
47     }
48
49     io_service::strand strand_;
50
51     blockchain_ptr chain_;
52     transaction_pool_ptr txpool_;
53     bool stopped_;
54
55     payment_address address_;
56     finish_handler handle_finish_;
57 };
58
59 typedef std::shared_ptr<query_history> query_history_ptr;
60
61 void keep_query_alive_proxy(const std::error_code& ec,
62     python::object handle_finish, query_history_ptr history)
63 {
64     pyfunction<const std::error_code&> f(handle_finish);
65     f(ec);
66 }
67
68 void payment_history(async_service_ptr service, blockchain_ptr chain,
69     transaction_pool_ptr txpool, const std::string& address,
70     python::object handle_finish)
71 {
72     query_history_ptr history =
73         std::make_shared<query_history>(*service, chain, txpool);
74     history->start(address,
75         std::bind(keep_query_alive_proxy, ph::_1,
76             handle_finish, history));
77 }
78
79 BOOST_PYTHON_MODULE(_history)
80 {
81     using namespace boost::python;
82     def("payment_history", payment_history);
83 }
84