-
Notifications
You must be signed in to change notification settings - Fork 188
Expand file tree
/
Copy patheth.rs
More file actions
4461 lines (4010 loc) · 154 KB
/
eth.rs
File metadata and controls
4461 lines (4010 loc) · 154 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
// Copyright 2019-2026 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
pub(crate) mod errors;
mod eth_tx;
pub mod filter;
pub mod pubsub;
pub(crate) mod pubsub_trait;
mod tipset_resolver;
pub(crate) mod trace;
pub mod types;
mod utils;
pub use tipset_resolver::TipsetResolver;
use self::eth_tx::*;
use self::filter::hex_str_to_epoch;
use self::trace::types::*;
use self::types::*;
use super::gas;
use crate::blocks::{Tipset, TipsetKey};
use crate::chain::{ChainStore, index::ResolveNullTipset};
use crate::chain_sync::NodeSyncStatus;
use crate::cid_collections::CidHashSet;
use crate::eth::{
EAMMethod, EVMMethod, EthChainId as EthChainIdType, EthEip1559TxArgs, EthLegacyEip155TxArgs,
EthLegacyHomesteadTxArgs, parse_eth_transaction,
};
use crate::interpreter::VMTrace;
use crate::lotus_json::{HasLotusJson, lotus_json_with_self};
use crate::message::{ChainMessage, Message as _, SignedMessage};
use crate::rpc::{
ApiPaths, Ctx, EthEventHandler, LOOKBACK_NO_LIMIT, Permission, RpcMethod, RpcMethodExt as _,
error::ServerError,
eth::{
errors::EthErrors,
filter::{SkipEvent, event::EventFilter, mempool::MempoolFilter, tipset::TipSetFilter},
utils::decode_revert_reason,
},
methods::chain::ChainGetTipSetV2,
state::ApiInvocResult,
types::{ApiTipsetKey, EventEntry, MessageLookup},
};
use crate::shim::actors::{EVMActorStateLoad as _, eam, evm, is_evm_actor, system};
use crate::shim::address::{Address as FilecoinAddress, Protocol};
use crate::shim::crypto::Signature;
use crate::shim::econ::{BLOCK_GAS_LIMIT, TokenAmount};
use crate::shim::error::ExitCode;
use crate::shim::executor::Receipt;
use crate::shim::fvm_shared_latest::MethodNum;
use crate::shim::fvm_shared_latest::address::{Address as VmAddress, DelegatedAddress};
use crate::shim::gas::GasOutputs;
use crate::shim::message::Message;
use crate::shim::trace::{CallReturn, ExecutionEvent};
use crate::shim::{clock::ChainEpoch, state_tree::StateTree};
use crate::state_manager::{ExecutedMessage, ExecutedTipset, StateLookupPolicy, VMFlush};
use crate::utils::cache::SizeTrackingLruCache;
use crate::utils::db::BlockstoreExt as _;
use crate::utils::encoding::from_slice_with_fallback;
use crate::utils::get_size::{CidWrapper, big_int_heap_size_helper};
use crate::utils::misc::env::{env_or_default, is_env_truthy};
use crate::utils::multihash::prelude::*;
use ahash::HashSet;
use anyhow::{Context, Error, Result, anyhow, bail, ensure};
use cid::Cid;
use enumflags2::{BitFlags, make_bitflags};
use filter::{ParsedFilter, ParsedFilterTipsets};
use fvm_ipld_blockstore::Blockstore;
use fvm_ipld_encoding::{CBOR, DAG_CBOR, IPLD_RAW, RawBytes};
use get_size2::GetSize;
use ipld_core::ipld::Ipld;
use itertools::Itertools;
use nonzero_ext::nonzero;
use num::{BigInt, Zero as _};
use nunny::Vec as NonEmpty;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::num::NonZeroUsize;
use std::ops::RangeInclusive;
use std::str::FromStr;
use std::sync::{Arc, LazyLock};
use utils::{decode_payload, lookup_eth_address};
static FOREST_TRACE_FILTER_MAX_RESULT: LazyLock<u64> =
LazyLock::new(|| env_or_default("FOREST_TRACE_FILTER_MAX_RESULT", 500));
const MASKED_ID_PREFIX: [u8; 12] = [0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
/// Ethereum Bloom filter size in bits.
/// Bloom filter is used in Ethereum to minimize the number of block queries.
const BLOOM_SIZE: usize = 2048;
/// Ethereum Bloom filter size in bytes.
const BLOOM_SIZE_IN_BYTES: usize = BLOOM_SIZE / 8;
/// Ethereum Bloom filter with all bits set to 1.
const FULL_BLOOM: [u8; BLOOM_SIZE_IN_BYTES] = [0xff; BLOOM_SIZE_IN_BYTES];
/// Ethereum Bloom filter with all bits set to 0.
const EMPTY_BLOOM: [u8; BLOOM_SIZE_IN_BYTES] = [0x0; BLOOM_SIZE_IN_BYTES];
/// Ethereum address size in bytes.
const ADDRESS_LENGTH: usize = 20;
/// Ethereum Virtual Machine word size in bytes.
const EVM_WORD_LENGTH: usize = 32;
/// Keccak-256 of an RLP of an empty array.
/// In Filecoin, we don't have the concept of uncle blocks but rather use tipsets to reward miners
/// who craft blocks.
const EMPTY_UNCLES: &str = "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347";
/// Keccak-256 of the RLP of null.
const EMPTY_ROOT: &str = "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421";
/// The address used in messages to actors that have since been deleted.
const REVERTED_ETH_ADDRESS: &str = "0xff0000000000000000000000ffffffffffffffff";
// TODO(forest): https://github.com/ChainSafe/forest/issues/4436
// use ethereum_types::U256 or use lotus_json::big_int
#[derive(
Eq,
Hash,
PartialEq,
Debug,
Deserialize,
Serialize,
Default,
Clone,
JsonSchema,
derive_more::From,
derive_more::Into,
)]
pub struct EthBigInt(
#[serde(with = "crate::lotus_json::hexify")]
#[schemars(with = "String")]
pub BigInt,
);
lotus_json_with_self!(EthBigInt);
impl GetSize for EthBigInt {
fn get_heap_size(&self) -> usize {
big_int_heap_size_helper(&self.0)
}
}
impl From<TokenAmount> for EthBigInt {
fn from(amount: TokenAmount) -> Self {
(&amount).into()
}
}
impl From<&TokenAmount> for EthBigInt {
fn from(amount: &TokenAmount) -> Self {
Self(amount.atto().to_owned())
}
}
type GasPriceResult = EthBigInt;
#[derive(PartialEq, Debug, Deserialize, Serialize, Default, Clone, JsonSchema)]
pub struct Nonce(
#[schemars(with = "String")]
#[serde(with = "crate::lotus_json::hexify_bytes")]
pub ethereum_types::H64,
);
lotus_json_with_self!(Nonce);
impl GetSize for Nonce {
fn get_heap_size(&self) -> usize {
0
}
}
#[derive(PartialEq, Debug, Deserialize, Serialize, Default, Clone, JsonSchema)]
pub struct Bloom(
#[schemars(with = "String")]
#[serde(with = "crate::lotus_json::hexify_bytes")]
pub ethereum_types::Bloom,
);
lotus_json_with_self!(Bloom);
impl GetSize for Bloom {
fn get_heap_size(&self) -> usize {
0
}
}
impl Bloom {
pub fn accrue(&mut self, input: &[u8]) {
self.0.accrue(ethereum_types::BloomInput::Raw(input));
}
}
#[derive(
Eq,
Hash,
PartialEq,
Debug,
Deserialize,
Serialize,
Default,
Clone,
Copy,
JsonSchema,
derive_more::From,
derive_more::Into,
derive_more::Deref,
GetSize,
)]
pub struct EthUint64(
#[schemars(with = "String")]
#[serde(with = "crate::lotus_json::hexify")]
pub u64,
);
lotus_json_with_self!(EthUint64);
impl EthUint64 {
pub fn from_bytes(data: &[u8]) -> Result<Self> {
if data.len() != EVM_WORD_LENGTH {
bail!("eth int must be {EVM_WORD_LENGTH} bytes");
}
// big endian format stores u64 in the last 8 bytes,
// since ethereum words are 32 bytes, the first 24 bytes must be 0
if data
.get(..24)
.is_none_or(|slice| slice.iter().any(|&byte| byte != 0))
{
bail!("eth int overflows 64 bits");
}
// Extract the uint64 from the last 8 bytes
Ok(Self(u64::from_be_bytes(
data.get(24..EVM_WORD_LENGTH)
.ok_or_else(|| anyhow::anyhow!("data too short"))?
.try_into()?,
)))
}
pub fn to_hex_string(self) -> String {
format!("0x{}", hex::encode(self.0.to_be_bytes()))
}
}
#[derive(
PartialEq,
Debug,
Deserialize,
Serialize,
Default,
Clone,
Copy,
JsonSchema,
derive_more::From,
derive_more::Into,
derive_more::Deref,
GetSize,
)]
pub struct EthInt64(
#[schemars(with = "String")]
#[serde(with = "crate::lotus_json::hexify")]
pub i64,
);
lotus_json_with_self!(EthInt64);
impl EthHash {
// Should ONLY be used for blocks and Filecoin messages. Eth transactions expect a different hashing scheme.
pub fn to_cid(self) -> cid::Cid {
let mh = MultihashCode::Blake2b256
.wrap(self.0.as_bytes())
.expect("should not fail");
Cid::new_v1(DAG_CBOR, mh)
}
pub fn empty_uncles() -> Self {
Self(ethereum_types::H256::from_str(EMPTY_UNCLES).unwrap())
}
pub fn empty_root() -> Self {
Self(ethereum_types::H256::from_str(EMPTY_ROOT).unwrap())
}
}
impl From<Cid> for EthHash {
fn from(cid: Cid) -> Self {
let (_, digest, _) = cid.hash().into_inner();
EthHash(ethereum_types::H256::from_slice(&digest[0..32]))
}
}
impl From<[u8; EVM_WORD_LENGTH]> for EthHash {
fn from(value: [u8; EVM_WORD_LENGTH]) -> Self {
Self(ethereum_types::H256(value))
}
}
#[derive(
PartialEq,
Debug,
Clone,
Copy,
Serialize,
Deserialize,
Default,
JsonSchema,
strum::Display,
strum::EnumString,
)]
#[strum(serialize_all = "lowercase")]
#[serde(rename_all = "lowercase")]
pub enum Predefined {
Earliest,
Pending,
#[default]
Latest,
Safe,
Finalized,
}
#[derive(PartialEq, Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct BlockNumber {
block_number: EthInt64,
}
#[derive(PartialEq, Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct BlockHash {
block_hash: EthHash,
#[serde(default)]
require_canonical: bool,
}
#[derive(
PartialEq, Debug, Clone, Serialize, Deserialize, JsonSchema, strum::Display, derive_more::From,
)]
#[serde(untagged)]
pub enum BlockNumberOrHash {
#[schemars(with = "String")]
PredefinedBlock(Predefined),
BlockNumber(EthInt64),
BlockHash(EthHash),
BlockNumberObject(BlockNumber),
BlockHashObject(BlockHash),
}
lotus_json_with_self!(BlockNumberOrHash);
impl BlockNumberOrHash {
pub fn from_block_number(number: i64) -> Self {
Self::BlockNumber(EthInt64(number))
}
/// Construct a block number using EIP-1898 Object scheme.
///
/// For details see <https://eips.ethereum.org/EIPS/eip-1898>
pub fn from_block_number_object(number: i64) -> Self {
Self::BlockNumberObject(BlockNumber {
block_number: EthInt64(number),
})
}
/// Construct a block hash using EIP-1898 Object scheme.
///
/// For details see <https://eips.ethereum.org/EIPS/eip-1898>
pub fn from_block_hash_object(hash: EthHash, require_canonical: bool) -> Self {
Self::BlockHashObject(BlockHash {
block_hash: hash,
require_canonical,
})
}
pub fn from_str(s: &str) -> Result<Self, Error> {
if s.starts_with("0x") {
let epoch = hex_str_to_epoch(s)?;
return Ok(BlockNumberOrHash::from_block_number(epoch));
}
s.parse::<Predefined>()
.map_err(|_| anyhow!("Invalid block identifier"))
.map(BlockNumberOrHash::from)
}
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, GetSize)]
#[serde(untagged)] // try a Vec<String>, then a Vec<Tx>
pub enum Transactions {
Hash(Vec<String>),
Full(Vec<ApiEthTx>),
}
impl Transactions {
pub fn is_empty(&self) -> bool {
match self {
Self::Hash(v) => v.is_empty(),
Self::Full(v) => v.is_empty(),
}
}
}
impl PartialEq for Transactions {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Hash(a), Self::Hash(b)) => a == b,
(Self::Full(a), Self::Full(b)) => a == b,
_ => self.is_empty() && other.is_empty(),
}
}
}
impl Default for Transactions {
fn default() -> Self {
Self::Hash(vec![])
}
}
#[derive(PartialEq, Debug, Clone, Default, Serialize, Deserialize, JsonSchema, GetSize)]
#[serde(rename_all = "camelCase")]
pub struct Block {
pub hash: EthHash,
pub parent_hash: EthHash,
pub sha3_uncles: EthHash,
pub miner: EthAddress,
pub state_root: EthHash,
pub transactions_root: EthHash,
pub receipts_root: EthHash,
pub logs_bloom: Bloom,
pub difficulty: EthUint64,
pub total_difficulty: EthUint64,
pub number: EthInt64,
pub gas_limit: EthUint64,
pub gas_used: EthUint64,
pub timestamp: EthUint64,
pub extra_data: EthBytes,
pub mix_hash: EthHash,
pub nonce: Nonce,
pub base_fee_per_gas: EthBigInt,
pub size: EthUint64,
// can be Vec<Tx> or Vec<String> depending on query params
pub transactions: Transactions,
pub uncles: Vec<EthHash>,
}
/// Specifies the level of detail for transactions in Ethereum blocks.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TxInfo {
/// Return only transaction hashes
Hash,
/// Return full transaction objects
Full,
}
impl From<bool> for TxInfo {
fn from(full: bool) -> Self {
if full { TxInfo::Full } else { TxInfo::Hash }
}
}
impl Block {
pub fn new(has_transactions: bool, tipset_len: usize) -> Self {
Self {
gas_limit: EthUint64(BLOCK_GAS_LIMIT.saturating_mul(tipset_len as _)),
logs_bloom: Bloom(ethereum_types::Bloom(FULL_BLOOM)),
sha3_uncles: EthHash::empty_uncles(),
transactions_root: if has_transactions {
EthHash::default()
} else {
EthHash::empty_root()
},
..Default::default()
}
}
/// Creates a new Ethereum block from a Filecoin tipset, executing transactions if requested.
///
/// Reference: <https://github.com/filecoin-project/lotus/blob/941455f1d23e73b9ee92a1a4ce745d8848969858/node/impl/eth/utils.go#L44>
pub async fn from_filecoin_tipset<DB: Blockstore + Send + Sync + 'static>(
ctx: Ctx<DB>,
tipset: crate::blocks::Tipset,
tx_info: TxInfo,
) -> Result<Self> {
static ETH_BLOCK_CACHE: LazyLock<SizeTrackingLruCache<CidWrapper, Block>> =
LazyLock::new(|| {
const DEFAULT_CACHE_SIZE: NonZeroUsize = nonzero!(500usize);
let cache_size = std::env::var("FOREST_ETH_BLOCK_CACHE_SIZE")
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(DEFAULT_CACHE_SIZE);
SizeTrackingLruCache::new_with_metrics("eth_block".into(), cache_size)
});
let block_cid = tipset.key().cid()?;
let mut block = if let Some(b) = ETH_BLOCK_CACHE.get_cloned(&block_cid.into()) {
b
} else {
let parent_cid = tipset.parents().cid()?;
let block_number = EthInt64(tipset.epoch());
let block_hash: EthHash = block_cid.into();
let ExecutedTipset {
state_root,
executed_messages,
} = ctx
.state_manager
.load_executed_tipset_without_events(&tipset)
.await?;
let has_transactions = !executed_messages.is_empty();
let state_tree = ctx.state_manager.get_state_tree(&state_root)?;
let mut full_transactions = vec![];
let mut gas_used = 0;
for (
i,
ExecutedMessage {
message, receipt, ..
},
) in executed_messages.into_iter().enumerate()
{
let ti = EthUint64(i as u64);
gas_used += receipt.gas_used();
let smsg = match message {
ChainMessage::Signed(msg) => msg.clone(),
ChainMessage::Unsigned(msg) => {
let sig = Signature::new_bls(vec![]);
SignedMessage::new_unchecked(msg.clone(), sig)
}
};
let mut tx = new_eth_tx_from_signed_message(
&smsg,
&state_tree,
ctx.chain_config().eth_chain_id,
)?;
tx.block_hash = block_hash;
tx.block_number = block_number;
tx.transaction_index = ti;
full_transactions.push(tx);
}
let b = Block {
hash: block_hash,
number: block_number,
parent_hash: parent_cid.into(),
timestamp: EthUint64(tipset.block_headers().first().timestamp),
base_fee_per_gas: tipset
.block_headers()
.first()
.parent_base_fee
.clone()
.into(),
gas_used: EthUint64(gas_used),
transactions: Transactions::Full(full_transactions),
..Block::new(has_transactions, tipset.len())
};
ETH_BLOCK_CACHE.push(block_cid.into(), b.clone());
b
};
if tx_info == TxInfo::Hash
&& let Transactions::Full(transactions) = &block.transactions
{
block.transactions =
Transactions::Hash(transactions.iter().map(|tx| tx.hash.to_string()).collect())
}
Ok(block)
}
}
lotus_json_with_self!(Block);
#[derive(PartialEq, Debug, Clone, Default, Serialize, Deserialize, JsonSchema, GetSize)]
#[serde(rename_all = "camelCase")]
pub struct ApiEthTx {
pub chain_id: EthUint64,
pub nonce: EthUint64,
pub hash: EthHash,
pub block_hash: EthHash,
pub block_number: EthInt64,
pub transaction_index: EthUint64,
pub from: EthAddress,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub to: Option<EthAddress>,
pub value: EthBigInt,
pub r#type: EthUint64,
pub input: EthBytes,
pub gas: EthUint64,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub max_fee_per_gas: Option<EthBigInt>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub max_priority_fee_per_gas: Option<EthBigInt>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub gas_price: Option<EthBigInt>,
#[schemars(with = "Option<Vec<EthHash>>")]
#[serde(with = "crate::lotus_json")]
pub access_list: Vec<EthHash>,
pub v: EthBigInt,
pub r: EthBigInt,
pub s: EthBigInt,
}
lotus_json_with_self!(ApiEthTx);
impl ApiEthTx {
fn gas_fee_cap(&self) -> anyhow::Result<EthBigInt> {
self.max_fee_per_gas
.as_ref()
.or(self.gas_price.as_ref())
.cloned()
.context("gas fee cap is not set")
}
fn gas_premium(&self) -> anyhow::Result<EthBigInt> {
self.max_priority_fee_per_gas
.as_ref()
.or(self.gas_price.as_ref())
.cloned()
.context("gas premium is not set")
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct EthSyncingResult {
pub done_sync: bool,
pub starting_block: i64,
pub current_block: i64,
pub highest_block: i64,
}
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(untagged)]
pub enum EthSyncingResultLotusJson {
DoneSync(bool),
Syncing {
#[schemars(with = "i64")]
#[serde(rename = "startingblock", with = "crate::lotus_json::hexify")]
starting_block: i64,
#[schemars(with = "i64")]
#[serde(rename = "currentblock", with = "crate::lotus_json::hexify")]
current_block: i64,
#[schemars(with = "i64")]
#[serde(rename = "highestblock", with = "crate::lotus_json::hexify")]
highest_block: i64,
},
}
// TODO(forest): https://github.com/ChainSafe/forest/issues/4032
// this shouldn't exist
impl HasLotusJson for EthSyncingResult {
type LotusJson = EthSyncingResultLotusJson;
#[cfg(test)]
fn snapshots() -> Vec<(serde_json::Value, Self)> {
vec![]
}
fn into_lotus_json(self) -> Self::LotusJson {
match self {
Self {
done_sync: false,
starting_block,
current_block,
highest_block,
} => EthSyncingResultLotusJson::Syncing {
starting_block,
current_block,
highest_block,
},
_ => EthSyncingResultLotusJson::DoneSync(false),
}
}
fn from_lotus_json(lotus_json: Self::LotusJson) -> Self {
match lotus_json {
EthSyncingResultLotusJson::DoneSync(syncing) => {
if syncing {
// Dangerous to panic here, log error instead.
tracing::error!("Invalid EthSyncingResultLotusJson: {syncing}");
}
Self {
done_sync: true,
..Default::default()
}
}
EthSyncingResultLotusJson::Syncing {
starting_block,
current_block,
highest_block,
} => Self {
done_sync: false,
starting_block,
current_block,
highest_block,
},
}
}
}
#[derive(PartialEq, Debug, Default, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct EthTxReceipt {
transaction_hash: EthHash,
transaction_index: EthUint64,
block_hash: EthHash,
block_number: EthInt64,
from: EthAddress,
to: Option<EthAddress>,
root: EthHash,
status: EthUint64,
contract_address: Option<EthAddress>,
cumulative_gas_used: EthUint64,
gas_used: EthUint64,
effective_gas_price: EthBigInt,
logs_bloom: EthBytes,
logs: Vec<EthLog>,
r#type: EthUint64,
}
lotus_json_with_self!(EthTxReceipt);
impl EthTxReceipt {
fn new() -> Self {
Self {
logs_bloom: EthBytes(EMPTY_BLOOM.to_vec()),
..Self::default()
}
}
}
/// Represents the results of an event filter execution.
#[derive(PartialEq, Debug, Default, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct EthLog {
/// The address of the actor that produced the event log.
address: EthAddress,
/// The value of the event log, excluding topics.
data: EthBytes,
/// List of topics associated with the event log.
topics: Vec<EthHash>,
/// Indicates whether the log was removed due to a chain reorganization.
removed: bool,
/// The index of the event log in the sequence of events produced by the message execution.
/// (this is the index in the events AMT on the message receipt)
log_index: EthUint64,
/// The index in the tipset of the transaction that produced the event log.
/// The index corresponds to the sequence of messages produced by `ChainGetParentMessages`
transaction_index: EthUint64,
/// The hash of the RLP message that produced the event log.
transaction_hash: EthHash,
/// The hash of the tipset containing the message that produced the log.
block_hash: EthHash,
/// The epoch of the tipset containing the message.
block_number: EthUint64,
}
lotus_json_with_self!(EthLog);
pub enum Web3ClientVersion {}
impl RpcMethod<0> for Web3ClientVersion {
const NAME: &'static str = "Filecoin.Web3ClientVersion";
const NAME_ALIAS: Option<&'static str> = Some("web3_clientVersion");
const PARAM_NAMES: [&'static str; 0] = [];
const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
const PERMISSION: Permission = Permission::Read;
type Params = ();
type Ok = String;
async fn handle(
_: Ctx<impl Blockstore + Send + Sync + 'static>,
(): Self::Params,
_: &http::Extensions,
) -> Result<Self::Ok, ServerError> {
Ok(format!(
"forest/{}",
*crate::utils::version::FOREST_VERSION_STRING
))
}
}
pub enum EthAccounts {}
impl RpcMethod<0> for EthAccounts {
const NAME: &'static str = "Filecoin.EthAccounts";
const NAME_ALIAS: Option<&'static str> = Some("eth_accounts");
const PARAM_NAMES: [&'static str; 0] = [];
const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
const PERMISSION: Permission = Permission::Read;
type Params = ();
type Ok = Vec<String>;
async fn handle(
_: Ctx<impl Blockstore + Send + Sync + 'static>,
(): Self::Params,
_: &http::Extensions,
) -> Result<Self::Ok, ServerError> {
// EthAccounts will always return [] since we don't expect Forest to manage private keys
Ok(vec![])
}
}
pub enum EthBlockNumber {}
impl RpcMethod<0> for EthBlockNumber {
const NAME: &'static str = "Filecoin.EthBlockNumber";
const NAME_ALIAS: Option<&'static str> = Some("eth_blockNumber");
const PARAM_NAMES: [&'static str; 0] = [];
const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
const PERMISSION: Permission = Permission::Read;
type Params = ();
type Ok = EthUint64;
async fn handle(
ctx: Ctx<impl Blockstore + Send + Sync + 'static>,
(): Self::Params,
_: &http::Extensions,
) -> Result<Self::Ok, ServerError> {
// `eth_block_number` needs to return the height of the latest committed tipset.
// Ethereum clients expect all transactions included in this block to have execution outputs.
// This is the parent of the head tipset. The head tipset is speculative, has not been
// recognized by the network, and its messages are only included, not executed.
// See https://github.com/filecoin-project/ref-fvm/issues/1135.
let heaviest = ctx.chain_store().heaviest_tipset();
if heaviest.epoch() == 0 {
// We're at genesis.
return Ok(EthUint64::default());
}
// First non-null parent.
let effective_parent = heaviest.parents();
if let Ok(Some(parent)) = ctx.chain_index().load_tipset(effective_parent) {
Ok((parent.epoch() as u64).into())
} else {
Ok(EthUint64::default())
}
}
}
pub enum EthChainId {}
impl RpcMethod<0> for EthChainId {
const NAME: &'static str = "Filecoin.EthChainId";
const NAME_ALIAS: Option<&'static str> = Some("eth_chainId");
const PARAM_NAMES: [&'static str; 0] = [];
const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
const PERMISSION: Permission = Permission::Read;
type Params = ();
type Ok = String;
async fn handle(
ctx: Ctx<impl Blockstore + Send + Sync + 'static>,
(): Self::Params,
_: &http::Extensions,
) -> Result<Self::Ok, ServerError> {
Ok(format!("{:#x}", ctx.chain_config().eth_chain_id))
}
}
pub enum EthGasPrice {}
impl RpcMethod<0> for EthGasPrice {
const NAME: &'static str = "Filecoin.EthGasPrice";
const NAME_ALIAS: Option<&'static str> = Some("eth_gasPrice");
const PARAM_NAMES: [&'static str; 0] = [];
const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
const PERMISSION: Permission = Permission::Read;
const DESCRIPTION: Option<&'static str> = Some("Returns the current gas price in attoFIL");
type Params = ();
type Ok = GasPriceResult;
async fn handle(
ctx: Ctx<impl Blockstore + Send + Sync + 'static>,
(): Self::Params,
_: &http::Extensions,
) -> Result<Self::Ok, ServerError> {
// According to Geth's implementation, eth_gasPrice should return base + tip
// Ref: https://github.com/ethereum/pm/issues/328#issuecomment-853234014
let ts = ctx.chain_store().heaviest_tipset();
let block0 = ts.block_headers().first();
let base_fee = block0.parent_base_fee.atto();
let tip = crate::rpc::gas::estimate_gas_premium(&ctx, 0, &ApiTipsetKey(None))
.await
.map(|gas_premium| gas_premium.atto().to_owned())
.unwrap_or_default();
Ok(EthBigInt(base_fee + tip))
}
}
pub enum EthGetBalance {}
impl RpcMethod<2> for EthGetBalance {
const NAME: &'static str = "Filecoin.EthGetBalance";
const NAME_ALIAS: Option<&'static str> = Some("eth_getBalance");
const PARAM_NAMES: [&'static str; 2] = ["address", "blockParam"];
const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
const PERMISSION: Permission = Permission::Read;
const DESCRIPTION: Option<&'static str> =
Some("Returns the balance of an Ethereum address at the specified block state");
type Params = (EthAddress, BlockNumberOrHash);
type Ok = EthBigInt;
async fn handle(
ctx: Ctx<impl Blockstore + Send + Sync + 'static>,
(address, block_param): Self::Params,
ext: &http::Extensions,
) -> Result<Self::Ok, ServerError> {
let resolver = TipsetResolver::new(&ctx, Self::api_path(ext)?);
let ts = resolver
.tipset_by_block_number_or_hash(block_param, ResolveNullTipset::TakeOlder)
.await?;
let balance = eth_get_balance(&ctx, &address, &ts).await?;
Ok(balance)
}
}
async fn eth_get_balance<DB: Blockstore + Send + Sync + 'static>(
ctx: &Ctx<DB>,
address: &EthAddress,
ts: &Tipset,
) -> Result<EthBigInt> {
let fil_addr = address.to_filecoin_address()?;
let (state_cid, _) = ctx
.state_manager
.tipset_state(ts, StateLookupPolicy::Enabled)
.await?;
let state_tree = ctx.state_manager.get_state_tree(&state_cid)?;
match state_tree.get_actor(&fil_addr)? {
Some(actor) => Ok(EthBigInt(actor.balance.atto().clone())),
None => Ok(EthBigInt::default()), // Balance is 0 if the actor doesn't exist
}
}
fn get_tipset_from_hash<DB: Blockstore>(
chain_store: &ChainStore<DB>,
block_hash: &EthHash,
) -> anyhow::Result<Tipset> {
let tsk = chain_store.get_required_tipset_key(block_hash)?;
Tipset::load_required(chain_store.blockstore(), &tsk)
}
fn resolve_block_number_tipset<DB: Blockstore>(
chain: &ChainStore<DB>,
block_number: EthInt64,
resolve: ResolveNullTipset,
) -> anyhow::Result<Tipset> {
let head = chain.heaviest_tipset();
let height = ChainEpoch::from(block_number.0);
if height > head.epoch() - 1 {
bail!("requested a future epoch (beyond \"latest\")");
}
Ok(chain
.chain_index()
.tipset_by_height(height, head, resolve)?)
}
fn resolve_block_hash_tipset<DB: Blockstore>(
chain: &ChainStore<DB>,
block_hash: &EthHash,
require_canonical: bool,
resolve: ResolveNullTipset,
) -> anyhow::Result<Tipset> {
let ts = get_tipset_from_hash(chain, block_hash)?;
// verify that the tipset is in the canonical chain
if require_canonical {
// walk up the current chain (our head) until we reach ts.epoch()
let walk_ts =
chain
.chain_index()
.tipset_by_height(ts.epoch(), chain.heaviest_tipset(), resolve)?;
// verify that it equals the expected tipset
if walk_ts != ts {
bail!("tipset is not canonical");
}
}
Ok(ts)
}
pub fn is_eth_address(addr: &VmAddress) -> bool {
if addr.protocol() != Protocol::Delegated {
return false;
}
let f4_addr: Result<DelegatedAddress, _> = addr.payload().try_into();
f4_addr.is_ok()
}
/// `eth_tx_from_signed_eth_message` does NOT populate:
/// - `hash`
/// - `block_hash`
/// - `block_number`
/// - `transaction_index`
pub fn eth_tx_from_signed_eth_message(
smsg: &SignedMessage,
chain_id: EthChainIdType,
) -> Result<(EthAddress, EthTx)> {
// The from address is always an f410f address, never an ID or other address.
let from = smsg.message().from;
if !is_eth_address(&from) {
bail!("sender must be an eth account, was {from}");
}
// This should be impossible to fail as we've already asserted that we have an
// Ethereum Address sender...
let from = EthAddress::from_filecoin_address(&from)?;
let tx = EthTx::from_signed_message(chain_id, smsg)?;