-
Notifications
You must be signed in to change notification settings - Fork 148
Expand file tree
/
Copy pathblockchain.rs
More file actions
817 lines (705 loc) · 27.9 KB
/
Copy pathblockchain.rs
File metadata and controls
817 lines (705 loc) · 27.9 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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
// SPDX-License-Identifier: MIT OR Apache-2.0
use std::collections::BTreeMap;
use bitcoin::Address;
use bitcoin::Block;
use bitcoin::BlockHash;
use bitcoin::MerkleBlock;
use bitcoin::OutPoint;
use bitcoin::Script;
use bitcoin::ScriptBuf;
use bitcoin::Txid;
use bitcoin::VarInt;
use bitcoin::block::Header;
use bitcoin::consensus::Encodable;
use bitcoin::consensus::encode::serialize_hex;
use bitcoin::constants::genesis_block;
use bitcoin::hashes::Hash;
use corepc_types::ScriptPubkey;
use corepc_types::v29::GetTxOut;
use corepc_types::v30::DeploymentInfo;
use corepc_types::v30::GetBlockHeaderVerbose;
use corepc_types::v30::GetBlockVerboseOne;
use corepc_types::v30::GetDeploymentInfo;
use floresta_chain::buried_deployments_for;
use floresta_chain::extensions::HeaderExt;
use floresta_chain::extensions::WorkExt;
use floresta_wire::block_proof::TipProof;
use miniscript::descriptor::checksum;
use serde_json::Value;
use serde_json::json;
use tracing::debug;
use super::res::GetBlockHeaderRes;
use super::res::GetBlockchainInfoRes;
use super::res::GetTxOutProof;
use super::res::JsonRpcError;
use super::server::RpcChain;
use super::server::RpcImpl;
use crate::json_rpc::res::GetBlockRes;
use crate::json_rpc::res::RescanConfidence;
use crate::json_rpc::res::VerifyUtxoChainTipInclusionProofRes;
use crate::json_rpc::res::VerifyUtxoChainTipInclusionProofVerbose;
impl<Blockchain: RpcChain> RpcImpl<Blockchain> {
async fn get_block_inner(&self, hash: BlockHash) -> Result<Block, JsonRpcError> {
let is_genesis = self.chain.get_block_hash(0).unwrap().eq(&hash);
if is_genesis {
return Ok(genesis_block(self.network));
}
self.node
.get_block(hash)
.await
.map_err(|e| JsonRpcError::Node(e.to_string()))
.and_then(|block| block.ok_or(JsonRpcError::BlockNotFound))
}
/// Return the block that contains the given Txid
pub fn get_block_by_txid(&self, txid: &Txid) -> Result<Block, JsonRpcError> {
let height = self
.wallet
.get_height(txid)
.ok_or(JsonRpcError::TxNotFound)?;
let blockhash = self.chain.get_block_hash(height).unwrap();
self.chain
.get_block(&blockhash)
.map_err(|_| JsonRpcError::BlockNotFound)
}
pub fn get_rescan_interval(
&self,
use_timestamp: bool,
start: Option<u32>,
stop: Option<u32>,
confidence: Option<RescanConfidence>,
) -> Result<(u32, u32), JsonRpcError> {
let start = start.unwrap_or(0u32);
let stop = stop.unwrap_or(0u32);
if use_timestamp {
let confidence = confidence.unwrap_or(RescanConfidence::Medium);
// `get_block_height_by_timestamp` already does the time validity checks.
let start_height = self.get_block_height_by_timestamp(start, &confidence)?;
let stop_height = self.get_block_height_by_timestamp(stop, &RescanConfidence::Exact)?;
return Ok((start_height, stop_height));
}
let (tip, _) = self
.chain
.get_best_block()
.map_err(|_| JsonRpcError::Chain)?;
if stop > tip {
return Err(JsonRpcError::InvalidRescanVal);
}
Ok((start, stop))
}
/// Retrieves the height of the block that was mined in the given timestamp.
///
/// `timestamp` has an alias, 0 will directly refer to the network's genesis timestamp.
pub fn get_block_height_by_timestamp(
&self,
timestamp: u32,
confidence: &RescanConfidence,
) -> Result<u32, JsonRpcError> {
/// Simple helper to avoid code reuse.
fn get_block_time<BlockChain: RpcChain>(
provider: &RpcImpl<BlockChain>,
at: u32,
) -> Result<u32, JsonRpcError> {
let hash = provider.get_block_hash(at)?;
let block = provider.get_block_header_inner(hash)?;
Ok(block.time)
}
let genesis_timestamp = genesis_block(self.network).header.time;
if timestamp == 0 || timestamp == genesis_timestamp {
return Ok(0);
};
let (tip_height, _) = self
.chain
.get_best_block()
.map_err(|_| JsonRpcError::BlockNotFound)?;
let tip_time = get_block_time(self, tip_height)?;
if timestamp < genesis_timestamp || timestamp > tip_time {
return Err(JsonRpcError::InvalidTimestamp);
}
let adjusted_target = timestamp.saturating_sub(confidence.as_secs());
let mut high = tip_height;
let mut low = 0;
let max_iters = tip_height.ilog2() + 1;
for _ in 0..max_iters {
let cut = (high + low) / 2;
let block_timestamp = get_block_time(self, cut)?;
if block_timestamp == adjusted_target {
debug!("found a precise block; returning {cut}");
return Ok(cut);
}
if high - low <= 2 {
debug!("didn't find a precise block; returning {low}");
return Ok(low);
}
if block_timestamp > adjusted_target {
high = cut;
} else {
low = cut;
}
}
// This is pretty much unreachable.
Err(JsonRpcError::BlockNotFound)
}
}
// blockchain rpcs
impl<Blockchain: RpcChain> RpcImpl<Blockchain> {
// dumputxoutset
// getbestblockhash
pub(super) fn get_best_block_hash(&self) -> Result<BlockHash, JsonRpcError> {
Ok(self.chain.get_best_block().unwrap().1)
}
// getblock
pub(super) async fn get_block(
&self,
hash: BlockHash,
verbosity: u8,
) -> Result<GetBlockRes, JsonRpcError> {
let block = self.get_block_inner(hash).await?;
if verbosity == 0 {
let hex = serialize_hex(&block);
return Ok(GetBlockRes::Zero(hex));
}
if verbosity == 1 {
let header_fields = self.get_block_header_verbose_inner(&block)?;
// Stripped size is the size of the block without witness data
// Header + VarInt for number of transactions + sum of base sizes of each transaction
let tx_count_varint_size = VarInt::from(block.txdata.len()).size();
let total_tx_base_size: usize = block.txdata.iter().map(|tx| tx.base_size()).sum();
let stripped_size_bytes = Header::SIZE + tx_count_varint_size + total_tx_base_size;
let stripped_size = Some(stripped_size_bytes.try_into()?);
let tx = block
.txdata
.iter()
.map(|tx| tx.compute_txid().to_string())
.collect();
let block = GetBlockVerboseOne {
bits: header_fields.bits,
chain_work: header_fields.chain_work,
confirmations: header_fields.confirmations,
difficulty: header_fields.difficulty,
hash: header_fields.hash,
height: header_fields.height,
merkle_root: header_fields.merkle_root,
nonce: header_fields.nonce,
previous_block_hash: header_fields.previous_block_hash,
size: block.total_size().try_into()?,
time: header_fields.time,
tx,
version: header_fields.version,
version_hex: header_fields.version_hex,
weight: block.weight().to_wu(),
median_time: Some(header_fields.median_time),
n_tx: header_fields.n_tx.into(),
next_block_hash: header_fields.next_block_hash,
stripped_size,
target: header_fields.target,
};
return Ok(GetBlockRes::One(Box::new(block)));
}
Err(JsonRpcError::InvalidVerbosityLevel)
}
// getblockchaininfo
pub(super) fn get_blockchain_info(&self) -> Result<GetBlockchainInfoRes, JsonRpcError> {
let (height, hash) = self.chain.get_best_block().unwrap();
let validated = self.chain.get_validation_index().unwrap();
let ibd = self.chain.is_in_ibd();
let latest_header = self.chain.get_block_header(&hash).unwrap();
let latest_work = latest_header
.calculate_chain_work(&self.chain)?
.to_string_hex();
let latest_block_time = latest_header.time;
let acc = self.chain.get_acc(None).map_err(|_| JsonRpcError::Chain)?;
let leaf_count = acc.leaves as u32;
let root_count = acc.roots.len() as u32;
let root_hashes = acc.roots.into_iter().map(|r| r.to_string()).collect();
let validated_blocks = self.chain.get_validation_index().unwrap();
let validated_percentage = if height != 0 {
validated_blocks as f32 / height as f32
} else {
0.0
};
Ok(GetBlockchainInfoRes {
best_block: hash.to_string(),
height,
ibd,
validated,
latest_work,
latest_block_time,
leaf_count,
root_count,
root_hashes,
chain: self.network.to_string(),
difficulty: latest_header.difficulty(self.chain.get_params()) as u64,
progress: validated_percentage,
})
}
// getblockcount
pub(super) fn get_block_count(&self) -> Result<u32, JsonRpcError> {
Ok(self.chain.get_height().unwrap())
}
// getblockfilter
// getblockfrompeer (just call getblock)
// getblockhash
pub(super) fn get_block_hash(&self, height: u32) -> Result<BlockHash, JsonRpcError> {
self.chain
.get_block_hash(height)
.map_err(|_| JsonRpcError::BlockNotFound)
}
// getblockheader
pub(super) async fn get_block_header(
&self,
hash: BlockHash,
verbosity: bool,
) -> Result<GetBlockHeaderRes, JsonRpcError> {
let header = self.get_block_header_inner(hash)?;
if !verbosity {
let hex = serialize_hex(&header);
return Ok(GetBlockHeaderRes::Raw(hex));
}
let block = self.get_block_inner(hash).await?;
let get_block_header = self.get_block_header_verbose_inner(&block)?;
Ok(GetBlockHeaderRes::Verbose(Box::new(get_block_header)))
}
// getblockstats
// getchainstates
// getchaintips
// getchaintxstats
// getdeploymentinfo
pub(super) fn get_deployment_info(
&self,
hash: Option<BlockHash>,
) -> Result<GetDeploymentInfo, JsonRpcError> {
let tip = self
.chain
.get_best_block()
.map_err(|_| JsonRpcError::Chain)?
.1;
let target_hash = hash.unwrap_or(tip);
let height = self
.chain
.get_block_height(&target_hash)
.map_err(|_| JsonRpcError::Chain)?
.ok_or(JsonRpcError::BlockNotFound)?;
let mut deployments = BTreeMap::new();
for &(name, activation_height) in buried_deployments_for(self.network) {
deployments.insert(
name.to_string(),
DeploymentInfo {
deployment_type: "buried".to_string(),
height: Some(activation_height),
active: height >= activation_height,
bip9: None,
},
);
}
Ok(GetDeploymentInfo {
hash: target_hash.to_string(),
height,
deployments,
})
}
// getdifficulty
pub(super) fn get_difficulty(&self) -> Result<f64, JsonRpcError> {
let (_, hash) = self
.chain
.get_best_block()
.map_err(|_| JsonRpcError::Chain)?;
let header = self
.chain
.get_block_header(&hash)
.map_err(|_| JsonRpcError::BlockNotFound)?;
Ok(header.difficulty_float())
}
// getmempoolancestors
// getmempooldescendants
// getmempoolentry
// getmempoolinfo
// getrawmempool
/// Same as `get_block_header_inner` but verbose.
fn get_block_header_verbose_inner(
&self,
block: &Block,
) -> Result<GetBlockHeaderVerbose, JsonRpcError> {
let header = &block.header;
let height = header.get_height(&self.chain)?;
let median_time = header.calculate_median_time_past(&self.chain)?;
let chain_work = header.calculate_chain_work(&self.chain)?.to_string_hex();
let confirmations = header.get_confirmations(&self.chain)?;
let version_hex = header.get_version_hex();
let next_block_hash = header
.get_next_block_hash(&self.chain)?
.map(|h| h.to_string());
let bits = header.get_bits_hex();
let difficulty = header.get_difficulty();
let target = header.get_target_hex();
let previous_block_hash = (header.prev_blockhash != BlockHash::all_zeros())
.then_some(header.prev_blockhash.to_string());
Ok(GetBlockHeaderVerbose {
bits,
chain_work,
confirmations: confirmations.into(),
difficulty,
hash: header.block_hash().to_string(),
height: height.into(),
median_time: median_time.into(),
next_block_hash,
version: header.version.to_consensus(),
version_hex,
previous_block_hash,
merkle_root: header.merkle_root.to_string(),
time: header.time.into(),
target,
nonce: header.nonce.into(),
n_tx: block.txdata.len().try_into()?,
})
}
/// Helper method to get a block header by its hash, used by multiple rpcs.
fn get_block_header_inner(&self, hash: BlockHash) -> Result<Header, JsonRpcError> {
self.chain
.get_block_header(&hash)
.map_err(|_| JsonRpcError::BlockNotFound)
}
/// Check if the script is anchor type
fn is_anchor_type(script: &Script) -> bool {
script.as_bytes().starts_with(&[0x51, 0x02, 0x4e, 0x73])
}
/// Returns a label about the scriptPubKey type
/// (pubkey, pubkeyhash, multisig, nulldata, scripthash, witness_v0_keyhash, witness_v0_scripthash, witness_v1_taproot, anchor, nonstandard)
fn get_script_type_label(script: &Script) -> &'static str {
if script.is_p2pk() {
return "pubkey";
}
if script.is_p2pkh() {
return "pubkeyhash";
}
if script.is_multisig() {
return "multisig";
}
if script.is_op_return() {
return "nulldata";
}
if script.is_p2sh() {
return "scripthash";
}
if script.is_p2wpkh() {
return "witness_v0_keyhash";
}
if script.is_p2wsh() {
return "witness_v0_scripthash";
}
if script.is_p2tr() {
return "witness_v1_taproot";
}
if Self::is_anchor_type(script) {
return "anchor";
}
"nonstandard"
}
fn get_script_type_descriptor(script: &Script, address: &Option<Address>) -> String {
let get_addr_str = || {
address
.as_ref()
.expect("address should be Some")
.to_string()
};
if script.is_p2pk() {
let addr = get_addr_str();
return format!("pk({addr}");
}
if let Some(addr) = address {
return format!("addr({addr})");
}
if script.is_op_return() {
let hex = script.to_hex_string();
return format!("raw({hex})");
}
if Self::is_anchor_type(script) {
let addr = get_addr_str();
return format!("addr({addr})");
}
let hex = script.to_hex_string();
format!("raw({hex})")
}
/// Parses the serialized opcodes in a [ScriptBuf] as numbers and it's hashes.
/// This differs from `ScriptBuf::to_asm_string` in that, `rust-bitcoin` will
/// show the the human representation of the opcode. It does not omit the number representations of
/// `OP_PUSHDATA_<N>` and `OP_PUSHBYTE<N>`. This method do the opposite: it not show the human
/// representation and omit the last opcodes, so it can be compliant with bitcoin-core.
/// For reference see <https://en.bitcoin.it/wiki/Script#Opcodes>
fn to_core_asm_string(script: &ScriptBuf) -> Result<String, JsonRpcError> {
let mut asm = vec![];
let bytes = script.as_bytes();
let mut i = 0usize;
// little reused helper to hex string
let to_hex_string = |r: &[u8]| r.iter().map(|b| format!("{b:02x}")).collect::<String>();
while i < bytes.len() {
let byte = bytes[i];
i += 1;
match byte {
// OP_0
0x00 => asm.push(format!("{}", 0)),
// OP_PUSHDATA_<N>: The next N bytes is data to be pushed onto the stack
0x01..=0x4b => {
let pushed_bytes = byte as usize;
let hex = to_hex_string(&bytes[i..i + pushed_bytes]);
asm.push(hex);
i += pushed_bytes;
}
// OP_PUSHBYTE1: the next byte contains the number of bytes to be pushed onto the stack.
0x4c => {
let pushed_bytes = bytes[i] as usize;
i += 1;
let hex = to_hex_string(&bytes[i..i + pushed_bytes]);
asm.push(hex);
i += pushed_bytes;
}
// OP_PUSHBYTE2: the next two bytes contain the number of bytes to be pushed onto the stack in little endian order.
0x4d => {
let pushed_bytes = u16::from_le_bytes([bytes[i], bytes[i + 1]]) as usize;
i += 2;
let hex = to_hex_string(&bytes[i..i + pushed_bytes]);
asm.push(hex);
i += pushed_bytes;
}
// OP_PUSHBYTE4: the next four bytes contain the number of bytes to be pushed onto the stack in little endian order.
0x4e => {
let pushed_bytes =
u32::from_le_bytes([bytes[i], bytes[i + 1], bytes[i + 2], bytes[i + 3]])
as usize;
i += 4;
let hex = to_hex_string(&bytes[i..i + pushed_bytes]);
asm.push(hex);
i += pushed_bytes;
}
// OP_1 to OP_16
0x51..=0x60 => {
// 0x50 is OP_RESERVED
let reserved = 0x50;
asm.push(format!("{}", byte - reserved));
}
// Any other opcode that should be pushed
another_one => {
asm.push(format!("{another_one:02x}"));
}
}
}
Ok(asm.join(" "))
}
/// gettxout: returns details about an unspent transaction output.
pub(super) fn get_tx_out(
&self,
txid: Txid,
outpoint: u32,
_include_mempool: bool,
) -> Result<Option<GetTxOut>, JsonRpcError> {
let res = match (
self.wallet.get_transaction(&txid),
self.wallet.get_height(&txid),
self.wallet.get_utxo(&OutPoint {
txid,
vout: outpoint,
}),
) {
(Some(cached_tx), Some(height), Some(txout)) => {
let is_coinbase = cached_tx.tx.is_coinbase();
let Ok((bestblock_height, bestblock_hash)) = self.chain.get_best_block() else {
return Err(JsonRpcError::BlockNotFound);
};
let script = txout.script_pubkey.as_script();
let network = self.chain.get_params().network;
let address = Address::from_script(script, network).ok();
let base_descriptor = Self::get_script_type_descriptor(script, &address);
let descriptor: Option<String> = match checksum::desc_checksum(&base_descriptor) {
Ok(checksum) => Some(format!("{base_descriptor}#{checksum}")),
Err(_) => None,
};
let asm = Self::to_core_asm_string(&txout.script_pubkey)?;
let script_pubkey = ScriptPubkey {
asm,
hex: txout.script_pubkey.to_hex_string(),
descriptor,
address: address.as_ref().map(ToString::to_string),
type_: Self::get_script_type_label(script).to_string(),
// Deprecated in Bitcoin Core v22, require flags in Bitcoin Core.
// Set to None as not required for consensus.
addresses: None,
required_signatures: None,
};
Some(GetTxOut {
best_block: bestblock_hash.to_string(),
confirmations: bestblock_height - height + 1,
value: txout.value.to_btc(),
script_pubkey,
coinbase: is_coinbase,
})
}
_ => None,
};
Ok(res)
}
/// Computes the necessary information for the RPC `gettxoutproof [txids] blockhash (optional)`
///
/// This function has two paths, when blockhash is inserted and when isn't.
///
/// Specifying the blockhash will make this function go after the block and search
/// for the transactions inside it, building a merkle proof from the block with its
/// indexes. Not specifying will redirect it to search for the merkle proof on our
/// watch-only wallet which may not have the transaction cached.
///
/// Not finding one of the specified transactions will raise [`JsonRpcError::TxNotFound`].
pub(super) async fn get_txout_proof(
&self,
tx_ids: &[Txid],
blockhash: Option<BlockHash>,
) -> Result<GetTxOutProof, JsonRpcError> {
let block = match blockhash {
Some(blockhash) => self.get_block_inner(blockhash).await?,
// Using the first Txid to get the block should be fine since they are expected to all
// live in the same block, otherwise, theres no way they have a common proof.
None => self.get_block_by_txid(&tx_ids[0])?,
};
// Before building the merkle block we try to remove all txids
// that aren't present in the block we found, meaning that
// at least one of the txids doesn't belong to the block which
// in case needs to make the command fails.
//
// this makes the use MerkleBlock::from_block_with_predicate useless.
let targeted_txids: Vec<Txid> = block
.txdata
.iter()
.filter_map(|tx| {
let txid = tx.compute_txid();
if tx_ids.contains(&txid) {
Some(txid)
} else {
None
}
})
.collect();
if targeted_txids.len() != tx_ids.len() {
return Err(JsonRpcError::TxNotFound);
};
let merkle_block = MerkleBlock::from_block_with_predicate(&block, |tx| tx_ids.contains(tx));
let mut bytes: Vec<u8> = Vec::new();
merkle_block
.consensus_encode(&mut bytes)
.expect("This will raise if a writer error happens");
Ok(GetTxOutProof(bytes))
}
// gettxoutsetinfo
// gettxspendigprevout
// importmempool
// loadtxoutset
// preciousblock
// pruneblockchain
// savemempool
// scanblocks
// scantxoutset
// verifychain
// verifytxoutproof
// floresta flavored rpcs. These are not part of the bitcoin rpc spec
// findtxout
pub(super) async fn find_tx_out(
&self,
txid: Txid,
vout: u32,
script: ScriptBuf,
height: u32,
) -> Result<Value, JsonRpcError> {
if let Some(txout) = self.wallet.get_utxo(&OutPoint { txid, vout }) {
return Ok(serde_json::to_value(txout).unwrap());
}
// if we are on IBD, we don't have any filters to find this txout.
if self.chain.is_in_ibd() {
return Err(JsonRpcError::InInitialBlockDownload);
}
// can't proceed without block filters
let Some(cfilters) = self.block_filter_storage.as_ref() else {
return Err(JsonRpcError::NoBlockFilters);
};
self.wallet.cache_address(script.clone());
let filter_key = script.to_bytes();
let candidates = cfilters
.match_any(
vec![filter_key.as_slice()],
Some(height),
None,
self.chain.clone(),
)
.map_err(|e| JsonRpcError::Filters(e.to_string()))?;
for candidate in candidates {
let candidate = self.node.get_block(candidate).await;
let candidate = match candidate {
Err(e) => {
return Err(JsonRpcError::Node(e.to_string()));
}
Ok(None) => {
return Err(JsonRpcError::Node(format!(
"BUG: block {candidate:?} is a match in our filters, but we can't get it?"
)));
}
Ok(Some(candidate)) => candidate,
};
let Ok(Some(height)) = self.chain.get_block_height(&candidate.block_hash()) else {
return Err(JsonRpcError::BlockNotFound);
};
self.wallet.block_process(&candidate, height);
}
let val = match self.get_tx_out(txid, vout, false)? {
Some(gettxout) => json!(gettxout),
None => json!({}),
};
Ok(val)
}
// getroots
pub(super) fn get_roots(&self) -> Result<Vec<String>, JsonRpcError> {
let hashes = self.chain.get_root_hashes();
Ok(hashes.iter().map(|h| h.to_string()).collect())
}
pub(super) fn list_descriptors(&self) -> Result<Vec<String>, JsonRpcError> {
let descriptors = self
.wallet
.get_descriptors()
.map_err(|e| JsonRpcError::Wallet(e.to_string()))?;
Ok(descriptors)
}
pub(super) fn verify_utxo_chain_tip_inclusion_proof(
&self,
proof: TipProof,
verbosity: u8,
blockhash: Option<BlockHash>,
) -> Result<VerifyUtxoChainTipInclusionProofRes, JsonRpcError> {
// The hash we got querying for the given blockhash
let internal_hash = blockhash.unwrap_or(self.get_best_block_hash()?);
if proof.proved_at_hash != internal_hash {
return Err(JsonRpcError::InvalidProof(format!(
"Possibly stale proof. Got {internal_hash} internally but proof was generated at block {}",
proof.proved_at_hash
)));
};
let stump = self
.chain
.get_acc(blockhash)
.map_err(|_| JsonRpcError::Chain)?;
let is_valid = stump
.verify(&proof.proof, &proof.hashes_proven)
.map_err(|e| JsonRpcError::InvalidProof(format!("Proof verification failed: {e:?}")))?;
match verbosity {
0 => Ok(VerifyUtxoChainTipInclusionProofRes::Zero(is_valid)),
1 => Ok(VerifyUtxoChainTipInclusionProofRes::One(
VerifyUtxoChainTipInclusionProofVerbose {
valid: is_valid,
proved_at_hash: proof.proved_at_hash.to_string(),
targets: proof.proof.targets,
num_proof_hashes: proof.proof.hashes.len(),
proof_hashes: proof.proof.hashes.iter().map(ToString::to_string).collect(),
hashes_proven: proof
.hashes_proven
.iter()
.map(ToString::to_string)
.collect(),
},
)),
_ => Err(JsonRpcError::InvalidVerbosityLevel),
}
}
}