forked from libbitcoin/libbitcoin-server
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprotocol_electrum.cpp
More file actions
582 lines (496 loc) · 17 KB
/
protocol_electrum.cpp
File metadata and controls
582 lines (496 loc) · 17 KB
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
/**
* Copyright (c) 2011-2026 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <bitcoin/server/protocols/protocol_electrum.hpp>
#include <algorithm>
#include <ranges>
#include <variant>
#include <bitcoin/server/define.hpp>
#include <bitcoin/server/interfaces/interfaces.hpp>
#include <bitcoin/server/protocols/protocol_rpc.hpp>
namespace libbitcoin {
namespace server {
#define CLASS protocol_electrum
using namespace system;
using namespace interface;
using namespace std::placeholders;
BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT)
BC_PUSH_WARNING(SMART_PTR_NOT_NEEDED)
BC_PUSH_WARNING(NO_VALUE_OR_CONST_REF_SHARED_PTR)
// Start.
// ----------------------------------------------------------------------------
void protocol_electrum::start() NOEXCEPT
{
BC_ASSERT(stranded());
if (started())
return;
// Events subscription is asynchronous, events may be missed.
subscribe_events(BIND(handle_event, _1, _2, _3));
// Blockchain methods.
SUBSCRIBE_RPC(handle_blockchain_block_header, _1, _2, _3, _4);
SUBSCRIBE_RPC(handle_blockchain_block_headers, _1, _2, _3, _4, _5);
SUBSCRIBE_RPC(handle_blockchain_headers_subscribe, _1, _2);
SUBSCRIBE_RPC(handle_blockchain_estimate_fee, _1, _2, _3, _4);
SUBSCRIBE_RPC(handle_blockchain_relay_fee, _1, _2);
SUBSCRIBE_RPC(handle_blockchain_scripthash_get_balance, _1, _2, _3);
SUBSCRIBE_RPC(handle_blockchain_scripthash_get_history, _1, _2, _3);
SUBSCRIBE_RPC(handle_blockchain_scripthash_get_mempool, _1, _2, _3);
SUBSCRIBE_RPC(handle_blockchain_scripthash_list_unspent, _1, _2, _3);
SUBSCRIBE_RPC(handle_blockchain_scripthash_subscribe, _1, _2, _3);
SUBSCRIBE_RPC(handle_blockchain_scripthash_unsubscribe, _1, _2, _3);
SUBSCRIBE_RPC(handle_blockchain_transaction_broadcast, _1, _2, _3);
SUBSCRIBE_RPC(handle_blockchain_transaction_get, _1, _2, _3, _4);
SUBSCRIBE_RPC(handle_blockchain_transaction_get_merkle, _1, _2, _3, _4);
SUBSCRIBE_RPC(handle_blockchain_transaction_id_from_pos, _1, _2, _3, _4, _5);
// Server methods
SUBSCRIBE_RPC(handle_server_add_peer, _1, _2, _3);
SUBSCRIBE_RPC(handle_server_banner, _1, _2);
SUBSCRIBE_RPC(handle_server_donation_address, _1, _2);
SUBSCRIBE_RPC(handle_server_features, _1, _2);
SUBSCRIBE_RPC(handle_server_peers_subscribe, _1, _2);
SUBSCRIBE_RPC(handle_server_ping, _1, _2);
////SUBSCRIBE_RPC(handle_server_version, _1, _2, _3, _4);
// Mempool methods.
SUBSCRIBE_RPC(handle_mempool_get_fee_histogram, _1, _2);
protocol_rpc<channel_electrum>::start();
}
void protocol_electrum::stopping(const code& ec) NOEXCEPT
{
BC_ASSERT(stranded());
// Unsubscription is asynchronous, race is ok.
unsubscribe_events();
protocol_rpc<channel_electrum>::stopping(ec);
}
// Handlers (event subscription).
// ----------------------------------------------------------------------------
bool protocol_electrum::handle_event(const code&, node::chase event_,
node::event_value value) NOEXCEPT
{
// Do not pass ec to stopped as it is not a call status.
if (stopped())
return false;
switch (event_)
{
case node::chase::organized:
{
if (subscribed_.load(std::memory_order_relaxed))
{
BC_ASSERT(std::holds_alternative<node::header_t>(value));
POST(do_header, std::get<node::header_t>(value));
}
break;
}
default:
{
break;
}
}
return true;
}
// Utility.
// ----------------------------------------------------------------------------
// TODO: centralize in server (also used in bitcoind and native interfaces).
template <typename Object, typename ...Args>
std::string to_hex(const Object& object, size_t size, Args&&... args) NOEXCEPT
{
std::string out(two * size, '\0');
stream::out::fast sink{ out };
write::base16::fast writer{ sink };
object.to_data(writer, std::forward<Args>(args)...);
BC_ASSERT(writer);
return out;
}
// Handlers (blockchain).
// ----------------------------------------------------------------------------
void protocol_electrum::handle_blockchain_block_header(const code& ec,
rpc_interface::blockchain_block_header, double height,
double cp_height) NOEXCEPT
{
using namespace system;
if (stopped(ec))
return;
size_t starting{};
size_t waypoint{};
if (!to_integer(starting, height) ||
!to_integer(waypoint, cp_height))
{
send_code(error::invalid_argument);
return;
}
blockchain_block_headers(starting, one, waypoint, false);
}
void protocol_electrum::handle_blockchain_block_headers(const code& ec,
rpc_interface::blockchain_block_headers, double start_height, double count,
double cp_height) NOEXCEPT
{
using namespace system;
if (stopped(ec))
return;
size_t quantity{};
size_t waypoint{};
size_t starting{};
if (!to_integer(quantity, count) ||
!to_integer(waypoint, cp_height) ||
!to_integer(starting, start_height))
{
send_code(error::invalid_argument);
return;
}
blockchain_block_headers(starting, quantity, waypoint, true);
}
// Common implementation for blockchain_block_header/s.
void protocol_electrum::blockchain_block_headers(size_t starting,
size_t quantity, size_t waypoint, bool multiplicity) NOEXCEPT
{
const auto prove = !is_zero(quantity) && !is_zero(waypoint);
const auto target = starting + sub1(quantity);
const auto& query = archive();
const auto top = query.get_top_confirmed();
using namespace system;
// The documented requirement: `start_height + (count - 1) <= cp_height` is
// ambiguous at count = 0 so guard must be applied to both args and prover.
if (is_add_overflow(starting, quantity))
{
send_code(error::argument_overflow);
return;
}
else if (starting > top)
{
send_code(error::not_found);
return;
}
else if (prove && waypoint > top)
{
send_code(error::not_found);
return;
}
else if (prove && target > waypoint)
{
send_code(error::target_overflow);
return;
}
// Recommended to be at least one difficulty retarget period, e.g. 2016.
// The maximum number of headers the server will return in single request.
const auto maximum = server_settings().electrum.maximum_headers;
// Returned headers are assured to be contiguous despite intervening reorg.
// No headers may be returned, which implies start > confirmed top block.
const auto count = limit(quantity, maximum);
const auto links = query.get_confirmed_headers(starting, count);
constexpr auto header_size = chain::header::serialized_size();
auto size = two * header_size * links.size();
// Fetch and serialize headers.
array_t headers{};
headers.reserve(links.size());
for (const auto& link: links)
{
if (const auto header = query.get_header(link); header)
{
headers.push_back(to_hex(*header, header_size));
continue;
}
send_code(error::server_error);
return;
};
value_t value{ object_t{} };
auto& result = std::get<object_t>(value.value());
if (multiplicity)
{
result["max"] = maximum;
result["count"] = uint64_t{ headers.size() };
result["headers"] = std::move(headers);
}
else if (!headers.empty())
{
result["header"] = headers.front();
}
// There is a very slim chance of inconsistency given an intervening reorg
// because of get_merkle_root_and_proof() use of height-based calculations.
// This is acceptable as it must be verified by caller in any case.
if (prove)
{
hashes proof{};
hash_digest root{};
if (const auto code = query.get_merkle_root_and_proof(root, proof,
target, waypoint))
{
send_code(code);
return;
}
array_t branch(proof.size());
std::ranges::transform(proof, branch.begin(),
[](const auto& hash) { return encode_hash(hash); });
result["branch"] = std::move(branch);
result["root"] = encode_hash(root);
size += two * hash_size * add1(proof.size());
}
send_result(std::move(value), size + 42u, BIND(complete, _1));
}
void protocol_electrum::handle_blockchain_headers_subscribe(const code& ec,
rpc_interface::blockchain_headers_subscribe) NOEXCEPT
{
if (stopped(ec))
return;
const auto& query = archive();
const auto top = query.get_top_confirmed();
const auto link = query.to_confirmed(top);
// This is unlikely but possible due to a race condition during reorg.
if (link.is_terminal())
{
send_code(error::not_found);
return;
}
const auto header = query.get_header(link);
if (!header)
{
send_code(error::server_error);
return;
}
subscribed_.store(true, std::memory_order_relaxed);
send_result(
{
object_t
{
{ "height", uint64_t{ top } },
{ "hex", to_hex(*header, chain::header::serialized_size()) }
}
}, 256, BIND(complete, _1));
}
// Notifier for blockchain_headers_subscribe events.
void protocol_electrum::do_header(node::header_t link) NOEXCEPT
{
BC_ASSERT(stranded());
const auto& query = archive();
const auto height = query.get_height(link);
const auto header = query.get_header(link);
if (height.is_terminal() || !header)
{
LOGF("Electrum::do_header, object not found (" << link << ").");
return;
}
send_notification("blockchain.headers.subscribe",
{
object_t
{
{ "height", height.value },
{ "hex", to_hex(*header, chain::header::serialized_size()) }
}
}, 100, BIND(complete, _1));
}
void protocol_electrum::handle_blockchain_estimate_fee(const code& ec,
rpc_interface::blockchain_estimate_fee, double number,
const std::string& ) NOEXCEPT
{
if (stopped(ec))
return;
// TODO: mode argument added in 1.6.
send_result(number, 70, BIND(complete, _1));
}
void protocol_electrum::handle_blockchain_relay_fee(const code& ec,
rpc_interface::blockchain_relay_fee) NOEXCEPT
{
if (stopped(ec))
return;
// TODO: deprecated in 1.4.2, removed in 1.6.
send_result(node_settings().minimum_fee_rate, 42, BIND(complete, _1));
}
void protocol_electrum::handle_blockchain_scripthash_get_balance(const code& ec,
rpc_interface::blockchain_scripthash_get_balance,
const std::string& ) NOEXCEPT
{
if (stopped(ec)) return;
send_code(error::not_implemented);
}
void protocol_electrum::handle_blockchain_scripthash_get_history(const code& ec,
rpc_interface::blockchain_scripthash_get_history,
const std::string& ) NOEXCEPT
{
if (stopped(ec)) return;
send_code(error::not_implemented);
}
void protocol_electrum::handle_blockchain_scripthash_get_mempool(const code& ec,
rpc_interface::blockchain_scripthash_get_mempool,
const std::string& ) NOEXCEPT
{
if (stopped(ec)) return;
send_code(error::not_implemented);
}
void protocol_electrum::handle_blockchain_scripthash_list_unspent(const code& ec,
rpc_interface::blockchain_scripthash_list_unspent,
const std::string& ) NOEXCEPT
{
if (stopped(ec)) return;
send_code(error::not_implemented);
}
void protocol_electrum::handle_blockchain_scripthash_subscribe(const code& ec,
rpc_interface::blockchain_scripthash_subscribe,
const std::string& ) NOEXCEPT
{
if (stopped(ec)) return;
send_code(error::not_implemented);
}
void protocol_electrum::handle_blockchain_scripthash_unsubscribe(const code& ec,
rpc_interface::blockchain_scripthash_unsubscribe,
const std::string& ) NOEXCEPT
{
if (stopped(ec)) return;
send_code(error::not_implemented);
}
void protocol_electrum::handle_blockchain_transaction_broadcast(const code& ec,
rpc_interface::blockchain_transaction_broadcast,
const std::string& raw_tx) NOEXCEPT
{
if (stopped(ec))
return;
// ElectrumX changed in version 1.1 to return error vs. bitcoind result.
// Previously it returned text string (bitcoind message) in the error case.
data_chunk tx_data{};
if (!decode_base16(tx_data, raw_tx))
{
send_code(error::invalid_argument);
return;
}
const auto tx = to_shared<chain::transaction>(tx_data, true);
if (!tx->is_valid())
{
send_code(error::invalid_argument);
return;
}
// TODO: handle just as any peer annoucement, validate and relay.
// TODO: requires tx pool in order to validate against unconfirmed txs.
constexpr auto confirmable = false;
if (!confirmable)
{
send_code(error::unconfirmable_transaction);
return;
}
constexpr auto size = two * hash_size;
send_result(encode_base16(tx->hash(false)), size, BIND(complete, _1));
}
void protocol_electrum::handle_blockchain_transaction_get(const code& ec,
rpc_interface::blockchain_transaction_get, const std::string& tx_hash,
bool verbose) NOEXCEPT
{
if (stopped(ec))
return;
// Changed in version 1.2: verbose argument added.
// Changed in version 1.1: ignored argument height removed.
hash_digest hash{};
if (!decode_hash(hash, tx_hash))
{
send_code(error::invalid_argument);
return;
}
const auto& query = archive();
const auto tx = query.get_transaction(query.to_tx(hash), true);
if (!tx)
{
send_code(error::not_found);
return;
}
const auto size = tx->serialized_size(true);
if (verbose)
{
// TODO: inject contextual tx properties.
// Verbose means whatever bitcoind returns for getrawtransaction, lolz.
send_result(value_from(bitcoind(*tx)), two * size, BIND(complete, _1));
}
else
{
send_result(to_hex(*tx, size, true), two * size, BIND(complete, _1));
}
}
void protocol_electrum::handle_blockchain_transaction_get_merkle(const code& ec,
rpc_interface::blockchain_transaction_get_merkle, const std::string& ,
double ) NOEXCEPT
{
if (stopped(ec)) return;
send_code(error::not_implemented);
}
void protocol_electrum::handle_blockchain_transaction_id_from_pos(const code& ec,
rpc_interface::blockchain_transaction_id_from_pos, double ,
double , bool ) NOEXCEPT
{
if (stopped(ec)) return;
send_code(error::not_implemented);
}
// Handlers (server).
// ----------------------------------------------------------------------------
void protocol_electrum::handle_server_add_peer(const code& ec,
rpc_interface::server_add_peer, const interface::object_t& ) NOEXCEPT
{
if (stopped(ec)) return;
send_code(error::not_implemented);
}
void protocol_electrum::handle_server_banner(const code& ec,
rpc_interface::server_banner) NOEXCEPT
{
if (stopped(ec))
return;
send_result(options().banner_message, 42, BIND(complete, _1));
}
void protocol_electrum::handle_server_donation_address(const code& ec,
rpc_interface::server_donation_address) NOEXCEPT
{
if (stopped(ec))
return;
send_result(options().donation_address, 42, BIND(complete, _1));
}
void protocol_electrum::handle_server_features(const code& ec,
rpc_interface::server_features) NOEXCEPT
{
if (stopped(ec)) return;
send_code(error::not_implemented);
}
// This is not actually a subscription method.
void protocol_electrum::handle_server_peers_subscribe(const code& ec,
rpc_interface::server_peers_subscribe) NOEXCEPT
{
if (stopped(ec)) return;
send_code(error::not_implemented);
}
void protocol_electrum::handle_server_ping(const code& ec,
rpc_interface::server_ping) NOEXCEPT
{
if (stopped(ec))
return;
// Any receive, including ping, resets the base channel inactivity timer.
send_result(null_t{}, 42, BIND(complete, _1));
}
// Handlers (mempool).
// ----------------------------------------------------------------------------
void protocol_electrum::handle_mempool_get_fee_histogram(const code& ec,
rpc_interface::mempool_get_fee_histogram) NOEXCEPT
{
if (stopped(ec))
return;
// TODO: requires tx pool metadata graph.
send_result(value_t
{
array_t
{
array_t{ 1, 1024 },
array_t{ 2, 2048 },
array_t{ 4, 4096 }
}
}, 256, BIND(complete, _1));
}
BC_POP_WARNING()
BC_POP_WARNING()
BC_POP_WARNING()
} // namespace server
} // namespace libbitcoin