-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathchain_store.rs
More file actions
3793 lines (3425 loc) · 137 KB
/
chain_store.rs
File metadata and controls
3793 lines (3425 loc) · 137 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
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 anyhow::anyhow;
use async_trait::async_trait;
use diesel::sql_types::Text;
use diesel::{insert_into, update, ExpressionMethods, OptionalExtension, QueryDsl};
use diesel_async::AsyncConnection;
use diesel_async::{scoped_futures::ScopedFutureExt, RunQueryDsl};
use graph::components::store::ChainHeadStore;
use graph::data::store::ethereum::call;
use graph::env::ENV_VARS;
use graph::parking_lot::RwLock;
use graph::prelude::alloy::primitives::B256;
use graph::prelude::MetricsRegistry;
use graph::prometheus::{CounterVec, GaugeVec};
use graph::slog::{info, o, Logger};
use graph::stable_hash::crypto_stable_hash;
use graph::util::herd_cache::HerdCache;
use std::collections::BTreeMap;
use std::future::Future;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
use std::{
collections::HashMap,
convert::{TryFrom, TryInto},
iter::FromIterator,
sync::Arc,
};
use graph::blockchain::{Block, BlockHash, ChainIdentifier, ExtendedBlockPtr};
use graph::cheap_clone::CheapClone;
use graph::components::ethereum::CachedBlock;
use graph::prelude::{
serde_json as json, transaction_receipt::LightTransactionReceipt, BlockNumber, BlockPtr,
CachedEthereumCall, ChainStore as ChainStoreTrait, Error, EthereumCallCache,
StaleCallCacheResult, StoreError,
};
use graph::{ensure, internal_error};
use self::recent_blocks_cache::RecentBlocksCache;
use crate::vid_batcher::AdaptiveBatchSize;
use crate::AsyncPgConnection;
use crate::{chain_head_listener::ChainHeadUpdateSender, pool::ConnectionPool};
/// Our own internal notion of a block
#[derive(Clone, Debug)]
struct JsonBlock {
ptr: BlockPtr,
parent_hash: BlockHash,
data: Option<json::Value>,
}
impl JsonBlock {
fn new(ptr: BlockPtr, parent_hash: BlockHash, data: Option<json::Value>) -> Self {
JsonBlock {
ptr,
parent_hash,
data,
}
}
fn timestamp(&self) -> Option<u64> {
self.data
.as_ref()
.and_then(|data| data.get("timestamp"))
.and_then(|ts| ts.as_str())
.and_then(|ts| ts.parse::<u64>().ok())
}
fn into_cache_block(self) -> CacheBlock {
let data = self.data.and_then(CachedBlock::from_json);
CacheBlock {
ptr: self.ptr,
parent_hash: self.parent_hash,
data,
}
}
}
/// Typed version of JsonBlock for the in-memory cache.
#[derive(Clone, Debug)]
struct CacheBlock {
ptr: BlockPtr,
parent_hash: BlockHash,
data: Option<CachedBlock>,
}
impl CacheBlock {
fn timestamp(&self) -> Option<u64> {
self.data.as_ref().and_then(|d| d.timestamp())
}
fn to_extended_block_ptr(&self) -> Result<ExtendedBlockPtr, Error> {
let hash = self.ptr.hash.clone();
let number = self.ptr.number;
let parent_hash = self.parent_hash.clone();
let timestamp = self
.timestamp()
.ok_or_else(|| anyhow!("Timestamp is missing"))?;
let ptr =
ExtendedBlockPtr::try_from((hash.as_b256(), number, parent_hash.as_b256(), timestamp))
.map_err(|e| anyhow!("Failed to convert to ExtendedBlockPtr: {}", e))?;
Ok(ptr)
}
}
/// Tables in the 'public' database schema that store chain-specific data
mod public {
table! {
ethereum_networks (name) {
name -> Varchar,
namespace -> Varchar,
head_block_hash -> Nullable<Varchar>,
head_block_number -> Nullable<BigInt>,
net_version -> Varchar,
genesis_block_hash -> Varchar,
head_block_cursor -> Nullable<Varchar>,
}
}
}
pub use data::Storage;
/// Encapuslate access to the blocks table for a chain.
mod data {
use crate::diesel::dsl::IntervalDsl;
use crate::{catalog, AsyncPgConnection};
use diesel::dsl::sql;
use diesel::insert_into;
use diesel::sql_types::{Array, Binary, Bool, Nullable, Text};
use diesel::{
delete, sql_query, BoolExpressionMethods, ExpressionMethods, JoinOnDsl,
NullableExpressionMethods, OptionalExtension, QueryDsl,
};
use diesel::{
deserialize::FromSql,
pg::Pg,
serialize::{Output, ToSql},
};
use diesel::{
sql_types::{BigInt, Bytea, Integer, Jsonb},
update,
};
use diesel_async::{RunQueryDsl, SimpleAsyncConnection};
use graph::blockchain::{Block, BlockHash};
use graph::data::store::scalar::Bytes;
use graph::internal_error;
use graph::prelude::alloy::primitives::{Address, B256};
use graph::prelude::transaction_receipt::LightTransactionReceipt;
use graph::prelude::{
info, serde_json as json, BlockNumber, BlockPtr, CachedEthereumCall, Error, Logger,
StoreError,
};
use std::collections::HashMap;
use std::convert::TryFrom;
use std::fmt;
use std::iter::FromIterator;
use std::str::FromStr;
use std::time::Instant;
use crate::transaction_receipt::RawTransactionReceipt;
use super::JsonBlock;
pub(crate) const ETHEREUM_BLOCKS_TABLE_NAME: &str = "public.ethereum_blocks";
pub(crate) const ETHEREUM_CALL_CACHE_TABLE_NAME: &str = "public.eth_call_cache";
pub(crate) const ETHEREUM_CALL_META_TABLE_NAME: &str = "public.eth_call_meta";
mod public {
pub(super) use super::super::public::ethereum_networks;
table! {
ethereum_blocks (hash) {
hash -> Varchar,
number -> BigInt,
parent_hash -> Nullable<Varchar>,
network_name -> Varchar, // REFERENCES ethereum_networks (name),
data -> Jsonb,
}
}
allow_tables_to_appear_in_same_query!(ethereum_networks, ethereum_blocks);
table! {
/// `id` is the hash of contract address + encoded function call + block number.
eth_call_cache (id) {
id -> Bytea,
return_value -> Bytea,
contract_address -> Bytea,
block_number -> Integer,
}
}
table! {
/// When was a cached call on a contract last used? This is useful to clean old data.
eth_call_meta (contract_address) {
contract_address -> Bytea,
accessed_at -> Date,
}
}
joinable!(eth_call_cache -> eth_call_meta (contract_address));
allow_tables_to_appear_in_same_query!(eth_call_cache, eth_call_meta);
}
// Helper for literal SQL queries that look up a block hash
#[derive(QueryableByName)]
struct BlockHashText {
#[diesel(sql_type = Text)]
hash: String,
}
#[derive(QueryableByName)]
struct BlockHashBytea {
#[diesel(sql_type = Bytea)]
hash: Vec<u8>,
}
// Like B256::from_slice, but returns an error instead of panicking
// when `bytes` does not have the right length
fn b256_from_bytes(bytes: &[u8]) -> Result<B256, StoreError> {
if bytes.len() == B256::len_bytes() {
Ok(B256::from_slice(bytes))
} else {
Err(internal_error!(
"invalid H256 value `{}` has {} bytes instead of {}",
graph::prelude::hex::encode(bytes),
bytes.len(),
B256::len_bytes()
))
}
}
type DynTable = diesel_dynamic_schema::Table<String>;
type DynColumn<ST> = diesel_dynamic_schema::Column<DynTable, &'static str, ST>;
/// The table that holds blocks when we store a chain in its own
/// dedicated database schema
#[derive(Clone, Debug)]
struct BlocksTable {
/// The fully qualified name of the blocks table, including the
/// schema
qname: String,
table: DynTable,
}
impl BlocksTable {
const TABLE_NAME: &'static str = "blocks";
fn new(namespace: &str) -> Self {
BlocksTable {
qname: format!("{}.{}", namespace, Self::TABLE_NAME),
table: diesel_dynamic_schema::schema(namespace.to_string())
.table(Self::TABLE_NAME.to_string()),
}
}
fn table(&self) -> DynTable {
self.table.clone()
}
fn hash(&self) -> DynColumn<Bytea> {
self.table.column::<Bytea, _>("hash")
}
fn number(&self) -> DynColumn<BigInt> {
self.table.column::<BigInt, _>("number")
}
fn parent_hash(&self) -> DynColumn<Bytea> {
self.table.column::<Bytea, _>("parent_hash")
}
fn data(&self) -> DynColumn<Jsonb> {
self.table.column::<Jsonb, _>("data")
}
}
#[derive(Clone, Debug)]
struct CallMetaTable {
qname: String,
table: DynTable,
}
impl CallMetaTable {
const TABLE_NAME: &'static str = "call_meta";
const ACCESSED_AT: &'static str = "accessed_at";
fn new(namespace: &str) -> Self {
CallMetaTable {
qname: format!("{}.{}", namespace, Self::TABLE_NAME),
table: diesel_dynamic_schema::schema(namespace.to_string())
.table(Self::TABLE_NAME.to_string()),
}
}
fn table(&self) -> DynTable {
self.table.clone()
}
fn contract_address(&self) -> DynColumn<Bytea> {
self.table.column::<Bytea, _>("contract_address")
}
}
#[derive(Clone, Debug)]
struct CallCacheTable {
qname: String,
table: DynTable,
}
impl CallCacheTable {
const TABLE_NAME: &'static str = "call_cache";
fn new(namespace: &str) -> Self {
CallCacheTable {
qname: format!("{}.{}", namespace, Self::TABLE_NAME),
table: diesel_dynamic_schema::schema(namespace.to_string())
.table(Self::TABLE_NAME.to_string()),
}
}
fn table(&self) -> DynTable {
self.table.clone()
}
fn id(&self) -> DynColumn<Bytea> {
self.table.column::<Bytea, _>("id")
}
fn block_number(&self) -> DynColumn<BigInt> {
self.table.column::<BigInt, _>("block_number")
}
fn return_value(&self) -> DynColumn<Bytea> {
self.table.column::<Bytea, _>("return_value")
}
fn contract_address(&self) -> DynColumn<Bytea> {
self.table.column::<Bytea, _>("contract_address")
}
}
#[derive(Clone, Debug)]
pub struct Schema {
name: String,
blocks: BlocksTable,
call_meta: CallMetaTable,
call_cache: CallCacheTable,
}
impl Schema {
fn new(name: String) -> Self {
let blocks = BlocksTable::new(&name);
let call_meta = CallMetaTable::new(&name);
let call_cache = CallCacheTable::new(&name);
Self {
name,
blocks,
call_meta,
call_cache,
}
}
}
#[derive(Clone, Debug, AsExpression, FromSqlRow)]
#[diesel(sql_type = Text)]
#[allow(clippy::large_enum_variant)]
/// Storage for a chain. The underlying namespace (database schema) is either
/// `public` or of the form `chain[0-9]+`.
pub enum Storage {
/// Chain data is stored in shared tables
Shared,
/// The chain has its own namespace in the database with dedicated
/// tables
Private(Schema),
}
impl fmt::Display for Storage {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Shared => Self::PUBLIC.fmt(f),
Self::Private(Schema { name, .. }) => name.fmt(f),
}
}
}
impl FromSql<Text, Pg> for Storage {
fn from_sql(bytes: diesel::pg::PgValue) -> diesel::deserialize::Result<Self> {
let s = <String as FromSql<Text, Pg>>::from_sql(bytes)?;
Self::new(s).map_err(Into::into)
}
}
impl ToSql<Text, Pg> for Storage {
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Pg>) -> diesel::serialize::Result {
let s = self.to_string();
<String as ToSql<Text, Pg>>::to_sql(&s, &mut out.reborrow())
}
}
impl Storage {
const PREFIX: &'static str = "chain";
const PUBLIC: &'static str = "public";
pub fn new(s: String) -> Result<Self, String> {
if s.as_str() == Self::PUBLIC {
return Ok(Self::Shared);
}
if !s.starts_with(Self::PREFIX) || s.len() <= Self::PREFIX.len() {
return Err(s);
}
for c in s.chars().skip(Self::PREFIX.len()) {
if !c.is_numeric() {
return Err(s);
}
}
Ok(Self::Private(Schema::new(s)))
}
/// Create dedicated database tables for this chain if it uses
/// `Storage::Private`. If it uses `Storage::Shared`, do nothing since
/// a regular migration will already have created the `ethereum_blocks`
/// table
pub(super) async fn create(&self, conn: &mut AsyncPgConnection) -> Result<(), Error> {
fn make_ddl(nsp: &str) -> String {
format!(
"
create schema {nsp};
create table {nsp}.blocks (
hash bytea not null primary key,
number int8 not null,
parent_hash bytea not null,
data jsonb not null
);
create index blocks_number ON {nsp}.blocks using btree(number);
create table {nsp}.call_cache (
id bytea not null primary key,
return_value bytea not null,
contract_address bytea not null,
block_number int4 not null
);
create index call_cache_block_number_idx ON {nsp}.call_cache(block_number);
create table {nsp}.call_meta (
contract_address bytea not null primary key,
accessed_at date not null
);
",
nsp = nsp
)
}
match self {
Storage::Shared => Ok(()),
Storage::Private(Schema { name, .. }) => {
conn.batch_execute(&make_ddl(name)).await?;
Ok(())
}
}
}
/// Returns a fully qualified table name to the blocks table
#[inline]
fn blocks_table(&self) -> &str {
match self {
Storage::Shared => ETHEREUM_BLOCKS_TABLE_NAME,
Storage::Private(Schema { blocks, .. }) => &blocks.qname,
}
}
pub(super) async fn drop_storage(
&self,
conn: &mut AsyncPgConnection,
name: &str,
) -> Result<(), StoreError> {
match &self {
Storage::Shared => {
use public::ethereum_blocks as b;
delete(b::table.filter(b::network_name.eq(name)))
.execute(conn)
.await?;
Ok(())
}
Storage::Private(Schema { name, .. }) => {
conn.batch_execute(&format!("drop schema {} cascade", name))
.await?;
Ok(())
}
}
}
pub(super) async fn truncate_block_cache(
&self,
conn: &mut AsyncPgConnection,
) -> Result<(), StoreError> {
let table_name = match &self {
Storage::Shared => ETHEREUM_BLOCKS_TABLE_NAME,
Storage::Private(Schema { blocks, .. }) => &blocks.qname,
};
conn.batch_execute(&format!("truncate table {} restart identity", table_name))
.await?;
Ok(())
}
async fn truncate_call_cache(
&self,
conn: &mut AsyncPgConnection,
) -> Result<(), StoreError> {
let table_name = match &self {
Storage::Shared => ETHEREUM_CALL_CACHE_TABLE_NAME,
Storage::Private(Schema { call_cache, .. }) => &call_cache.qname,
};
conn.batch_execute(&format!("truncate table {} restart identity", table_name))
.await?;
Ok(())
}
pub(super) async fn cleanup_shallow_blocks(
&self,
conn: &mut AsyncPgConnection,
lowest_block: i32,
) -> Result<(), StoreError> {
let table_name = match &self {
Storage::Shared => ETHEREUM_BLOCKS_TABLE_NAME,
Storage::Private(Schema { blocks, .. }) => &blocks.qname,
};
conn.batch_execute(&format!(
"delete from {} WHERE number >= {} AND data->'block'->'data' = 'null'::jsonb;",
table_name, lowest_block,
))
.await?;
Ok(())
}
pub(super) async fn remove_cursor(
&self,
conn: &mut AsyncPgConnection,
chain: &str,
) -> Result<Option<BlockNumber>, StoreError> {
use diesel::dsl::not;
use public::ethereum_networks as n;
let head_block_number = update(
n::table
.filter(n::name.eq(chain))
.filter(not(n::head_block_cursor.is_null())),
)
.set(n::head_block_cursor.eq(None as Option<String>))
.returning(n::head_block_number)
.get_result::<Option<i64>>(conn)
.await
.optional()?
.flatten()
.map(|num| num as i32);
Ok(head_block_number)
}
/// Insert a block. If the table already contains a block with the
/// same hash, then overwrite that block since it may be adding
/// transaction receipts. If `overwrite` is `true`, overwrite a
/// possibly existing entry. If it is `false`, keep the old entry.
pub(super) async fn upsert_block(
&self,
conn: &mut AsyncPgConnection,
chain: &str,
block: &dyn Block,
overwrite: bool,
) -> Result<(), StoreError> {
// Hash indicating 'no parent'. It seems to be customary at
// least on EVM-compatible chains to fill the parent hash of the
// genesis block with this value
const NO_PARENT: &str =
"0000000000000000000000000000000000000000000000000000000000000000";
let number = block.number() as i64;
let data = block.data().expect("Failed to serialize block");
let hash = block.hash();
let parent_hash = block.parent_hash().unwrap_or_else(|| {
BlockHash::try_from(NO_PARENT).expect("NO_PARENT is a valid hash")
});
match self {
Storage::Shared => {
use public::ethereum_blocks as b;
let values = (
b::hash.eq(hash.hash_hex()),
b::number.eq(number),
b::parent_hash.eq(parent_hash.hash_hex()),
b::network_name.eq(chain),
b::data.eq(data),
);
if overwrite {
insert_into(b::table)
.values(values.clone())
.on_conflict(b::hash)
.do_update()
.set(values)
.execute(conn)
.await?;
} else {
insert_into(b::table)
.values(values.clone())
.on_conflict(b::hash)
.do_nothing()
.execute(conn)
.await?;
}
}
Storage::Private(Schema { blocks, .. }) => {
let query = if overwrite {
format!(
"insert into {}(hash, number, parent_hash, data) \
values ($1, $2, $3, $4) \
on conflict(hash) \
do update set number = $2, parent_hash = $3, data = $4",
blocks.qname,
)
} else {
format!(
"insert into {}(hash, number, parent_hash, data) \
values ($1, $2, $3, $4) \
on conflict(hash) do nothing",
blocks.qname
)
};
sql_query(query)
.bind::<Bytea, _>(hash.as_slice())
.bind::<BigInt, _>(number)
.bind::<Bytea, _>(parent_hash.as_slice())
.bind::<Jsonb, _>(data)
.execute(conn)
.await?;
}
};
Ok(())
}
pub(super) async fn block_ptrs_by_numbers(
&self,
conn: &mut AsyncPgConnection,
chain: &str,
numbers: &[BlockNumber],
) -> Result<Vec<JsonBlock>, StoreError> {
let x = match self {
Storage::Shared => {
use public::ethereum_blocks as b;
b::table
.select((
b::hash,
b::number,
b::parent_hash,
sql::<Jsonb>("coalesce(data -> 'block', data)"),
))
.filter(b::network_name.eq(chain))
.filter(b::number.eq_any(Vec::from_iter(numbers.iter().map(|&n| n as i64))))
.load::<(BlockHash, i64, BlockHash, json::Value)>(conn)
.await
}
Storage::Private(Schema { blocks, .. }) => {
blocks
.table()
.select((
blocks.hash(),
blocks.number(),
blocks.parent_hash(),
sql::<Jsonb>("coalesce(data -> 'block', data)"),
))
.filter(
blocks
.number()
.eq_any(Vec::from_iter(numbers.iter().map(|&n| n as i64))),
)
.load::<(BlockHash, i64, BlockHash, json::Value)>(conn)
.await
}
}?;
Ok(x.into_iter()
.map(|(hash, nr, parent, data)| {
JsonBlock::new(BlockPtr::new(hash, nr as i32), parent, Some(data))
})
.collect())
}
pub(super) async fn blocks(
&self,
conn: &mut AsyncPgConnection,
chain: &str,
hashes: &[BlockHash],
) -> Result<Vec<JsonBlock>, StoreError> {
// We need to deal with chain stores where some entries have a
// toplevel 'block' field and others directly contain what would
// be in the 'block' field. Make sure we return the contents of
// the 'block' field if it exists, otherwise assume the whole
// Json object is what should be in 'block'
//
// see also 7736e440-4c6b-11ec-8c4d-b42e99f52061
let x = match self {
Storage::Shared => {
use public::ethereum_blocks as b;
b::table
.select((
b::hash,
b::number,
b::parent_hash,
sql::<Jsonb>("coalesce(data -> 'block', data)"),
))
.filter(b::network_name.eq(chain))
.filter(
b::hash
.eq_any(Vec::from_iter(hashes.iter().map(|h| format!("{:x}", h)))),
)
.load::<(BlockHash, i64, BlockHash, json::Value)>(conn)
.await
}
Storage::Private(Schema { blocks, .. }) => {
blocks
.table()
.select((
blocks.hash(),
blocks.number(),
blocks.parent_hash(),
sql::<Jsonb>("coalesce(data -> 'block', data)"),
))
.filter(
blocks
.hash()
.eq_any(Vec::from_iter(hashes.iter().map(|h| h.as_slice()))),
)
.load::<(BlockHash, i64, BlockHash, json::Value)>(conn)
.await
}
}?;
Ok(x.into_iter()
.map(|(hash, nr, parent, data)| {
JsonBlock::new(BlockPtr::new(hash, nr as i32), parent, Some(data))
})
.collect())
}
/// Return the parent block pointer for the block with the given hash.
/// Only reads header columns, not the data column.
pub(super) async fn block_parent_ptr(
&self,
conn: &mut AsyncPgConnection,
chain: &str,
hash: &BlockHash,
) -> Result<Option<BlockPtr>, Error> {
let result = match self {
Storage::Shared => {
use public::ethereum_blocks as b;
let (child, parent) = diesel::alias!(
public::ethereum_blocks as child,
public::ethereum_blocks as parent
);
child
.inner_join(
parent.on(child
.field(b::parent_hash)
.assume_not_null()
.eq(parent.field(b::hash))
.and(parent.field(b::network_name).eq(chain))),
)
.select((parent.field(b::hash), parent.field(b::number)))
.filter(child.field(b::hash).eq(format!("{:x}", hash)))
.filter(child.field(b::network_name).eq(chain))
.first::<(String, i64)>(conn)
.await
.optional()?
.map(|(h, n)| {
Ok::<_, Error>(BlockPtr::new(h.parse()?, i32::try_from(n).unwrap()))
})
.transpose()?
}
Storage::Private(Schema { blocks, .. }) => {
// We can't use diesel::alias! here because the table is
// dynamic, so we write the SQL query manually
let query = format!(
"SELECT parent.hash, parent.number \
FROM {qname} child, {qname} parent \
WHERE child.hash = $1 \
AND child.parent_hash = parent.hash",
qname = blocks.qname
);
#[derive(QueryableByName)]
struct BlockHashAndNumber {
#[diesel(sql_type = Bytea)]
hash: Vec<u8>,
#[diesel(sql_type = BigInt)]
number: i64,
}
sql_query(query)
.bind::<Bytea, _>(hash.as_slice())
.get_result::<BlockHashAndNumber>(conn)
.await
.optional()?
.map(|block| BlockPtr::from((block.hash, block.number)))
}
};
Ok(result)
}
pub(super) async fn block_hashes_by_block_number(
&self,
conn: &mut AsyncPgConnection,
chain: &str,
number: BlockNumber,
) -> Result<Vec<BlockHash>, Error> {
match self {
Storage::Shared => {
use public::ethereum_blocks as b;
b::table
.select(b::hash)
.filter(b::network_name.eq(&chain))
.filter(b::number.eq(number as i64))
.get_results::<String>(conn)
.await?
.into_iter()
.map(|h| h.parse())
.collect::<Result<Vec<BlockHash>, _>>()
}
Storage::Private(Schema { blocks, .. }) => Ok(blocks
.table()
.select(blocks.hash())
.filter(blocks.number().eq(number as i64))
.get_results::<Vec<u8>>(conn)
.await?
.into_iter()
.map(BlockHash::from)
.collect::<Vec<BlockHash>>()),
}
}
pub(super) async fn confirm_block_hash(
&self,
conn: &mut AsyncPgConnection,
chain: &str,
number: BlockNumber,
hash: &BlockHash,
) -> Result<usize, Error> {
let number = number as i64;
match self {
Storage::Shared => {
use public::ethereum_blocks as b;
let hash = format!("{:x}", hash);
diesel::delete(b::table)
.filter(b::network_name.eq(chain))
.filter(b::number.eq(number))
.filter(b::hash.ne(&hash))
.execute(conn)
.await
.map_err(Error::from)
}
Storage::Private(Schema { blocks, .. }) => {
let query = format!(
"delete from {} where number = $1 and hash != $2",
blocks.qname
);
sql_query(query)
.bind::<BigInt, _>(number)
.bind::<Bytea, _>(hash.as_slice())
.execute(conn)
.await
.map_err(Error::from)
}
}
}
/// timestamp's representation depends the blockchain::Block implementation, on
/// ethereum this is a U256 but on different chains it will most likely be different.
pub(super) async fn block_number(
&self,
conn: &mut AsyncPgConnection,
hash: &BlockHash,
) -> Result<Option<(BlockNumber, Option<u64>, Option<BlockHash>)>, StoreError> {
const TIMESTAMP_QUERY: &str =
"coalesce(data->'block'->>'timestamp', data->>'timestamp')";
let number = match self {
Storage::Shared => {
use public::ethereum_blocks as b;
b::table
.select((
b::number,
sql::<Nullable<Text>>(TIMESTAMP_QUERY),
b::parent_hash,
))
.filter(b::hash.eq(format!("{:x}", hash)))
.first::<(i64, Option<String>, Option<String>)>(conn)
.await
.optional()?
.map(|(number, ts, parent_hash)| {
// Convert parent_hash from Hex String to Vec<u8>
let parent_hash_bytes = parent_hash
.map(|h| hex::decode(&h).expect("Invalid hex in parent_hash"));
(number, ts, parent_hash_bytes)
})
}
Storage::Private(Schema { blocks, .. }) => blocks
.table()
.select((
blocks.number(),
sql::<Nullable<Text>>(TIMESTAMP_QUERY),
blocks.parent_hash(),
))
.filter(blocks.hash().eq(hash.as_slice()))
.first::<(i64, Option<String>, Vec<u8>)>(conn)
.await
.optional()?
.map(|(number, ts, parent_hash)| (number, ts, Some(parent_hash))),
};
match number {
None => Ok(None),
Some((number, ts, parent_hash)) => {
let number = BlockNumber::try_from(number)
.map_err(|e| StoreError::QueryExecutionError(e.to_string()))?;
Ok(Some((
number,
crate::chain_store::try_parse_timestamp(ts)?,
parent_hash.map(BlockHash::from),
)))
}
}
}
pub(super) async fn block_numbers(
&self,
conn: &mut AsyncPgConnection,
hashes: &[BlockHash],
) -> Result<HashMap<BlockHash, BlockNumber>, StoreError> {
let pairs = match self {
Storage::Shared => {
use public::ethereum_blocks as b;
let hashes = hashes
.iter()
.map(|h| format!("{:x}", h))
.collect::<Vec<String>>();
b::table
.select((b::hash, b::number))
.filter(b::hash.eq_any(hashes))
.load::<(String, i64)>(conn)
.await?
.into_iter()
.map(|(hash, n)| {
let hash = hex::decode(&hash).expect("Invalid hex in parent_hash");
(BlockHash::from(hash), n)
})
.collect::<Vec<_>>()
}
Storage::Private(Schema { blocks, .. }) => {
// let hashes: Vec<_> = hashes.into_iter().map(|hash| &hash.0).collect();
blocks
.table()
.select((blocks.hash(), blocks.number()))
.filter(blocks.hash().eq_any(hashes))
.load::<(BlockHash, i64)>(conn)
.await?
}
};
let pairs = pairs
.into_iter()
.map(|(hash, number)| (hash, number as i32));
Ok(HashMap::from_iter(pairs))
}
/// Find the first block that is missing from the database needed to
/// complete the chain from block `hash` to the block with number
/// `first_block`.
pub(super) async fn missing_parent(
&self,
conn: &mut AsyncPgConnection,
chain: &str,