This commit is contained in:
pgherveou
2025-10-08 08:22:26 +02:00
parent 6e64f678ee
commit 765569a8b6
39 changed files with 662 additions and 1178 deletions
+9 -24
View File
@@ -33,10 +33,7 @@ impl Process {
let log_file_prefix = log_file_prefix.into();
let (stdout_file_name, stderr_file_name) = match log_file_prefix {
Some(prefix) => (
format!("{prefix}_stdout.log"),
format!("{prefix}_stderr.log"),
),
Some(prefix) => (format!("{prefix}_stdout.log"), format!("{prefix}_stderr.log")),
None => ("stdout.log".to_string(), "stderr.log".to_string()),
};
@@ -57,20 +54,16 @@ impl Process {
.context("Failed to open the stderr logs file")?;
let mut command = {
let stdout_logs_file = stdout_logs_file
.try_clone()
.context("Failed to clone the stdout logs file")?;
let stderr_logs_file = stderr_logs_file
.try_clone()
.context("Failed to clone the stderr logs file")?;
let stdout_logs_file =
stdout_logs_file.try_clone().context("Failed to clone the stdout logs file")?;
let stderr_logs_file =
stderr_logs_file.try_clone().context("Failed to clone the stderr logs file")?;
let mut command = Command::new(binary_path.as_ref());
command_building_callback(&mut command, stdout_logs_file, stderr_logs_file);
command
};
let mut child = command
.spawn()
.context("Failed to spawn the built command")?;
let mut child = command.spawn().context("Failed to spawn the built command")?;
match process_readiness_wait_behavior {
ProcessReadinessWaitBehavior::NoStartupWait => {}
@@ -128,11 +121,7 @@ impl Process {
}
}
ProcessReadinessWaitBehavior::WaitForCommandToExit => {
if !child
.wait()
.context("Failed waiting for process to finish")?
.success()
{
if !child.wait().context("Failed waiting for process to finish")?.success() {
anyhow::bail!("Failed to spawn command");
}
}
@@ -149,12 +138,8 @@ impl Process {
impl Drop for Process {
fn drop(&mut self) {
self.child.kill().expect("Failed to kill the process");
self.stdout_logs_file
.flush()
.expect("Failed to flush the stdout logs file");
self.stderr_logs_file
.flush()
.expect("Failed to flush the stderr logs file");
self.stdout_logs_file.flush().expect("Failed to flush the stdout logs file");
self.stderr_logs_file.flush().expect("Failed to flush the stderr logs file");
}
}
+54 -81
View File
@@ -18,7 +18,9 @@ use alloy::{
eips::BlockNumberOrTag,
genesis::{Genesis, GenesisAccount},
network::{Ethereum, EthereumWallet, NetworkWallet},
primitives::{Address, BlockHash, BlockNumber, BlockTimestamp, StorageKey, TxHash, U256},
primitives::{
Address, BlockHash, BlockNumber, BlockTimestamp, ChainId, StorageKey, TxHash, U256,
},
providers::{
Provider,
ext::DebugApi,
@@ -75,6 +77,7 @@ pub struct GethNode {
wallet: Arc<EthereumWallet>,
nonce_manager: CachedNonceManager,
provider: OnceCell<ConcreteProvider<Ethereum, Arc<EthereumWallet>>>,
chain_id: ChainId,
}
impl GethNode {
@@ -105,9 +108,7 @@ impl GethNode {
let wallet_configuration = AsRef::<WalletConfiguration>::as_ref(&context);
let geth_configuration = AsRef::<GethConfiguration>::as_ref(&context);
let geth_directory = working_directory_configuration
.as_path()
.join(Self::BASE_DIRECTORY);
let geth_directory = working_directory_configuration.as_path().join(Self::BASE_DIRECTORY);
let id = NODE_COUNT.fetch_add(1, Ordering::SeqCst);
let base_directory = geth_directory.join(id.to_string());
@@ -125,6 +126,25 @@ impl GethNode {
wallet: wallet.clone(),
nonce_manager: Default::default(),
provider: Default::default(),
chain_id: CHAIN_ID,
}
}
pub fn new_existing() -> Self {
let wallet_config = revive_dt_config::WalletConfiguration::default();
Self {
connection_string: "http://localhost:8545".to_string(),
base_directory: PathBuf::new(),
data_directory: PathBuf::new(),
logs_directory: PathBuf::new(),
geth: PathBuf::new(),
id: 0,
chain_id: 1337,
handle: None,
start_timeout: Duration::from_secs(0),
wallet: wallet_config.wallet(),
nonce_manager: Default::default(),
provider: Default::default(),
}
}
@@ -176,11 +196,7 @@ impl GethNode {
.read_to_string(&mut stderr)
.context("Failed to read geth --init stderr")?;
if !child
.wait()
.context("Failed waiting for geth --init process to finish")?
.success()
{
if !child.wait().context("Failed waiting for geth --init process to finish")?.success() {
anyhow::bail!("failed to initialize geth node #{:?}: {stderr}", &self.id);
}
@@ -240,8 +256,7 @@ impl GethNode {
Ok(process) => self.handle = Some(process),
Err(err) => {
error!(?err, "Failed to start geth, shutting down gracefully");
self.shutdown()
.context("Failed to gracefully shutdown after geth start error")?;
self.shutdown().context("Failed to gracefully shutdown after geth start error")?;
return Err(err);
}
}
@@ -255,7 +270,7 @@ impl GethNode {
construct_concurrency_limited_provider::<Ethereum, _>(
self.connection_string.as_str(),
FallbackGasFiller::default(),
ChainIdFiller::new(Some(CHAIN_ID)),
ChainIdFiller::new(Some(self.chain_id)),
NonceFiller::new(self.nonce_manager.clone()),
self.wallet.clone(),
)
@@ -386,10 +401,7 @@ impl EthereumNode for GethNode {
}
},
)
.instrument(tracing::info_span!(
"Awaiting transaction receipt",
?transaction_hash
))
.instrument(tracing::info_span!("Awaiting transaction receipt", ?transaction_hash))
.await
})
}
@@ -401,10 +413,8 @@ impl EthereumNode for GethNode {
trace_options: GethDebugTracingOptions,
) -> Pin<Box<dyn Future<Output = anyhow::Result<GethTrace>> + '_>> {
Box::pin(async move {
let provider = self
.provider()
.await
.context("Failed to create provider for tracing")?;
let provider =
self.provider().await.context("Failed to create provider for tracing")?;
poll(
Self::TRACE_POLLING_DURATION,
PollingWaitBehavior::Constant(Duration::from_millis(200)),
@@ -412,10 +422,7 @@ impl EthereumNode for GethNode {
let provider = provider.clone();
let trace_options = trace_options.clone();
async move {
match provider
.debug_trace_transaction(tx_hash, trace_options)
.await
{
match provider.debug_trace_transaction(tx_hash, trace_options).await {
Ok(trace) => Ok(ControlFlow::Break(trace)),
Err(error) => {
let error_string = error.to_string();
@@ -495,7 +502,10 @@ impl EthereumNode for GethNode {
Box::pin(async move {
let id = self.id;
let provider = self.provider().await?;
Ok(Arc::new(GethNodeResolver { id, provider }) as Arc<dyn ResolverApi>)
Ok(Arc::new(GethNodeResolver {
id,
provider,
}) as Arc<dyn ResolverApi>)
})
}
@@ -543,19 +553,13 @@ impl EthereumNode for GethNode {
})
}
fn new_existing() -> Self {
Self {
connection_string: "http://localhost:8545".to_string(),
base_directory: PathBuf::new(),
data_directory: PathBuf::new(),
logs_directory: PathBuf::new(),
geth: PathBuf::new(),
id: 0,
handle: None,
start_timeout: Duration::from_secs(0),
wallet: Arc::new(EthereumWallet::default()),
nonce_manager: Default::default(),
provider: Default::default(),
fn resolve_signer_or_default(&self, address: Address) -> Address {
let signer_addresses: Vec<_> =
<EthereumWallet as NetworkWallet<Ethereum>>::signer_addresses(&self.wallet).collect();
if signer_addresses.contains(&address) {
address
} else {
self.wallet.default_signer().address()
}
}
}
@@ -644,10 +648,7 @@ impl ResolverApi for GethNodeResolver {
.context("Failed to get the geth block")?
.context("Failed to get the Geth block, perhaps there are no blocks?")
.and_then(|block| {
block
.header
.base_fee_per_gas
.context("Failed to get the base fee per gas")
block.header.base_fee_per_gas.context("Failed to get the base fee per gas")
})
})
}
@@ -764,11 +765,7 @@ mod tests {
// Arrange
let (context, node) = shared_state();
let account_address = context
.wallet_configuration
.wallet()
.default_signer()
.address();
let account_address = context.wallet_configuration.wallet().default_signer().address();
let transaction = TransactionRequest::default()
.to(account_address)
.value(U256::from(100_000_000_000_000u128));
@@ -791,10 +788,7 @@ mod tests {
// Assert
let version = version.expect("Failed to get the version");
assert!(
version.starts_with("geth version"),
"expected version string, got: '{version}'"
);
assert!(version.starts_with("geth version"), "expected version string, got: '{version}'");
}
#[tokio::test]
@@ -818,12 +812,8 @@ mod tests {
let node = shared_node();
// Act
let gas_limit = node
.resolver()
.await
.unwrap()
.block_gas_limit(BlockNumberOrTag::Latest)
.await;
let gas_limit =
node.resolver().await.unwrap().block_gas_limit(BlockNumberOrTag::Latest).await;
// Assert
let _ = gas_limit.expect("Failed to get the gas limit");
@@ -836,12 +826,8 @@ mod tests {
let node = shared_node();
// Act
let coinbase = node
.resolver()
.await
.unwrap()
.block_coinbase(BlockNumberOrTag::Latest)
.await;
let coinbase =
node.resolver().await.unwrap().block_coinbase(BlockNumberOrTag::Latest).await;
// Assert
let _ = coinbase.expect("Failed to get the coinbase");
@@ -854,12 +840,8 @@ mod tests {
let node = shared_node();
// Act
let block_difficulty = node
.resolver()
.await
.unwrap()
.block_difficulty(BlockNumberOrTag::Latest)
.await;
let block_difficulty =
node.resolver().await.unwrap().block_difficulty(BlockNumberOrTag::Latest).await;
// Assert
let _ = block_difficulty.expect("Failed to get the block difficulty");
@@ -872,12 +854,7 @@ mod tests {
let node = shared_node();
// Act
let block_hash = node
.resolver()
.await
.unwrap()
.block_hash(BlockNumberOrTag::Latest)
.await;
let block_hash = node.resolver().await.unwrap().block_hash(BlockNumberOrTag::Latest).await;
// Assert
let _ = block_hash.expect("Failed to get the block hash");
@@ -890,12 +867,8 @@ mod tests {
let node = shared_node();
// Act
let block_timestamp = node
.resolver()
.await
.unwrap()
.block_timestamp(BlockNumberOrTag::Latest)
.await;
let block_timestamp =
node.resolver().await.unwrap().block_timestamp(BlockNumberOrTag::Latest).await;
// Assert
let _ = block_timestamp.expect("Failed to get the block timestamp");
@@ -132,9 +132,7 @@ impl LighthouseGethNode {
let wallet_configuration = AsRef::<WalletConfiguration>::as_ref(&context);
let kurtosis_configuration = AsRef::<KurtosisConfiguration>::as_ref(&context);
let geth_directory = working_directory_configuration
.as_path()
.join(Self::BASE_DIRECTORY);
let geth_directory = working_directory_configuration.as_path().join(Self::BASE_DIRECTORY);
let id = NODE_COUNT.fetch_add(1, Ordering::SeqCst);
let base_directory = geth_directory.join(id.to_string());
@@ -147,10 +145,7 @@ impl LighthouseGethNode {
http_connection_string: String::default(),
enclave_name: format!(
"enclave-{}-{}",
SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("Must not fail")
.as_nanos(),
SystemTime::now().duration_since(UNIX_EPOCH).expect("Must not fail").as_nanos(),
id
),
@@ -183,8 +178,7 @@ impl LighthouseGethNode {
fn init(&mut self, _: Genesis) -> anyhow::Result<&mut Self> {
self.init_directories()
.context("Failed to initialize the directories of the Lighthouse Geth node.")?;
self.init_kurtosis_config_file()
.context("Failed to write the config file to the FS")?;
self.init_kurtosis_config_file().context("Failed to write the config file to the FS")?;
Ok(self)
}
@@ -426,9 +420,8 @@ impl LighthouseGethNode {
.context("Full block subscriber")?;
let mut tx_hashes = futures::future::try_join_all(
NetworkWallet::<Ethereum>::signer_addresses(self.wallet.as_ref())
.enumerate()
.map(|(nonce, address)| async move {
NetworkWallet::<Ethereum>::signer_addresses(self.wallet.as_ref()).enumerate().map(
|(nonce, address)| async move {
let mut transaction = TransactionRequest::default()
.from(self.prefunded_account_address)
.to(address)
@@ -436,7 +429,8 @@ impl LighthouseGethNode {
.value(INITIAL_BALANCE.try_into().unwrap());
transaction.chain_id = Some(CHAIN_ID);
self.submit_transaction(transaction).await
}),
},
),
)
.await
.context("Failed to submit all transactions")?
@@ -531,10 +525,7 @@ impl LighthouseGethNode {
}
},
)
.instrument(tracing::info_span!(
"Awaiting transaction receipt",
?transaction_hash
))
.instrument(tracing::info_span!("Awaiting transaction receipt", ?transaction_hash))
.await
})
}
@@ -623,9 +614,7 @@ impl EthereumNode for LighthouseGethNode {
) -> Pin<Box<dyn Future<Output = anyhow::Result<GethTrace>> + '_>> {
Box::pin(async move {
let provider = Arc::new(
self.http_provider()
.await
.context("Failed to create provider for tracing")?,
self.http_provider().await.context("Failed to create provider for tracing")?,
);
poll(
Self::TRACE_POLLING_DURATION,
@@ -634,10 +623,7 @@ impl EthereumNode for LighthouseGethNode {
let provider = provider.clone();
let trace_options = trace_options.clone();
async move {
match provider
.debug_trace_transaction(tx_hash, trace_options)
.await
{
match provider.debug_trace_transaction(tx_hash, trace_options).await {
Ok(trace) => Ok(ControlFlow::Break(trace)),
Err(error) => {
let error_string = error.to_string();
@@ -717,7 +703,10 @@ impl EthereumNode for LighthouseGethNode {
Box::pin(async move {
let id = self.id;
let provider = self.ws_provider().await?;
Ok(Arc::new(LighthouseGethNodeResolver { id, provider }) as Arc<dyn ResolverApi>)
Ok(Arc::new(LighthouseGethNodeResolver {
id,
provider,
}) as Arc<dyn ResolverApi>)
})
}
@@ -761,6 +750,16 @@ impl EthereumNode for LighthouseGethNode {
as Pin<Box<dyn Stream<Item = MinedBlockInformation>>>)
})
}
fn resolve_signer_or_default(&self, address: Address) -> Address {
let signer_addresses: Vec<_> =
<EthereumWallet as NetworkWallet<Ethereum>>::signer_addresses(&self.wallet).collect();
if signer_addresses.contains(&address) {
address
} else {
self.wallet.default_signer().address()
}
}
}
pub struct LighthouseGethNodeResolver<F: TxFiller<Ethereum>, P: Provider<Ethereum>> {
@@ -849,10 +848,7 @@ impl<F: TxFiller<Ethereum>, P: Provider<Ethereum>> ResolverApi
.context("Failed to get the geth block")?
.context("Failed to get the Geth block, perhaps there are no blocks?")
.and_then(|block| {
block
.header
.base_fee_per_gas
.context("Failed to get the base fee per gas")
block.header.base_fee_per_gas.context("Failed to get the base fee per gas")
})
})
}
@@ -906,11 +902,7 @@ impl Node for LighthouseGethNode {
.spawn()
.expect("Failed to spawn the enclave kill command");
if !child
.wait()
.expect("Failed to wait for the enclave kill command")
.success()
{
if !child.wait().expect("Failed to wait for the enclave kill command").success() {
let stdout = {
let mut stdout = String::default();
child
@@ -1136,11 +1128,7 @@ mod tests {
let (context, node) = new_node();
node.fund_all_accounts().await.expect("Failed");
let account_address = context
.wallet_configuration
.wallet()
.default_signer()
.address();
let account_address = context.wallet_configuration.wallet().default_signer().address();
let transaction = TransactionRequest::default()
.to(account_address)
.value(U256::from(100_000_000_000_000u128));
@@ -1163,10 +1151,7 @@ mod tests {
// Assert
let version = version.expect("Failed to get the version");
assert!(
version.starts_with("CLI Version"),
"expected version string, got: '{version}'"
);
assert!(version.starts_with("CLI Version"), "expected version string, got: '{version}'");
}
#[tokio::test]
@@ -1190,12 +1175,8 @@ mod tests {
let (_context, node) = new_node();
// Act
let gas_limit = node
.resolver()
.await
.unwrap()
.block_gas_limit(BlockNumberOrTag::Latest)
.await;
let gas_limit =
node.resolver().await.unwrap().block_gas_limit(BlockNumberOrTag::Latest).await;
// Assert
let _ = gas_limit.expect("Failed to get the gas limit");
@@ -1208,12 +1189,8 @@ mod tests {
let (_context, node) = new_node();
// Act
let coinbase = node
.resolver()
.await
.unwrap()
.block_coinbase(BlockNumberOrTag::Latest)
.await;
let coinbase =
node.resolver().await.unwrap().block_coinbase(BlockNumberOrTag::Latest).await;
// Assert
let _ = coinbase.expect("Failed to get the coinbase");
@@ -1226,12 +1203,8 @@ mod tests {
let (_context, node) = new_node();
// Act
let block_difficulty = node
.resolver()
.await
.unwrap()
.block_difficulty(BlockNumberOrTag::Latest)
.await;
let block_difficulty =
node.resolver().await.unwrap().block_difficulty(BlockNumberOrTag::Latest).await;
// Assert
let _ = block_difficulty.expect("Failed to get the block difficulty");
@@ -1244,12 +1217,7 @@ mod tests {
let (_context, node) = new_node();
// Act
let block_hash = node
.resolver()
.await
.unwrap()
.block_hash(BlockNumberOrTag::Latest)
.await;
let block_hash = node.resolver().await.unwrap().block_hash(BlockNumberOrTag::Latest).await;
// Assert
let _ = block_hash.expect("Failed to get the block hash");
@@ -1262,12 +1230,8 @@ mod tests {
let (_context, node) = new_node();
// Act
let block_timestamp = node
.resolver()
.await
.unwrap()
.block_timestamp(BlockNumberOrTag::Latest)
.await;
let block_timestamp =
node.resolver().await.unwrap().block_timestamp(BlockNumberOrTag::Latest).await;
// Assert
let _ = block_timestamp.expect("Failed to get the block timestamp");
+74 -103
View File
@@ -108,9 +108,7 @@ impl SubstrateNode {
) -> Self {
let working_directory_path =
AsRef::<WorkingDirectoryConfiguration>::as_ref(&context).as_path();
let eth_rpc_path = AsRef::<EthRpcConfiguration>::as_ref(&context)
.path
.as_path();
let eth_rpc_path = AsRef::<EthRpcConfiguration>::as_ref(&context).path.as_path();
let wallet = AsRef::<WalletConfiguration>::as_ref(&context).wallet();
let substrate_directory = working_directory_path.join(Self::BASE_DIRECTORY);
@@ -134,6 +132,24 @@ impl SubstrateNode {
}
}
pub fn new_existing() -> Self {
let wallet_config = revive_dt_config::WalletConfiguration::default();
Self {
id: 0,
node_binary: PathBuf::new(),
eth_proxy_binary: PathBuf::new(),
export_chainspec_command: String::new(),
rpc_url: "http://localhost:8545".to_string(),
base_directory: PathBuf::new(),
logs_directory: PathBuf::new(),
substrate_process: None,
eth_proxy_process: None,
wallet: wallet_config.wallet(),
nonce_manager: Default::default(),
provider: Default::default(),
}
}
fn init(&mut self, mut genesis: Genesis) -> anyhow::Result<&mut Self> {
let _ = remove_dir_all(self.base_directory.as_path());
let _ = clear_directory(&self.base_directory);
@@ -309,15 +325,12 @@ impl SubstrateNode {
&self,
genesis: &Genesis,
) -> anyhow::Result<Vec<(String, u128)>> {
genesis
.alloc
.iter()
.try_fold(Vec::new(), |mut vec, (address, acc)| {
let substrate_address = Self::eth_to_substrate_address(address);
let balance = acc.balance.try_into()?;
vec.push((substrate_address, balance));
Ok(vec)
})
genesis.alloc.iter().try_fold(Vec::new(), |mut vec, (address, acc)| {
let substrate_address = Self::eth_to_substrate_address(address);
let balance = acc.balance.try_into()?;
vec.push((substrate_address, balance));
Ok(vec)
})
}
fn eth_to_substrate_address(address: &Address) -> String {
@@ -412,10 +425,7 @@ impl EthereumNode for SubstrateNode {
transaction: TransactionRequest,
) -> Pin<Box<dyn Future<Output = anyhow::Result<TransactionReceipt>> + '_>> {
Box::pin(async move {
let provider = self
.provider()
.await
.context("Failed to create the provider")?;
let provider = self.provider().await.context("Failed to create the provider")?;
execute_transaction(provider, transaction).await
})
}
@@ -492,7 +502,10 @@ impl EthereumNode for SubstrateNode {
Box::pin(async move {
let id = self.id;
let provider = self.provider().await?;
Ok(Arc::new(SubstrateNodeResolver { id, provider }) as Arc<dyn ResolverApi>)
Ok(Arc::new(SubstrateNodeResolver {
id,
provider,
}) as Arc<dyn ResolverApi>)
})
}
@@ -513,10 +526,8 @@ impl EthereumNode for SubstrateNode {
.provider()
.await
.context("Failed to create the provider for block subscription")?;
let mut block_subscription = provider
.watch_full_blocks()
.await
.context("Failed to create the blocks stream")?;
let mut block_subscription =
provider.watch_full_blocks().await.context("Failed to create the blocks stream")?;
block_subscription.set_channel_size(0xFFFF);
block_subscription.set_poll_interval(Duration::from_secs(1));
let block_stream = block_subscription.into_stream();
@@ -542,20 +553,13 @@ impl EthereumNode for SubstrateNode {
})
}
fn new_existing() -> Self {
Self {
id: 0,
node_binary: PathBuf::new(),
eth_proxy_binary: PathBuf::new(),
export_chainspec_command: String::new(),
rpc_url: "http://localhost:8545".to_string(),
base_directory: PathBuf::new(),
logs_directory: PathBuf::new(),
substrate_process: None,
eth_proxy_process: None,
wallet: Arc::new(EthereumWallet::default()),
nonce_manager: Default::default(),
provider: Default::default(),
fn resolve_signer_or_default(&self, address: Address) -> Address {
let signer_addresses: Vec<_> =
<EthereumWallet as NetworkWallet<Ethereum>>::signer_addresses(&self.wallet).collect();
if signer_addresses.contains(&address) {
address
} else {
self.wallet.default_signer().address()
}
}
}
@@ -644,10 +648,7 @@ impl ResolverApi for SubstrateNodeResolver {
.context("Failed to get the substrate block")?
.context("Failed to get the substrate block, perhaps the chain has no blocks?")
.and_then(|block| {
block
.header
.base_fee_per_gas
.context("Failed to get the base fee per gas")
block.header.base_fee_per_gas.context("Failed to get the base fee per gas")
})
})
}
@@ -926,25 +927,26 @@ impl TransactionBuilder<ReviveNetwork> for <Ethereum as Network>::TransactionReq
);
match result {
Ok(unsigned_tx) => Ok(unsigned_tx),
Err(UnbuiltTransactionError { request, error }) => {
Err(UnbuiltTransactionError::<ReviveNetwork> {
request,
error: match error {
TransactionBuilderError::InvalidTransactionRequest(tx_type, items) => {
TransactionBuilderError::InvalidTransactionRequest(tx_type, items)
}
TransactionBuilderError::UnsupportedSignatureType => {
TransactionBuilderError::UnsupportedSignatureType
}
TransactionBuilderError::Signer(error) => {
TransactionBuilderError::Signer(error)
}
TransactionBuilderError::Custom(error) => {
TransactionBuilderError::Custom(error)
}
},
})
}
Err(UnbuiltTransactionError {
request,
error,
}) => Err(UnbuiltTransactionError::<ReviveNetwork> {
request,
error: match error {
TransactionBuilderError::InvalidTransactionRequest(tx_type, items) => {
TransactionBuilderError::InvalidTransactionRequest(tx_type, items)
}
TransactionBuilderError::UnsupportedSignatureType => {
TransactionBuilderError::UnsupportedSignatureType
}
TransactionBuilderError::Signer(error) => {
TransactionBuilderError::Signer(error)
}
TransactionBuilderError::Custom(error) => {
TransactionBuilderError::Custom(error)
}
},
}),
}
}
@@ -1212,11 +1214,7 @@ mod tests {
let provider = node.provider().await.expect("Failed to create provider");
let account_address = context
.wallet_configuration
.wallet()
.default_signer()
.address();
let account_address = context.wallet_configuration.wallet().default_signer().address();
let transaction = TransactionRequest::default()
.to(account_address)
.value(U256::from(100_000_000_000_000u128));
@@ -1256,14 +1254,11 @@ mod tests {
);
// Call `init()`
dummy_node
.init(serde_json::from_str(genesis_content).unwrap())
.expect("init failed");
dummy_node.init(serde_json::from_str(genesis_content).unwrap()).expect("init failed");
// Check that the patched chainspec file was generated
let final_chainspec_path = dummy_node
.base_directory
.join(SubstrateNode::CHAIN_SPEC_JSON_FILE);
let final_chainspec_path =
dummy_node.base_directory.join(SubstrateNode::CHAIN_SPEC_JSON_FILE);
assert!(final_chainspec_path.exists(), "Chainspec file should exist");
let contents = fs::read_to_string(&final_chainspec_path).expect("Failed to read chainspec");
@@ -1369,10 +1364,7 @@ mod tests {
for (eth_addr, expected_ss58) in cases {
let result = SubstrateNode::eth_to_substrate_address(&eth_addr.parse().unwrap());
assert_eq!(
result, expected_ss58,
"Mismatch for Ethereum address {eth_addr}"
);
assert_eq!(result, expected_ss58, "Mismatch for Ethereum address {eth_addr}");
}
}
@@ -1423,12 +1415,8 @@ mod tests {
let node = shared_node();
// Act
let gas_limit = node
.resolver()
.await
.unwrap()
.block_gas_limit(BlockNumberOrTag::Latest)
.await;
let gas_limit =
node.resolver().await.unwrap().block_gas_limit(BlockNumberOrTag::Latest).await;
// Assert
let _ = gas_limit.expect("Failed to get the gas limit");
@@ -1441,12 +1429,8 @@ mod tests {
let node = shared_node();
// Act
let coinbase = node
.resolver()
.await
.unwrap()
.block_coinbase(BlockNumberOrTag::Latest)
.await;
let coinbase =
node.resolver().await.unwrap().block_coinbase(BlockNumberOrTag::Latest).await;
// Assert
let _ = coinbase.expect("Failed to get the coinbase");
@@ -1459,12 +1443,8 @@ mod tests {
let node = shared_node();
// Act
let block_difficulty = node
.resolver()
.await
.unwrap()
.block_difficulty(BlockNumberOrTag::Latest)
.await;
let block_difficulty =
node.resolver().await.unwrap().block_difficulty(BlockNumberOrTag::Latest).await;
// Assert
let _ = block_difficulty.expect("Failed to get the block difficulty");
@@ -1477,12 +1457,7 @@ mod tests {
let node = shared_node();
// Act
let block_hash = node
.resolver()
.await
.unwrap()
.block_hash(BlockNumberOrTag::Latest)
.await;
let block_hash = node.resolver().await.unwrap().block_hash(BlockNumberOrTag::Latest).await;
// Assert
let _ = block_hash.expect("Failed to get the block hash");
@@ -1495,12 +1470,8 @@ mod tests {
let node = shared_node();
// Act
let block_timestamp = node
.resolver()
.await
.unwrap()
.block_timestamp(BlockNumberOrTag::Latest)
.await;
let block_timestamp =
node.resolver().await.unwrap().block_timestamp(BlockNumberOrTag::Latest).await;
// Assert
let _ = block_timestamp.expect("Failed to get the block timestamp");
@@ -130,14 +130,10 @@ impl ZombieNode {
+ AsRef<EthRpcConfiguration>
+ AsRef<WalletConfiguration>,
) -> Self {
let eth_proxy_binary = AsRef::<EthRpcConfiguration>::as_ref(&context)
.path
.to_owned();
let eth_proxy_binary = AsRef::<EthRpcConfiguration>::as_ref(&context).path.to_owned();
let working_directory_path = AsRef::<WorkingDirectoryConfiguration>::as_ref(&context);
let id = NODE_COUNT.fetch_add(1, Ordering::SeqCst);
let base_directory = working_directory_path
.join(Self::BASE_DIRECTORY)
.join(id.to_string());
let base_directory = working_directory_path.join(Self::BASE_DIRECTORY).join(id.to_string());
let logs_directory = base_directory.join(Self::LOGS_DIRECTORY);
let wallet = AsRef::<WalletConfiguration>::as_ref(&context).wallet();
@@ -169,10 +165,8 @@ impl ZombieNode {
let template_chainspec_path = self.base_directory.join(Self::CHAIN_SPEC_JSON_FILE);
self.prepare_chainspec(template_chainspec_path.clone(), genesis)?;
let polkadot_parachain_path = self
.polkadot_parachain_path
.to_str()
.context("Invalid polkadot parachain path")?;
let polkadot_parachain_path =
self.polkadot_parachain_path.to_str().context("Invalid polkadot parachain path")?;
let node_rpc_port = Self::NODE_BASE_RPC_PORT + self.id as u16;
@@ -204,10 +198,8 @@ impl ZombieNode {
}
fn spawn_process(&mut self) -> anyhow::Result<()> {
let network_config = self
.network_config
.clone()
.context("Node not initialized, call init() first")?;
let network_config =
self.network_config.clone().context("Node not initialized, call init() first")?;
let rt = tokio::runtime::Runtime::new().unwrap();
let network = rt.block_on(async {
@@ -272,17 +264,12 @@ impl ZombieNode {
mut genesis: Genesis,
) -> anyhow::Result<()> {
let mut cmd: Command = std::process::Command::new(&self.polkadot_parachain_path);
cmd.arg(Self::EXPORT_CHAINSPEC_COMMAND)
.arg("--chain")
.arg("asset-hub-westend-local");
cmd.arg(Self::EXPORT_CHAINSPEC_COMMAND).arg("--chain").arg("asset-hub-westend-local");
let output = cmd.output().context("Failed to export the chain-spec")?;
if !output.status.success() {
anyhow::bail!(
"Build chain-spec failed: {}",
String::from_utf8_lossy(&output.stderr)
);
anyhow::bail!("Build chain-spec failed: {}", String::from_utf8_lossy(&output.stderr));
}
let content = String::from_utf8(output.stdout)
@@ -343,15 +330,12 @@ impl ZombieNode {
&self,
genesis: &Genesis,
) -> anyhow::Result<Vec<(String, u128)>> {
genesis
.alloc
.iter()
.try_fold(Vec::new(), |mut vec, (address, acc)| {
let polkadot_address = Self::eth_to_polkadot_address(address);
let balance = acc.balance.try_into()?;
vec.push((polkadot_address, balance));
Ok(vec)
})
genesis.alloc.iter().try_fold(Vec::new(), |mut vec, (address, acc)| {
let polkadot_address = Self::eth_to_polkadot_address(address);
let balance = acc.balance.try_into()?;
vec.push((polkadot_address, balance));
Ok(vec)
})
}
fn eth_to_polkadot_address(address: &Address) -> String {
@@ -535,7 +519,10 @@ impl EthereumNode for ZombieNode {
let id = self.id;
let provider = self.provider().await?;
Ok(Arc::new(ZombieNodeResolver { id, provider }) as Arc<dyn ResolverApi>)
Ok(Arc::new(ZombieNodeResolver {
id,
provider,
}) as Arc<dyn ResolverApi>)
})
}
@@ -556,10 +543,8 @@ impl EthereumNode for ZombieNode {
.provider()
.await
.context("Failed to create the provider for block subscription")?;
let mut block_subscription = provider
.watch_full_blocks()
.await
.context("Failed to create the blocks stream")?;
let mut block_subscription =
provider.watch_full_blocks().await.context("Failed to create the blocks stream")?;
block_subscription.set_channel_size(0xFFFF);
block_subscription.set_poll_interval(Duration::from_secs(1));
let block_stream = block_subscription.into_stream();
@@ -584,6 +569,16 @@ impl EthereumNode for ZombieNode {
as Pin<Box<dyn Stream<Item = MinedBlockInformation>>>)
})
}
fn resolve_signer_or_default(&self, address: Address) -> Address {
let signer_addresses: Vec<_> =
<EthereumWallet as NetworkWallet<Ethereum>>::signer_addresses(&self.wallet).collect();
if signer_addresses.contains(&address) {
address
} else {
self.wallet.default_signer().address()
}
}
}
pub struct ZombieNodeResolver<F: TxFiller<ReviveNetwork>, P: Provider<ReviveNetwork>> {
@@ -672,10 +667,7 @@ impl<F: TxFiller<ReviveNetwork>, P: Provider<ReviveNetwork>> ResolverApi
.context("Failed to get the zombie block")?
.context("Failed to get the zombie block, perhaps the chain has no blocks?")
.and_then(|block| {
block
.header
.base_fee_per_gas
.context("Failed to get the base fee per gas")
block.header.base_fee_per_gas.context("Failed to get the base fee per gas")
})
})
}
@@ -787,10 +779,8 @@ mod tests {
pub async fn new_node() -> (TestExecutionContext, ZombieNode) {
let context = test_config();
let mut node = ZombieNode::new(
context.polkadot_parachain_configuration.path.clone(),
&context,
);
let mut node =
ZombieNode::new(context.polkadot_parachain_configuration.path.clone(), &context);
let genesis = context.genesis_configuration.genesis().unwrap().clone();
node.init(genesis).unwrap();
@@ -855,14 +845,11 @@ mod tests {
"#;
let context = test_config();
let mut node = ZombieNode::new(
context.polkadot_parachain_configuration.path.clone(),
&context,
);
let mut node =
ZombieNode::new(context.polkadot_parachain_configuration.path.clone(), &context);
// Call `init()`
node.init(serde_json::from_str(genesis_content).unwrap())
.expect("init failed");
node.init(serde_json::from_str(genesis_content).unwrap()).expect("init failed");
// Check that the patched chainspec file was generated
let final_chainspec_path = node.base_directory.join(ZombieNode::CHAIN_SPEC_JSON_FILE);
@@ -903,10 +890,7 @@ mod tests {
"#;
let context = test_config();
let node = ZombieNode::new(
context.polkadot_parachain_configuration.path.clone(),
&context,
);
let node = ZombieNode::new(context.polkadot_parachain_configuration.path.clone(), &context);
let result = node
.extract_balance_from_genesis_file(&serde_json::from_str(genesis_json).unwrap())
@@ -968,10 +952,7 @@ mod tests {
for (eth_addr, expected_ss58) in cases {
let result = ZombieNode::eth_to_polkadot_address(&eth_addr.parse().unwrap());
assert_eq!(
result, expected_ss58,
"Mismatch for Ethereum address {eth_addr}"
);
assert_eq!(result, expected_ss58, "Mismatch for Ethereum address {eth_addr}");
}
}
@@ -979,10 +960,7 @@ mod tests {
fn eth_rpc_version_works() {
// Arrange
let context = test_config();
let node = ZombieNode::new(
context.polkadot_parachain_configuration.path.clone(),
&context,
);
let node = ZombieNode::new(context.polkadot_parachain_configuration.path.clone(), &context);
// Act
let version = node.eth_rpc_version().unwrap();
@@ -998,10 +976,7 @@ mod tests {
fn version_works() {
// Arrange
let context = test_config();
let node = ZombieNode::new(
context.polkadot_parachain_configuration.path.clone(),
&context,
);
let node = ZombieNode::new(context.polkadot_parachain_configuration.path.clone(), &context);
// Act
let version = node.version().unwrap();
@@ -1039,12 +1014,8 @@ mod tests {
let node = shared_node().await;
// Act
let gas_limit = node
.resolver()
.await
.unwrap()
.block_gas_limit(BlockNumberOrTag::Latest)
.await;
let gas_limit =
node.resolver().await.unwrap().block_gas_limit(BlockNumberOrTag::Latest).await;
// Assert
let _ = gas_limit.expect("Failed to get the gas limit");
@@ -1057,12 +1028,8 @@ mod tests {
let node = shared_node().await;
// Act
let coinbase = node
.resolver()
.await
.unwrap()
.block_coinbase(BlockNumberOrTag::Latest)
.await;
let coinbase =
node.resolver().await.unwrap().block_coinbase(BlockNumberOrTag::Latest).await;
// Assert
let _ = coinbase.expect("Failed to get the coinbase");
@@ -1075,12 +1042,8 @@ mod tests {
let node = shared_node().await;
// Act
let block_difficulty = node
.resolver()
.await
.unwrap()
.block_difficulty(BlockNumberOrTag::Latest)
.await;
let block_difficulty =
node.resolver().await.unwrap().block_difficulty(BlockNumberOrTag::Latest).await;
// Assert
let _ = block_difficulty.expect("Failed to get the block difficulty");
@@ -1093,12 +1056,7 @@ mod tests {
let node = shared_node().await;
// Act
let block_hash = node
.resolver()
.await
.unwrap()
.block_hash(BlockNumberOrTag::Latest)
.await;
let block_hash = node.resolver().await.unwrap().block_hash(BlockNumberOrTag::Latest).await;
// Assert
let _ = block_hash.expect("Failed to get the block hash");
@@ -1111,12 +1069,8 @@ mod tests {
let node = shared_node().await;
// Act
let block_timestamp = node
.resolver()
.await
.unwrap()
.block_timestamp(BlockNumberOrTag::Latest)
.await;
let block_timestamp =
node.resolver().await.unwrap().block_timestamp(BlockNumberOrTag::Latest).await;
// Assert
let _ = block_timestamp.expect("Failed to get the block timestamp");
@@ -55,10 +55,7 @@ where
let future = self.service.call(req);
Box::pin(async move {
let _permit = semaphore
.acquire()
.await
.expect("Semaphore has been closed");
let _permit = semaphore.acquire().await.expect("Semaphore has been closed");
tracing::debug!(
available_permits = semaphore.available_permits(),
"Acquired Semaphore Permit"
+14 -19
View File
@@ -80,10 +80,8 @@ where
NonceFiller: TxFiller<N>,
WalletFiller<W>: TxFiller<N>,
{
let sendable_transaction = provider
.fill(transaction)
.await
.context("Failed to fill transaction")?;
let sendable_transaction =
provider.fill(transaction).await.context("Failed to fill transaction")?;
let transaction_envelope = sendable_transaction
.try_into_envelope()
@@ -105,24 +103,21 @@ where
debug!(%tx_hash, "Submitted Transaction");
pending_transaction.set_timeout(Some(Duration::from_secs(120)));
let tx_hash = pending_transaction.watch().await.context(format!(
"Transaction inclusion watching timeout for {tx_hash}"
))?;
let tx_hash = pending_transaction
.watch()
.await
.context(format!("Transaction inclusion watching timeout for {tx_hash}"))?;
poll(
Duration::from_secs(60),
PollingWaitBehavior::Constant(Duration::from_secs(3)),
|| {
let provider = provider.clone();
poll(Duration::from_secs(60), PollingWaitBehavior::Constant(Duration::from_secs(3)), || {
let provider = provider.clone();
async move {
match provider.get_transaction_receipt(tx_hash).await {
Ok(Some(receipt)) => Ok(ControlFlow::Break(receipt)),
_ => Ok(ControlFlow::Continue(())),
}
async move {
match provider.get_transaction_receipt(tx_hash).await {
Ok(Some(receipt)) => Ok(ControlFlow::Break(receipt)),
_ => Ok(ControlFlow::Continue(())),
}
},
)
}
})
.await
.context(format!("Polling for receipt failed for {tx_hash}"))
}