]> git.bitcoin.ninja Git - rust-lightning/blob - lightning-c-bindings/demo.cpp
Update C++ bindings demo to use `ChannelManager` de/serialization
[rust-lightning] / lightning-c-bindings / demo.cpp
1 extern "C" {
2 #include "include/rust_types.h"
3 #include "include/lightning.h"
4 }
5 #include "include/lightningpp.hpp"
6
7 #include <assert.h>
8 #include <stdio.h>
9 #include <sys/socket.h>
10 #include <unistd.h>
11
12 #include <atomic>
13 #include <chrono>
14 #include <functional>
15 #include <thread>
16 #include <mutex>
17 #include <vector>
18
19 const uint8_t valid_node_announcement[] = {
20         0x94, 0xe4, 0xf5, 0x61, 0x41, 0x24, 0x7d, 0x90, 0x23, 0xa0, 0xc8, 0x34, 0x8c, 0xc4, 0xca, 0x51,
21         0xd8, 0x17, 0x59, 0xff, 0x7d, 0xac, 0x8c, 0x9b, 0x63, 0x29, 0x1c, 0xe6, 0x12, 0x12, 0x93, 0xbd,
22         0x66, 0x4d, 0x6b, 0x9c, 0xfb, 0x35, 0xda, 0x16, 0x06, 0x3d, 0xf0, 0x8f, 0x8a, 0x39, 0x99, 0xa2,
23         0xf2, 0x5d, 0x12, 0x0f, 0x2b, 0x42, 0x1b, 0x8b, 0x9a, 0xfe, 0x33, 0x0c, 0xeb, 0x33, 0x5e, 0x52,
24         0xee, 0x99, 0xa1, 0x07, 0x06, 0xed, 0xf8, 0x48, 0x7a, 0xc6, 0xe5, 0xf5, 0x5e, 0x01, 0x3a, 0x41,
25         0x2f, 0x18, 0x94, 0x8a, 0x3b, 0x0a, 0x52, 0x3f, 0xbf, 0x61, 0xa9, 0xc5, 0x4f, 0x70, 0xee, 0xb8,
26         0x79, 0x23, 0xbb, 0x1a, 0x44, 0x7d, 0x91, 0xe6, 0x2a, 0xbc, 0xa1, 0x07, 0xbc, 0x65, 0x3b, 0x02,
27         0xd9, 0x1d, 0xb2, 0xf2, 0x3a, 0xcb, 0x75, 0x79, 0xc6, 0x66, 0xd8, 0xc1, 0x71, 0x29, 0xdf, 0x04,
28         0x60, 0xf4, 0xbf, 0x07, 0x7b, 0xb9, 0xc2, 0x11, 0x94, 0x6a, 0x28, 0xc2, 0xdd, 0xd8, 0x7b, 0x44,
29         0x8f, 0x08, 0xe3, 0xc8, 0xd8, 0xf4, 0x81, 0xb0, 0x9f, 0x94, 0xcb, 0xc8, 0xc1, 0x3c, 0xc2, 0x6e,
30         0x31, 0x26, 0xfc, 0x33, 0x16, 0x3b, 0xe0, 0xde, 0xa1, 0x16, 0x21, 0x9f, 0x89, 0xdd, 0x97, 0xa4,
31         0x41, 0xf2, 0x9f, 0x19, 0xb1, 0xae, 0x82, 0xf7, 0x85, 0x9a, 0xb7, 0x8f, 0xb7, 0x52, 0x7a, 0x72,
32         0xf1, 0x5e, 0x89, 0xe1, 0x8a, 0xcd, 0x40, 0xb5, 0x8e, 0xc3, 0xca, 0x42, 0x76, 0xa3, 0x6e, 0x1b,
33         0xf4, 0x87, 0x35, 0x30, 0x58, 0x43, 0x04, 0xd9, 0x2c, 0x50, 0x54, 0x55, 0x47, 0x6f, 0x70, 0x9b,
34         0x42, 0x1f, 0x91, 0xfc, 0xa1, 0xdb, 0x72, 0x53, 0x96, 0xc8, 0xe5, 0xcd, 0x0e, 0xcb, 0xa0, 0xfe,
35         0x6b, 0x08, 0x77, 0x48, 0xb7, 0xad, 0x4a, 0x69, 0x7c, 0xdc, 0xd8, 0x04, 0x28, 0x35, 0x9b, 0x73,
36         0x00, 0x00, 0x43, 0x49, 0x7f, 0xd7, 0xf8, 0x26, 0x95, 0x71, 0x08, 0xf4, 0xa3, 0x0f, 0xd9, 0xce,
37         0xc3, 0xae, 0xba, 0x79, 0x97, 0x20, 0x84, 0xe9, 0x0e, 0xad, 0x01, 0xea, 0x33, 0x09, 0x00, 0x00,
38         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x5b, 0xe5, 0xe9, 0x47, 0x82,
39         0x09, 0x67, 0x4a, 0x96, 0xe6, 0x0f, 0x1f, 0x03, 0x7f, 0x61, 0x76, 0x54, 0x0f, 0xd0, 0x01, 0xfa,
40         0x1d, 0x64, 0x69, 0x47, 0x70, 0xc5, 0x6a, 0x77, 0x09, 0xc4, 0x2c, 0x03, 0x5c, 0x4e, 0x0d, 0xec,
41         0x72, 0x15, 0xe2, 0x68, 0x33, 0x93, 0x87, 0x30, 0xe5, 0xe5, 0x05, 0xaa, 0x62, 0x50, 0x4d, 0xa8,
42         0x5b, 0xa5, 0x71, 0x06, 0xa4, 0x6b, 0x5a, 0x24, 0x04, 0xfc, 0x9d, 0x8e, 0x02, 0xba, 0x72, 0xa6,
43         0xe8, 0xba, 0x53, 0xe8, 0xb9, 0x71, 0xad, 0x0c, 0x98, 0x23, 0x96, 0x8a, 0xef, 0x4d, 0x78, 0xce,
44         0x8a, 0xf2, 0x55, 0xab, 0x43, 0xdf, 0xf8, 0x30, 0x03, 0xc9, 0x02, 0xfb, 0x8d, 0x02, 0x16, 0x34,
45         0x5b, 0xf8, 0x31, 0x16, 0x4a, 0x03, 0x75, 0x8e, 0xae, 0xa5, 0xe8, 0xb6, 0x6f, 0xee, 0x2b, 0xe7,
46         0x71, 0x0b, 0x8f, 0x19, 0x0e, 0xe8, 0x80, 0x24, 0x90, 0x32, 0xa2, 0x9e, 0xd6, 0x6e
47 };
48
49 // A simple block containing only one transaction (which is the channel-open transaction for the
50 // channel we'll create). This was originally created by printing additional data in a simple
51 // rust-lightning unit test.
52 const uint8_t channel_open_header[80] = {
53         0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
54         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
55         0x00, 0x00, 0x00, 0x00, 0xa2, 0x47, 0xd2, 0xf8, 0xd4, 0xe0, 0x6a, 0x3f, 0xf9, 0x7a, 0x9a, 0x34,
56         0xbb, 0xa9, 0x96, 0xde, 0x63, 0x84, 0x5a, 0xce, 0xcf, 0x98, 0xb8, 0xbb, 0x75, 0x4c, 0x4f, 0x7d,
57         0xee, 0x4c, 0xa9, 0x5f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
58 };
59
60 const uint8_t channel_open_tx[] = {
61         0x02, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
62         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
63         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
64         0x01, 0x40, 0x9c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x22, 0x00, 0x20, 0x20, 0x12, 0x70, 0x44,
65         0x41, 0x40, 0xaf, 0xc5, 0x72, 0x97, 0xc8, 0x69, 0xba, 0x04, 0xdb, 0x28, 0x7b, 0xd7, 0x32, 0x07,
66         0x33, 0x3a, 0x4a, 0xc2, 0xc5, 0x56, 0x06, 0x05, 0x65, 0xd7, 0xa8, 0xcf, 0x01, 0x00, 0x00, 0x00,
67         0x00, 0x00
68 };
69
70 // The first transaction in the block is header (80 bytes) + transaction count (1 byte) into the block data.
71 const uint8_t channel_open_txid[] = {
72         0x5f, 0xa9, 0x4c, 0xee, 0x7d, 0x4f, 0x4c, 0x75, 0xbb, 0xb8, 0x98, 0xcf, 0xce, 0x5a, 0x84, 0x63,
73         0xde, 0x96, 0xa9, 0xbb, 0x34, 0x9a, 0x7a, 0xf9, 0x3f, 0x6a, 0xe0, 0xd4, 0xf8, 0xd2, 0x47, 0xa2
74 };
75
76 // Two blocks built on top of channel_open_block:
77 const uint8_t header_1[80] = {
78         0x01, 0x00, 0x00, 0x00, 0x65, 0x8e, 0xf1, 0x90, 0x88, 0xfa, 0x13, 0x9c, 0x6a, 0xea, 0xf7, 0xc1,
79         0x5a, 0xdd, 0x52, 0x4d, 0x3c, 0x48, 0x03, 0xb3, 0x9b, 0x25, 0x4f, 0x02, 0x79, 0x05, 0x90, 0xe0,
80         0xc4, 0x8d, 0xa0, 0x62, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
81         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
82         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
83 };
84 const uint8_t header_2[80] = {
85         0x01, 0x00, 0x00, 0x00, 0xf2, 0x08, 0x87, 0x51, 0xcb, 0xb1, 0x1a, 0x51, 0x76, 0x01, 0x6c, 0x5d,
86         0x76, 0x26, 0x54, 0x6f, 0xd9, 0xbd, 0xa6, 0xa5, 0xe9, 0x4b, 0x21, 0x6e, 0xda, 0xa3, 0x64, 0x23,
87         0xcd, 0xf1, 0xe2, 0xe2, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
88         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
89         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
90 };
91
92 const LDKThirtyTwoBytes payment_preimage_1 = {
93         .data = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1 }
94 };
95 const LDKThirtyTwoBytes payment_hash_1 = {
96         .data = {
97                 0xdc, 0xb1, 0xac, 0x4a, 0x5d, 0xe3, 0x70, 0xca, 0xd0, 0x91, 0xc1, 0x3f, 0x13, 0xae, 0xe2, 0xf9,
98                 0x36, 0xc2, 0x78, 0xfa, 0x05, 0xd2, 0x64, 0x65, 0x3c, 0x0c, 0x13, 0x21, 0x85, 0x2a, 0x35, 0xe8
99         }
100 };
101
102 const LDKThirtyTwoBytes genesis_hash = { // We don't care particularly if this is "right"
103         .data = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1 }
104 };
105
106 void print_log(const void *this_arg, const char *record) {
107         printf("%p - %s\n", this_arg, record);
108 }
109
110 uint32_t get_fee(const void *this_arg, LDKConfirmationTarget target) {
111         if (target == LDKConfirmationTarget_Background) {
112                 return 253;
113         } else {
114                 return 507;
115         }
116         // Note that we don't call _free() on target, but that's OK, its unitary
117 }
118 // We use the same fee estimator globally:
119 const LDKFeeEstimator fee_est {
120         .this_arg = NULL,
121         .get_est_sat_per_1000_weight = get_fee,
122         .free = NULL,
123 };
124
125 static std::atomic_int num_txs_broadcasted(0);
126 void broadcast_tx(const void *this_arg, LDKTransaction tx) {
127         num_txs_broadcasted += 1;
128         //TODO
129         Transaction_free(tx);
130 }
131
132 struct NodeMonitors {
133         std::mutex mut;
134         std::vector<std::pair<LDK::OutPoint, LDK::ChannelMonitor>> mons;
135         LDKLogger* logger;
136
137         void ConnectBlock(const uint8_t (*header)[80], uint32_t height, LDKCVec_C2Tuple_usizeTransactionZZ tx_data, LDKBroadcasterInterface broadcast, LDKFeeEstimator fee_est) {
138                 std::unique_lock<std::mutex> l(mut);
139                 for (auto& mon : mons) {
140                         LDK::CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ res = ChannelMonitor_block_connected(&mon.second, &header_2, tx_data, height, broadcast, fee_est, *logger);
141                 }
142         }
143 };
144
145 LDKCResult_NoneChannelMonitorUpdateErrZ add_channel_monitor(const void *this_arg, LDKOutPoint funding_txo_arg, LDKChannelMonitor monitor_arg) {
146         // First bind the args to C++ objects so they auto-free
147         LDK::ChannelMonitor mon(std::move(monitor_arg));
148         LDK::OutPoint funding_txo(std::move(funding_txo_arg));
149
150         NodeMonitors* arg = (NodeMonitors*) this_arg;
151         std::unique_lock<std::mutex> l(arg->mut);
152
153         arg->mons.push_back(std::make_pair(std::move(funding_txo), std::move(mon)));
154         return CResult_NoneChannelMonitorUpdateErrZ_ok();
155 }
156 static std::atomic_int mons_updated(0);
157 LDKCResult_NoneChannelMonitorUpdateErrZ update_channel_monitor(const void *this_arg, LDKOutPoint funding_txo_arg, LDKChannelMonitorUpdate monitor_arg) {
158         // First bind the args to C++ objects so they auto-free
159         LDK::ChannelMonitorUpdate update(std::move(monitor_arg));
160         LDK::OutPoint funding_txo(std::move(funding_txo_arg));
161
162         NodeMonitors* arg = (NodeMonitors*) this_arg;
163         std::unique_lock<std::mutex> l(arg->mut);
164
165         bool updated = false;
166         for (auto& mon : arg->mons) {
167                 if (OutPoint_get_index(&mon.first) == OutPoint_get_index(&funding_txo) &&
168                                 !memcmp(OutPoint_get_txid(&mon.first), OutPoint_get_txid(&funding_txo), 32)) {
169                         updated = true;
170                         LDKBroadcasterInterface broadcaster = {
171                                 .broadcast_transaction = broadcast_tx,
172                         };
173                         LDK::CResult_NoneMonitorUpdateErrorZ res = ChannelMonitor_update_monitor(&mon.second, &update, &broadcaster, &fee_est, arg->logger);
174                         assert(res->result_ok);
175                 }
176         }
177         assert(updated);
178
179         mons_updated += 1;
180         return CResult_NoneChannelMonitorUpdateErrZ_ok();
181 }
182 LDKCVec_MonitorEventZ monitors_pending_monitor_events(const void *this_arg) {
183         NodeMonitors* arg = (NodeMonitors*) this_arg;
184         std::unique_lock<std::mutex> l(arg->mut);
185
186         if (arg->mons.size() == 0) {
187                 return LDKCVec_MonitorEventZ {
188                         .data = NULL,
189                         .datalen = 0,
190                 };
191         } else {
192                 // We only ever actually have one channel per node, plus concatenating two
193                 // Rust Vecs to each other from C++ will require a bit of effort.
194                 assert(arg->mons.size() == 1);
195                 return ChannelMonitor_get_and_clear_pending_monitor_events(&arg->mons[0].second);
196         }
197 }
198
199 uintptr_t sock_send_data(void *this_arg, LDKu8slice data, bool resume_read) {
200         return write((int)((long)this_arg), data.data, data.datalen);
201 }
202 void sock_disconnect_socket(void *this_arg) {
203         close((int)((long)this_arg));
204 }
205 bool sock_eq(const void *this_arg, const LDKSocketDescriptor *other_arg) {
206         return this_arg == other_arg->this_arg;
207 }
208 uint64_t sock_hash(const void *this_arg) {
209         return (uint64_t)this_arg;
210 }
211 void sock_read_data_thread(int rdfd, LDKSocketDescriptor *peer_descriptor, LDKPeerManager *pm) {
212         unsigned char buf[1024];
213         LDKu8slice data;
214         data.data = buf;
215         ssize_t readlen = 0;
216         while ((readlen = read(rdfd, buf, 1024)) > 0) {
217                 data.datalen = readlen;
218                 LDK::CResult_boolPeerHandleErrorZ res = PeerManager_read_event(&*pm, peer_descriptor, data);
219                 if (!res->result_ok) {
220                         peer_descriptor->disconnect_socket(peer_descriptor->this_arg);
221                         return;
222                 }
223                 PeerManager_process_events(pm);
224         }
225         PeerManager_socket_disconnected(&*pm, peer_descriptor);
226 }
227
228 class PeersConnection {
229         int pipefds_1_to_2[2];
230         int pipefds_2_to_1[2];
231         std::thread t1, t2;
232         LDKSocketDescriptor sock1, sock2;
233
234 public:
235         PeersConnection(LDK::ChannelManager& cm1, LDK::ChannelManager& cm2, LDK::PeerManager& net1, LDK::PeerManager& net2) {
236                 assert(!pipe(pipefds_1_to_2));
237                 assert(!pipe(pipefds_2_to_1));
238
239                 sock1 = LDKSocketDescriptor {
240                         .this_arg = (void*)(long)pipefds_1_to_2[1],
241                         .send_data = sock_send_data,
242                         .disconnect_socket = sock_disconnect_socket,
243                         .eq = sock_eq,
244                         .hash = sock_hash,
245                         .clone = NULL,
246                         .free = NULL,
247                 };
248
249                 sock2 = LDKSocketDescriptor {
250                         .this_arg = (void*)(long)pipefds_2_to_1[1],
251                         .send_data = sock_send_data,
252                         .disconnect_socket = sock_disconnect_socket,
253                         .eq = sock_eq,
254                         .hash = sock_hash,
255                         .clone = NULL,
256                         .free = NULL,
257                 };
258
259                 t1 = std::thread(&sock_read_data_thread, pipefds_2_to_1[0], &sock1, &net1);
260                 t2 = std::thread(&sock_read_data_thread, pipefds_1_to_2[0], &sock2, &net2);
261
262                 // Note that we have to bind the result to a C++ class to make sure it gets free'd
263                 LDK::CResult_CVec_u8ZPeerHandleErrorZ con_res = PeerManager_new_outbound_connection(&net1, ChannelManager_get_our_node_id(&cm2), sock1);
264                 assert(con_res->result_ok);
265                 LDK::CResult_NonePeerHandleErrorZ con_res2 = PeerManager_new_inbound_connection(&net2, sock2);
266                 assert(con_res2->result_ok);
267
268                 auto writelen = write(pipefds_1_to_2[1], con_res->contents.result->data, con_res->contents.result->datalen);
269                 assert(writelen > 0 && uint64_t(writelen) == con_res->contents.result->datalen);
270
271                 while (true) {
272                         // Wait for the initial handshakes to complete...
273                         LDK::CVec_PublicKeyZ peers_1 = PeerManager_get_peer_node_ids(&net1);
274                         LDK::CVec_PublicKeyZ peers_2 = PeerManager_get_peer_node_ids(&net2);
275                         if (peers_1->datalen == 1 && peers_2->datalen ==1) { break; }
276                         std::this_thread::yield();
277                 }
278         }
279
280         void stop() {
281                 close(pipefds_1_to_2[0]);
282                 close(pipefds_2_to_1[0]);
283                 close(pipefds_1_to_2[1]);
284                 close(pipefds_2_to_1[1]);
285                 t1.join();
286                 t2.join();
287         }
288 };
289
290 int main() {
291         LDKPublicKey null_pk;
292         memset(&null_pk, 0, sizeof(null_pk));
293
294         LDKThirtyTwoBytes random_bytes;
295
296         LDKNetwork network = LDKNetwork_Testnet;
297
298         // Trait implementations:
299         LDKBroadcasterInterface broadcast {
300                 .this_arg = NULL,
301                 .broadcast_transaction = broadcast_tx,
302                 .free = NULL,
303         };
304
305         // Instantiate classes for the nodes that don't get reloaded on a ser-des reload
306         LDKLogger logger1 {
307                 .this_arg = (void*)1,
308                 .log = print_log,
309                 .free = NULL,
310         };
311
312         NodeMonitors mons1;
313         mons1.logger = &logger1;
314         LDKWatch mon1 {
315                 .this_arg = &mons1,
316                 .watch_channel = add_channel_monitor,
317                 .update_channel = update_channel_monitor,
318                 .release_pending_monitor_events = monitors_pending_monitor_events,
319                 .free = NULL,
320         };
321
322         LDK::NetGraphMsgHandler net_graph1 = NetGraphMsgHandler_new(genesis_hash, NULL, logger1);
323         LDKSecretKey node_secret1;
324
325         LDKLogger logger2 {
326                 .this_arg = (void*)2,
327                 .log = print_log,
328                 .free = NULL,
329         };
330
331         NodeMonitors mons2;
332         mons2.logger = &logger2;
333         LDKWatch mon2 {
334                 .this_arg = &mons2,
335                 .watch_channel = add_channel_monitor,
336                 .update_channel = update_channel_monitor,
337                 .release_pending_monitor_events = monitors_pending_monitor_events,
338                 .free = NULL,
339         };
340
341         LDK::NetGraphMsgHandler net_graph2 = NetGraphMsgHandler_new(genesis_hash, NULL, logger2);
342         LDKSecretKey node_secret2;
343
344         LDK::CVec_u8Z cm1_ser = LDKCVec_u8Z {}; // ChannelManager 1 serialization at the end of the ser-des scope
345         LDK::CVec_u8Z cm2_ser = LDKCVec_u8Z {}; // ChannelManager 2 serialization at the end of the ser-des scope
346
347         { // Scope for the ser-des reload
348                 // Instantiate classes for node 1:
349                 uint8_t node_seed[32];
350                 memset(&node_seed, 0, 32);
351                 LDK::KeysManager keys1 = KeysManager_new(&node_seed, network, 0, 0);
352                 LDK::KeysInterface keys_source1 = KeysManager_as_KeysInterface(&keys1);
353                 node_secret1 = keys_source1->get_node_secret(keys_source1->this_arg);
354
355                 LDK::ChannelManager cm1 = ChannelManager_new(network, fee_est, mon1, broadcast, logger1, KeysManager_as_KeysInterface(&keys1), UserConfig_default(), 0);
356
357                 LDK::CVec_ChannelDetailsZ channels = ChannelManager_list_channels(&cm1);
358                 assert(channels->datalen == 0);
359
360                 LDK::MessageHandler msg_handler1 = MessageHandler_new(ChannelManager_as_ChannelMessageHandler(&cm1), NetGraphMsgHandler_as_RoutingMessageHandler(&net_graph1));
361
362                 random_bytes = keys_source1->get_secure_random_bytes(keys_source1->this_arg);
363                 LDK::PeerManager net1 = PeerManager_new(std::move(msg_handler1), node_secret1, &random_bytes.data, logger1);
364
365                 // Demo getting a channel key and check that its returning real pubkeys:
366                 LDK::ChannelKeys chan_keys1 = keys_source1->get_channel_keys(keys_source1->this_arg, false, 42);
367                 chan_keys1->set_pubkeys(&chan_keys1); // Make sure pubkeys is defined
368                 LDKPublicKey payment_point = ChannelPublicKeys_get_payment_point(&chan_keys1->pubkeys);
369                 assert(memcmp(&payment_point, &null_pk, sizeof(null_pk)));
370
371                 // Instantiate classes for node 2:
372                 memset(&node_seed, 1, 32);
373                 LDK::KeysManager keys2 = KeysManager_new(&node_seed, network, 0, 0);
374                 LDK::KeysInterface keys_source2 = KeysManager_as_KeysInterface(&keys2);
375                 node_secret2 = keys_source2->get_node_secret(keys_source2->this_arg);
376
377                 LDK::ChannelHandshakeConfig handshake_config2 = ChannelHandshakeConfig_default();
378                 ChannelHandshakeConfig_set_minimum_depth(&handshake_config2, 2);
379                 LDK::UserConfig config2 = UserConfig_default();
380                 UserConfig_set_own_channel_config(&config2, std::move(handshake_config2));
381
382                 LDK::ChannelManager cm2 = ChannelManager_new(network, fee_est, mon2, broadcast, logger2, KeysManager_as_KeysInterface(&keys2), std::move(config2), 0);
383
384                 LDK::CVec_ChannelDetailsZ channels2 = ChannelManager_list_channels(&cm2);
385                 assert(channels2->datalen == 0);
386
387                 LDK::RoutingMessageHandler net_msgs2 = NetGraphMsgHandler_as_RoutingMessageHandler(&net_graph2);
388                 LDK::ChannelAnnouncement chan_ann = ChannelAnnouncement_read(LDKu8slice { .data = valid_node_announcement, .datalen = sizeof(valid_node_announcement) });
389                 LDK::CResult_boolLightningErrorZ ann_res = net_msgs2->handle_channel_announcement(net_msgs2->this_arg, &chan_ann);
390                 assert(ann_res->result_ok);
391
392                 LDK::MessageHandler msg_handler2 = MessageHandler_new(ChannelManager_as_ChannelMessageHandler(&cm2), std::move(net_msgs2));
393
394                 random_bytes = keys_source2->get_secure_random_bytes(keys_source2->this_arg);
395                 LDK::PeerManager net2 = PeerManager_new(std::move(msg_handler2), node_secret2, &random_bytes.data, logger2);
396
397                 // Open a connection!
398                 PeersConnection conn(cm1, cm2, net1, net2);
399
400                 // Note that we have to bind the result to a C++ class to make sure it gets free'd
401                 LDK::CResult_NoneAPIErrorZ res = ChannelManager_create_channel(&cm1, ChannelManager_get_our_node_id(&cm2), 40000, 1000, 42, UserConfig_default());
402                 assert(res->result_ok);
403                 PeerManager_process_events(&net1);
404
405                 LDK::CVec_ChannelDetailsZ new_channels = ChannelManager_list_channels(&cm1);
406                 assert(new_channels->datalen == 1);
407                 LDKPublicKey chan_open_pk = ChannelDetails_get_remote_network_id(&new_channels->data[0]);
408                 assert(!memcmp(chan_open_pk.compressed_form, ChannelManager_get_our_node_id(&cm2).compressed_form, 33));
409
410                 while (true) {
411                         LDK::CVec_ChannelDetailsZ new_channels_2 = ChannelManager_list_channels(&cm2);
412                         if (new_channels_2->datalen == 1) {
413                                 // Sample getting our counterparty's init features (which used to be hard to do without a memory leak):
414                                 const LDK::InitFeatures init_feats = ChannelDetails_get_counterparty_features(&new_channels_2->data[0]);
415                                 assert(init_feats->inner != NULL);
416                                 break;
417                         }
418                         std::this_thread::yield();
419                 }
420
421                 LDKEventsProvider ev1 = ChannelManager_as_EventsProvider(&cm1);
422                 while (true) {
423                         LDK::CVec_EventZ events = ev1.get_and_clear_pending_events(ev1.this_arg);
424                         if (events->datalen == 1) {
425                                 assert(events->data[0].tag == LDKEvent_FundingGenerationReady);
426                                 assert(events->data[0].funding_generation_ready.user_channel_id == 42);
427                                 assert(events->data[0].funding_generation_ready.channel_value_satoshis == 40000);
428                                 assert(events->data[0].funding_generation_ready.output_script.datalen == 34);
429                                 assert(!memcmp(events->data[0].funding_generation_ready.output_script.data, channel_open_tx + 58, 34));
430                                 LDKThirtyTwoBytes txid;
431                                 for (int i = 0; i < 32; i++) { txid.data[i] = channel_open_txid[31-i]; }
432                                 LDK::OutPoint outp = OutPoint_new(txid, 0);
433                                 ChannelManager_funding_transaction_generated(&cm1, &events->data[0].funding_generation_ready.temporary_channel_id.data, std::move(outp));
434                                 break;
435                         }
436                         std::this_thread::yield();
437                 }
438
439                 // We observe when the funding signed messages have been exchanged by
440                 // waiting for two monitors to be registered.
441                 PeerManager_process_events(&net1);
442                 while (true) {
443                         LDK::CVec_EventZ events = ev1.get_and_clear_pending_events(ev1.this_arg);
444                         if (events->datalen == 1) {
445                                 assert(events->data[0].tag == LDKEvent_FundingBroadcastSafe);
446                                 assert(events->data[0].funding_broadcast_safe.user_channel_id == 42);
447                                 break;
448                         }
449                         std::this_thread::yield();
450                 }
451
452                 LDKCVec_C2Tuple_usizeTransactionZZ txdata { .data = (LDKC2TupleTempl_usize__Transaction*)malloc(sizeof(LDKC2Tuple_usizeTransactionZ)), .datalen = 1 };
453                 *txdata.data = C2Tuple_usizeTransactionZ_new(0, LDKTransaction { .data = (uint8_t*)channel_open_tx, .datalen = sizeof(channel_open_tx), .data_is_owned = false });
454                 ChannelManager_block_connected(&cm1, &channel_open_header, txdata, 1);
455
456                 txdata = LDKCVec_C2Tuple_usizeTransactionZZ { .data = (LDKC2TupleTempl_usize__Transaction*)malloc(sizeof(LDKC2Tuple_usizeTransactionZ)), .datalen = 1 };
457                 *txdata.data = C2Tuple_usizeTransactionZ_new(0, LDKTransaction { .data = (uint8_t*)channel_open_tx, .datalen = sizeof(channel_open_tx), .data_is_owned = false });
458                 ChannelManager_block_connected(&cm2, &channel_open_header, txdata, 1);
459
460                 txdata = LDKCVec_C2Tuple_usizeTransactionZZ { .data = (LDKC2TupleTempl_usize__Transaction*)malloc(sizeof(LDKC2Tuple_usizeTransactionZ)), .datalen = 1 };
461                 *txdata.data = C2Tuple_usizeTransactionZ_new(0, LDKTransaction { .data = (uint8_t*)channel_open_tx, .datalen = sizeof(channel_open_tx), .data_is_owned = false });
462                 mons1.ConnectBlock(&channel_open_header, 1, txdata, broadcast, fee_est);
463
464                 txdata = LDKCVec_C2Tuple_usizeTransactionZZ { .data = (LDKC2TupleTempl_usize__Transaction*)malloc(sizeof(LDKC2Tuple_usizeTransactionZ)), .datalen = 1 };
465                 *txdata.data = C2Tuple_usizeTransactionZ_new(0, LDKTransaction { .data = (uint8_t*)channel_open_tx, .datalen = sizeof(channel_open_tx), .data_is_owned = false });
466                 mons2.ConnectBlock(&channel_open_header, 1, txdata, broadcast, fee_est);
467
468                 ChannelManager_block_connected(&cm1, &header_1, LDKCVec_C2Tuple_usizeTransactionZZ { .data = NULL, .datalen = 0 }, 2);
469                 ChannelManager_block_connected(&cm2, &header_1, LDKCVec_C2Tuple_usizeTransactionZZ { .data = NULL, .datalen = 0 }, 2);
470                 mons1.ConnectBlock(&header_1, 2, LDKCVec_C2Tuple_usizeTransactionZZ { .data = NULL, .datalen = 0 }, broadcast, fee_est);
471                 mons2.ConnectBlock(&header_1, 2, LDKCVec_C2Tuple_usizeTransactionZZ { .data = NULL, .datalen = 0 }, broadcast, fee_est);
472
473                 ChannelManager_block_connected(&cm1, &header_2, LDKCVec_C2Tuple_usizeTransactionZZ { .data = NULL, .datalen = 0 }, 3);
474                 ChannelManager_block_connected(&cm2, &header_2, LDKCVec_C2Tuple_usizeTransactionZZ { .data = NULL, .datalen = 0 }, 3);
475                 mons1.ConnectBlock(&header_2, 3, LDKCVec_C2Tuple_usizeTransactionZZ { .data = NULL, .datalen = 0 }, broadcast, fee_est);
476                 mons2.ConnectBlock(&header_2, 3, LDKCVec_C2Tuple_usizeTransactionZZ { .data = NULL, .datalen = 0 }, broadcast, fee_est);
477
478                 PeerManager_process_events(&net1);
479                 PeerManager_process_events(&net2);
480
481                 // Now send funds from 1 to 2!
482                 while (true) {
483                         LDK::CVec_ChannelDetailsZ outbound_channels = ChannelManager_list_usable_channels(&cm1);
484                         if (outbound_channels->datalen == 1) {
485                                 const LDKChannelDetails *channel = &outbound_channels->data[0];
486                                 // Note that the channel ID is the same as the channel txid reversed as the output index is 0
487                                 uint8_t expected_chan_id[32];
488                                 for (int i = 0; i < 32; i++) { expected_chan_id[i] = channel_open_txid[31-i]; }
489                                 assert(!memcmp(ChannelDetails_get_channel_id(channel), expected_chan_id, 32));
490                                 assert(!memcmp(ChannelDetails_get_remote_network_id(channel).compressed_form,
491                                                 ChannelManager_get_our_node_id(&cm2).compressed_form, 33));
492                                 assert(ChannelDetails_get_channel_value_satoshis(channel) == 40000);
493                                 // We opened the channel with 1000 push_msat:
494                                 assert(ChannelDetails_get_outbound_capacity_msat(channel) == 40000*1000 - 1000);
495                                 assert(ChannelDetails_get_inbound_capacity_msat(channel) == 1000);
496                                 assert(ChannelDetails_get_is_live(channel));
497                                 break;
498                         }
499                         std::this_thread::yield();
500                 }
501
502                 LDK::CVec_ChannelDetailsZ outbound_channels = ChannelManager_list_usable_channels(&cm1);
503                 LDKThirtyTwoBytes payment_secret;
504                 memset(payment_secret.data, 0x42, 32);
505                 {
506                         LDK::LockedNetworkGraph graph_2_locked = NetGraphMsgHandler_read_locked_graph(&net_graph2);
507                         LDK::NetworkGraph graph_2_ref = LockedNetworkGraph_graph(&graph_2_locked);
508                         LDK::CResult_RouteLightningErrorZ route = get_route(ChannelManager_get_our_node_id(&cm1), &graph_2_ref, ChannelManager_get_our_node_id(&cm2), &outbound_channels, LDKCVec_RouteHintZ {
509                                         .data = NULL, .datalen = 0
510                                 }, 5000, 10, logger1);
511                         assert(route->result_ok);
512                         LDK::CResult_NonePaymentSendFailureZ send_res = ChannelManager_send_payment(&cm1, route->contents.result, payment_hash_1, payment_secret);
513                         assert(send_res->result_ok);
514                 }
515
516                 mons_updated = 0;
517                 PeerManager_process_events(&net1);
518                 while (mons_updated != 4) {
519                         std::this_thread::yield();
520                 }
521
522                 // Check that we received the payment!
523                 LDKEventsProvider ev2 = ChannelManager_as_EventsProvider(&cm2);
524                 while (true) {
525                         LDK::CVec_EventZ events = ev2.get_and_clear_pending_events(ev2.this_arg);
526                         if (events->datalen == 1) {
527                                 assert(events->data[0].tag == LDKEvent_PendingHTLCsForwardable);
528                                 break;
529                         }
530                         std::this_thread::yield();
531                 }
532                 ChannelManager_process_pending_htlc_forwards(&cm2);
533                 PeerManager_process_events(&net2);
534
535                 mons_updated = 0;
536                 {
537                         LDK::CVec_EventZ events = ev2.get_and_clear_pending_events(ev2.this_arg);
538                         assert(events->datalen == 1);
539                         assert(events->data[0].tag == LDKEvent_PaymentReceived);
540                         assert(!memcmp(events->data[0].payment_received.payment_hash.data, payment_hash_1.data, 32));
541                         assert(!memcmp(events->data[0].payment_received.payment_secret.data, payment_secret.data, 32));
542                         assert(events->data[0].payment_received.amt == 5000);
543                         assert(ChannelManager_claim_funds(&cm2, payment_preimage_1, payment_secret, 5000));
544                 }
545                 PeerManager_process_events(&net2);
546                 // Wait until we've passed through a full set of monitor updates (ie new preimage + CS/RAA messages)
547                 while (mons_updated != 5) {
548                         std::this_thread::yield();
549                 }
550                 {
551                         LDK::CVec_EventZ events = ev1.get_and_clear_pending_events(ev1.this_arg);
552                         assert(events->datalen == 1);
553                         assert(events->data[0].tag == LDKEvent_PaymentSent);
554                         assert(!memcmp(events->data[0].payment_sent.payment_preimage.data, payment_preimage_1.data, 32));
555                 }
556
557                 conn.stop();
558
559                 cm1_ser = ChannelManager_write(&cm1);
560                 cm2_ser = ChannelManager_write(&cm2);
561         }
562
563         LDK::CVec_ChannelMonitorZ mons_list1 = LDKCVec_ChannelMonitorZ { .data = (LDKChannelMonitor*)malloc(sizeof(LDKChannelMonitor)), .datalen = 1 };
564         assert(mons1.mons.size() == 1);
565         mons_list1->data[0] = *& std::get<1>(mons1.mons[0]); // Note that we need a reference, thus need a raw clone here, which *& does.
566         mons_list1->data[0].is_owned = false; // XXX: God this sucks
567         uint8_t node_seed[32];
568         memset(&node_seed, 0, 32);
569         LDK::KeysManager keys1 = KeysManager_new(&node_seed, network, 1, 0);
570         LDK::KeysInterface keys_source1 = KeysManager_as_KeysInterface(&keys1);
571
572         LDK::ChannelManagerReadArgs cm1_args = ChannelManagerReadArgs_new(KeysManager_as_KeysInterface(&keys1), fee_est, mon1, broadcast, logger1, UserConfig_default(), std::move(mons_list1));
573         LDK::CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ cm1_read =
574                 C2Tuple_BlockHashChannelManagerZ_read(LDKu8slice { .data = cm1_ser->data, .datalen = cm1_ser -> datalen}, std::move(cm1_args));
575         assert(cm1_read->result_ok);
576         LDK::ChannelManager cm1(std::move(cm1_read->contents.result->b));
577
578         LDK::CVec_ChannelMonitorZ mons_list2 = LDKCVec_ChannelMonitorZ { .data = (LDKChannelMonitor*)malloc(sizeof(LDKChannelMonitor)), .datalen = 1 };
579         assert(mons2.mons.size() == 1);
580         mons_list2->data[0] = *& std::get<1>(mons2.mons[0]); // Note that we need a reference, thus need a raw clone here, which *& does.
581         mons_list2->data[0].is_owned = false; // XXX: God this sucks
582         memset(&node_seed, 1, 32);
583         LDK::KeysManager keys2 = KeysManager_new(&node_seed, network, 1, 0);
584
585         LDK::ChannelManagerReadArgs cm2_args = ChannelManagerReadArgs_new(KeysManager_as_KeysInterface(&keys2), fee_est, mon2, broadcast, logger2, UserConfig_default(), std::move(mons_list2));
586         LDK::CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ cm2_read =
587                 C2Tuple_BlockHashChannelManagerZ_read(LDKu8slice { .data = cm2_ser->data, .datalen = cm2_ser -> datalen}, std::move(cm2_args));
588         assert(cm2_read->result_ok);
589         LDK::ChannelManager cm2(std::move(cm2_read->contents.result->b));
590
591         // Attempt to close the channel...
592         uint8_t chan_id[32];
593         for (int i = 0; i < 32; i++) { chan_id[i] = channel_open_txid[31-i]; }
594         LDK::CResult_NoneAPIErrorZ close_res = ChannelManager_close_channel(&cm1, &chan_id);
595         assert(!close_res->result_ok); // Note that we can't close while disconnected!
596
597         // Open a connection!
598         LDK::MessageHandler msg_handler1 = MessageHandler_new(ChannelManager_as_ChannelMessageHandler(&cm1), NetGraphMsgHandler_as_RoutingMessageHandler(&net_graph1));
599         random_bytes = keys_source1->get_secure_random_bytes(keys_source1->this_arg);
600         LDK::PeerManager net1 = PeerManager_new(std::move(msg_handler1), node_secret1, &random_bytes.data, logger1);
601
602         LDK::MessageHandler msg_handler2 = MessageHandler_new(ChannelManager_as_ChannelMessageHandler(&cm2), NetGraphMsgHandler_as_RoutingMessageHandler(&net_graph2));
603         random_bytes = keys_source1->get_secure_random_bytes(keys_source1->this_arg);
604         LDK::PeerManager net2 = PeerManager_new(std::move(msg_handler2), node_secret2, &random_bytes.data, logger2);
605
606         PeersConnection conn(cm1, cm2, net1, net2);
607
608         while (true) {
609                 // Wait for the channels to be considered up once the reestablish messages are processed
610                 LDK::CVec_ChannelDetailsZ outbound_channels = ChannelManager_list_usable_channels(&cm1);
611                 if (outbound_channels->datalen == 1) {
612                         break;
613                 }
614         }
615
616         // Actually close the channel
617         close_res = ChannelManager_close_channel(&cm1, &chan_id);
618         assert(close_res->result_ok);
619         PeerManager_process_events(&net1);
620         num_txs_broadcasted = 0;
621         while (num_txs_broadcasted != 2) {
622                 std::this_thread::yield();
623         }
624         LDK::CVec_ChannelDetailsZ chans_after_close1 = ChannelManager_list_channels(&cm1);
625         assert(chans_after_close1->datalen == 0);
626         LDK::CVec_ChannelDetailsZ chans_after_close2 = ChannelManager_list_channels(&cm2);
627         assert(chans_after_close2->datalen == 0);
628
629         conn.stop();
630
631         // Few extra random tests:
632         LDKSecretKey sk;
633         memset(&sk, 42, 32);
634         LDKC2Tuple_u64u64Z kdiv_params;
635         kdiv_params.a = 42;
636         kdiv_params.b = 42;
637         LDK::InMemoryChannelKeys keys = InMemoryChannelKeys_new(sk, sk, sk, sk, sk, random_bytes, 42, kdiv_params);
638 }