-
Notifications
You must be signed in to change notification settings - Fork 991
/
ethereum_adapter.rs
1848 lines (1704 loc) · 71.4 KB
/
ethereum_adapter.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 futures::future;
use futures::prelude::*;
use graph::blockchain::BlockHash;
use graph::blockchain::ChainIdentifier;
use graph::components::transaction_receipt::LightTransactionReceipt;
use graph::data::subgraph::UnifiedMappingApiVersion;
use graph::prelude::ethabi::ParamType;
use graph::prelude::ethabi::Token;
use graph::prelude::tokio::try_join;
use graph::prelude::StopwatchMetrics;
use graph::{
blockchain::{block_stream::BlockWithTriggers, BlockPtr, IngestorError},
prelude::{
anyhow::{self, anyhow, bail},
async_trait, debug, error, ethabi,
futures03::{self, compat::Future01CompatExt, FutureExt, StreamExt, TryStreamExt},
hex, info, retry, serde_json as json, stream, tiny_keccak, trace, warn,
web3::{
self,
types::{
Address, Block, BlockId, BlockNumber as Web3BlockNumber, Bytes, CallRequest,
Filter, FilterBuilder, Log, Transaction, TransactionReceipt, H256,
},
},
BlockNumber, ChainStore, CheapClone, DynTryFuture, Error, EthereumCallCache, Logger,
TimeoutError, TryFutureExt,
},
};
use graph::{
components::ethereum::*,
prelude::web3::api::Web3,
prelude::web3::transports::batch::Batch,
prelude::web3::types::{Trace, TraceFilter, TraceFilterBuilder, H160},
};
use itertools::Itertools;
use lazy_static::lazy_static;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::convert::TryFrom;
use std::iter::FromIterator;
use std::sync::Arc;
use std::time::Instant;
use crate::chain::BlockFinality;
use crate::{
adapter::{
EthGetLogsFilter, EthereumAdapter as EthereumAdapterTrait, EthereumBlockFilter,
EthereumCallFilter, EthereumContractCall, EthereumContractCallError, EthereumLogFilter,
ProviderEthRpcMetrics, SubgraphEthRpcMetrics,
},
transport::Transport,
trigger::{EthereumBlockTriggerType, EthereumTrigger},
TriggerFilter,
};
#[derive(Clone)]
pub struct EthereumAdapter {
logger: Logger,
url_hostname: Arc<String>,
/// The label for the provider from the configuration
provider: String,
web3: Arc<Web3<Transport>>,
metrics: Arc<ProviderEthRpcMetrics>,
supports_eip_1898: bool,
}
lazy_static! {
static ref TRACE_STREAM_STEP_SIZE: BlockNumber = std::env::var("ETHEREUM_TRACE_STREAM_STEP_SIZE")
.unwrap_or("50".into())
.parse::<BlockNumber>()
.expect("invalid trace stream step size");
/// Maximum range size for `eth.getLogs` requests that dont filter on
/// contract address, only event signature, and are therefore expensive.
///
/// According to Ethereum node operators, size 500 is reasonable here.
static ref MAX_EVENT_ONLY_RANGE: BlockNumber = std::env::var("GRAPH_ETHEREUM_MAX_EVENT_ONLY_RANGE")
.unwrap_or("500".into())
.parse::<BlockNumber>()
.expect("invalid number of parallel Ethereum block ranges to scan");
static ref BLOCK_BATCH_SIZE: usize = std::env::var("ETHEREUM_BLOCK_BATCH_SIZE")
.unwrap_or("10".into())
.parse::<usize>()
.expect("invalid ETHEREUM_BLOCK_BATCH_SIZE env var");
/// This should not be too large that it causes requests to timeout without us catching it, nor
/// too small that it causes us to timeout requests that would've succeeded. We've seen
/// successful `eth_getLogs` requests take over 120 seconds.
static ref JSON_RPC_TIMEOUT: u64 = std::env::var("GRAPH_ETHEREUM_JSON_RPC_TIMEOUT")
.unwrap_or("180".into())
.parse::<u64>()
.expect("invalid GRAPH_ETHEREUM_JSON_RPC_TIMEOUT env var");
/// This is used for requests that will not fail the subgraph if the limit is reached, but will
/// simply restart the syncing step, so it can be low. This limit guards against scenarios such
/// as requesting a block hash that has been reorged.
static ref REQUEST_RETRIES: usize = std::env::var("GRAPH_ETHEREUM_REQUEST_RETRIES")
.unwrap_or("10".into())
.parse::<usize>()
.expect("invalid GRAPH_ETHEREUM_REQUEST_RETRIES env var");
/// Additional deterministic errors that have not yet been hardcoded. Separated by `;`.
static ref GETH_ETH_CALL_ERRORS_ENV: Vec<String> = {
std::env::var("GRAPH_GETH_ETH_CALL_ERRORS")
.map(|s| s.split(';').filter(|s| s.len() > 0).map(ToOwned::to_owned).collect())
.unwrap_or(Vec::new())
};
}
/// Gas limit for `eth_call`. The value of 50_000_000 is a protocol-wide parameter so this
/// should be changed only for debugging purposes and never on an indexer in the network. This
/// value was chosen because it is the Geth default
/// https://github.com/ethereum/go-ethereum/blob/e4b687cf462870538743b3218906940ae590e7fd/eth/ethconfig/config.go#L91.
/// It is not safe to set something higher because Geth will silently override the gas limit
/// with the default. This means that we do not support indexing against a Geth node with
/// `RPCGasCap` set below 50 million.
// See also f0af4ab0-6b7c-4b68-9141-5b79346a5f61.
const ETH_CALL_GAS: u32 = 50_000_000;
impl CheapClone for EthereumAdapter {
fn cheap_clone(&self) -> Self {
Self {
logger: self.logger.clone(),
provider: self.provider.clone(),
url_hostname: self.url_hostname.cheap_clone(),
web3: self.web3.cheap_clone(),
metrics: self.metrics.cheap_clone(),
supports_eip_1898: self.supports_eip_1898,
}
}
}
impl EthereumAdapter {
pub async fn new(
logger: Logger,
provider: String,
url: &str,
transport: Transport,
provider_metrics: Arc<ProviderEthRpcMetrics>,
supports_eip_1898: bool,
) -> Self {
// Unwrap: The transport was constructed with this url, so it is valid and has a host.
let hostname = graph::url::Url::parse(url)
.unwrap()
.host_str()
.unwrap()
.to_string();
let web3 = Arc::new(Web3::new(transport));
// Use the client version to check if it is ganache. For compatibility with unit tests, be
// are lenient with errors, defaulting to false.
let is_ganache = web3
.web3()
.client_version()
.await
.map(|s| s.contains("TestRPC"))
.unwrap_or(false);
EthereumAdapter {
logger,
provider,
url_hostname: Arc::new(hostname),
web3,
metrics: provider_metrics,
supports_eip_1898: supports_eip_1898 && !is_ganache,
}
}
async fn traces(
self,
logger: Logger,
subgraph_metrics: Arc<SubgraphEthRpcMetrics>,
from: BlockNumber,
to: BlockNumber,
addresses: Vec<H160>,
) -> Result<Vec<Trace>, Error> {
let eth = self.clone();
retry("trace_filter RPC call", &logger)
.limit(*REQUEST_RETRIES)
.timeout_secs(*JSON_RPC_TIMEOUT)
.run(move || {
let trace_filter: TraceFilter = match addresses.len() {
0 => TraceFilterBuilder::default()
.from_block(from.into())
.to_block(to.into())
.build(),
_ => TraceFilterBuilder::default()
.from_block(from.into())
.to_block(to.into())
.to_address(addresses.clone())
.build(),
};
let eth = eth.cheap_clone();
let logger_for_triggers = logger.clone();
let logger_for_error = logger.clone();
let start = Instant::now();
let subgraph_metrics = subgraph_metrics.clone();
let provider_metrics = eth.metrics.clone();
let provider = self.provider.clone();
async move {
let result = eth
.web3
.trace()
.filter(trace_filter)
.await
.map(move |traces| {
if traces.len() > 0 {
if to == from {
debug!(
logger_for_triggers,
"Received {} traces for block {}",
traces.len(),
to
);
} else {
debug!(
logger_for_triggers,
"Received {} traces for blocks [{}, {}]",
traces.len(),
from,
to
);
}
}
traces
})
.map_err(Error::from);
let elapsed = start.elapsed().as_secs_f64();
provider_metrics.observe_request(elapsed, "trace_filter", &provider);
subgraph_metrics.observe_request(elapsed, "trace_filter", &provider);
if result.is_err() {
provider_metrics.add_error("trace_filter", &provider);
subgraph_metrics.add_error("trace_filter", &provider);
debug!(
logger_for_error,
"Error querying traces error = {:?} from = {:?} to = {:?}",
result,
from,
to
);
}
result
}
})
.map_err(move |e| {
e.into_inner().unwrap_or_else(move || {
anyhow::anyhow!(
"Ethereum node took too long to respond to trace_filter \
(from block {}, to block {})",
from,
to
)
})
})
.await
}
async fn logs_with_sigs(
&self,
logger: Logger,
subgraph_metrics: Arc<SubgraphEthRpcMetrics>,
from: BlockNumber,
to: BlockNumber,
filter: Arc<EthGetLogsFilter>,
too_many_logs_fingerprints: &'static [&'static str],
) -> Result<Vec<Log>, TimeoutError<web3::error::Error>> {
let eth_adapter = self.clone();
retry("eth_getLogs RPC call", &logger)
.when(move |res: &Result<_, web3::error::Error>| match res {
Ok(_) => false,
Err(e) => !too_many_logs_fingerprints
.iter()
.any(|f| e.to_string().contains(f)),
})
.limit(*REQUEST_RETRIES)
.timeout_secs(*JSON_RPC_TIMEOUT)
.run(move || {
let eth_adapter = eth_adapter.cheap_clone();
let subgraph_metrics = subgraph_metrics.clone();
let provider_metrics = eth_adapter.metrics.clone();
let filter = filter.clone();
let provider = eth_adapter.provider.clone();
async move {
let start = Instant::now();
// Create a log filter
let log_filter: Filter = FilterBuilder::default()
.from_block(from.into())
.to_block(to.into())
.address(filter.contracts.clone())
.topics(Some(filter.event_signatures.clone()), None, None, None)
.build();
// Request logs from client
let result = eth_adapter.web3.eth().logs(log_filter).boxed().await;
let elapsed = start.elapsed().as_secs_f64();
provider_metrics.observe_request(elapsed, "eth_getLogs", &provider);
subgraph_metrics.observe_request(elapsed, "eth_getLogs", &provider);
if result.is_err() {
provider_metrics.add_error("eth_getLogs", &provider);
subgraph_metrics.add_error("eth_getLogs", &provider);
}
result
}
})
.await
}
fn trace_stream(
self,
logger: &Logger,
subgraph_metrics: Arc<SubgraphEthRpcMetrics>,
from: BlockNumber,
to: BlockNumber,
addresses: Vec<H160>,
) -> impl Stream<Item = Trace, Error = Error> + Send {
if from > to {
panic!(
"Can not produce a call stream on a backwards block range: from = {}, to = {}",
from, to,
);
}
let step_size = *TRACE_STREAM_STEP_SIZE;
let eth = self.clone();
let logger = logger.to_owned();
stream::unfold(from, move |start| {
if start > to {
return None;
}
let end = (start + step_size - 1).min(to);
let new_start = end + 1;
if start == end {
debug!(logger, "Requesting traces for block {}", start);
} else {
debug!(logger, "Requesting traces for blocks [{}, {}]", start, end);
}
Some(futures::future::ok((
eth.clone()
.traces(
logger.cheap_clone(),
subgraph_metrics.clone(),
start,
end,
addresses.clone(),
)
.boxed()
.compat(),
new_start,
)))
})
.buffered(*BLOCK_BATCH_SIZE)
.map(stream::iter_ok)
.flatten()
}
fn log_stream(
&self,
logger: Logger,
subgraph_metrics: Arc<SubgraphEthRpcMetrics>,
from: BlockNumber,
to: BlockNumber,
filter: EthGetLogsFilter,
) -> DynTryFuture<'static, Vec<Log>, Error> {
// Codes returned by Ethereum node providers if an eth_getLogs request is too heavy.
// The first one is for Infura when it hits the log limit, the rest for Alchemy timeouts.
const TOO_MANY_LOGS_FINGERPRINTS: &[&str] = &[
"ServerError(-32005)",
"503 Service Unavailable",
"ServerError(-32000)",
];
if from > to {
panic!(
"cannot produce a log stream on a backwards block range (from={}, to={})",
from, to
);
}
// Collect all event sigs
let eth = self.cheap_clone();
let filter = Arc::new(filter);
let step = match filter.contracts.is_empty() {
// `to - from + 1` blocks will be scanned.
false => to - from,
true => (to - from).min(*MAX_EVENT_ONLY_RANGE - 1),
};
// Typically this will loop only once and fetch the entire range in one request. But if the
// node returns an error that signifies the request is to heavy to process, the range will
// be broken down to smaller steps.
futures03::stream::try_unfold((from, step), move |(start, step)| {
let logger = logger.cheap_clone();
let filter = filter.cheap_clone();
let eth = eth.cheap_clone();
let subgraph_metrics = subgraph_metrics.cheap_clone();
async move {
if start > to {
return Ok(None);
}
let end = (start + step).min(to);
debug!(
logger,
"Requesting logs for blocks [{}, {}], {}", start, end, filter
);
let res = eth
.logs_with_sigs(
logger.cheap_clone(),
subgraph_metrics.cheap_clone(),
start,
end,
filter.cheap_clone(),
TOO_MANY_LOGS_FINGERPRINTS,
)
.await;
match res {
Err(e) => {
let string_err = e.to_string();
// If the step is already 0, the request is too heavy even for a single
// block. We hope this never happens, but if it does, make sure to error.
if TOO_MANY_LOGS_FINGERPRINTS
.iter()
.any(|f| string_err.contains(f))
&& step > 0
{
// The range size for a request is `step + 1`. So it's ok if the step
// goes down to 0, in that case we'll request one block at a time.
let new_step = step / 10;
debug!(logger, "Reducing block range size to scan for events";
"new_size" => new_step + 1);
Ok(Some((vec![], (start, new_step))))
} else {
warn!(logger, "Unexpected RPC error"; "error" => &string_err);
Err(anyhow!("{}", string_err))
}
}
Ok(logs) => Ok(Some((logs, (end + 1, step)))),
}
}
})
.try_concat()
.boxed()
}
fn call(
&self,
logger: Logger,
contract_address: Address,
call_data: Bytes,
block_ptr: BlockPtr,
) -> impl Future<Item = Bytes, Error = EthereumContractCallError> + Send {
let web3 = self.web3.clone();
// Ganache does not support calls by block hash.
// See https://github.com/trufflesuite/ganache-cli/issues/973
let block_id = if !self.supports_eip_1898 {
BlockId::Number(block_ptr.number.into())
} else {
BlockId::Hash(block_ptr.hash_as_h256())
};
retry("eth_call RPC call", &logger)
.when(|result| match result {
Ok(_) | Err(EthereumContractCallError::Revert(_)) => false,
Err(_) => true,
})
.limit(10)
.timeout_secs(*JSON_RPC_TIMEOUT)
.run(move || {
let call_data = call_data.clone();
let web3 = web3.cheap_clone();
async move {
let req = CallRequest {
from: None,
to: Some(contract_address),
gas: Some(web3::types::U256::from(ETH_CALL_GAS)),
gas_price: None,
value: None,
data: Some(call_data.clone()),
};
let result = web3.eth().call(req, Some(block_id)).boxed().await;
// Try to check if the call was reverted. The JSON-RPC response for reverts is
// not standardized, so we have ad-hoc checks for each Ethereum client // Ganache.
// 0xfe is the "designated bad instruction" of the EVM, and Solidity uses it for
// asserts.
const PARITY_BAD_INSTRUCTION_FE: &str = "Bad instruction fe";
// 0xfd is REVERT, but on some contracts, and only on older blocks,
// this happens. Makes sense to consider it a revert as well.
const PARITY_BAD_INSTRUCTION_FD: &str = "Bad instruction fd";
const PARITY_BAD_JUMP_PREFIX: &str = "Bad jump";
const PARITY_STACK_LIMIT_PREFIX: &str = "Out of stack";
// See f0af4ab0-6b7c-4b68-9141-5b79346a5f61.
const PARITY_OUT_OF_GAS: &str = "Out of gas";
const PARITY_VM_EXECUTION_ERROR: i64 = -32015;
const PARITY_REVERT_PREFIX: &str = "Reverted 0x";
// Deterministic Geth execution errors. We might need to expand this as
// subgraphs come across other errors. See
// https://github.com/ethereum/go-ethereum/blob/cd57d5cd38ef692de8fbedaa56598b4e9fbfbabc/core/vm/errors.go
const GETH_EXECUTION_ERRORS: &[&str] = &[
// Hardhat format.
"error: transaction reverted",
// Ganache and Moonbeam format.
"vm exception while processing transaction: revert",
// Geth errors
"execution reverted",
"invalid jump destination",
"invalid opcode",
// Ethereum says 1024 is the stack sizes limit, so this is deterministic.
"stack limit reached 1024",
// See f0af4ab0-6b7c-4b68-9141-5b79346a5f61 for why the gas limit is considered deterministic.
"out of gas",
];
let mut geth_execution_errors = GETH_EXECUTION_ERRORS
.iter()
.map(|s| *s)
.chain(GETH_ETH_CALL_ERRORS_ENV.iter().map(|s| s.as_str()));
let as_solidity_revert_with_reason = |bytes: &[u8]| {
let solidity_revert_function_selector =
&tiny_keccak::keccak256(b"Error(string)")[..4];
match bytes.len() >= 4 && &bytes[..4] == solidity_revert_function_selector {
false => None,
true => ethabi::decode(&[ParamType::String], &bytes[4..])
.ok()
.and_then(|tokens| tokens[0].clone().into_string()),
}
};
match result {
// A successful response.
Ok(bytes) => Ok(bytes),
// Check for Geth revert.
Err(web3::Error::Rpc(rpc_error))
if geth_execution_errors
.any(|e| rpc_error.message.to_lowercase().contains(e)) =>
{
Err(EthereumContractCallError::Revert(rpc_error.message))
}
// Check for Parity revert.
Err(web3::Error::Rpc(ref rpc_error))
if rpc_error.code.code() == PARITY_VM_EXECUTION_ERROR =>
{
match rpc_error.data.as_ref().and_then(|d| d.as_str()) {
Some(data)
if data.starts_with(PARITY_REVERT_PREFIX)
|| data.starts_with(PARITY_BAD_JUMP_PREFIX)
|| data.starts_with(PARITY_STACK_LIMIT_PREFIX)
|| data == PARITY_BAD_INSTRUCTION_FE
|| data == PARITY_BAD_INSTRUCTION_FD
|| data == PARITY_OUT_OF_GAS =>
{
let reason = if data == PARITY_BAD_INSTRUCTION_FE {
PARITY_BAD_INSTRUCTION_FE.to_owned()
} else {
let payload = data.trim_start_matches(PARITY_REVERT_PREFIX);
hex::decode(payload)
.ok()
.and_then(|payload| {
as_solidity_revert_with_reason(&payload)
})
.unwrap_or("no reason".to_owned())
};
Err(EthereumContractCallError::Revert(reason))
}
// The VM execution error was not identified as a revert.
_ => Err(EthereumContractCallError::Web3Error(web3::Error::Rpc(
rpc_error.clone(),
))),
}
}
// The error was not identified as a revert.
Err(err) => Err(EthereumContractCallError::Web3Error(err)),
}
}
})
.map_err(|e| e.into_inner().unwrap_or(EthereumContractCallError::Timeout))
.boxed()
.compat()
}
/// Request blocks by hash through JSON-RPC.
fn load_blocks_rpc(
&self,
logger: Logger,
ids: Vec<H256>,
) -> impl Stream<Item = Arc<LightEthereumBlock>, Error = Error> + Send {
let web3 = self.web3.clone();
stream::iter_ok::<_, Error>(ids.into_iter().map(move |hash| {
let web3 = web3.clone();
retry(format!("load block {}", hash), &logger)
.limit(*REQUEST_RETRIES)
.timeout_secs(*JSON_RPC_TIMEOUT)
.run(move || {
Box::pin(web3.eth().block_with_txs(BlockId::Hash(hash)))
.compat()
.from_err::<Error>()
.and_then(move |block| {
block.map(|block| Arc::new(block)).ok_or_else(|| {
anyhow::anyhow!("Ethereum node did not find block {:?}", hash)
})
})
.compat()
})
.boxed()
.compat()
.from_err()
}))
.buffered(*BLOCK_BATCH_SIZE)
}
/// Request blocks ptrs for numbers through JSON-RPC.
///
/// Reorg safety: If ids are numbers, they must be a final blocks.
fn load_block_ptrs_rpc(
&self,
logger: Logger,
block_nums: Vec<BlockNumber>,
) -> impl Stream<Item = BlockPtr, Error = Error> + Send {
let web3 = self.web3.clone();
stream::iter_ok::<_, Error>(block_nums.into_iter().map(move |block_num| {
let web3 = web3.clone();
retry(format!("load block ptr {}", block_num), &logger)
.no_limit()
.timeout_secs(*JSON_RPC_TIMEOUT)
.run(move || {
let web3 = web3.clone();
async move {
let block = web3
.eth()
.block(BlockId::Number(Web3BlockNumber::Number(block_num.into())))
.boxed()
.await?;
block.ok_or_else(|| {
anyhow!("Ethereum node did not find block {:?}", block_num)
})
}
})
.boxed()
.compat()
.from_err()
}))
.buffered(*BLOCK_BATCH_SIZE)
.map(|b| b.into())
}
/// Check if `block_ptr` refers to a block that is on the main chain, according to the Ethereum
/// node.
///
/// Careful: don't use this function without considering race conditions.
/// Chain reorgs could happen at any time, and could affect the answer received.
/// Generally, it is only safe to use this function with blocks that have received enough
/// confirmations to guarantee no further reorgs, **and** where the Ethereum node is aware of
/// those confirmations.
/// If the Ethereum node is far behind in processing blocks, even old blocks can be subject to
/// reorgs.
pub(crate) async fn is_on_main_chain(
&self,
logger: &Logger,
block_ptr: BlockPtr,
) -> Result<bool, Error> {
let block_hash = self
.block_hash_by_block_number(&logger, block_ptr.number)
.compat()
.await?;
block_hash
.ok_or_else(|| anyhow!("Ethereum node is missing block #{}", block_ptr.number))
.map(|block_hash| block_hash == block_ptr.hash_as_h256())
}
pub(crate) fn logs_in_block_range(
&self,
logger: &Logger,
subgraph_metrics: Arc<SubgraphEthRpcMetrics>,
from: BlockNumber,
to: BlockNumber,
log_filter: EthereumLogFilter,
) -> DynTryFuture<'static, Vec<Log>, Error> {
let eth: Self = self.cheap_clone();
let logger = logger.clone();
futures03::stream::iter(log_filter.eth_get_logs_filters().map(move |filter| {
eth.cheap_clone().log_stream(
logger.cheap_clone(),
subgraph_metrics.cheap_clone(),
from,
to,
filter,
)
}))
// Real limits on the number of parallel requests are imposed within the adapter.
.buffered(1000)
.try_concat()
.boxed()
}
pub(crate) fn calls_in_block_range<'a>(
&self,
logger: &Logger,
subgraph_metrics: Arc<SubgraphEthRpcMetrics>,
from: BlockNumber,
to: BlockNumber,
call_filter: &'a EthereumCallFilter,
) -> Box<dyn Stream<Item = EthereumCall, Error = Error> + Send + 'a> {
let eth = self.clone();
let addresses: Vec<H160> = call_filter
.contract_addresses_function_signatures
.iter()
.filter(|(_addr, (start_block, _fsigs))| start_block <= &to)
.map(|(addr, (_start_block, _fsigs))| *addr)
.collect::<HashSet<H160>>()
.into_iter()
.collect::<Vec<H160>>();
if addresses.is_empty() {
// The filter has no started data sources in the requested range, nothing to do.
// This prevents an expensive call to `trace_filter` with empty `addresses`.
return Box::new(stream::empty());
}
Box::new(
eth.trace_stream(&logger, subgraph_metrics, from, to, addresses)
.filter_map(|trace| EthereumCall::try_from_trace(&trace))
.filter(move |call| {
// `trace_filter` can only filter by calls `to` an address and
// a block range. Since subgraphs are subscribing to calls
// for a specific contract function an additional filter needs
// to be applied
call_filter.matches(&call)
}),
)
}
pub(crate) async fn calls_in_block(
&self,
logger: &Logger,
subgraph_metrics: Arc<SubgraphEthRpcMetrics>,
block_number: BlockNumber,
block_hash: H256,
) -> Result<Vec<EthereumCall>, Error> {
let eth = self.clone();
let addresses = Vec::new();
let traces = eth
.trace_stream(
&logger,
subgraph_metrics.clone(),
block_number,
block_number,
addresses,
)
.collect()
.compat()
.await?;
// `trace_stream` returns all of the traces for the block, and this
// includes a trace for the block reward which every block should have.
// If there are no traces something has gone wrong.
if traces.is_empty() {
return Err(anyhow!(
"Trace stream returned no traces for block: number = `{}`, hash = `{}`",
block_number,
block_hash,
));
}
// Since we can only pull traces by block number and we have
// all the traces for the block, we need to ensure that the
// block hash for the traces is equal to the desired block hash.
// Assume all traces are for the same block.
if traces.iter().nth(0).unwrap().block_hash != block_hash {
return Err(anyhow!(
"Trace stream returned traces for an unexpected block: \
number = `{}`, hash = `{}`",
block_number,
block_hash,
));
}
Ok(traces
.iter()
.filter_map(EthereumCall::try_from_trace)
.collect())
}
/// Reorg safety: `to` must be a final block.
pub(crate) fn block_range_to_ptrs(
&self,
logger: Logger,
from: BlockNumber,
to: BlockNumber,
) -> Box<dyn Future<Item = Vec<BlockPtr>, Error = Error> + Send> {
// Currently we can't go to the DB for this because there might be duplicate entries for
// the same block number.
debug!(&logger, "Requesting hashes for blocks [{}, {}]", from, to);
Box::new(
self.load_block_ptrs_rpc(logger, (from..=to).collect())
.collect(),
)
}
pub async fn chain_id(&self) -> Result<u64, Error> {
let logger = self.logger.clone();
let web3 = self.web3.clone();
u64::try_from(
retry("chain_id RPC call", &logger)
.no_limit()
.timeout_secs(*JSON_RPC_TIMEOUT)
.run(move || {
let web3 = web3.cheap_clone();
async move { web3.eth().chain_id().await }
})
.await?,
)
.map_err(Error::msg)
}
}
#[async_trait]
impl EthereumAdapterTrait for EthereumAdapter {
fn url_hostname(&self) -> &str {
&self.url_hostname
}
fn provider(&self) -> &str {
&self.provider
}
async fn net_identifiers(&self) -> Result<ChainIdentifier, Error> {
let logger = self.logger.clone();
let web3 = self.web3.clone();
let net_version_future = retry("net_version RPC call", &logger)
.no_limit()
.timeout_secs(20)
.run(move || {
let web3 = web3.cheap_clone();
async move { web3.net().version().await.map_err(Into::into) }
})
.boxed();
let web3 = self.web3.clone();
let gen_block_hash_future = retry("eth_getBlockByNumber(0, false) RPC call", &logger)
.no_limit()
.timeout_secs(30)
.run(move || {
let web3 = web3.cheap_clone();
async move {
web3.eth()
.block(BlockId::Number(Web3BlockNumber::Number(0.into())))
.await?
.map(|gen_block| gen_block.hash.map(BlockHash::from))
.flatten()
.ok_or_else(|| anyhow!("Ethereum node could not find genesis block"))
}
});
let (net_version, genesis_block_hash) =
try_join!(net_version_future, gen_block_hash_future).map_err(|e| {
anyhow!(
"Ethereum node took too long to read network identifiers: {}",
e
)
})?;
let ident = ChainIdentifier {
net_version,
genesis_block_hash,
};
Ok(ident)
}
fn latest_block_header(
&self,
logger: &Logger,
) -> Box<dyn Future<Item = web3::types::Block<H256>, Error = IngestorError> + Send> {
let web3 = self.web3.clone();
Box::new(
retry("eth_getBlockByNumber(latest) no txs RPC call", logger)
.no_limit()
.timeout_secs(*JSON_RPC_TIMEOUT)
.run(move || {
let web3 = web3.cheap_clone();
async move {
let block_opt = web3
.eth()
.block(Web3BlockNumber::Latest.into())
.await
.map_err(|e| {
anyhow!("could not get latest block from Ethereum: {}", e)
})?;
block_opt
.ok_or_else(|| anyhow!("no latest block returned from Ethereum").into())
}
})
.map_err(move |e| {
e.into_inner().unwrap_or_else(move || {
anyhow!("Ethereum node took too long to return latest block").into()
})
})
.boxed()
.compat(),
)
}
fn latest_block(
&self,
logger: &Logger,
) -> Box<dyn Future<Item = LightEthereumBlock, Error = IngestorError> + Send + Unpin> {
let web3 = self.web3.clone();
Box::new(
retry("eth_getBlockByNumber(latest) with txs RPC call", logger)
.no_limit()
.timeout_secs(*JSON_RPC_TIMEOUT)
.run(move || {
let web3 = web3.cheap_clone();
async move {
let block_opt = web3
.eth()
.block_with_txs(Web3BlockNumber::Latest.into())
.await
.map_err(|e| {
anyhow!("could not get latest block from Ethereum: {}", e)
})?;
block_opt
.ok_or_else(|| anyhow!("no latest block returned from Ethereum").into())
}
})
.map_err(move |e| {
e.into_inner().unwrap_or_else(move || {
anyhow!("Ethereum node took too long to return latest block").into()
})
})
.boxed()
.compat(),
)
}
fn load_block(
&self,
logger: &Logger,
block_hash: H256,
) -> Box<dyn Future<Item = LightEthereumBlock, Error = Error> + Send> {
Box::new(
self.block_by_hash(&logger, block_hash)
.and_then(move |block_opt| {
block_opt.ok_or_else(move || {
anyhow!(
"Ethereum node could not find block with hash {}",
block_hash
)
})
}),
)
}
fn block_by_hash(
&self,
logger: &Logger,
block_hash: H256,
) -> Box<dyn Future<Item = Option<LightEthereumBlock>, Error = Error> + Send> {
let web3 = self.web3.clone();
let logger = logger.clone();
Box::new(
retry("eth_getBlockByHash RPC call", &logger)
.limit(*REQUEST_RETRIES)
.timeout_secs(*JSON_RPC_TIMEOUT)