diff --git a/cmd/cartesi-rollups-node/handlers.go b/cmd/cartesi-rollups-node/handlers.go index 329e76935..94957a71d 100644 --- a/cmd/cartesi-rollups-node/handlers.go +++ b/cmd/cartesi-rollups-node/handlers.go @@ -12,31 +12,43 @@ import ( "github.com/cartesi/rollups-node/internal/config" ) -func newHttpServiceHandler() http.Handler { +func newHttpServiceHandler(nodeConfig config.NodeConfig) http.Handler { handler := http.NewServeMux() handler.Handle("/healthz", http.HandlerFunc(healthcheckHandler)) - graphqlProxy, err := newReverseProxy(getPort(portOffsetGraphQLServer)) + graphqlProxy, err := newReverseProxy( + nodeConfig.CartesiHttpAddress(), + getPort(nodeConfig.CartesiHttpPort(), portOffsetGraphQLServer), + ) if err != nil { config.ErrorLogger.Fatal(err) } handler.Handle("/graphql", graphqlProxy) - dispatcherProxy, err := newReverseProxy(getPort(portOffsetDispatcher)) + dispatcherProxy, err := newReverseProxy( + nodeConfig.CartesiHttpAddress(), + getPort(nodeConfig.CartesiHttpPort(), portOffsetDispatcher), + ) if err != nil { config.ErrorLogger.Fatal(err) } handler.Handle("/metrics", dispatcherProxy) - inspectProxy, err := newReverseProxy(getPort(portOffsetInspectServer)) + inspectProxy, err := newReverseProxy( + nodeConfig.CartesiHttpAddress(), + getPort(nodeConfig.CartesiHttpPort(), portOffsetInspectServer), + ) if err != nil { config.ErrorLogger.Fatal(err) } handler.Handle("/inspect", inspectProxy) handler.Handle("/inspect/", inspectProxy) - if config.GetCartesiFeatureHostMode() { - hostProxy, err := newReverseProxy(getPort(portOffsetHostRunnerRollups)) + if nodeConfig.CartesiFeatureHostMode() { + hostProxy, err := newReverseProxy( + nodeConfig.CartesiHttpAddress(), + getPort(nodeConfig.CartesiHttpPort(), portOffsetHostRunnerRollups), + ) if err != nil { config.ErrorLogger.Fatal(err) } @@ -50,10 +62,10 @@ func healthcheckHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } -func newReverseProxy(port int) (*httputil.ReverseProxy, error) { +func newReverseProxy(httpAddress string, port int) (*httputil.ReverseProxy, error) { urlStr := fmt.Sprintf( "http://%v:%v/", - config.GetCartesiHttpAddress(), + httpAddress, port, ) diff --git a/cmd/cartesi-rollups-node/main.go b/cmd/cartesi-rollups-node/main.go index b9b7cab68..a18f5f254 100644 --- a/cmd/cartesi-rollups-node/main.go +++ b/cmd/cartesi-rollups-node/main.go @@ -20,35 +20,41 @@ func main() { ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer stop() - sunodoValidatorEnabled := config.GetCartesiExperimentalSunodoValidatorEnabled() + nodeConfig := config.NewNodeConfigFromEnv() + + nodeConfig.Validate() + + config.InitLog(nodeConfig) + + sunodoValidatorEnabled := nodeConfig.CartesiExperimentalSunodoValidatorEnabled() if !sunodoValidatorEnabled { // add Redis first - s = append(s, newRedis()) + s = append(s, newRedis(nodeConfig)) } // add services without dependencies - s = append(s, newGraphQLServer()) - s = append(s, newIndexer()) - s = append(s, newStateServer()) + s = append(s, newGraphQLServer(nodeConfig)) + s = append(s, newIndexer(nodeConfig)) + s = append(s, newStateServer(nodeConfig)) // start either the server manager or host runner - if config.GetCartesiFeatureHostMode() { - s = append(s, newHostRunner()) + if nodeConfig.CartesiFeatureHostMode() { + s = append(s, newHostRunner(nodeConfig)) } else { - s = append(s, newServerManager()) + s = append(s, newServerManager(nodeConfig)) } // enable claimer if reader mode and sunodo validator mode are disabled - if !config.GetCartesiFeatureDisableClaimer() && !sunodoValidatorEnabled { - s = append(s, newAuthorityClaimer()) + if !nodeConfig.CartesiFeatureDisableClaimer() && !sunodoValidatorEnabled { + s = append(s, newAuthorityClaimer(nodeConfig)) } // add services with dependencies - s = append(s, newAdvanceRunner()) // Depends on the server-manager/host-runner - s = append(s, newDispatcher()) // Depends on the state server - s = append(s, newInspectServer()) // Depends on the server-manager/host-runner + s = append(s, newAdvanceRunner(nodeConfig)) // Depends on the server-manager/host-runner + s = append(s, newDispatcher(nodeConfig)) // Depends on the state server + s = append(s, newInspectServer(nodeConfig)) // Depends on the server-manager/host-runner - s = append(s, newHttpService()) + s = append(s, newHttpService(nodeConfig)) ready := make(chan struct{}, 1) // logs startup time diff --git a/cmd/cartesi-rollups-node/services.go b/cmd/cartesi-rollups-node/services.go index ad5395d2f..3626c7763 100644 --- a/cmd/cartesi-rollups-node/services.go +++ b/cmd/cartesi-rollups-node/services.go @@ -37,23 +37,27 @@ const ( ) // Get the port of the given service. -func getPort(offset portOffset) int { - return config.GetCartesiHttpPort() + int(offset) +func getPort(httpPort int, offset portOffset) int { + return httpPort + int(offset) } // Get the redis endpoint based on whether the experimental sunodo validator mode is enabled. -func getRedisEndpoint() string { - if config.GetCartesiExperimentalSunodoValidatorEnabled() { - return config.GetCartesiExperimentalSunodoValidatorRedisEndpoint() +func getRedisEndpoint(nodeConfig config.NodeConfig) string { + if nodeConfig.CartesiExperimentalSunodoValidatorEnabled() { + return nodeConfig.CartesiExperimentalSunodoValidatorRedisEndpoint() } else { - return fmt.Sprintf("redis://%v:%v", localhost, getPort(portOffsetRedis)) + return fmt.Sprintf( + "redis://%v:%v", + localhost, + getPort(nodeConfig.CartesiHttpPort(), portOffsetRedis), + ) } } // Create the RUST_LOG variable using the config log level. // If the log level is set to debug, set tracing log for the given rust module. -func getRustLog(rustModule string) string { - switch config.GetCartesiLogLevel() { +func getRustLog(nodeConfig config.NodeConfig, rustModule string) string { + switch nodeConfig.CartesiLogLevel() { case config.LogLevelDebug: return fmt.Sprintf("RUST_LOG=info,%v=trace", rustModule) case config.LogLevelInfo: @@ -67,72 +71,81 @@ func getRustLog(rustModule string) string { } } -func newAdvanceRunner() services.CommandService { +func newAdvanceRunner(nodeConfig config.NodeConfig) services.CommandService { var s services.CommandService s.Name = "advance-runner" - s.HealthcheckPort = getPort(portOffsetAdvanceRunner) + s.HealthcheckPort = getPort(nodeConfig.CartesiHttpPort(), portOffsetAdvanceRunner) s.Path = "cartesi-rollups-advance-runner" s.Env = append(s.Env, "LOG_ENABLE_TIMESTAMP=false") s.Env = append(s.Env, "LOG_ENABLE_COLOR=false") - s.Env = append(s.Env, getRustLog("advance_runner")) + s.Env = append(s.Env, getRustLog(nodeConfig, "advance_runner")) s.Env = append(s.Env, fmt.Sprintf("SERVER_MANAGER_ENDPOINT=http://%v:%v", localhost, - getPort(portOffsetServerManager))) + getPort(nodeConfig.CartesiHttpPort(), portOffsetServerManager), + ), + ) s.Env = append(s.Env, fmt.Sprintf("SESSION_ID=%v", serverManagerSessionId)) s.Env = append(s.Env, - fmt.Sprintf("REDIS_ENDPOINT=%v", getRedisEndpoint())) + fmt.Sprintf("REDIS_ENDPOINT=%v", getRedisEndpoint(nodeConfig))) s.Env = append(s.Env, - fmt.Sprintf("CHAIN_ID=%v", config.GetCartesiBlockchainId())) + fmt.Sprintf("CHAIN_ID=%v", nodeConfig.CartesiBlockchainId())) s.Env = append(s.Env, - fmt.Sprintf("DAPP_CONTRACT_ADDRESS=%v", config.GetCartesiContractsApplicationAddress())) + fmt.Sprintf("DAPP_CONTRACT_ADDRESS=%v", nodeConfig.CartesiContractsApplicationAddress())) s.Env = append(s.Env, - fmt.Sprintf("PROVIDER_HTTP_ENDPOINT=%v", config.GetCartesiBlockchainHttpEndpoint())) + fmt.Sprintf("PROVIDER_HTTP_ENDPOINT=%v", nodeConfig.CartesiBlockchainHttpEndpoint())) s.Env = append(s.Env, - fmt.Sprintf("ADVANCE_RUNNER_HEALTHCHECK_PORT=%v", getPort(portOffsetAdvanceRunner))) + fmt.Sprintf("ADVANCE_RUNNER_HEALTHCHECK_PORT=%v", + getPort(nodeConfig.CartesiHttpPort(), portOffsetAdvanceRunner), + ), + ) s.Env = append(s.Env, - fmt.Sprintf("READER_MODE=%v", config.GetCartesiFeatureDisableClaimer())) - if config.GetCartesiFeatureHostMode() || config.GetCartesiFeatureDisableMachineHashCheck() { + fmt.Sprintf("READER_MODE=%v", nodeConfig.CartesiFeatureDisableClaimer())) + if nodeConfig.CartesiFeatureHostMode() || nodeConfig.CartesiFeatureDisableMachineHashCheck() { s.Env = append(s.Env, "SNAPSHOT_VALIDATION_ENABLED=false") } - if !config.GetCartesiFeatureHostMode() { + if !nodeConfig.CartesiFeatureHostMode() { s.Env = append(s.Env, - fmt.Sprintf("MACHINE_SNAPSHOT_PATH=%v", config.GetCartesiSnapshotDir())) + fmt.Sprintf("MACHINE_SNAPSHOT_PATH=%v", nodeConfig.CartesiSnapshotDir())) } s.Env = append(s.Env, os.Environ()...) return s } -func newAuthorityClaimer() services.CommandService { +func newAuthorityClaimer(nodeConfig config.NodeConfig) services.CommandService { var s services.CommandService s.Name = "authority-claimer" - s.HealthcheckPort = getPort(portOffsetAuthorityClaimer) + s.HealthcheckPort = getPort(nodeConfig.CartesiHttpPort(), portOffsetAuthorityClaimer) s.Path = "cartesi-rollups-authority-claimer" s.Env = append(s.Env, "LOG_ENABLE_TIMESTAMP=false") s.Env = append(s.Env, "LOG_ENABLE_COLOR=false") - s.Env = append(s.Env, getRustLog("authority_claimer")) + s.Env = append(s.Env, getRustLog(nodeConfig, "authority_claimer")) s.Env = append(s.Env, - fmt.Sprintf("TX_PROVIDER_HTTP_ENDPOINT=%v", config.GetCartesiBlockchainHttpEndpoint())) + fmt.Sprintf("TX_PROVIDER_HTTP_ENDPOINT=%v", nodeConfig.CartesiBlockchainHttpEndpoint())) s.Env = append(s.Env, - fmt.Sprintf("TX_CHAIN_ID=%v", config.GetCartesiBlockchainId())) + fmt.Sprintf("TX_CHAIN_ID=%v", nodeConfig.CartesiBlockchainId())) s.Env = append(s.Env, - fmt.Sprintf("TX_CHAIN_IS_LEGACY=%v", config.GetCartesiBlockchainIsLegacy())) + fmt.Sprintf("TX_CHAIN_IS_LEGACY=%v", nodeConfig.CartesiBlockchainIsLegacy())) s.Env = append(s.Env, - fmt.Sprintf("TX_DEFAULT_CONFIRMATIONS=%v", config.GetCartesiBlockchainFinalityOffset())) + fmt.Sprintf("TX_DEFAULT_CONFIRMATIONS=%v", nodeConfig.CartesiBlockchainFinalityOffset())) s.Env = append(s.Env, - fmt.Sprintf("REDIS_ENDPOINT=%v", getRedisEndpoint())) + fmt.Sprintf("REDIS_ENDPOINT=%v", getRedisEndpoint(nodeConfig))) s.Env = append(s.Env, - fmt.Sprintf("HISTORY_ADDRESS=%v", config.GetCartesiContractsHistoryAddress())) + fmt.Sprintf("HISTORY_ADDRESS=%v", nodeConfig.CartesiContractsHistoryAddress())) s.Env = append(s.Env, - fmt.Sprintf("AUTHORITY_ADDRESS=%v", config.GetCartesiContractsAuthorityAddress())) + fmt.Sprintf("AUTHORITY_ADDRESS=%v", nodeConfig.CartesiContractsAuthorityAddress())) s.Env = append(s.Env, - fmt.Sprintf("INPUT_BOX_ADDRESS=%v", config.GetCartesiContractsInputBoxAddress())) + fmt.Sprintf("INPUT_BOX_ADDRESS=%v", nodeConfig.CartesiContractsInputBoxAddress())) s.Env = append(s.Env, - fmt.Sprintf("GENESIS_BLOCK=%v", config.GetCartesiContractsInputBoxDeploymentBlockNumber())) + fmt.Sprintf("GENESIS_BLOCK=%v", nodeConfig.CartesiContractsInputBoxDeploymentBlockNumber())) s.Env = append(s.Env, - fmt.Sprintf("AUTHORITY_CLAIMER_HTTP_SERVER_PORT=%v", getPort(portOffsetAuthorityClaimer))) - switch auth := config.GetAuth().(type) { + fmt.Sprintf( + "AUTHORITY_CLAIMER_HTTP_SERVER_PORT=%v", + getPort(nodeConfig.CartesiHttpPort(), portOffsetAuthorityClaimer), + ), + ) + switch auth := nodeConfig.CartesiAuth().(type) { case config.AuthMnemonic: s.Env = append(s.Env, fmt.Sprintf("TX_SIGNING_MNEMONIC=%v", auth.Mnemonic)) @@ -150,128 +163,169 @@ func newAuthorityClaimer() services.CommandService { return s } -func newDispatcher() services.CommandService { +func newDispatcher(nodeConfig config.NodeConfig) services.CommandService { var s services.CommandService s.Name = "dispatcher" - s.HealthcheckPort = getPort(portOffsetDispatcher) + s.HealthcheckPort = getPort(nodeConfig.CartesiHttpPort(), portOffsetDispatcher) s.Path = "cartesi-rollups-dispatcher" s.Env = append(s.Env, "LOG_ENABLE_TIMESTAMP=false") s.Env = append(s.Env, "LOG_ENABLE_COLOR=false") - s.Env = append(s.Env, getRustLog("dispatcher")) + s.Env = append(s.Env, getRustLog(nodeConfig, "dispatcher")) s.Env = append(s.Env, - fmt.Sprintf("SC_GRPC_ENDPOINT=http://%v:%v", localhost, getPort(portOffsetStateServer))) + fmt.Sprintf( + "SC_GRPC_ENDPOINT=http://%v:%v", + localhost, getPort(nodeConfig.CartesiHttpPort(), portOffsetStateServer), + ), + ) s.Env = append(s.Env, - fmt.Sprintf("SC_DEFAULT_CONFIRMATIONS=%v", config.GetCartesiBlockchainFinalityOffset())) + fmt.Sprintf("SC_DEFAULT_CONFIRMATIONS=%v", nodeConfig.CartesiBlockchainFinalityOffset())) s.Env = append(s.Env, - fmt.Sprintf("REDIS_ENDPOINT=%v", getRedisEndpoint())) + fmt.Sprintf("REDIS_ENDPOINT=%v", getRedisEndpoint(nodeConfig))) s.Env = append(s.Env, - fmt.Sprintf("DAPP_ADDRESS=%v", config.GetCartesiContractsApplicationAddress())) + fmt.Sprintf("DAPP_ADDRESS=%v", nodeConfig.CartesiContractsApplicationAddress())) s.Env = append(s.Env, fmt.Sprintf("DAPP_DEPLOYMENT_BLOCK_NUMBER=%v", - config.GetCartesiContractsApplicationDeploymentBlockNumber())) + nodeConfig.CartesiContractsApplicationDeploymentBlockNumber())) s.Env = append(s.Env, - fmt.Sprintf("HISTORY_ADDRESS=%v", config.GetCartesiContractsHistoryAddress())) + fmt.Sprintf("HISTORY_ADDRESS=%v", nodeConfig.CartesiContractsHistoryAddress())) s.Env = append(s.Env, - fmt.Sprintf("AUTHORITY_ADDRESS=%v", config.GetCartesiContractsAuthorityAddress())) + fmt.Sprintf("AUTHORITY_ADDRESS=%v", nodeConfig.CartesiContractsAuthorityAddress())) s.Env = append(s.Env, - fmt.Sprintf("INPUT_BOX_ADDRESS=%v", config.GetCartesiContractsInputBoxAddress())) + fmt.Sprintf("INPUT_BOX_ADDRESS=%v", nodeConfig.CartesiContractsInputBoxAddress())) s.Env = append(s.Env, - fmt.Sprintf("RD_EPOCH_DURATION=%v", int(config.GetCartesiEpochDuration().Seconds()))) + fmt.Sprintf("RD_EPOCH_DURATION=%v", int(nodeConfig.CartesiEpochDuration().Seconds()))) s.Env = append(s.Env, - fmt.Sprintf("CHAIN_ID=%v", config.GetCartesiBlockchainId())) + fmt.Sprintf("CHAIN_ID=%v", nodeConfig.CartesiBlockchainId())) s.Env = append(s.Env, - fmt.Sprintf("DISPATCHER_HTTP_SERVER_PORT=%v", getPort(portOffsetDispatcher))) + fmt.Sprintf( + "DISPATCHER_HTTP_SERVER_PORT=%v", + getPort(nodeConfig.CartesiHttpPort(), portOffsetDispatcher), + ), + ) s.Env = append(s.Env, os.Environ()...) return s } -func newGraphQLServer() services.CommandService { +func newGraphQLServer(nodeConfig config.NodeConfig) services.CommandService { var s services.CommandService s.Name = "graphql-server" - s.HealthcheckPort = getPort(portOffsetGraphQLHealthcheck) + s.HealthcheckPort = getPort(nodeConfig.CartesiHttpPort(), portOffsetGraphQLHealthcheck) s.Path = "cartesi-rollups-graphql-server" s.Env = append(s.Env, "LOG_ENABLE_TIMESTAMP=false") s.Env = append(s.Env, "LOG_ENABLE_COLOR=false") - s.Env = append(s.Env, getRustLog("graphql_server")) + s.Env = append(s.Env, getRustLog(nodeConfig, "graphql_server")) s.Env = append(s.Env, - fmt.Sprintf("POSTGRES_ENDPOINT=%v", config.GetCartesiPostgresEndpoint())) + fmt.Sprintf("POSTGRES_ENDPOINT=%v", nodeConfig.CartesiPostgresEndpoint())) s.Env = append(s.Env, fmt.Sprintf("GRAPHQL_HOST=%v", localhost)) s.Env = append(s.Env, - fmt.Sprintf("GRAPHQL_PORT=%v", getPort(portOffsetGraphQLServer))) + fmt.Sprintf( + "GRAPHQL_PORT=%v", + getPort(nodeConfig.CartesiHttpPort(), portOffsetGraphQLServer)), + ) s.Env = append(s.Env, - fmt.Sprintf("GRAPHQL_HEALTHCHECK_PORT=%v", getPort(portOffsetGraphQLHealthcheck))) + fmt.Sprintf("GRAPHQL_HEALTHCHECK_PORT=%v", + getPort(nodeConfig.CartesiHttpPort(), portOffsetGraphQLHealthcheck))) s.Env = append(s.Env, os.Environ()...) return s } -func newHostRunner() services.CommandService { +func newHostRunner(nodeConfig config.NodeConfig) services.CommandService { var s services.CommandService s.Name = "host-runner" - s.HealthcheckPort = getPort(portOffsetHostRunnerHealthcheck) + s.HealthcheckPort = getPort(nodeConfig.CartesiHttpPort(), portOffsetHostRunnerHealthcheck) s.Path = "cartesi-rollups-host-runner" s.Env = append(s.Env, "LOG_ENABLE_TIMESTAMP=false") s.Env = append(s.Env, "LOG_ENABLE_COLOR=false") - s.Env = append(s.Env, getRustLog("host_runner")) + s.Env = append(s.Env, getRustLog(nodeConfig, "host_runner")) s.Env = append(s.Env, fmt.Sprintf("GRPC_SERVER_MANAGER_ADDRESS=%v", localhost)) s.Env = append(s.Env, - fmt.Sprintf("GRPC_SERVER_MANAGER_PORT=%v", getPort(portOffsetServerManager))) + fmt.Sprintf( + "GRPC_SERVER_MANAGER_PORT=%v", + getPort(nodeConfig.CartesiHttpPort(), portOffsetServerManager), + ), + ) s.Env = append(s.Env, fmt.Sprintf("HTTP_ROLLUP_SERVER_ADDRESS=%v", localhost)) s.Env = append(s.Env, - fmt.Sprintf("HTTP_ROLLUP_SERVER_PORT=%v", getPort(portOffsetHostRunnerRollups))) + fmt.Sprintf("HTTP_ROLLUP_SERVER_PORT=%v", + getPort(nodeConfig.CartesiHttpPort(), portOffsetHostRunnerRollups), + ), + ) s.Env = append(s.Env, - fmt.Sprintf("HOST_RUNNER_HEALTHCHECK_PORT=%v", getPort(portOffsetHostRunnerHealthcheck))) + fmt.Sprintf("HOST_RUNNER_HEALTHCHECK_PORT=%v", + getPort(nodeConfig.CartesiHttpPort(), portOffsetHostRunnerHealthcheck))) s.Env = append(s.Env, os.Environ()...) return s } -func newIndexer() services.CommandService { +func newIndexer(nodeConfig config.NodeConfig) services.CommandService { var s services.CommandService s.Name = "indexer" - s.HealthcheckPort = getPort(portOffsetIndexer) + s.HealthcheckPort = getPort(nodeConfig.CartesiHttpPort(), portOffsetIndexer) s.Path = "cartesi-rollups-indexer" s.Env = append(s.Env, "LOG_ENABLE_TIMESTAMP=false") s.Env = append(s.Env, "LOG_ENABLE_COLOR=false") - s.Env = append(s.Env, getRustLog("indexer")) + s.Env = append(s.Env, getRustLog(nodeConfig, "indexer")) s.Env = append(s.Env, - fmt.Sprintf("POSTGRES_ENDPOINT=%v", config.GetCartesiPostgresEndpoint())) + fmt.Sprintf("POSTGRES_ENDPOINT=%v", nodeConfig.CartesiPostgresEndpoint())) s.Env = append(s.Env, - fmt.Sprintf("CHAIN_ID=%v", config.GetCartesiBlockchainId())) + fmt.Sprintf("CHAIN_ID=%v", nodeConfig.CartesiBlockchainId())) s.Env = append(s.Env, - fmt.Sprintf("DAPP_CONTRACT_ADDRESS=%v", config.GetCartesiContractsApplicationAddress())) + fmt.Sprintf("DAPP_CONTRACT_ADDRESS=%v", nodeConfig.CartesiContractsApplicationAddress())) s.Env = append(s.Env, - fmt.Sprintf("REDIS_ENDPOINT=%v", getRedisEndpoint())) + fmt.Sprintf("REDIS_ENDPOINT=%v", getRedisEndpoint(nodeConfig))) s.Env = append(s.Env, - fmt.Sprintf("INDEXER_HEALTHCHECK_PORT=%v", getPort(portOffsetIndexer))) + fmt.Sprintf( + "INDEXER_HEALTHCHECK_PORT=%v", + getPort(nodeConfig.CartesiHttpPort(), portOffsetIndexer), + ), + ) s.Env = append(s.Env, os.Environ()...) return s } -func newInspectServer() services.CommandService { +func newInspectServer(nodeConfig config.NodeConfig) services.CommandService { var s services.CommandService s.Name = "inspect-server" - s.HealthcheckPort = getPort(portOffsetInspectHealthcheck) + s.HealthcheckPort = getPort(nodeConfig.CartesiHttpPort(), portOffsetInspectHealthcheck) s.Path = "cartesi-rollups-inspect-server" s.Env = append(s.Env, "LOG_ENABLE_TIMESTAMP=false") s.Env = append(s.Env, "LOG_ENABLE_COLOR=false") - s.Env = append(s.Env, getRustLog("inspect_server")) + s.Env = append(s.Env, getRustLog(nodeConfig, "inspect_server")) s.Env = append(s.Env, - fmt.Sprintf("INSPECT_SERVER_ADDRESS=%v:%v", localhost, getPort(portOffsetInspectServer))) + fmt.Sprintf( + "INSPECT_SERVER_ADDRESS=%v:%v", + localhost, + getPort(nodeConfig.CartesiHttpPort(), portOffsetInspectServer), + ), + ) s.Env = append(s.Env, - fmt.Sprintf("SERVER_MANAGER_ADDRESS=%v:%v", localhost, getPort(portOffsetServerManager))) + fmt.Sprintf( + "SERVER_MANAGER_ADDRESS=%v:%v", + localhost, + getPort(nodeConfig.CartesiHttpPort(), portOffsetServerManager), + ), + ) s.Env = append(s.Env, fmt.Sprintf("SESSION_ID=%v", serverManagerSessionId)) s.Env = append(s.Env, - fmt.Sprintf("INSPECT_SERVER_HEALTHCHECK_PORT=%v", getPort(portOffsetInspectHealthcheck))) + fmt.Sprintf( + "INSPECT_SERVER_HEALTHCHECK_PORT=%v", + getPort(nodeConfig.CartesiHttpPort(), portOffsetInspectHealthcheck), + ), + ) s.Env = append(s.Env, os.Environ()...) return s } -func newRedis() services.CommandService { +func newRedis(nodeConfig config.NodeConfig) services.CommandService { var s services.CommandService s.Name = "redis" - s.HealthcheckPort = getPort(portOffsetRedis) + s.HealthcheckPort = getPort(nodeConfig.CartesiHttpPort(), portOffsetRedis) s.Path = "redis-server" - s.Args = append(s.Args, "--port", fmt.Sprint(getPort(portOffsetRedis))) + s.Args = append(s.Args, + "--port", + fmt.Sprint(getPort(nodeConfig.CartesiHttpPort(), portOffsetRedis)), + ) // Disable persistence with --save and --appendonly config s.Args = append(s.Args, "--save", "") s.Args = append(s.Args, "--appendonly", "no") @@ -279,15 +333,20 @@ func newRedis() services.CommandService { return s } -func newServerManager() services.ServerManager { +func newServerManager(nodeConfig config.NodeConfig) services.ServerManager { var s services.ServerManager s.Name = "server-manager" - s.HealthcheckPort = getPort(portOffsetServerManager) + s.HealthcheckPort = getPort(nodeConfig.CartesiHttpPort(), portOffsetServerManager) s.Path = "server-manager" s.Args = append(s.Args, - fmt.Sprintf("--manager-address=%v:%v", localhost, getPort(portOffsetServerManager))) + fmt.Sprintf( + "--manager-address=%v:%v", + localhost, + getPort(nodeConfig.CartesiHttpPort(), portOffsetServerManager), + ), + ) s.Env = append(s.Env, "REMOTE_CARTESI_MACHINE_LOG_LEVEL=info") - if config.GetCartesiLogLevel() == config.LogLevelDebug { + if nodeConfig.CartesiLogLevel() == config.LogLevelDebug { s.Env = append(s.Env, "SERVER_MANAGER_LOG_LEVEL=info") } else { s.Env = append(s.Env, "SERVER_MANAGER_LOG_LEVEL=warning") @@ -296,28 +355,34 @@ func newServerManager() services.ServerManager { return s } -func newStateServer() services.CommandService { +func newStateServer(nodeConfig config.NodeConfig) services.CommandService { var s services.CommandService s.Name = "state-server" - s.HealthcheckPort = getPort(portOffsetStateServer) + s.HealthcheckPort = getPort(nodeConfig.CartesiHttpPort(), portOffsetStateServer) s.Path = "cartesi-rollups-state-server" s.Env = append(s.Env, "LOG_ENABLE_TIMESTAMP=false") s.Env = append(s.Env, "LOG_ENABLE_COLOR=false") - s.Env = append(s.Env, getRustLog("state_server")) + s.Env = append(s.Env, getRustLog(nodeConfig, "state_server")) s.Env = append(s.Env, "SF_CONCURRENT_EVENTS_FETCH=1") s.Env = append(s.Env, - fmt.Sprintf("SF_GENESIS_BLOCK=%v", - config.GetCartesiContractsInputBoxDeploymentBlockNumber())) + fmt.Sprintf( + "SF_GENESIS_BLOCK=%v", + nodeConfig.CartesiContractsInputBoxDeploymentBlockNumber()), + ) s.Env = append(s.Env, - fmt.Sprintf("SF_SAFETY_MARGIN=%v", config.GetCartesiBlockchainFinalityOffset())) + fmt.Sprintf("SF_SAFETY_MARGIN=%v", nodeConfig.CartesiBlockchainFinalityOffset())) s.Env = append(s.Env, - fmt.Sprintf("BH_WS_ENDPOINT=%v", config.GetCartesiBlockchainWsEndpoint())) + fmt.Sprintf("BH_WS_ENDPOINT=%v", nodeConfig.CartesiBlockchainWsEndpoint())) s.Env = append(s.Env, - fmt.Sprintf("BH_HTTP_ENDPOINT=%v", config.GetCartesiBlockchainHttpEndpoint())) + fmt.Sprintf("BH_HTTP_ENDPOINT=%v", nodeConfig.CartesiBlockchainHttpEndpoint())) s.Env = append(s.Env, - fmt.Sprintf("BLOCKCHAIN_BLOCK_TIMEOUT=%v", config.GetCartesiBlockchainBlockTimeout())) + fmt.Sprintf("BLOCKCHAIN_BLOCK_TIMEOUT=%v", nodeConfig.CartesiBlockchainBlockTimeout())) s.Env = append(s.Env, - fmt.Sprintf("SS_SERVER_ADDRESS=%v:%v", localhost, getPort(portOffsetStateServer))) + fmt.Sprintf( + "SS_SERVER_ADDRESS=%v:%v", + localhost, getPort(nodeConfig.CartesiHttpPort(), portOffsetStateServer), + ), + ) s.Env = append(s.Env, os.Environ()...) return s } @@ -329,9 +394,13 @@ func newSupervisorService(s []services.Service) services.SupervisorService { } } -func newHttpService() services.HttpService { - addr := fmt.Sprintf("%v:%v", config.GetCartesiHttpAddress(), getPort(portOffsetProxy)) - handler := newHttpServiceHandler() +func newHttpService(nodeConfig config.NodeConfig) services.HttpService { + addr := fmt.Sprintf( + "%v:%v", + nodeConfig.CartesiHttpAddress(), + getPort(nodeConfig.CartesiHttpPort(), portOffsetProxy), + ) + handler := newHttpServiceHandler(nodeConfig) return services.HttpService{ Name: "http", Address: addr, diff --git a/cmd/gen-devnet/main.go b/cmd/gen-devnet/main.go index 936a03bef..ac1f54434 100644 --- a/cmd/gen-devnet/main.go +++ b/cmd/gen-devnet/main.go @@ -11,6 +11,7 @@ import ( "os" "path/filepath" + "github.com/cartesi/rollups-node/internal/config" "github.com/cartesi/rollups-node/internal/services" "github.com/spf13/cobra" ) @@ -84,6 +85,9 @@ func main() { } func run(cmd *cobra.Command, args []string) { + + config.InitLogFromEnv() + ctx, cancel := context.WithCancel(context.Background()) defer cancel() diff --git a/internal/config/config.go b/internal/config/config.go index 717cedd51..67102c4aa 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -8,7 +8,7 @@ // Its code is automatically generated by the generate/main.go script, // given the environment variable configured in the generate/Config.toml file. // -// Custom getters are defined in the config.go file. +// Custom getters are defined in the custom_getters.go file. package config import ( @@ -48,37 +48,6 @@ var ( toLogLevel = toLogLevelFromString ) -// ------------------------------------------------------------------------------------------------ -// Custom GETs -// ------------------------------------------------------------------------------------------------ - -func GetAuth() Auth { - // getting the (optional) account index - index, _ := getCartesiAuthMnemonicAccountIndex() - - // if the mnemonic is coming from an environment variable - if mnemonic, ok := getCartesiAuthMnemonic(); ok { - return AuthMnemonic{Mnemonic: mnemonic, AccountIndex: index} - } - - // if the mnemonic is coming from a file - if file, ok := getCartesiAuthMnemonicFile(); ok { - mnemonic, err := os.ReadFile(file) - if err != nil { - fail("mnemonic file error: %s", err) - } - return AuthMnemonic{Mnemonic: string(mnemonic), AccountIndex: index} - } - - // if we are not using mnemonics, but AWS authentication - keyID, ok1 := getCartesiAuthAwsKmsKeyId() - region, ok2 := getCartesiAuthAwsKmsRegion() - if !ok1 || !ok2 { - fail("missing auth environment variables") - } - return AuthAWS{KeyID: keyID, Region: region} -} - // ------------------------------------------------------------------------------------------------ // Get Helpers // ------------------------------------------------------------------------------------------------ @@ -106,6 +75,8 @@ func read(name string, redact bool) (string, bool) { } else if s, ok := os.LookupEnv(name); ok { if !redact { configLogger.Printf("read %s environment variable: %v", name, s) + } else { + configLogger.Printf("read %s environment variable: ***************", name) } cache.values[name] = s return s, true @@ -124,7 +95,7 @@ func parse[T any](s string, f func(string) (T, error)) T { return v } -// Returns a zero value and false or the value of an environment variable and true. +// Returns nil value or the value of an environment variable. // // If the variable could not be read from the environment and it has a default value, // then this function will set the cache with the default value and return it parsed. @@ -133,11 +104,11 @@ func getOptional[T any]( default_ string, hasDefault bool, redact bool, - parser func(string) (T, error)) (T, bool) { + parser func(string) (T, error)) *T { if s, ok := read(name, redact); ok { v := parse(s, parser) - return v, true + return &v } if hasDefault { @@ -145,26 +116,10 @@ func getOptional[T any]( defer cache.Unlock() cache.values[name] = default_ v := parse(default_, parser) - return v, true - } - - var zeroValue T - return zeroValue, false -} - -// Same as getOptional, but fails instead of returning a zero value and false. -func get[T any]( - name string, - defaultValue string, - hasDefault bool, - redact bool, - parser func(string) (T, error)) T { - v, ok := getOptional(name, defaultValue, hasDefault, redact, parser) - if !ok { - fail("missing required %s env var", name) + return &v } - return v + return nil } func fail(s string, v ...any) { diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 6ad1d26f5..57f0b2a18 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -28,7 +28,7 @@ func (suite *EnvSuite) TearDownTest() { os.Unsetenv(BAR) os.Unsetenv(BAZ) cache.values = make(map[string]string) - logInit() + InitLog(NewNodeConfigFromEnv()) } // ------------------------------------------------------------------------------------------------ @@ -77,7 +77,7 @@ func (suite *EnvSuite) TestRead() { require.True(ok) require.Equal(bar, s) require.Equal(cacheLen+2, len(cache.values)) - require.Equal(1, len(getMockedLog(buffer))) + require.Equal(2, len(getMockedLog(buffer))) } { // empty string os.Setenv(BAZ, "") @@ -85,50 +85,40 @@ func (suite *EnvSuite) TestRead() { require.True(ok) require.Equal("", s) require.Equal(cacheLen+3, len(cache.values)) - require.Equal(2, len(getMockedLog(buffer))) + require.Equal(3, len(getMockedLog(buffer))) } } func (suite *EnvSuite) TestGetOptional() { require := suite.Require() { // not set | not cached | no default - _, ok := getOptional[int](FOO, "", false, true, toInt) - require.False(ok) + v := getOptional[int](FOO, "", false, true, toInt) + require.Nil(v) } { // not set | not cached | has default - v, ok := getOptional[int](FOO, "10", true, true, toInt) - require.True(ok) - require.Equal(10, v) + v := getOptional[int](FOO, "10", true, true, toInt) + require.NotNil(v) + require.Equal(10, *v) } { // not set | cached | no default - v, ok := getOptional[int](FOO, "", false, true, toInt) - require.True(ok) - require.Equal(10, v) + v := getOptional[int](FOO, "", false, true, toInt) + require.NotNil(v) + require.Equal(10, *v) } { // set | cached | has default os.Setenv(FOO, foo) - v, ok := getOptional[int](FOO, "20", true, true, toInt) - require.True(ok) - require.Equal(10, v) + v := getOptional[int](FOO, "20", true, true, toInt) + require.NotNil(v) + require.Equal(10, *v) } { // set | not cached | no default os.Setenv(BAR, bar) - v, ok := getOptional[string](BAR, "", false, true, toString) - require.True(ok) - require.Equal(bar, v) + v := getOptional[string](BAR, "", false, true, toString) + require.NotNil(v) + require.Equal(bar, *v) } } -func (suite *EnvSuite) TestGet() { - os.Setenv(FOO, foo) - v := get[string](FOO, "", false, true, toString) - require.Equal(suite.T(), foo, v) -} - -func (suite *EnvSuite) TestLogInit() { - require.Equal(suite.T(), 2, len(cache.values)) -} - // ------------------------------------------------------------------------------------------------ // Individual Tests // ------------------------------------------------------------------------------------------------ @@ -144,13 +134,6 @@ func TestParseFail(t *testing.T) { }) } -func TestGetFail(t *testing.T) { - os.Unsetenv(FOO) - requireExit(t, "TestGetFail", func() { - get[string](FOO, "", false, true, toString) - }) -} - // ------------------------------------------------------------------------------------------------ // Auxiliary // ------------------------------------------------------------------------------------------------ diff --git a/internal/config/custom_getters.go b/internal/config/custom_getters.go new file mode 100644 index 000000000..a8f6fff82 --- /dev/null +++ b/internal/config/custom_getters.go @@ -0,0 +1,43 @@ +// (c) Cartesi and individual authors (see AUTHORS) +// SPDX-License-Identifier: Apache-2.0 (see LICENSE) + +package config + +import ( + "fmt" + "os" +) + +// ------------------------------------------------------------------------------------------------ +// Custom GETs +// ------------------------------------------------------------------------------------------------ + +func getAuth() (*Auth, error) { + // getting the (optional) account index + index := getCartesiAuthMnemonicAccountIndex() + + // if the mnemonic is coming from an environment variable + if mnemonic := getCartesiAuthMnemonic(); mnemonic != nil && index != nil { + var auth Auth = AuthMnemonic{Mnemonic: *mnemonic, AccountIndex: *index} + return &auth, nil + } + + // if the mnemonic is coming from a file + if file := getCartesiAuthMnemonicFile(); file != nil { + mnemonic, err := os.ReadFile(*file) + if err != nil { + return nil, fmt.Errorf("mnemonic file error: %s", err) + } + var auth Auth = AuthMnemonic{Mnemonic: string(mnemonic), AccountIndex: *index} + return &auth, nil + } + + // if we are not using mnemonics, but AWS authentication + keyID := getCartesiAuthAwsKmsKeyId() + region := getCartesiAuthAwsKmsRegion() + if keyID == nil || region == nil { + return nil, fmt.Errorf("missing auth environment variables") + } + var auth Auth = AuthAWS{KeyID: *keyID, Region: *region} + return &auth, nil +} diff --git a/internal/config/generate/helpers.go b/internal/config/generate/helpers.go index 0e476090b..034519481 100644 --- a/internal/config/generate/helpers.go +++ b/internal/config/generate/helpers.go @@ -66,6 +66,19 @@ func addLine(builder *strings.Builder, s string, a ...any) { builder.WriteString("\n") } +func addGetHeader(builder *strings.Builder) { + addLine(builder, `// Code generated by internal/config/generate.`) + addLine(builder, `// DO NOT EDIT.`) + addLine(builder, "") + + addLine(builder, `// (c) Cartesi and individual authors (see AUTHORS)`) + addLine(builder, `// SPDX-License-Identifier: Apache-2.0 (see LICENSE)`) + addLine(builder, "") + + addLine(builder, `package config`) + addLine(builder, "") +} + func addCodeHeader(builder *strings.Builder) { addLine(builder, `// Code generated by internal/config/generate.`) addLine(builder, `// DO NOT EDIT.`) @@ -76,6 +89,7 @@ func addCodeHeader(builder *strings.Builder) { addLine(builder, "") addLine(builder, `package config`) + addLine(builder, `import (`) addLine(builder, `"time"`) addLine(builder, `)`) @@ -86,6 +100,7 @@ func addCodeHeader(builder *strings.Builder) { addLine(builder, `Duration = time.Duration`) addLine(builder, `)`) addLine(builder, "") + } func addDocHeader(builder *strings.Builder) { diff --git a/internal/config/generate/main.go b/internal/config/generate/main.go index ff5346fce..820c5e1a9 100644 --- a/internal/config/generate/main.go +++ b/internal/config/generate/main.go @@ -14,7 +14,11 @@ import ( // This script will read the Config.toml file and create: // -// - a formatted get.go file, with get functions for each environment variable; +// - a formatted get.go file, with get functions for some environment variables; +// +// - a formatted nodeconfig.go file with the NodeConfig struct and two init functions: +// one that initializes it by reading the values from environment variables and another that +// initializes it with default values; // // - a config.md file with documentation for the environment variables. // @@ -27,20 +31,125 @@ func main() { config := decodeTOML(data) envs := sortConfig(config) + //Validate envs + for i := range envs { + envs[i].validate() + } + + writeDoc(envs) + writeCode(envs) +} + +func writeCode(envs []Env) { + var privateGetFunctions strings.Builder + addGetHeader(&privateGetFunctions) + // //Add get functions + for _, env := range envs { + if !*env.Export { + addLine(&privateGetFunctions, env.toFunction()) + } + } + writeToFile("get.go", formatCode(privateGetFunctions.String())) + var code strings.Builder + addCodeHeader(&code) + //Add NodeConfig Struct + addLine(&code, "type NodeConfig struct{") + for _, env := range envs { + if *env.Export { + addLine(&code, env.toStructMember()) + } + } + addLine(&code, "cartesiAuth *Auth") + addLine(&code, "cartesiAuthError error") + addLine(&code, "}") + + //Add Getters and Setters + addLine(&code, "") + for _, env := range envs { + if *env.Export { + name := toTitleCase(env.Name) + varName := toVarName(env.Name) + //Getter + addLine(&code, "func (nodeConfig* NodeConfig) "+name+"() "+env.GoType+" {") + addLine(&code, "if nodeConfig."+varName+" == nil {") + addLine(&code, `fail("Missing required `+env.Name+` env var")`) + addLine(&code, "}") + addLine(&code, "return *nodeConfig."+varName) + addLine(&code, "}") + addLine(&code, "") + //Setter + addLine(&code, "func (nodeConfig* NodeConfig) Set"+name+"(v *"+env.GoType+") {") + addLine(&code, "nodeConfig."+varName+" = v") + addLine(&code, "}") + addLine(&code, "") + addLine(&code, "") + } + } + + addLine(&code, "func (nodeConfig* NodeConfig) CartesiAuth() Auth {") + addLine(&code, "if nodeConfig.cartesiAuth == nil {panic(nodeConfig.cartesiAuthError)}") + addLine(&code, "return *nodeConfig.cartesiAuth") + addLine(&code, "}") + addLine(&code, "") + + addLine(&code, "func (nodeConfig* NodeConfig) SetCartesiAuth(v *Auth) {") + addLine(&code, "nodeConfig.cartesiAuth = v") + addLine(&code, "}") + addLine(&code, "") + addLine(&code, "") + + //Add init function from System Environment + addLine(&code, "") + addLine(&code, "func NewNodeConfigFromEnv() (NodeConfig){") + addLine(&code, "nodeConfig := NodeConfig{") + for _, env := range envs { + if *env.Export { + name := toVarName(env.Name) + addLine(&code, name+": "+env.toEnvGetCall()+",") + } + } + addLine(&code, "}") + addLine(&code, "nodeConfig.cartesiAuth, nodeConfig.cartesiAuthError = getAuth()") + addLine(&code, "return nodeConfig") + addLine(&code, "}") + + //Add init function from Default Values + addLine(&code, "") + addLine(&code, "func NewNodeConfig() (NodeConfig){") + addLine(&code, "nodeConfig := NodeConfig{}") + for _, env := range envs { + if *env.Export && env.Default != nil && *env.Default != "" { + name := toVarName(env.Name) + varName := toVarName(name) + addLine(&code, varName+", err := "+toToFuncName(env.GoType)+`("`+*env.Default+`")`) + addLine(&code, "if err != nil {") + addLine(&code, "panic(err)") + addLine(&code, "}") + addLine(&code, "nodeConfig."+name+" = &"+varName) + addLine(&code, "") + } + } + addLine(&code, `var auth Auth = AuthMnemonic{`) + addLine(&code, `Mnemonic: "test test test test test test test test test test test junk",`) + addLine(&code, `AccountIndex: 0,`) + addLine(&code, "}") + addLine(&code, "nodeConfig.cartesiAuth = &auth") + addLine(&code, "nodeConfig.cartesiAuthError = nil") + addLine(&code, "return nodeConfig") + addLine(&code, "}") + + writeToFile("nodeconfig.go", formatCode(code.String())) +} + +func writeDoc(envs []Env) { var doc strings.Builder - addCodeHeader(&code) addDocHeader(&doc) - addLine(&doc, "") for _, env := range envs { - env.validate() - addLine(&code, env.toFunction()) addLine(&doc, env.toDoc()) } - - writeToFile("get.go", formatCode(code.String())) writeToFile("../../docs/config.md", []byte(doc.String())) } @@ -92,7 +201,7 @@ func (e *Env) validate() { // Generates the get function for the environment variable. func (e Env) toFunction() string { - name := toFunctionName(e.Name) + name := toTitleCase(e.Name) typ := e.GoType get := "get" vars := "v" @@ -103,26 +212,43 @@ func (e Env) toFunction() string { defaultValue = *e.Default } - to_ := []rune(e.GoType) - to_[0] = unicode.ToUpper(to_[0]) - to := "to" + string(to_) + to := toToFuncName(e.GoType) args := fmt.Sprintf(`"%s", "%s", %t, %t, %s`, e.Name, defaultValue, hasDefault, *e.Redact, to) - if *e.Export { - name = "Get" + name - } else { - name = "get" + name - typ = fmt.Sprintf("(%s, bool)", typ) - get += "Optional" - vars += ", ok" - } + name = "get" + name + + typ = fmt.Sprintf("*%s", typ) + get += "Optional" body := fmt.Sprintf("%s := %s(%s)\n", vars, get, args) body += "return " + vars return fmt.Sprintf("func %s() %s { %s }\n", name, typ, body) } +func (e Env) toEnvGetCall() string { + + var defaultValue string + hasDefault := e.Default != nil + if hasDefault { + defaultValue = *e.Default + } + + to := toToFuncName(e.GoType) + + args := fmt.Sprintf(`"%s", "%s", %t, %t, %s`, e.Name, defaultValue, hasDefault, *e.Redact, to) + + get := "getOptional" + + return fmt.Sprintf("%s(%s)", get, args) +} + +// Generates the Config Struct member for the envrionemnt variable. +func (e Env) toStructMember() string { + name := toVarName(e.Name) + return name + " *" + e.GoType +} + // Generates the documentation entry for the environment variable. func (e Env) toDoc() string { s := fmt.Sprintf("## `%s`\n\n%s\n\n", e.Name, e.Description) @@ -134,7 +260,7 @@ func (e Env) toDoc() string { } // Splits the string by "_" and joins each substring with the first letter in upper case. -func toFunctionName(env string) string { +func toTitleCase(env string) string { caser := cases.Title(language.English) words := strings.Split(env, "_") for i, word := range words { @@ -142,3 +268,16 @@ func toFunctionName(env string) string { } return strings.Join(words, "") } + +func toVarName(name string) string { + name = toTitleCase(name) + name_ := []rune(name) + name_[0] = unicode.ToLower(name_[0]) + return string(name_) +} + +func toToFuncName(goType string) string { + to_ := []rune(goType) + to_[0] = unicode.ToUpper(to_[0]) + return "to" + string(to_) +} diff --git a/internal/config/get.go b/internal/config/get.go index f3ce1a792..f6d4294bb 100644 --- a/internal/config/get.go +++ b/internal/config/get.go @@ -6,155 +6,27 @@ package config -import ( - "time" -) - -type ( - Duration = time.Duration -) - -func getCartesiAuthAwsKmsKeyId() (string, bool) { - v, ok := getOptional("CARTESI_AUTH_AWS_KMS_KEY_ID", "", false, true, toString) - return v, ok -} - -func getCartesiAuthAwsKmsRegion() (string, bool) { - v, ok := getOptional("CARTESI_AUTH_AWS_KMS_REGION", "", false, true, toString) - return v, ok -} - -func getCartesiAuthMnemonic() (string, bool) { - v, ok := getOptional("CARTESI_AUTH_MNEMONIC", "", false, true, toString) - return v, ok -} - -func getCartesiAuthMnemonicAccountIndex() (int, bool) { - v, ok := getOptional("CARTESI_AUTH_MNEMONIC_ACCOUNT_INDEX", "0", true, true, toInt) - return v, ok -} - -func getCartesiAuthMnemonicFile() (string, bool) { - v, ok := getOptional("CARTESI_AUTH_MNEMONIC_FILE", "", false, true, toString) - return v, ok -} - -func GetCartesiBlockchainBlockTimeout() int { - v := get("CARTESI_BLOCKCHAIN_BLOCK_TIMEOUT", "60", true, false, toInt) - return v -} - -func GetCartesiBlockchainFinalityOffset() int { - v := get("CARTESI_BLOCKCHAIN_FINALITY_OFFSET", "10", true, false, toInt) - return v -} - -func GetCartesiBlockchainHttpEndpoint() string { - v := get("CARTESI_BLOCKCHAIN_HTTP_ENDPOINT", "", false, false, toString) - return v -} - -func GetCartesiBlockchainId() int { - v := get("CARTESI_BLOCKCHAIN_ID", "", false, false, toInt) - return v -} - -func GetCartesiBlockchainIsLegacy() bool { - v := get("CARTESI_BLOCKCHAIN_IS_LEGACY", "false", true, false, toBool) - return v -} - -func GetCartesiBlockchainWsEndpoint() string { - v := get("CARTESI_BLOCKCHAIN_WS_ENDPOINT", "", false, false, toString) - return v -} - -func GetCartesiContractsInputBoxDeploymentBlockNumber() int64 { - v := get("CARTESI_CONTRACTS_INPUT_BOX_DEPLOYMENT_BLOCK_NUMBER", "", false, false, toInt64) - return v -} - -func GetCartesiContractsApplicationAddress() string { - v := get("CARTESI_CONTRACTS_APPLICATION_ADDRESS", "", false, false, toString) - return v -} - -func GetCartesiContractsApplicationDeploymentBlockNumber() string { - v := get("CARTESI_CONTRACTS_APPLICATION_DEPLOYMENT_BLOCK_NUMBER", "", false, false, toString) - return v -} - -func GetCartesiContractsAuthorityAddress() string { - v := get("CARTESI_CONTRACTS_AUTHORITY_ADDRESS", "", false, false, toString) - return v -} - -func GetCartesiContractsHistoryAddress() string { - v := get("CARTESI_CONTRACTS_HISTORY_ADDRESS", "", false, false, toString) - return v -} - -func GetCartesiContractsInputBoxAddress() string { - v := get("CARTESI_CONTRACTS_INPUT_BOX_ADDRESS", "", false, false, toString) - return v -} - -func GetCartesiExperimentalSunodoValidatorEnabled() bool { - v := get("CARTESI_EXPERIMENTAL_SUNODO_VALIDATOR_ENABLED", "false", true, false, toBool) - return v -} - -func GetCartesiExperimentalSunodoValidatorRedisEndpoint() string { - v := get("CARTESI_EXPERIMENTAL_SUNODO_VALIDATOR_REDIS_ENDPOINT", "", false, false, toString) - return v -} - -func GetCartesiFeatureDisableClaimer() bool { - v := get("CARTESI_FEATURE_DISABLE_CLAIMER", "false", true, false, toBool) - return v -} - -func GetCartesiFeatureDisableMachineHashCheck() bool { - v := get("CARTESI_FEATURE_DISABLE_MACHINE_HASH_CHECK", "false", true, false, toBool) - return v -} - -func GetCartesiFeatureHostMode() bool { - v := get("CARTESI_FEATURE_HOST_MODE", "false", true, false, toBool) - return v -} - -func GetCartesiHttpAddress() string { - v := get("CARTESI_HTTP_ADDRESS", "127.0.0.1", true, false, toString) - return v -} - -func GetCartesiHttpPort() int { - v := get("CARTESI_HTTP_PORT", "10000", true, false, toInt) - return v -} - -func GetCartesiLogLevel() LogLevel { - v := get("CARTESI_LOG_LEVEL", "info", true, false, toLogLevel) +func getCartesiAuthAwsKmsKeyId() *string { + v := getOptional("CARTESI_AUTH_AWS_KMS_KEY_ID", "", false, true, toString) return v } -func GetCartesiLogTimestamp() bool { - v := get("CARTESI_LOG_TIMESTAMP", "false", true, false, toBool) +func getCartesiAuthAwsKmsRegion() *string { + v := getOptional("CARTESI_AUTH_AWS_KMS_REGION", "", false, true, toString) return v } -func GetCartesiPostgresEndpoint() string { - v := get("CARTESI_POSTGRES_ENDPOINT", "", true, true, toString) +func getCartesiAuthMnemonic() *string { + v := getOptional("CARTESI_AUTH_MNEMONIC", "", false, true, toString) return v } -func GetCartesiEpochDuration() Duration { - v := get("CARTESI_EPOCH_DURATION", "86400", true, false, toDuration) +func getCartesiAuthMnemonicAccountIndex() *int { + v := getOptional("CARTESI_AUTH_MNEMONIC_ACCOUNT_INDEX", "0", true, true, toInt) return v } -func GetCartesiSnapshotDir() string { - v := get("CARTESI_SNAPSHOT_DIR", "", false, false, toString) +func getCartesiAuthMnemonicFile() *string { + v := getOptional("CARTESI_AUTH_MNEMONIC_FILE", "", false, true, toString) return v } diff --git a/internal/config/log.go b/internal/config/log.go index 57a3882f1..013e51b9f 100644 --- a/internal/config/log.go +++ b/internal/config/log.go @@ -17,13 +17,14 @@ var ( DebugLogger *log.Logger ) -func init() { - logInit() +func InitLogFromEnv() { + nodeConfig := NewNodeConfigFromEnv() + InitLog(nodeConfig) } -func logInit() { +func InitLog(nodeConfig NodeConfig) { var flags int - if GetCartesiLogTimestamp() { + if nodeConfig.CartesiLogTimestamp() { flags = log.LstdFlags } @@ -32,7 +33,7 @@ func logInit() { InfoLogger = log.New(os.Stdout, "INFO ", flags) DebugLogger = log.New(os.Stdout, "DEBUG ", flags) - switch GetCartesiLogLevel() { + switch nodeConfig.CartesiLogLevel() { case LogLevelError: WarningLogger.SetOutput(io.Discard) fallthrough diff --git a/internal/config/nodeconfig.go b/internal/config/nodeconfig.go new file mode 100644 index 000000000..6db2531eb --- /dev/null +++ b/internal/config/nodeconfig.go @@ -0,0 +1,433 @@ +// Code generated by internal/config/generate. +// DO NOT EDIT. + +// (c) Cartesi and individual authors (see AUTHORS) +// SPDX-License-Identifier: Apache-2.0 (see LICENSE) + +package config + +import ( + "time" +) + +type ( + Duration = time.Duration +) + +type NodeConfig struct { + cartesiBlockchainBlockTimeout *int + cartesiBlockchainFinalityOffset *int + cartesiBlockchainHttpEndpoint *string + cartesiBlockchainId *int + cartesiBlockchainIsLegacy *bool + cartesiBlockchainWsEndpoint *string + cartesiContractsInputBoxDeploymentBlockNumber *int64 + cartesiContractsApplicationAddress *string + cartesiContractsApplicationDeploymentBlockNumber *string + cartesiContractsAuthorityAddress *string + cartesiContractsHistoryAddress *string + cartesiContractsInputBoxAddress *string + cartesiExperimentalSunodoValidatorEnabled *bool + cartesiExperimentalSunodoValidatorRedisEndpoint *string + cartesiFeatureDisableClaimer *bool + cartesiFeatureDisableMachineHashCheck *bool + cartesiFeatureHostMode *bool + cartesiHttpAddress *string + cartesiHttpPort *int + cartesiLogLevel *LogLevel + cartesiLogTimestamp *bool + cartesiPostgresEndpoint *string + cartesiEpochDuration *Duration + cartesiSnapshotDir *string + cartesiAuth *Auth + cartesiAuthError error +} + +func (nodeConfig *NodeConfig) CartesiBlockchainBlockTimeout() int { + if nodeConfig.cartesiBlockchainBlockTimeout == nil { + fail("Missing required CARTESI_BLOCKCHAIN_BLOCK_TIMEOUT env var") + } + return *nodeConfig.cartesiBlockchainBlockTimeout +} + +func (nodeConfig *NodeConfig) SetCartesiBlockchainBlockTimeout(v *int) { + nodeConfig.cartesiBlockchainBlockTimeout = v +} + +func (nodeConfig *NodeConfig) CartesiBlockchainFinalityOffset() int { + if nodeConfig.cartesiBlockchainFinalityOffset == nil { + fail("Missing required CARTESI_BLOCKCHAIN_FINALITY_OFFSET env var") + } + return *nodeConfig.cartesiBlockchainFinalityOffset +} + +func (nodeConfig *NodeConfig) SetCartesiBlockchainFinalityOffset(v *int) { + nodeConfig.cartesiBlockchainFinalityOffset = v +} + +func (nodeConfig *NodeConfig) CartesiBlockchainHttpEndpoint() string { + if nodeConfig.cartesiBlockchainHttpEndpoint == nil { + fail("Missing required CARTESI_BLOCKCHAIN_HTTP_ENDPOINT env var") + } + return *nodeConfig.cartesiBlockchainHttpEndpoint +} + +func (nodeConfig *NodeConfig) SetCartesiBlockchainHttpEndpoint(v *string) { + nodeConfig.cartesiBlockchainHttpEndpoint = v +} + +func (nodeConfig *NodeConfig) CartesiBlockchainId() int { + if nodeConfig.cartesiBlockchainId == nil { + fail("Missing required CARTESI_BLOCKCHAIN_ID env var") + } + return *nodeConfig.cartesiBlockchainId +} + +func (nodeConfig *NodeConfig) SetCartesiBlockchainId(v *int) { + nodeConfig.cartesiBlockchainId = v +} + +func (nodeConfig *NodeConfig) CartesiBlockchainIsLegacy() bool { + if nodeConfig.cartesiBlockchainIsLegacy == nil { + fail("Missing required CARTESI_BLOCKCHAIN_IS_LEGACY env var") + } + return *nodeConfig.cartesiBlockchainIsLegacy +} + +func (nodeConfig *NodeConfig) SetCartesiBlockchainIsLegacy(v *bool) { + nodeConfig.cartesiBlockchainIsLegacy = v +} + +func (nodeConfig *NodeConfig) CartesiBlockchainWsEndpoint() string { + if nodeConfig.cartesiBlockchainWsEndpoint == nil { + fail("Missing required CARTESI_BLOCKCHAIN_WS_ENDPOINT env var") + } + return *nodeConfig.cartesiBlockchainWsEndpoint +} + +func (nodeConfig *NodeConfig) SetCartesiBlockchainWsEndpoint(v *string) { + nodeConfig.cartesiBlockchainWsEndpoint = v +} + +func (nodeConfig *NodeConfig) CartesiContractsInputBoxDeploymentBlockNumber() int64 { + if nodeConfig.cartesiContractsInputBoxDeploymentBlockNumber == nil { + fail("Missing required CARTESI_CONTRACTS_INPUT_BOX_DEPLOYMENT_BLOCK_NUMBER env var") + } + return *nodeConfig.cartesiContractsInputBoxDeploymentBlockNumber +} + +func (nodeConfig *NodeConfig) SetCartesiContractsInputBoxDeploymentBlockNumber(v *int64) { + nodeConfig.cartesiContractsInputBoxDeploymentBlockNumber = v +} + +func (nodeConfig *NodeConfig) CartesiContractsApplicationAddress() string { + if nodeConfig.cartesiContractsApplicationAddress == nil { + fail("Missing required CARTESI_CONTRACTS_APPLICATION_ADDRESS env var") + } + return *nodeConfig.cartesiContractsApplicationAddress +} + +func (nodeConfig *NodeConfig) SetCartesiContractsApplicationAddress(v *string) { + nodeConfig.cartesiContractsApplicationAddress = v +} + +func (nodeConfig *NodeConfig) CartesiContractsApplicationDeploymentBlockNumber() string { + if nodeConfig.cartesiContractsApplicationDeploymentBlockNumber == nil { + fail("Missing required CARTESI_CONTRACTS_APPLICATION_DEPLOYMENT_BLOCK_NUMBER env var") + } + return *nodeConfig.cartesiContractsApplicationDeploymentBlockNumber +} + +func (nodeConfig *NodeConfig) SetCartesiContractsApplicationDeploymentBlockNumber(v *string) { + nodeConfig.cartesiContractsApplicationDeploymentBlockNumber = v +} + +func (nodeConfig *NodeConfig) CartesiContractsAuthorityAddress() string { + if nodeConfig.cartesiContractsAuthorityAddress == nil { + fail("Missing required CARTESI_CONTRACTS_AUTHORITY_ADDRESS env var") + } + return *nodeConfig.cartesiContractsAuthorityAddress +} + +func (nodeConfig *NodeConfig) SetCartesiContractsAuthorityAddress(v *string) { + nodeConfig.cartesiContractsAuthorityAddress = v +} + +func (nodeConfig *NodeConfig) CartesiContractsHistoryAddress() string { + if nodeConfig.cartesiContractsHistoryAddress == nil { + fail("Missing required CARTESI_CONTRACTS_HISTORY_ADDRESS env var") + } + return *nodeConfig.cartesiContractsHistoryAddress +} + +func (nodeConfig *NodeConfig) SetCartesiContractsHistoryAddress(v *string) { + nodeConfig.cartesiContractsHistoryAddress = v +} + +func (nodeConfig *NodeConfig) CartesiContractsInputBoxAddress() string { + if nodeConfig.cartesiContractsInputBoxAddress == nil { + fail("Missing required CARTESI_CONTRACTS_INPUT_BOX_ADDRESS env var") + } + return *nodeConfig.cartesiContractsInputBoxAddress +} + +func (nodeConfig *NodeConfig) SetCartesiContractsInputBoxAddress(v *string) { + nodeConfig.cartesiContractsInputBoxAddress = v +} + +func (nodeConfig *NodeConfig) CartesiExperimentalSunodoValidatorEnabled() bool { + if nodeConfig.cartesiExperimentalSunodoValidatorEnabled == nil { + fail("Missing required CARTESI_EXPERIMENTAL_SUNODO_VALIDATOR_ENABLED env var") + } + return *nodeConfig.cartesiExperimentalSunodoValidatorEnabled +} + +func (nodeConfig *NodeConfig) SetCartesiExperimentalSunodoValidatorEnabled(v *bool) { + nodeConfig.cartesiExperimentalSunodoValidatorEnabled = v +} + +func (nodeConfig *NodeConfig) CartesiExperimentalSunodoValidatorRedisEndpoint() string { + if nodeConfig.cartesiExperimentalSunodoValidatorRedisEndpoint == nil { + fail("Missing required CARTESI_EXPERIMENTAL_SUNODO_VALIDATOR_REDIS_ENDPOINT env var") + } + return *nodeConfig.cartesiExperimentalSunodoValidatorRedisEndpoint +} + +func (nodeConfig *NodeConfig) SetCartesiExperimentalSunodoValidatorRedisEndpoint(v *string) { + nodeConfig.cartesiExperimentalSunodoValidatorRedisEndpoint = v +} + +func (nodeConfig *NodeConfig) CartesiFeatureDisableClaimer() bool { + if nodeConfig.cartesiFeatureDisableClaimer == nil { + fail("Missing required CARTESI_FEATURE_DISABLE_CLAIMER env var") + } + return *nodeConfig.cartesiFeatureDisableClaimer +} + +func (nodeConfig *NodeConfig) SetCartesiFeatureDisableClaimer(v *bool) { + nodeConfig.cartesiFeatureDisableClaimer = v +} + +func (nodeConfig *NodeConfig) CartesiFeatureDisableMachineHashCheck() bool { + if nodeConfig.cartesiFeatureDisableMachineHashCheck == nil { + fail("Missing required CARTESI_FEATURE_DISABLE_MACHINE_HASH_CHECK env var") + } + return *nodeConfig.cartesiFeatureDisableMachineHashCheck +} + +func (nodeConfig *NodeConfig) SetCartesiFeatureDisableMachineHashCheck(v *bool) { + nodeConfig.cartesiFeatureDisableMachineHashCheck = v +} + +func (nodeConfig *NodeConfig) CartesiFeatureHostMode() bool { + if nodeConfig.cartesiFeatureHostMode == nil { + fail("Missing required CARTESI_FEATURE_HOST_MODE env var") + } + return *nodeConfig.cartesiFeatureHostMode +} + +func (nodeConfig *NodeConfig) SetCartesiFeatureHostMode(v *bool) { + nodeConfig.cartesiFeatureHostMode = v +} + +func (nodeConfig *NodeConfig) CartesiHttpAddress() string { + if nodeConfig.cartesiHttpAddress == nil { + fail("Missing required CARTESI_HTTP_ADDRESS env var") + } + return *nodeConfig.cartesiHttpAddress +} + +func (nodeConfig *NodeConfig) SetCartesiHttpAddress(v *string) { + nodeConfig.cartesiHttpAddress = v +} + +func (nodeConfig *NodeConfig) CartesiHttpPort() int { + if nodeConfig.cartesiHttpPort == nil { + fail("Missing required CARTESI_HTTP_PORT env var") + } + return *nodeConfig.cartesiHttpPort +} + +func (nodeConfig *NodeConfig) SetCartesiHttpPort(v *int) { + nodeConfig.cartesiHttpPort = v +} + +func (nodeConfig *NodeConfig) CartesiLogLevel() LogLevel { + if nodeConfig.cartesiLogLevel == nil { + fail("Missing required CARTESI_LOG_LEVEL env var") + } + return *nodeConfig.cartesiLogLevel +} + +func (nodeConfig *NodeConfig) SetCartesiLogLevel(v *LogLevel) { + nodeConfig.cartesiLogLevel = v +} + +func (nodeConfig *NodeConfig) CartesiLogTimestamp() bool { + if nodeConfig.cartesiLogTimestamp == nil { + fail("Missing required CARTESI_LOG_TIMESTAMP env var") + } + return *nodeConfig.cartesiLogTimestamp +} + +func (nodeConfig *NodeConfig) SetCartesiLogTimestamp(v *bool) { + nodeConfig.cartesiLogTimestamp = v +} + +func (nodeConfig *NodeConfig) CartesiPostgresEndpoint() string { + if nodeConfig.cartesiPostgresEndpoint == nil { + fail("Missing required CARTESI_POSTGRES_ENDPOINT env var") + } + return *nodeConfig.cartesiPostgresEndpoint +} + +func (nodeConfig *NodeConfig) SetCartesiPostgresEndpoint(v *string) { + nodeConfig.cartesiPostgresEndpoint = v +} + +func (nodeConfig *NodeConfig) CartesiEpochDuration() Duration { + if nodeConfig.cartesiEpochDuration == nil { + fail("Missing required CARTESI_EPOCH_DURATION env var") + } + return *nodeConfig.cartesiEpochDuration +} + +func (nodeConfig *NodeConfig) SetCartesiEpochDuration(v *Duration) { + nodeConfig.cartesiEpochDuration = v +} + +func (nodeConfig *NodeConfig) CartesiSnapshotDir() string { + if nodeConfig.cartesiSnapshotDir == nil { + fail("Missing required CARTESI_SNAPSHOT_DIR env var") + } + return *nodeConfig.cartesiSnapshotDir +} + +func (nodeConfig *NodeConfig) SetCartesiSnapshotDir(v *string) { + nodeConfig.cartesiSnapshotDir = v +} + +func (nodeConfig *NodeConfig) CartesiAuth() Auth { + if nodeConfig.cartesiAuth == nil { + panic(nodeConfig.cartesiAuthError) + } + return *nodeConfig.cartesiAuth +} + +func (nodeConfig *NodeConfig) SetCartesiAuth(v *Auth) { + nodeConfig.cartesiAuth = v +} + +func NewNodeConfigFromEnv() NodeConfig { + nodeConfig := NodeConfig{ + cartesiBlockchainBlockTimeout: getOptional("CARTESI_BLOCKCHAIN_BLOCK_TIMEOUT", "60", true, false, toInt), + cartesiBlockchainFinalityOffset: getOptional("CARTESI_BLOCKCHAIN_FINALITY_OFFSET", "10", true, false, toInt), + cartesiBlockchainHttpEndpoint: getOptional("CARTESI_BLOCKCHAIN_HTTP_ENDPOINT", "", false, false, toString), + cartesiBlockchainId: getOptional("CARTESI_BLOCKCHAIN_ID", "", false, false, toInt), + cartesiBlockchainIsLegacy: getOptional("CARTESI_BLOCKCHAIN_IS_LEGACY", "false", true, false, toBool), + cartesiBlockchainWsEndpoint: getOptional("CARTESI_BLOCKCHAIN_WS_ENDPOINT", "", false, false, toString), + cartesiContractsInputBoxDeploymentBlockNumber: getOptional("CARTESI_CONTRACTS_INPUT_BOX_DEPLOYMENT_BLOCK_NUMBER", "", false, false, toInt64), + cartesiContractsApplicationAddress: getOptional("CARTESI_CONTRACTS_APPLICATION_ADDRESS", "", false, false, toString), + cartesiContractsApplicationDeploymentBlockNumber: getOptional("CARTESI_CONTRACTS_APPLICATION_DEPLOYMENT_BLOCK_NUMBER", "", false, false, toString), + cartesiContractsAuthorityAddress: getOptional("CARTESI_CONTRACTS_AUTHORITY_ADDRESS", "", false, false, toString), + cartesiContractsHistoryAddress: getOptional("CARTESI_CONTRACTS_HISTORY_ADDRESS", "", false, false, toString), + cartesiContractsInputBoxAddress: getOptional("CARTESI_CONTRACTS_INPUT_BOX_ADDRESS", "", false, false, toString), + cartesiExperimentalSunodoValidatorEnabled: getOptional("CARTESI_EXPERIMENTAL_SUNODO_VALIDATOR_ENABLED", "false", true, false, toBool), + cartesiExperimentalSunodoValidatorRedisEndpoint: getOptional("CARTESI_EXPERIMENTAL_SUNODO_VALIDATOR_REDIS_ENDPOINT", "", false, false, toString), + cartesiFeatureDisableClaimer: getOptional("CARTESI_FEATURE_DISABLE_CLAIMER", "false", true, false, toBool), + cartesiFeatureDisableMachineHashCheck: getOptional("CARTESI_FEATURE_DISABLE_MACHINE_HASH_CHECK", "false", true, false, toBool), + cartesiFeatureHostMode: getOptional("CARTESI_FEATURE_HOST_MODE", "false", true, false, toBool), + cartesiHttpAddress: getOptional("CARTESI_HTTP_ADDRESS", "127.0.0.1", true, false, toString), + cartesiHttpPort: getOptional("CARTESI_HTTP_PORT", "10000", true, false, toInt), + cartesiLogLevel: getOptional("CARTESI_LOG_LEVEL", "info", true, false, toLogLevel), + cartesiLogTimestamp: getOptional("CARTESI_LOG_TIMESTAMP", "false", true, false, toBool), + cartesiPostgresEndpoint: getOptional("CARTESI_POSTGRES_ENDPOINT", "", true, true, toString), + cartesiEpochDuration: getOptional("CARTESI_EPOCH_DURATION", "86400", true, false, toDuration), + cartesiSnapshotDir: getOptional("CARTESI_SNAPSHOT_DIR", "", false, false, toString), + } + nodeConfig.cartesiAuth, nodeConfig.cartesiAuthError = getAuth() + return nodeConfig +} + +func NewNodeConfig() NodeConfig { + nodeConfig := NodeConfig{} + cartesiblockchainblocktimeout, err := toInt("60") + if err != nil { + panic(err) + } + nodeConfig.cartesiBlockchainBlockTimeout = &cartesiblockchainblocktimeout + + cartesiblockchainfinalityoffset, err := toInt("10") + if err != nil { + panic(err) + } + nodeConfig.cartesiBlockchainFinalityOffset = &cartesiblockchainfinalityoffset + + cartesiblockchainislegacy, err := toBool("false") + if err != nil { + panic(err) + } + nodeConfig.cartesiBlockchainIsLegacy = &cartesiblockchainislegacy + + cartesiexperimentalsunodovalidatorenabled, err := toBool("false") + if err != nil { + panic(err) + } + nodeConfig.cartesiExperimentalSunodoValidatorEnabled = &cartesiexperimentalsunodovalidatorenabled + + cartesifeaturedisableclaimer, err := toBool("false") + if err != nil { + panic(err) + } + nodeConfig.cartesiFeatureDisableClaimer = &cartesifeaturedisableclaimer + + cartesifeaturedisablemachinehashcheck, err := toBool("false") + if err != nil { + panic(err) + } + nodeConfig.cartesiFeatureDisableMachineHashCheck = &cartesifeaturedisablemachinehashcheck + + cartesifeaturehostmode, err := toBool("false") + if err != nil { + panic(err) + } + nodeConfig.cartesiFeatureHostMode = &cartesifeaturehostmode + + cartesihttpaddress, err := toString("127.0.0.1") + if err != nil { + panic(err) + } + nodeConfig.cartesiHttpAddress = &cartesihttpaddress + + cartesihttpport, err := toInt("10000") + if err != nil { + panic(err) + } + nodeConfig.cartesiHttpPort = &cartesihttpport + + cartesiloglevel, err := toLogLevel("info") + if err != nil { + panic(err) + } + nodeConfig.cartesiLogLevel = &cartesiloglevel + + cartesilogtimestamp, err := toBool("false") + if err != nil { + panic(err) + } + nodeConfig.cartesiLogTimestamp = &cartesilogtimestamp + + cartesiepochduration, err := toDuration("86400") + if err != nil { + panic(err) + } + nodeConfig.cartesiEpochDuration = &cartesiepochduration + + var auth Auth = AuthMnemonic{ + Mnemonic: "test test test test test test test test test test test junk", + AccountIndex: 0, + } + nodeConfig.cartesiAuth = &auth + nodeConfig.cartesiAuthError = nil + return nodeConfig +} diff --git a/internal/config/validate.go b/internal/config/validate.go new file mode 100644 index 000000000..e10d83290 --- /dev/null +++ b/internal/config/validate.go @@ -0,0 +1,72 @@ +// (c) Cartesi and individual authors (see AUTHORS) +// SPDX-License-Identifier: Apache-2.0 (see LICENSE) +package config + +import "fmt" + +func (nodeConfig *NodeConfig) Validate() { + if nodeConfig.cartesiExperimentalSunodoValidatorEnabled != nil && + *nodeConfig.cartesiExperimentalSunodoValidatorEnabled { + if nodeConfig.cartesiExperimentalSunodoValidatorRedisEndpoint == nil { + fail("Missing required %s env var", + "CARTESI_EXPERIMENTAL_SUNODO_VALIDATOR_REDIS_ENDPOINT") + } + } + + if nodeConfig.cartesiFeatureDisableClaimer != nil && !*nodeConfig.cartesiFeatureDisableClaimer { + if nodeConfig.cartesiAuthError != nil { + panic(fmt.Errorf("Auth config error: %w ", nodeConfig.cartesiAuthError)) + } + } + + if nodeConfig.cartesiBlockchainHttpEndpoint == nil { + fail("Missing required %s env var", + "CARTESI_BLOCKCHAIN_HTTP_ENDPOINT") + } + + if nodeConfig.cartesiBlockchainId == nil { + fail("Missing required %s env var", + "CARTESI_BLOCKCHAIN_ID config") + } + + if nodeConfig.cartesiBlockchainWsEndpoint == nil { + fail("Missing required %s env var", + "CARTESI_BLOCKCHAIN_WS_ENDPOINT config") + } + + if nodeConfig.cartesiContractsInputBoxDeploymentBlockNumber == nil { + fail("Missing required %s env var", + "CARTESI_CONTRACTS_INPUT_BOX_DEPLOYMENT_BLOCK_NUMBER config") + } + + if nodeConfig.cartesiContractsApplicationAddress == nil { + fail("Missing required %s env var", + "CARTESI_CONTRACTS_APPLICATION_ADDRESS config") + } + + if nodeConfig.cartesiContractsApplicationDeploymentBlockNumber == nil { + fail("Missing required %s env var", + "CARTESI_CONTRACTS_APPLICATION_DEPLOYMENT_BLOCK_NUMBER config") + } + + if nodeConfig.cartesiContractsAuthorityAddress == nil { + fail("Missing required %s env var", + "CARTESI_CONTRACTS_AUTHORITY_ADDRESS config") + } + + if nodeConfig.cartesiContractsHistoryAddress == nil { + fail("Missing required %s env var", + "CARTESI_CONTRACTS_HISTORY_ADDRESS config") + } + + if nodeConfig.cartesiContractsInputBoxAddress == nil { + fail("Missing required %s env var", + "CARTESI_CONTRACTS_INPUT_BOX_ADDRESS config") + } + + if nodeConfig.cartesiSnapshotDir == nil { + fail("Missing required %s env var", + "CARTESI_SNAPSHOT_DIR config") + } + +} diff --git a/internal/services/command_test.go b/internal/services/command_test.go index e8e0c5eff..1baaec7ea 100644 --- a/internal/services/command_test.go +++ b/internal/services/command_test.go @@ -12,6 +12,7 @@ import ( "testing" "time" + "github.com/cartesi/rollups-node/internal/config" "github.com/stretchr/testify/suite" ) @@ -134,5 +135,6 @@ func (s *CommandServiceSuite) buildFakeService() { } func TestCommandService(t *testing.T) { + config.InitLogFromEnv() suite.Run(t, new(CommandServiceSuite)) }