forked from romanz/electrs
-
Notifications
You must be signed in to change notification settings - Fork 139
/
Copy pathschema.rs
1665 lines (1455 loc) · 51.3 KB
/
schema.rs
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
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use bitcoin::hashes::sha256d::Hash as Sha256dHash;
#[cfg(not(feature = "liquid"))]
use bitcoin::merkle_tree::MerkleBlock;
use bitcoin::VarInt;
use crypto::digest::Digest;
use crypto::sha2::Sha256;
use hex::FromHex;
use itertools::Itertools;
use rayon::prelude::*;
#[cfg(not(feature = "liquid"))]
use bitcoin::consensus::encode::{deserialize, serialize};
#[cfg(feature = "liquid")]
use elements::{
confidential,
encode::{deserialize, serialize},
AssetId,
};
use std::collections::{BTreeSet, HashMap, HashSet};
use std::path::Path;
use std::sync::{Arc, RwLock};
use crate::chain::{
BlockHash, BlockHeader, Network, OutPoint, Script, Transaction, TxOut, Txid, Value,
};
use crate::config::Config;
use crate::daemon::Daemon;
use crate::errors::*;
use crate::metrics::{Gauge, HistogramOpts, HistogramTimer, HistogramVec, MetricOpts, Metrics};
use crate::util::{
bincode, full_hash, has_prevout, is_spendable, BlockHeaderMeta, BlockId, BlockMeta,
BlockStatus, Bytes, HeaderEntry, HeaderList, ScriptToAddr,
};
use crate::new_index::db::{DBFlush, DBRow, ReverseScanIterator, ScanIterator, DB};
use crate::new_index::fetch::{start_fetcher, BlockEntry, FetchFrom};
#[cfg(feature = "liquid")]
use crate::elements::{asset, peg};
const MIN_HISTORY_ITEMS_TO_CACHE: usize = 100;
pub struct Store {
// TODO: should be column families
txstore_db: DB,
history_db: DB,
cache_db: DB,
added_blockhashes: RwLock<HashSet<BlockHash>>,
indexed_blockhashes: RwLock<HashSet<BlockHash>>,
indexed_headers: RwLock<HeaderList>,
}
impl Store {
pub fn open(path: &Path, config: &Config) -> Self {
let txstore_db = DB::open(&path.join("txstore"), config);
let added_blockhashes = load_blockhashes(&txstore_db, &BlockRow::done_filter());
debug!("{} blocks were added", added_blockhashes.len());
let history_db = DB::open(&path.join("history"), config);
let indexed_blockhashes = load_blockhashes(&history_db, &BlockRow::done_filter());
debug!("{} blocks were indexed", indexed_blockhashes.len());
let cache_db = DB::open(&path.join("cache"), config);
let headers = if let Some(tip_hash) = txstore_db.get(b"t") {
let tip_hash = deserialize(&tip_hash).expect("invalid chain tip in `t`");
let headers_map = load_blockheaders(&txstore_db);
debug!(
"{} headers were loaded, tip at {:?}",
headers_map.len(),
tip_hash
);
HeaderList::new(headers_map, tip_hash)
} else {
HeaderList::empty()
};
Store {
txstore_db,
history_db,
cache_db,
added_blockhashes: RwLock::new(added_blockhashes),
indexed_blockhashes: RwLock::new(indexed_blockhashes),
indexed_headers: RwLock::new(headers),
}
}
pub fn txstore_db(&self) -> &DB {
&self.txstore_db
}
pub fn history_db(&self) -> &DB {
&self.history_db
}
pub fn cache_db(&self) -> &DB {
&self.cache_db
}
pub fn done_initial_sync(&self) -> bool {
self.txstore_db.get(b"t").is_some()
}
}
type UtxoMap = HashMap<OutPoint, (BlockId, Value)>;
#[derive(Debug)]
pub struct Utxo {
pub txid: Txid,
pub vout: u32,
pub confirmed: Option<BlockId>,
pub value: Value,
#[cfg(feature = "liquid")]
pub asset: confidential::Asset,
#[cfg(feature = "liquid")]
pub nonce: confidential::Nonce,
#[cfg(feature = "liquid")]
pub witness: elements::TxOutWitness,
}
impl From<&Utxo> for OutPoint {
fn from(utxo: &Utxo) -> Self {
OutPoint {
txid: utxo.txid,
vout: utxo.vout,
}
}
}
#[derive(Debug)]
pub struct SpendingInput {
pub txid: Txid,
pub vin: u32,
pub confirmed: Option<BlockId>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ScriptStats {
pub tx_count: usize,
pub funded_txo_count: usize,
pub spent_txo_count: usize,
#[cfg(not(feature = "liquid"))]
pub funded_txo_sum: u64,
#[cfg(not(feature = "liquid"))]
pub spent_txo_sum: u64,
}
impl ScriptStats {
pub fn default() -> Self {
ScriptStats {
tx_count: 0,
funded_txo_count: 0,
spent_txo_count: 0,
#[cfg(not(feature = "liquid"))]
funded_txo_sum: 0,
#[cfg(not(feature = "liquid"))]
spent_txo_sum: 0,
}
}
}
pub struct Indexer {
store: Arc<Store>,
flush: DBFlush,
from: FetchFrom,
iconfig: IndexerConfig,
duration: HistogramVec,
tip_metric: Gauge,
}
struct IndexerConfig {
light_mode: bool,
address_search: bool,
index_unspendables: bool,
network: Network,
#[cfg(feature = "liquid")]
parent_network: crate::chain::BNetwork,
}
impl From<&Config> for IndexerConfig {
fn from(config: &Config) -> Self {
IndexerConfig {
light_mode: config.light_mode,
address_search: config.address_search,
index_unspendables: config.index_unspendables,
network: config.network_type,
#[cfg(feature = "liquid")]
parent_network: config.parent_network,
}
}
}
pub struct ChainQuery {
store: Arc<Store>, // TODO: should be used as read-only
daemon: Arc<Daemon>,
light_mode: bool,
duration: HistogramVec,
network: Network,
}
// TODO: &[Block] should be an iterator / a queue.
impl Indexer {
pub fn open(store: Arc<Store>, from: FetchFrom, config: &Config, metrics: &Metrics) -> Self {
Indexer {
store,
flush: DBFlush::Disable,
from,
iconfig: IndexerConfig::from(config),
duration: metrics.histogram_vec(
HistogramOpts::new("index_duration", "Index update duration (in seconds)"),
&["step"],
),
tip_metric: metrics.gauge(MetricOpts::new("tip_height", "Current chain tip height")),
}
}
fn start_timer(&self, name: &str) -> HistogramTimer {
self.duration.with_label_values(&[name]).start_timer()
}
fn headers_to_add(&self, new_headers: &[HeaderEntry]) -> Vec<HeaderEntry> {
let added_blockhashes = self.store.added_blockhashes.read().unwrap();
new_headers
.iter()
.filter(|e| !added_blockhashes.contains(e.hash()))
.cloned()
.collect()
}
fn headers_to_index(&self, new_headers: &[HeaderEntry]) -> Vec<HeaderEntry> {
let indexed_blockhashes = self.store.indexed_blockhashes.read().unwrap();
new_headers
.iter()
.filter(|e| !indexed_blockhashes.contains(e.hash()))
.cloned()
.collect()
}
fn start_auto_compactions(&self, db: &DB) {
let key = b"F".to_vec();
if db.get(&key).is_none() {
db.full_compaction();
db.put_sync(&key, b"");
assert!(db.get(&key).is_some());
}
db.enable_auto_compaction();
}
fn get_new_headers(&self, daemon: &Daemon, tip: &BlockHash) -> Result<Vec<HeaderEntry>> {
let headers = self.store.indexed_headers.read().unwrap();
let new_headers = daemon.get_new_headers(&headers, &tip)?;
let result = headers.order(new_headers);
if let Some(tip) = result.last() {
info!("{:?} ({} left to index)", tip, result.len());
};
Ok(result)
}
pub fn update(&mut self, daemon: &Daemon) -> Result<BlockHash> {
let daemon = daemon.reconnect()?;
let tip = daemon.getbestblockhash()?;
let new_headers = self.get_new_headers(&daemon, &tip)?;
let to_add = self.headers_to_add(&new_headers);
debug!(
"adding transactions from {} blocks using {:?}",
to_add.len(),
self.from
);
start_fetcher(self.from, &daemon, to_add)?.map(|blocks| self.add(&blocks));
self.start_auto_compactions(&self.store.txstore_db);
let to_index = self.headers_to_index(&new_headers);
debug!(
"indexing history from {} blocks using {:?}",
to_index.len(),
self.from
);
start_fetcher(self.from, &daemon, to_index)?.map(|blocks| self.index(&blocks));
self.start_auto_compactions(&self.store.history_db);
if let DBFlush::Disable = self.flush {
debug!("flushing to disk");
self.store.txstore_db.flush();
self.store.history_db.flush();
self.flush = DBFlush::Enable;
}
// update the synced tip *after* the new data is flushed to disk
debug!("updating synced tip to {:?}", tip);
self.store.txstore_db.put_sync(b"t", &serialize(&tip));
let mut headers = self.store.indexed_headers.write().unwrap();
headers.apply(new_headers);
assert_eq!(tip, *headers.tip());
if let FetchFrom::BlkFiles = self.from {
self.from = FetchFrom::Bitcoind;
}
self.tip_metric.set(headers.len() as i64 - 1);
Ok(tip)
}
fn add(&self, blocks: &[BlockEntry]) {
// TODO: skip orphaned blocks?
let rows = {
let _timer = self.start_timer("add_process");
add_blocks(blocks, &self.iconfig)
};
{
let _timer = self.start_timer("add_write");
self.store.txstore_db.write(rows, self.flush);
}
self.store
.added_blockhashes
.write()
.unwrap()
.extend(blocks.iter().map(|b| b.entry.hash()));
}
fn index(&self, blocks: &[BlockEntry]) {
let previous_txos_map = {
let _timer = self.start_timer("index_lookup");
lookup_txos(&self.store.txstore_db, &get_previous_txos(blocks), false)
};
let rows = {
let _timer = self.start_timer("index_process");
let added_blockhashes = self.store.added_blockhashes.read().unwrap();
for b in blocks {
let blockhash = b.entry.hash();
// TODO: replace by lookup into txstore_db?
if !added_blockhashes.contains(blockhash) {
panic!("cannot index block {} (missing from store)", blockhash);
}
}
index_blocks(blocks, &previous_txos_map, &self.iconfig)
};
self.store.history_db.write(rows, self.flush);
}
pub fn fetch_from(&mut self, from: FetchFrom) {
self.from = from;
}
}
impl ChainQuery {
pub fn new(store: Arc<Store>, daemon: Arc<Daemon>, config: &Config, metrics: &Metrics) -> Self {
ChainQuery {
store,
daemon,
light_mode: config.light_mode,
network: config.network_type,
duration: metrics.histogram_vec(
HistogramOpts::new("query_duration", "Index query duration (in seconds)"),
&["name"],
),
}
}
pub fn network(&self) -> Network {
self.network
}
pub fn store(&self) -> &Store {
&self.store
}
fn start_timer(&self, name: &str) -> HistogramTimer {
self.duration.with_label_values(&[name]).start_timer()
}
pub fn get_block_txids(&self, hash: &BlockHash) -> Option<Vec<Txid>> {
let _timer = self.start_timer("get_block_txids");
if self.light_mode {
// TODO fetch block as binary from REST API instead of as hex
let mut blockinfo = self.daemon.getblock_raw(hash, 1).ok()?;
Some(serde_json::from_value(blockinfo["tx"].take()).unwrap())
} else {
self.store
.txstore_db
.get(&BlockRow::txids_key(full_hash(&hash[..])))
.map(|val| bincode::deserialize_little(&val).expect("failed to parse block txids"))
}
}
pub fn get_block_meta(&self, hash: &BlockHash) -> Option<BlockMeta> {
let _timer = self.start_timer("get_block_meta");
if self.light_mode {
let blockinfo = self.daemon.getblock_raw(hash, 1).ok()?;
Some(serde_json::from_value(blockinfo).unwrap())
} else {
self.store
.txstore_db
.get(&BlockRow::meta_key(full_hash(&hash[..])))
.map(|val| bincode::deserialize_little(&val).expect("failed to parse BlockMeta"))
}
}
pub fn get_block_raw(&self, hash: &BlockHash) -> Option<Vec<u8>> {
let _timer = self.start_timer("get_block_raw");
if self.light_mode {
let blockval = self.daemon.getblock_raw(hash, 0).ok()?;
let blockhex = blockval.as_str().expect("valid block from bitcoind");
Some(Vec::from_hex(blockhex).expect("valid block from bitcoind"))
} else {
let entry = self.header_by_hash(hash)?;
let meta = self.get_block_meta(hash)?;
let txids = self.get_block_txids(hash)?;
// Reconstruct the raw block using the header and txids,
// as <raw header><tx count varint><raw txs>
let mut raw = Vec::with_capacity(meta.size as usize);
raw.append(&mut serialize(entry.header()));
raw.append(&mut serialize(&VarInt(txids.len() as u64)));
for txid in txids {
// we don't need to provide the blockhash because we know we're not in light mode
raw.append(&mut self.lookup_raw_txn(&txid, None)?);
}
Some(raw)
}
}
pub fn get_block_header(&self, hash: &BlockHash) -> Option<BlockHeader> {
let _timer = self.start_timer("get_block_header");
Some(self.header_by_hash(hash)?.header().clone())
}
pub fn get_mtp(&self, height: usize) -> u32 {
let _timer = self.start_timer("get_block_mtp");
self.store.indexed_headers.read().unwrap().get_mtp(height)
}
pub fn get_block_with_meta(&self, hash: &BlockHash) -> Option<BlockHeaderMeta> {
let _timer = self.start_timer("get_block_with_meta");
let header_entry = self.header_by_hash(hash)?;
Some(BlockHeaderMeta {
meta: self.get_block_meta(hash)?,
mtp: self.get_mtp(header_entry.height()),
header_entry,
})
}
pub fn history_iter_scan(&self, code: u8, hash: &[u8], start_height: usize) -> ScanIterator {
self.store.history_db.iter_scan_from(
&TxHistoryRow::filter(code, &hash[..]),
&TxHistoryRow::prefix_height(code, &hash[..], start_height as u32),
)
}
fn history_iter_scan_reverse(&self, code: u8, hash: &[u8]) -> ReverseScanIterator {
self.store.history_db.iter_scan_reverse(
&TxHistoryRow::filter(code, &hash[..]),
&TxHistoryRow::prefix_end(code, &hash[..]),
)
}
pub fn history(
&self,
scripthash: &[u8],
last_seen_txid: Option<&Txid>,
limit: usize,
) -> Vec<(Transaction, BlockId)> {
// scripthash lookup
self._history(b'H', scripthash, last_seen_txid, limit)
}
fn _history(
&self,
code: u8,
hash: &[u8],
last_seen_txid: Option<&Txid>,
limit: usize,
) -> Vec<(Transaction, BlockId)> {
let _timer_scan = self.start_timer("history");
let txs_conf = self
.history_iter_scan_reverse(code, hash)
.map(|row| TxHistoryRow::from_row(row).get_txid())
// XXX: unique() requires keeping an in-memory list of all txids, can we avoid that?
.unique()
// TODO seek directly to last seen tx without reading earlier rows
.skip_while(|txid| {
// skip until we reach the last_seen_txid
last_seen_txid.map_or(false, |last_seen_txid| last_seen_txid != txid)
})
.skip(match last_seen_txid {
Some(_) => 1, // skip the last_seen_txid itself
None => 0,
})
.filter_map(|txid| self.tx_confirming_block(&txid).map(|b| (txid, b)))
.take(limit)
.collect::<Vec<(Txid, BlockId)>>();
self.lookup_txns(&txs_conf)
.expect("failed looking up txs in history index")
.into_iter()
.zip(txs_conf)
.map(|(tx, (_, blockid))| (tx, blockid))
.collect()
}
pub fn history_txids(&self, scripthash: &[u8], limit: usize) -> Vec<(Txid, BlockId)> {
// scripthash lookup
self._history_txids(b'H', scripthash, limit)
}
fn _history_txids(&self, code: u8, hash: &[u8], limit: usize) -> Vec<(Txid, BlockId)> {
let _timer = self.start_timer("history_txids");
self.history_iter_scan(code, hash, 0)
.map(|row| TxHistoryRow::from_row(row).get_txid())
.unique()
.filter_map(|txid| self.tx_confirming_block(&txid).map(|b| (txid, b)))
.take(limit)
.collect()
}
// TODO: avoid duplication with stats/stats_delta?
pub fn utxo(&self, scripthash: &[u8], limit: usize) -> Result<Vec<Utxo>> {
let _timer = self.start_timer("utxo");
// get the last known utxo set and the blockhash it was updated for.
// invalidates the cache if the block was orphaned.
let cache: Option<(UtxoMap, usize)> = self
.store
.cache_db
.get(&UtxoCacheRow::key(scripthash))
.map(|c| bincode::deserialize_little(&c).unwrap())
.and_then(|(utxos_cache, blockhash)| {
self.height_by_hash(&blockhash)
.map(|height| (utxos_cache, height))
})
.map(|(utxos_cache, height)| (from_utxo_cache(utxos_cache, self), height));
let had_cache = cache.is_some();
// update utxo set with new transactions since
let (newutxos, lastblock, processed_items) = cache.map_or_else(
|| self.utxo_delta(scripthash, HashMap::new(), 0, limit),
|(oldutxos, blockheight)| self.utxo_delta(scripthash, oldutxos, blockheight + 1, limit),
)?;
// save updated utxo set to cache
if let Some(lastblock) = lastblock {
if had_cache || processed_items > MIN_HISTORY_ITEMS_TO_CACHE {
self.store.cache_db.write(
vec![UtxoCacheRow::new(scripthash, &newutxos, &lastblock).into_row()],
DBFlush::Enable,
);
}
}
// format as Utxo objects
Ok(newutxos
.into_iter()
.map(|(outpoint, (blockid, value))| {
// in elements/liquid chains, we have to lookup the txo in order to get its
// associated asset. the asset information could be kept in the db history rows
// alongside the value to avoid this.
#[cfg(feature = "liquid")]
let txo = self.lookup_txo(&outpoint).expect("missing utxo");
Utxo {
txid: outpoint.txid,
vout: outpoint.vout,
value,
confirmed: Some(blockid),
#[cfg(feature = "liquid")]
asset: txo.asset,
#[cfg(feature = "liquid")]
nonce: txo.nonce,
#[cfg(feature = "liquid")]
witness: txo.witness,
}
})
.collect())
}
fn utxo_delta(
&self,
scripthash: &[u8],
init_utxos: UtxoMap,
start_height: usize,
limit: usize,
) -> Result<(UtxoMap, Option<BlockHash>, usize)> {
let _timer = self.start_timer("utxo_delta");
let history_iter = self
.history_iter_scan(b'H', scripthash, start_height)
.map(TxHistoryRow::from_row)
.filter_map(|history| {
self.tx_confirming_block(&history.get_txid())
.map(|b| (history, b))
});
let mut utxos = init_utxos;
let mut processed_items = 0;
let mut lastblock = None;
for (history, blockid) in history_iter {
processed_items += 1;
lastblock = Some(blockid.hash);
match history.key.txinfo {
TxHistoryInfo::Funding(ref info) => {
utxos.insert(history.get_funded_outpoint(), (blockid, info.value))
}
TxHistoryInfo::Spending(_) => utxos.remove(&history.get_funded_outpoint()),
#[cfg(feature = "liquid")]
TxHistoryInfo::Issuing(_)
| TxHistoryInfo::Burning(_)
| TxHistoryInfo::Pegin(_)
| TxHistoryInfo::Pegout(_) => unreachable!(),
};
// abort if the utxo set size excedees the limit at any point in time
if utxos.len() > limit {
bail!(ErrorKind::TooPopular)
}
}
Ok((utxos, lastblock, processed_items))
}
pub fn stats(&self, scripthash: &[u8]) -> ScriptStats {
let _timer = self.start_timer("stats");
// get the last known stats and the blockhash they are updated for.
// invalidates the cache if the block was orphaned.
let cache: Option<(ScriptStats, usize)> = self
.store
.cache_db
.get(&StatsCacheRow::key(scripthash))
.map(|c| bincode::deserialize_little(&c).unwrap())
.and_then(|(stats, blockhash)| {
self.height_by_hash(&blockhash)
.map(|height| (stats, height))
});
// update stats with new transactions since
let (newstats, lastblock) = cache.map_or_else(
|| self.stats_delta(scripthash, ScriptStats::default(), 0),
|(oldstats, blockheight)| self.stats_delta(scripthash, oldstats, blockheight + 1),
);
// save updated stats to cache
if let Some(lastblock) = lastblock {
if newstats.funded_txo_count + newstats.spent_txo_count > MIN_HISTORY_ITEMS_TO_CACHE {
self.store.cache_db.write(
vec![StatsCacheRow::new(scripthash, &newstats, &lastblock).into_row()],
DBFlush::Enable,
);
}
}
newstats
}
fn stats_delta(
&self,
scripthash: &[u8],
init_stats: ScriptStats,
start_height: usize,
) -> (ScriptStats, Option<BlockHash>) {
let _timer = self.start_timer("stats_delta"); // TODO: measure also the number of txns processed.
let history_iter = self
.history_iter_scan(b'H', scripthash, start_height)
.map(TxHistoryRow::from_row)
.filter_map(|history| {
self.tx_confirming_block(&history.get_txid())
// drop history entries that were previously confirmed in a re-orged block and later
// confirmed again at a different height
.filter(|blockid| blockid.height == history.key.confirmed_height as usize)
.map(|blockid| (history, blockid))
});
let mut stats = init_stats;
let mut seen_txids = HashSet::new();
let mut lastblock = None;
for (history, blockid) in history_iter {
if lastblock != Some(blockid.hash) {
seen_txids.clear();
}
if seen_txids.insert(history.get_txid()) {
stats.tx_count += 1;
}
match history.key.txinfo {
#[cfg(not(feature = "liquid"))]
TxHistoryInfo::Funding(ref info) => {
stats.funded_txo_count += 1;
stats.funded_txo_sum += info.value;
}
#[cfg(not(feature = "liquid"))]
TxHistoryInfo::Spending(ref info) => {
stats.spent_txo_count += 1;
stats.spent_txo_sum += info.value;
}
#[cfg(feature = "liquid")]
TxHistoryInfo::Funding(_) => {
stats.funded_txo_count += 1;
}
#[cfg(feature = "liquid")]
TxHistoryInfo::Spending(_) => {
stats.spent_txo_count += 1;
}
#[cfg(feature = "liquid")]
TxHistoryInfo::Issuing(_)
| TxHistoryInfo::Burning(_)
| TxHistoryInfo::Pegin(_)
| TxHistoryInfo::Pegout(_) => unreachable!(),
}
lastblock = Some(blockid.hash);
}
(stats, lastblock)
}
pub fn address_search(&self, prefix: &str, limit: usize) -> Vec<String> {
let _timer_scan = self.start_timer("address_search");
self.store
.history_db
.iter_scan(&addr_search_filter(prefix))
.take(limit)
.map(|row| std::str::from_utf8(&row.key[1..]).unwrap().to_string())
.collect()
}
fn header_by_hash(&self, hash: &BlockHash) -> Option<HeaderEntry> {
self.store
.indexed_headers
.read()
.unwrap()
.header_by_blockhash(hash)
.cloned()
}
// Get the height of a blockhash, only if its part of the best chain
pub fn height_by_hash(&self, hash: &BlockHash) -> Option<usize> {
self.store
.indexed_headers
.read()
.unwrap()
.header_by_blockhash(hash)
.map(|header| header.height())
}
pub fn header_by_height(&self, height: usize) -> Option<HeaderEntry> {
self.store
.indexed_headers
.read()
.unwrap()
.header_by_height(height)
.cloned()
}
pub fn hash_by_height(&self, height: usize) -> Option<BlockHash> {
self.store
.indexed_headers
.read()
.unwrap()
.header_by_height(height)
.map(|entry| *entry.hash())
}
pub fn blockid_by_height(&self, height: usize) -> Option<BlockId> {
self.store
.indexed_headers
.read()
.unwrap()
.header_by_height(height)
.map(BlockId::from)
}
// returns None for orphaned blocks
pub fn blockid_by_hash(&self, hash: &BlockHash) -> Option<BlockId> {
self.store
.indexed_headers
.read()
.unwrap()
.header_by_blockhash(hash)
.map(BlockId::from)
}
pub fn best_height(&self) -> usize {
self.store.indexed_headers.read().unwrap().len() - 1
}
pub fn best_hash(&self) -> BlockHash {
*self.store.indexed_headers.read().unwrap().tip()
}
pub fn best_header(&self) -> HeaderEntry {
let headers = self.store.indexed_headers.read().unwrap();
headers
.header_by_blockhash(headers.tip())
.expect("missing chain tip")
.clone()
}
// TODO: can we pass txids as a "generic iterable"?
// TODO: should also use a custom ThreadPoolBuilder?
pub fn lookup_txns(&self, txids: &[(Txid, BlockId)]) -> Result<Vec<Transaction>> {
let _timer = self.start_timer("lookup_txns");
txids
.par_iter()
.map(|(txid, blockid)| {
self.lookup_txn(txid, Some(&blockid.hash))
.chain_err(|| "missing tx")
})
.collect::<Result<Vec<Transaction>>>()
}
pub fn lookup_txn(&self, txid: &Txid, blockhash: Option<&BlockHash>) -> Option<Transaction> {
let _timer = self.start_timer("lookup_txn");
self.lookup_raw_txn(txid, blockhash).map(|rawtx| {
let txn: Transaction = deserialize(&rawtx).expect("failed to parse Transaction");
assert_eq!(*txid, txn.txid());
txn
})
}
pub fn lookup_raw_txn(&self, txid: &Txid, blockhash: Option<&BlockHash>) -> Option<Bytes> {
let _timer = self.start_timer("lookup_raw_txn");
if self.light_mode {
let queried_blockhash =
blockhash.map_or_else(|| self.tx_confirming_block(txid).map(|b| b.hash), |_| None);
let blockhash = blockhash.or_else(|| queried_blockhash.as_ref())?;
// TODO fetch transaction as binary from REST API instead of as hex
let txval = self
.daemon
.gettransaction_raw(txid, blockhash, false)
.ok()?;
let txhex = txval.as_str().expect("valid tx from bitcoind");
Some(Bytes::from_hex(txhex).expect("valid tx from bitcoind"))
} else {
self.store.txstore_db.get(&TxRow::key(&txid[..]))
}
}
pub fn lookup_txo(&self, outpoint: &OutPoint) -> Option<TxOut> {
let _timer = self.start_timer("lookup_txo");
lookup_txo(&self.store.txstore_db, outpoint)
}
pub fn lookup_txos(&self, outpoints: &BTreeSet<OutPoint>) -> HashMap<OutPoint, TxOut> {
let _timer = self.start_timer("lookup_txos");
lookup_txos(&self.store.txstore_db, outpoints, false)
}
pub fn lookup_avail_txos(&self, outpoints: &BTreeSet<OutPoint>) -> HashMap<OutPoint, TxOut> {
let _timer = self.start_timer("lookup_available_txos");
lookup_txos(&self.store.txstore_db, outpoints, true)
}
pub fn lookup_spend(&self, outpoint: &OutPoint) -> Option<SpendingInput> {
let _timer = self.start_timer("lookup_spend");
self.store
.history_db
.iter_scan(&TxEdgeRow::filter(&outpoint))
.map(TxEdgeRow::from_row)
.find_map(|edge| {
let txid: Txid = deserialize(&edge.key.spending_txid).unwrap();
self.tx_confirming_block(&txid).map(|b| SpendingInput {
txid,
vin: edge.key.spending_vin,
confirmed: Some(b),
})
})
}
pub fn tx_confirming_block(&self, txid: &Txid) -> Option<BlockId> {
let _timer = self.start_timer("tx_confirming_block");
let headers = self.store.indexed_headers.read().unwrap();
self.store
.txstore_db
.iter_scan(&TxConfRow::filter(&txid[..]))
.map(TxConfRow::from_row)
// header_by_blockhash only returns blocks that are part of the best chain,
// or None for orphaned blocks.
.filter_map(|conf| {
headers.header_by_blockhash(&deserialize(&conf.key.blockhash).unwrap())
})
.next()
.map(BlockId::from)
}
pub fn get_block_status(&self, hash: &BlockHash) -> BlockStatus {
// TODO differentiate orphaned and non-existing blocks? telling them apart requires
// an additional db read.
let headers = self.store.indexed_headers.read().unwrap();
// header_by_blockhash only returns blocks that are part of the best chain,
// or None for orphaned blocks.
headers
.header_by_blockhash(hash)
.map_or_else(BlockStatus::orphaned, |header| {
BlockStatus::confirmed(
header.height(),
headers
.header_by_height(header.height() + 1)
.map(|h| *h.hash()),
)
})
}
#[cfg(not(feature = "liquid"))]
pub fn get_merkleblock_proof(&self, txid: &Txid) -> Option<MerkleBlock> {
let _timer = self.start_timer("get_merkleblock_proof");
let blockid = self.tx_confirming_block(txid)?;
let headerentry = self.header_by_hash(&blockid.hash)?;
let block_txids = self.get_block_txids(&blockid.hash)?;
Some(MerkleBlock::from_header_txids_with_predicate(
headerentry.header(),
&block_txids,
|t| t == txid,
))
}
#[cfg(feature = "liquid")]
pub fn asset_history(
&self,
asset_id: &AssetId,
last_seen_txid: Option<&Txid>,
limit: usize,
) -> Vec<(Transaction, BlockId)> {
self._history(b'I', &asset_id.into_inner()[..], last_seen_txid, limit)
}
#[cfg(feature = "liquid")]
pub fn asset_history_txids(&self, asset_id: &AssetId, limit: usize) -> Vec<(Txid, BlockId)> {
self._history_txids(b'I', &asset_id.into_inner()[..], limit)
}
}
fn load_blockhashes(db: &DB, prefix: &[u8]) -> HashSet<BlockHash> {
db.iter_scan(prefix)
.map(BlockRow::from_row)
.map(|r| deserialize(&r.key.hash).expect("failed to parse BlockHash"))
.collect()
}
fn load_blockheaders(db: &DB) -> HashMap<BlockHash, BlockHeader> {
db.iter_scan(&BlockRow::header_filter())
.map(BlockRow::from_row)
.map(|r| {
let key: BlockHash = deserialize(&r.key.hash).expect("failed to parse BlockHash");
let value: BlockHeader = deserialize(&r.value).expect("failed to parse BlockHeader");
(key, value)
})
.collect()
}
fn add_blocks(block_entries: &[BlockEntry], iconfig: &IndexerConfig) -> Vec<DBRow> {
// persist individual transactions:
// T{txid} → {rawtx}
// C{txid}{blockhash}{height} →
// O{txid}{index} → {txout}
// persist block headers', block txids' and metadata rows:
// B{blockhash} → {header}
// X{blockhash} → {txid1}...{txidN}
// M{blockhash} → {tx_count}{size}{weight}
block_entries
.par_iter() // serialization is CPU-intensive
.map(|b| {
let mut rows = vec![];
let blockhash = full_hash(&b.entry.hash()[..]);
let txids: Vec<Txid> = b.block.txdata.iter().map(|tx| tx.txid()).collect();
for tx in &b.block.txdata {
add_transaction(tx, blockhash, &mut rows, iconfig);
}
if !iconfig.light_mode {
rows.push(BlockRow::new_txids(blockhash, &txids).into_row());
rows.push(BlockRow::new_meta(blockhash, &BlockMeta::from(b)).into_row());
}
rows.push(BlockRow::new_header(&b).into_row());
rows.push(BlockRow::new_done(blockhash).into_row()); // mark block as "added"
rows
})
.flatten()
.collect()