Skip to main content

cast/cmd/tip20/
mine.rs

1use crate::{
2    cmd::send::cast_send_raw,
3    tempo,
4    tx::{CastTxSender, SendTxOpts, TxParams, apply_poll_interval, fill_transaction_gas_fees},
5};
6use alloy_network::EthereumWallet;
7use alloy_primitives::{Address, B256, keccak256};
8use alloy_signer::Signer;
9use eyre::Result;
10use foundry_cli::utils::get_chain;
11use foundry_common::{FoundryTransactionBuilder, provider::ProviderBuilder};
12use foundry_evm::hardforks::latest_active_tempo_hardfork;
13use rand::{RngCore, SeedableRng, rngs::StdRng};
14use std::time::{Duration, Instant};
15use tempo_alloy::{
16    TempoNetwork,
17    chainspec::hardfork::TempoHardfork,
18    contracts::precompiles::{ADDRESS_REGISTRY_ADDRESS, IAddressRegistry},
19};
20use tempo_primitives::{MasterId, TempoAddressExt, UserTag};
21
22/// Number of leading zero bytes a TIP-1022 registration hash must have.
23pub(crate) const POW_BYTES: usize = 4;
24
25pub(crate) struct Output {
26    pub(crate) salt: B256,
27    pub(crate) registration_hash: B256,
28    pub(crate) master_id: MasterId,
29    pub(crate) zero_tag_virtual_address: Address,
30}
31
32impl Output {
33    fn new(salt: B256, registration_hash: B256) -> Self {
34        let master_id = MasterId::from_slice(&registration_hash[4..8]);
35        let zero_tag_virtual_address = Address::new_virtual(master_id, UserTag::ZERO);
36        Self { salt, registration_hash, master_id, zero_tag_virtual_address }
37    }
38}
39
40/// Command-specific wording for [`register_virtual_master`].
41pub(crate) struct RegisterMessages {
42    pub(crate) no_signer: &'static str,
43    /// Prefix of the sender-mismatch error, completed with the salt owner and actual sender.
44    pub(crate) mismatch: &'static str,
45    /// Suffix of the `Submitting registerVirtualMaster(..)` status line.
46    pub(crate) submitting: &'static str,
47}
48
49pub(super) fn run(
50    master: Address,
51    salt: Option<B256>,
52    threads: Option<usize>,
53    seed: Option<B256>,
54    no_random: bool,
55) -> Result<Output> {
56    let (output, elapsed) = find_salt(master, salt, threads, seed, no_random, false, "master")?;
57    let header = elapsed.map(|elapsed| format!("Found salt in {elapsed:?}\n")).unwrap_or_default();
58    sh_println!(
59        r#"{header}Salt:              {}
60Registration hash: {}
61Master ID:         {}
62Zero-tag address:  {}"#,
63        output.salt,
64        output.registration_hash,
65        output.master_id,
66        output.zero_tag_virtual_address,
67    )?;
68    Ok(output)
69}
70
71/// Validates `master` and returns the registration to submit: `salt` after checking its proof of
72/// work, or a freshly mined salt together with the time it took to find it.
73pub(crate) fn find_salt(
74    master: Address,
75    salt: Option<B256>,
76    threads: Option<usize>,
77    seed: Option<B256>,
78    no_random: bool,
79    quiet: bool,
80    label: &str,
81) -> Result<(Output, Option<Duration>)> {
82    // The rules a master must satisfy depend on the hardfork, so check the latest active one;
83    // the chain enforces its own when the registration is submitted.
84    if !master.is_valid_master(latest_active_tempo_hardfork()) {
85        eyre::bail!(
86            "invalid {label} address {master}; see https://docs.tempo.xyz/protocol/tips/tip-1022"
87        );
88    }
89
90    if let Some(salt) = salt {
91        let output = derive(master, salt);
92        if !has_pow(&output.registration_hash, POW_BYTES) {
93            eyre::bail!(
94                "provided salt does not satisfy TIP-1022 proof of work: {}",
95                output.registration_hash
96            );
97        }
98        return Ok((output, None));
99    }
100
101    let n_threads = match threads {
102        Some(n) if n > 0 => n,
103        _ => std::thread::available_parallelism().map_or(1, |n| n.get()),
104    };
105    let mut salt = B256::ZERO;
106    if !no_random {
107        let mut rng = match seed {
108            Some(seed) => StdRng::from_seed(seed.0),
109            None => StdRng::from_os_rng(),
110        };
111        rng.fill_bytes(&mut salt[..]);
112    }
113
114    if !quiet {
115        sh_status!("Mining TIP-1022 salt for {master} with {n_threads} threads...")?;
116    }
117    let timer = Instant::now();
118    let output = mine(master, salt, n_threads, POW_BYTES)?;
119    Ok((output, Some(timer.elapsed())))
120}
121
122/// Submits `registerVirtualMaster(salt)` from `master` and returns the transaction hash.
123///
124/// With `quiet`, neither the transaction hash nor the receipt is printed, but the receipt is still
125/// awaited unless `--async` was passed.
126pub(crate) async fn register_virtual_master(
127    master: Address,
128    salt: B256,
129    send_tx: SendTxOpts,
130    mut tx_opts: TxParams,
131    quiet: bool,
132    msgs: &RegisterMessages,
133) -> Result<B256> {
134    let (config, provider) = tempo::tempo_provider(&send_tx.eth.rpc)?;
135    tempo::ensure_tempo_precompile_active(
136        &provider,
137        TempoHardfork::T3,
138        ADDRESS_REGISTRY_ADDRESS,
139        "virtual master registration requires a Tempo T3-capable AddressRegistry RPC",
140    )
141    .await?;
142    apply_poll_interval(&provider, send_tx.poll_interval);
143    let chain = get_chain(config.chain, &provider).await?;
144    tempo::ensure_session_not_browser(&tx_opts.tempo, send_tx.browser.browser)?;
145    let (signer, access_key) =
146        tempo::resolve_session_or_wallet_signer(&tx_opts.tempo, &send_tx.eth.wallet, chain.id())
147            .await?;
148    let sender = match (&access_key, &signer) {
149        (Some(wallet), _) => wallet.account(),
150        (None, Some(signer)) => signer.address(),
151        (None, None) => eyre::bail!("{}", msgs.no_signer),
152    };
153    if sender != master {
154        eyre::bail!(
155            "{} {master}, but the configured signer would register as {sender}",
156            msgs.mismatch
157        );
158    }
159
160    let mut tx = IAddressRegistry::new(ADDRESS_REGISTRY_ADDRESS, &provider)
161        .registerVirtualMaster(salt)
162        .into_transaction_request();
163    tempo::print_expires(tx_opts.tempo.resolve_expires())?;
164    tx_opts.apply::<TempoNetwork>(&mut tx, chain.is_legacy());
165    sh_status!("Submitting registerVirtualMaster({salt}){}", msgs.submitting)?;
166
167    let timeout = send_tx.timeout.unwrap_or(config.transaction_timeout);
168    let fee_provider = (!config.eth_rpc_curl).then_some(&provider);
169    let (tx_hash, receipt) = if let Some(access_key) = &access_key {
170        let prepared = tempo::fill_access_key_transaction(
171            &provider,
172            &mut tx,
173            access_key,
174            chain,
175            config.eip1559_fee_estimate,
176        )
177        .await?;
178        tempo::resolve_and_print_fee_token(fee_provider, &mut tx, Some(sender)).await?;
179        let raw_tx = tx.sign_with_tempo_wallet(&prepared).await?;
180        cast_send_raw(&provider, &raw_tx, send_tx.sync).await?
181    } else {
182        // The wallet provider fills the nonce and gas limit; only the fees are filled here.
183        let wallet = EthereumWallet::from(signer.expect("sender was derived from the signer"));
184        let signer_provider =
185            ProviderBuilder::<TempoNetwork>::from_config(&config)?.build_with_wallet(wallet)?;
186        fill_transaction_gas_fees(
187            &signer_provider,
188            &mut tx,
189            chain.is_legacy(),
190            false,
191            config.eip1559_fee_estimate,
192        )
193        .await?;
194        tempo::resolve_and_print_fee_token(fee_provider, &mut tx, Some(sender)).await?;
195        let cast = CastTxSender::new(&signer_provider);
196        if send_tx.sync {
197            let (tx_hash, receipt) = cast.send_sync(tx).await?;
198            (tx_hash, Some(receipt))
199        } else {
200            (*cast.send(tx).await?.inner().tx_hash(), None)
201        }
202    };
203
204    let cast = CastTxSender::new(&provider);
205    match receipt {
206        Some(receipt) if !quiet => sh_println!("{receipt}")?,
207        Some(_) => {}
208        None if quiet => {
209            if !send_tx.cast_async {
210                cast.sent_tx_receipt(tx_hash, send_tx.confirmations, timeout).await?;
211            }
212        }
213        None => {
214            cast.print_tx_result(tx_hash, send_tx.cast_async, send_tx.confirmations, timeout)
215                .await?
216        }
217    }
218    Ok(tx_hash)
219}
220
221pub(crate) fn mine(
222    master: Address,
223    salt: B256,
224    n_threads: usize,
225    pow_bytes: usize,
226) -> Result<Output> {
227    let mut packed = [0u8; 52];
228    packed[..20].copy_from_slice(master.as_slice());
229
230    crate::cmd::miner::mine_salt(salt, n_threads, move |salt| {
231        packed[20..].copy_from_slice(salt.as_slice());
232        let registration_hash = keccak256(packed);
233        has_pow(&registration_hash, pow_bytes).then(|| Output::new(salt, registration_hash))
234    })
235    .ok_or_else(|| eyre::eyre!("virtual master mining failed: all threads panicked"))
236}
237
238pub(crate) fn derive(master: Address, salt: B256) -> Output {
239    let mut packed = [0u8; 52];
240    packed[..20].copy_from_slice(master.as_slice());
241    packed[20..].copy_from_slice(salt.as_slice());
242    Output::new(salt, keccak256(packed))
243}
244
245pub(crate) fn has_pow(registration_hash: &B256, pow_bytes: usize) -> bool {
246    registration_hash[..pow_bytes].iter().all(|byte| *byte == 0)
247}
248
249#[cfg(test)]
250mod tests {
251    use super::*;
252    use alloy_primitives::{address, b256};
253
254    #[test]
255    fn derives_master_id_and_zero_tag_address() {
256        let master = address!("0x1234567890123456789012345678901234567890");
257        let salt = B256::with_last_byte(1);
258        let output = derive(master, salt);
259
260        assert_eq!(
261            output.registration_hash,
262            b256!("0x661db5481211842e0330ea3e4cf0b4e7e5abd2314161ce16e9a99e7460480f21"),
263        );
264        assert_eq!(output.master_id, MasterId::from([0x12, 0x11, 0x84, 0x2e]));
265        assert_eq!(
266            output.zero_tag_virtual_address,
267            address!("0x1211842efdfdfdfdfdfdfdfdfdfd000000000000"),
268        );
269    }
270
271    #[test]
272    fn mines_pow_with_reduced_difficulty() -> Result<()> {
273        let master = address!("0x1234567890123456789012345678901234567890");
274        let output = mine(master, B256::ZERO, 1, 1)?;
275
276        assert_eq!(
277            output.salt,
278            b256!("0x000000000000000000000000000000000000000000000000f301000000000000"),
279        );
280        assert_eq!(output.registration_hash[0], 0);
281        assert_eq!(output.master_id, MasterId::from_slice(&output.registration_hash[4..8]));
282        Ok(())
283    }
284
285    #[test]
286    fn has_pow_checks_leading_zero_bytes() {
287        let mut hash = B256::ZERO;
288        assert!(has_pow(&hash, 4));
289        assert!(has_pow(&hash, 0));
290
291        hash[3] = 1;
292        assert!(!has_pow(&hash, 4));
293        assert!(has_pow(&hash, 3));
294        assert!(has_pow(&hash, 0));
295    }
296}