brc20-prog 0.16.1

BRC20 programmable module - Smart contract execution engine compatible with BRC20 standard
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
use std::env;

use alloy::primitives::Address;

use crate::global::shared_data::SharedData;

lazy_static::lazy_static! {
    pub(crate) static ref DB_VERSION_KEY: String = "DB_VERSION".to_string();
    pub(crate) static ref DB_VERSION: u32 = 7;

    pub(crate) static ref PROTOCOL_VERSION_KEY: String = "PROTOCOL_VERSION".to_string();
    pub(crate) static ref PROTOCOL_VERSION: u32 = 2;

    static ref DB_PATH_KEY: String = "BRC20_PROG_DB_PATH".to_string();
    static ref DB_PATH_DEFAULT: String = "target/db".to_string();

    static ref BRC20_PROG_RPC_SERVER_ENABLE_AUTH_KEY: String = "BRC20_PROG_RPC_SERVER_ENABLE_AUTH".to_string();
    static ref BRC20_PROG_RPC_SERVER_ENABLE_AUTH_DEFAULT: bool = false;

    static ref BRC20_PROG_RPC_SERVER_USER_KEY: String = "BRC20_PROG_RPC_SERVER_USER".to_string();
    static ref BRC20_PROG_RPC_SERVER_PASSWORD_KEY: String = "BRC20_PROG_RPC_SERVER_PASSWORD".to_string();

    static ref BRC20_PROG_RPC_SERVER_URL_KEY: String = "BRC20_PROG_RPC_SERVER_URL".to_string();
    static ref BRC20_PROG_RPC_SERVER_URL_DEFAULT: String = "127.0.0.1:18545".to_string();

    static ref FAIL_ON_BITCOIN_RPC_ERROR_KEY: String = "FAIL_ON_BITCOIN_RPC_ERROR".to_string();
    static ref FAIL_ON_BITCOIN_RPC_ERROR_DEFAULT: bool = true;

    pub(crate) static ref EVM_RECORD_TRACES_KEY: String = "EVM_RECORD_TRACES".to_string();
    static ref EVM_RECORD_TRACES_DEFAULT: bool = false;

    static ref EVM_CALL_GAS_LIMIT_KEY: String = "EVM_CALL_GAS_LIMIT".to_string();
    static ref EVM_CALL_GAS_LIMIT: u64 = 1_000_000_000;

    static ref BITCOIN_RPC_URL_KEY: String = "BITCOIN_RPC_URL".to_string();
    static ref BITCOIN_RPC_URL_DEFAULT_SIGNET: String = "http://localhost:38332".to_string();

    static ref BITCOIN_RPC_USER_KEY: String = "BITCOIN_RPC_USER".to_string();
    static ref BITCOIN_RPC_PASSWORD_KEY: String = "BITCOIN_RPC_PASSWORD".to_string();

    pub(crate) static ref BITCOIN_RPC_NETWORK_KEY: String = "BITCOIN_RPC_NETWORK".to_string();
    static ref BITCOIN_RPC_NETWORK_DEFAULT_SIGNET: String = "signet".to_string();

    static ref MAX_REQUEST_SIZE_KEY: String = "MAX_REQUEST_SIZE".to_string();
    static ref MAX_REQUEST_SIZE_DEFAULT: u32 = 10 * 1024 * 1024; // 10MB

    static ref MAX_RESPONSE_SIZE_KEY: String = "MAX_RESPONSE_SIZE".to_string();
    static ref MAX_RESPONSE_SIZE_DEFAULT: u32 = 100 * 1024 * 1024; // 100MB

    static ref BATCH_REQUEST_LIMIT_KEY: String = "BATCH_REQUEST_LIMIT".to_string();
    static ref BATCH_REQUEST_LIMIT_DEFAULT: u32 = 50; // 50 requests

    pub static ref CARGO_PKG_VERSION: String = {
        let version = env!("CARGO_PKG_VERSION");
        if version.is_empty() {
            "0.0.0".to_string()
        } else {
            version.to_string()
        }
    };

    pub static ref CARGO_RUST_VERSION: String = {
        let version = env!("CARGO_PKG_RUST_VERSION");
        if version.is_empty() {
            "unknown".to_string()
        } else {
            version.to_string()
        }
    };

    pub static ref INDEXER_ADDRESS: Address = "0x0000000000000000000000000000000000003Ca6".parse().expect("Failed to parse indexer address");
    pub static ref INDEXER_ADDRESS_STRING: String = INDEXER_ADDRESS.to_string();
    pub static ref INVALID_ADDRESS: Address = "0x000000000000000000000000000000000000dead".parse().expect("Failed to parse invalid address");
}

lazy_static::lazy_static! {
    pub static ref CONFIG: SharedData<Brc20ProgConfig> = SharedData::new(Brc20ProgConfig::from_env());
}

pub const MAX_REORG_HISTORY_SIZE: u64 = 10; // 10 blocks, this is the maximum reorg history size
pub const MAX_BLOCK_SIZE: u64 = 4 * 1024 * 1024; // 4MB
pub const GAS_PER_BYTE: u64 = 12000; // 12K gas per byte

pub const MAX_FUTURE_TRANSACTION_NONCES: u64 = 10; // Maximum future transaction nonces allowed
pub const MAX_FUTURE_TRANSACTION_BLOCKS: u64 = 10; // Maximum future transaction block depth allowed

pub const GAS_PER_OP_RETURN_TX_ID: u64 = 40; // 40 gas for fetching the op return tx id
pub const GAS_PER_BITCOIN_RPC_CALL: u64 = 400000; // 400K gas per Bitcoin RPC call
pub const GAS_PER_BIP_322_VERIFY: u64 = 20000; // 20K gas per BIP-322 verify call
pub const GAS_PER_LOCKED_PKSCRIPT: u64 = 20000; // 20K gas per locked pkscript call

const CHAIN_ID: u64 = 0x4252433230; // Mainnet Chain ID: BRC20 in hex
const CHAIN_ID_TESTNETS: u64 = 0x425243323073; // Testnets Chain ID: BRC20s in hex

pub const CALLDATA_LIMIT: usize = 1024 * 1024; // 1MB

/// Configuration for the BRC20 Prog server
/// This struct holds the configuration values for the BRC20 Prog server.
#[derive(Clone, Debug)]
pub struct Brc20ProgConfig {
    /// The URL of the BRC20 Prog RPC server
    pub brc20_prog_rpc_server_url: String,
    /// Whether to enable authentication for the BRC20 Prog RPC server
    pub brc20_prog_rpc_server_enable_auth: bool,
    /// The username for the BRC20 Prog RPC server, if authentication is enabled
    pub brc20_prog_rpc_server_user: Option<String>,
    /// The password for the BRC20 Prog RPC server, if authentication is enabled
    pub brc20_prog_rpc_server_password: Option<String>,
    /// Whether to record EVM traces
    pub evm_record_traces: bool,
    /// Gas limit for EVM calls, through eth_call or eth_estimate_gas
    pub evm_call_gas_limit: u64,
    /// The URL of the Bitcoin RPC server
    pub bitcoin_rpc_url: String,
    /// The username for the Bitcoin RPC server
    /// This is used for authentication with the Bitcoin RPC server
    pub bitcoin_rpc_user: String,
    /// The password for the Bitcoin RPC server
    /// This is used for authentication with the Bitcoin RPC server
    pub bitcoin_rpc_password: String,
    /// The network type for the Bitcoin RPC server
    /// This is used to determine the network (mainnet, testnet, signet, etc.) for the Bitcoin RPC server
    pub bitcoin_rpc_network: String,
    /// Chain ID for the Bitcoin RPC server
    /// This is used to determine the chain ID for the Bitcoin RPC server
    pub chain_id: u64,
    /// Whether to fail on Bitcoin RPC errors, if set to true, the server will stop if Bitcoin RPC server is not reachable when needed
    pub fail_on_bitcoin_rpc_error: bool,
    /// Database path
    pub db_path: String,

    /// Max request size in bytes
    pub max_request_size: u32,
    /// Max response size in bytes
    pub max_response_size: u32,
    /// Batch request limit (0 for unlimited)
    pub batch_request_limit: u32,
}

impl Default for Brc20ProgConfig {
    fn default() -> Self {
        Self::from_env()
    }
}

impl Brc20ProgConfig {
    /// Creates a new instance of `Brc20ProgConfig` with the given parameters.
    ///
    /// Every argument corresponds to an environment variable.
    ///
    /// # Arguments
    /// * `brc20_prog_rpc_server_url` - The URL of the BRC20 Prog RPC server
    /// * `brc20_prog_rpc_server_enable_auth` - Whether to enable authentication for the BRC20 Prog RPC server
    /// * `brc20_prog_rpc_server_user` - The username for the BRC20 Prog RPC server, if authentication is enabled
    /// * `brc20_prog_rpc_server_password` - The password for the BRC20 Prog RPC server, if authentication is enabled
    /// * `evm_call_gas_limit` - Gas limit for EVM calls (default: 1_000_000_000)
    /// * `evm_record_traces` - Whether to record EVM traces
    /// * `bitcoin_rpc_url` - The URL of the Bitcoin RPC server
    /// * `bitcoin_rpc_user` - The username for the Bitcoin RPC server
    /// * `bitcoin_rpc_password` - The password for the Bitcoin RPC server
    /// * `bitcoin_rpc_network` - The network type for the Bitcoin RPC server
    /// * `fail_on_bitcoin_rpc_error` - Whether to fail on Bitcoin RPC errors
    /// * `db_path` - The path to the database folder
    /// * `max_request_size` - Max request size in bytes
    /// * `max_response_size` - Max response size in bytes
    /// * `batch_request_limit` - Batch request limit (0 for unlimited)
    pub fn new(
        brc20_prog_rpc_server_url: String,
        brc20_prog_rpc_server_enable_auth: bool,
        brc20_prog_rpc_server_user: Option<String>,
        brc20_prog_rpc_server_password: Option<String>,
        evm_record_traces: bool,
        evm_call_gas_limit: u64,
        bitcoin_rpc_url: String,
        bitcoin_rpc_user: String,
        bitcoin_rpc_password: String,
        bitcoin_rpc_network: String,
        chain_id: u64,
        fail_on_bitcoin_rpc_error: bool,
        db_path: String,
        max_request_size: u32,
        max_response_size: u32,
        batch_request_limit: u32,
    ) -> Self {
        Self {
            brc20_prog_rpc_server_url,
            brc20_prog_rpc_server_enable_auth,
            brc20_prog_rpc_server_user,
            brc20_prog_rpc_server_password,
            evm_record_traces,
            evm_call_gas_limit,
            bitcoin_rpc_url,
            bitcoin_rpc_user,
            bitcoin_rpc_password,
            bitcoin_rpc_network,
            chain_id,
            fail_on_bitcoin_rpc_error,
            db_path,
            max_request_size,
            max_response_size,
            batch_request_limit,
        }
    }

    /// Creates a new instance of `Brc20ProgConfig` from environment variables
    ///
    /// This function reads the configuration values from environment variables and returns a new instance of `Brc20ProgConfig`.
    ///
    /// List of environment variables read:
    /// * `BRC20_PROG_DB_PATH` - The path to the database folder (Default: "target/db")
    /// * `BRC20_PROG_RPC_SERVER_URL` - The URL of the BRC20 Prog RPC server (Default: "127.0.0.1:18545")
    /// * `BRC20_PROG_RPC_SERVER_ENABLE_AUTH` - Whether to enable authentication for the BRC20 Prog RPC server (Default: false)
    /// * `BRC20_PROG_RPC_SERVER_USER` - The username for the BRC20 Prog RPC server, if authentication is enabled
    /// * `BRC20_PROG_RPC_SERVER_PASSWORD` - The password for the BRC20 Prog RPC server, if authentication is enabled
    /// * `EVM_RECORD_TRACES` - Whether to record EVM traces (Default: false)
    /// * `BITCOIN_RPC_URL` - The URL of the Bitcoin RPC server (Default: "http://localhost:38332" for signet)
    /// * `BITCOIN_RPC_USER` - The username for the Bitcoin RPC server
    /// * `BITCOIN_RPC_PASSWORD` - The password for the Bitcoin RPC server
    /// * `BITCOIN_RPC_NETWORK` - The network type for the Bitcoin RPC server (Default: "signet")
    /// * `FAIL_ON_BITCOIN_RPC_ERROR` - Whether to fail on Bitcoin RPC errors (Default: true)
    /// * `EVM_CALL_GAS_LIMIT` - Gas limit for EVM calls (Default: 1_000_000_000)
    /// * `MAX_REQUEST_SIZE` - Max request size in bytes (Default: 10MB)
    /// * `MAX_RESPONSE_SIZE` - Max response size in bytes (Default: 100MB)
    /// * `BATCH_REQUEST_LIMIT` - Batch request limit (0 for unlimited) (Default: 50)
    /// # Returns
    /// A new instance of `Brc20ProgConfig` with the configuration values read from environment variables.
    pub fn from_env() -> Self {
        let bitcoin_rpc_network =
            env::var(&*BITCOIN_RPC_NETWORK_KEY).unwrap_or("signet".to_string());

        let chain_id = if bitcoin_rpc_network == "bitcoin" || bitcoin_rpc_network == "mainnet" {
            CHAIN_ID
        } else {
            CHAIN_ID_TESTNETS
        };

        Self {
            brc20_prog_rpc_server_url: env::var(&*BRC20_PROG_RPC_SERVER_URL_KEY)
                .unwrap_or(BRC20_PROG_RPC_SERVER_URL_DEFAULT.clone()),
            brc20_prog_rpc_server_enable_auth: env::var(&*BRC20_PROG_RPC_SERVER_ENABLE_AUTH_KEY)
                .map(|x| x == "true")
                .unwrap_or(*BRC20_PROG_RPC_SERVER_ENABLE_AUTH_DEFAULT),
            brc20_prog_rpc_server_user: env::var(&*BRC20_PROG_RPC_SERVER_USER_KEY).ok(),
            brc20_prog_rpc_server_password: env::var(&*BRC20_PROG_RPC_SERVER_PASSWORD_KEY).ok(),
            evm_record_traces: env::var(&*EVM_RECORD_TRACES_KEY)
                .map(|x| x == "true")
                .unwrap_or(*EVM_RECORD_TRACES_DEFAULT),
            evm_call_gas_limit: env::var(&*EVM_CALL_GAS_LIMIT_KEY)
                .map(|x| x.parse::<u64>().unwrap_or(*EVM_CALL_GAS_LIMIT))
                .unwrap_or(*EVM_CALL_GAS_LIMIT),
            bitcoin_rpc_url: env::var(&*BITCOIN_RPC_URL_KEY)
                .unwrap_or(BITCOIN_RPC_URL_DEFAULT_SIGNET.clone()),
            bitcoin_rpc_user: env::var(&*BITCOIN_RPC_USER_KEY).unwrap_or(Default::default()),
            bitcoin_rpc_password: env::var(&*BITCOIN_RPC_PASSWORD_KEY)
                .unwrap_or(Default::default()),
            bitcoin_rpc_network: env::var(&*BITCOIN_RPC_NETWORK_KEY)
                .unwrap_or("signet".to_string()),
            chain_id,
            fail_on_bitcoin_rpc_error: env::var(&*FAIL_ON_BITCOIN_RPC_ERROR_KEY)
                .map(|x| x == "true")
                .unwrap_or(*FAIL_ON_BITCOIN_RPC_ERROR_DEFAULT),
            db_path: env::var(&*DB_PATH_KEY).unwrap_or(DB_PATH_DEFAULT.clone()),

            max_request_size: env::var(&*MAX_REQUEST_SIZE_KEY)
                .map(|x| x.parse::<u32>().unwrap_or(*MAX_REQUEST_SIZE_DEFAULT))
                .unwrap_or(*MAX_REQUEST_SIZE_DEFAULT),
            max_response_size: env::var(&*MAX_RESPONSE_SIZE_KEY)
                .map(|x| x.parse::<u32>().unwrap_or(*MAX_RESPONSE_SIZE_DEFAULT))
                .unwrap_or(*MAX_RESPONSE_SIZE_DEFAULT),
            batch_request_limit: env::var(&*BATCH_REQUEST_LIMIT_KEY)
                .map(|x| x.parse::<u32>().unwrap_or(*BATCH_REQUEST_LIMIT_DEFAULT))
                .unwrap_or(*BATCH_REQUEST_LIMIT_DEFAULT),
        }
    }
}

#[cfg(feature = "server")]
pub fn validate_config(config: &Brc20ProgConfig) -> Result<(), Box<dyn std::error::Error>> {
    if config.brc20_prog_rpc_server_enable_auth
        && (config.brc20_prog_rpc_server_user.is_none()
            || config.brc20_prog_rpc_server_password.is_none())
    {
        return Err("Authentication is enabled but no username or password is set".into());
    }

    if config.brc20_prog_rpc_server_url.is_empty() {
        return Err("RPC server URL is empty".into());
    }

    if config.bitcoin_rpc_url.is_empty() && config.fail_on_bitcoin_rpc_error {
        return Err("Bitcoin RPC URL is empty".into());
    }

    if config.bitcoin_rpc_network.is_empty() && config.fail_on_bitcoin_rpc_error {
        return Err("Bitcoin RPC network is empty".into());
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(feature = "server")]
    fn valid_config() -> Brc20ProgConfig {
        Brc20ProgConfig::new(
            "127.0.0.1:18545".to_string(), // rpc url
            false,                          // enable auth
            None,                           // user
            None,                           // password
            false,                          // record traces
            1_000_000_000,                  // call gas limit
            "http://localhost:38332".to_string(), // bitcoin rpc url
            "user".to_string(),
            "pass".to_string(),
            "signet".to_string(), // network
            CHAIN_ID_TESTNETS,
            true, // fail_on_bitcoin_rpc_error
            "target/db".to_string(),
            10 * 1024 * 1024,
            100 * 1024 * 1024,
            50,
        )
    }

    #[cfg(feature = "server")]
    #[test]
    fn test_validate_config_accepts_valid() {
        assert!(validate_config(&valid_config()).is_ok());
    }

    #[cfg(feature = "server")]
    #[test]
    fn test_validate_config_rejects_auth_without_credentials() {
        let mut config = valid_config();
        config.brc20_prog_rpc_server_enable_auth = true;
        config.brc20_prog_rpc_server_user = None;
        config.brc20_prog_rpc_server_password = None;
        assert!(validate_config(&config).is_err());

        // User without password is still incomplete.
        config.brc20_prog_rpc_server_user = Some("user".to_string());
        assert!(validate_config(&config).is_err());

        // Both present is accepted.
        config.brc20_prog_rpc_server_password = Some("pass".to_string());
        assert!(validate_config(&config).is_ok());
    }

    #[cfg(feature = "server")]
    #[test]
    fn test_validate_config_rejects_empty_rpc_url() {
        let mut config = valid_config();
        config.brc20_prog_rpc_server_url = String::new();
        assert!(validate_config(&config).is_err());
    }

    #[cfg(feature = "server")]
    #[test]
    fn test_validate_config_bitcoin_url_only_required_when_failing_on_rpc_error() {
        let mut config = valid_config();
        config.bitcoin_rpc_url = String::new();

        // Empty Bitcoin URL is fatal only when we fail on Bitcoin RPC errors.
        config.fail_on_bitcoin_rpc_error = true;
        assert!(validate_config(&config).is_err());

        config.fail_on_bitcoin_rpc_error = false;
        assert!(validate_config(&config).is_ok());
    }

    // Restores a process-global env var to its previous value on drop, so these
    // tests stay isolated and panic-safe (cleanup runs even if an assert fails).
    struct EnvVarGuard {
        key: String,
        previous: Option<String>,
    }

    impl EnvVarGuard {
        fn set(key: &str, value: &str) -> Self {
            let previous = env::var(key).ok();
            env::set_var(key, value);
            EnvVarGuard {
                key: key.to_string(),
                previous,
            }
        }
    }

    impl Drop for EnvVarGuard {
        fn drop(&mut self) {
            match &self.previous {
                Some(value) => env::set_var(&self.key, value),
                None => env::remove_var(&self.key),
            }
        }
    }

    #[test]
    fn test_from_env_selects_chain_id_by_network() {
        let key = &*BITCOIN_RPC_NETWORK_KEY;
        // Guard captures the original value once; it is restored on drop.
        let _guard = EnvVarGuard::set(key, "bitcoin");
        assert_eq!(Brc20ProgConfig::from_env().chain_id, CHAIN_ID);

        env::set_var(key, "mainnet");
        assert_eq!(Brc20ProgConfig::from_env().chain_id, CHAIN_ID);

        env::set_var(key, "signet");
        assert_eq!(Brc20ProgConfig::from_env().chain_id, CHAIN_ID_TESTNETS);
    }

    #[test]
    fn test_from_env_falls_back_on_malformed_numeric() {
        let key = &*EVM_CALL_GAS_LIMIT_KEY;
        let _guard = EnvVarGuard::set(key, "not-a-number");
        assert_eq!(
            Brc20ProgConfig::from_env().evm_call_gas_limit,
            *EVM_CALL_GAS_LIMIT
        );
    }
}