github.com/opzlabs/tendermint@v0.34.27-terra.rc.2/config/toml.go (about) 1 package config 2 3 import ( 4 "bytes" 5 "fmt" 6 "os" 7 "path/filepath" 8 "strings" 9 "text/template" 10 11 cmtos "github.com/tendermint/tendermint/libs/os" 12 ) 13 14 // DefaultDirPerm is the default permissions used when creating directories. 15 const DefaultDirPerm = 0o700 16 17 var configTemplate *template.Template 18 19 func init() { 20 var err error 21 tmpl := template.New("configFileTemplate").Funcs(template.FuncMap{ 22 "StringsJoin": strings.Join, 23 }) 24 if configTemplate, err = tmpl.Parse(defaultConfigTemplate); err != nil { 25 panic(err) 26 } 27 } 28 29 /****** these are for production settings ***********/ 30 31 // EnsureRoot creates the root, config, and data directories if they don't exist, 32 // and panics if it fails. 33 func EnsureRoot(rootDir string) { 34 if err := cmtos.EnsureDir(rootDir, DefaultDirPerm); err != nil { 35 panic(err.Error()) 36 } 37 if err := cmtos.EnsureDir(filepath.Join(rootDir, defaultConfigDir), DefaultDirPerm); err != nil { 38 panic(err.Error()) 39 } 40 if err := cmtos.EnsureDir(filepath.Join(rootDir, defaultDataDir), DefaultDirPerm); err != nil { 41 panic(err.Error()) 42 } 43 44 configFilePath := filepath.Join(rootDir, defaultConfigFilePath) 45 46 // Write default config file if missing. 47 if !cmtos.FileExists(configFilePath) { 48 writeDefaultConfigFile(configFilePath) 49 } 50 } 51 52 // XXX: this func should probably be called by cmd/cometbft/commands/init.go 53 // alongside the writing of the genesis.json and priv_validator.json 54 func writeDefaultConfigFile(configFilePath string) { 55 WriteConfigFile(configFilePath, DefaultConfig()) 56 } 57 58 // WriteConfigFile renders config using the template and writes it to configFilePath. 59 func WriteConfigFile(configFilePath string, config *Config) { 60 var buffer bytes.Buffer 61 62 if err := configTemplate.Execute(&buffer, config); err != nil { 63 panic(err) 64 } 65 66 cmtos.MustWriteFile(configFilePath, buffer.Bytes(), 0o644) 67 } 68 69 // Note: any changes to the comments/variables/mapstructure 70 // must be reflected in the appropriate struct in config/config.go 71 const defaultConfigTemplate = `# This is a TOML config file. 72 # For more information, see https://github.com/toml-lang/toml 73 74 # NOTE: Any path below can be absolute (e.g. "/var/myawesomeapp/data") or 75 # relative to the home directory (e.g. "data"). The home directory is 76 # "$HOME/.cometbft" by default, but could be changed via $CMTHOME env variable 77 # or --home cmd flag. 78 79 ####################################################################### 80 ### Main Base Config Options ### 81 ####################################################################### 82 83 # TCP or UNIX socket address of the ABCI application, 84 # or the name of an ABCI application compiled in with the CometBFT binary 85 proxy_app = "{{ .BaseConfig.ProxyApp }}" 86 87 # A custom human readable name for this node 88 moniker = "{{ .BaseConfig.Moniker }}" 89 90 # If this node is many blocks behind the tip of the chain, FastSync 91 # allows them to catchup quickly by downloading blocks in parallel 92 # and verifying their commits 93 fast_sync = {{ .BaseConfig.FastSyncMode }} 94 95 # Database backend: goleveldb | cleveldb | boltdb | rocksdb | badgerdb 96 # * goleveldb (github.com/syndtr/goleveldb - most popular implementation) 97 # - pure go 98 # - stable 99 # * cleveldb (uses levigo wrapper) 100 # - fast 101 # - requires gcc 102 # - use cleveldb build tag (go build -tags cleveldb) 103 # * boltdb (uses etcd's fork of bolt - github.com/etcd-io/bbolt) 104 # - EXPERIMENTAL 105 # - may be faster is some use-cases (random reads - indexer) 106 # - use boltdb build tag (go build -tags boltdb) 107 # * rocksdb (uses github.com/tecbot/gorocksdb) 108 # - EXPERIMENTAL 109 # - requires gcc 110 # - use rocksdb build tag (go build -tags rocksdb) 111 # * badgerdb (uses github.com/dgraph-io/badger) 112 # - EXPERIMENTAL 113 # - use badgerdb build tag (go build -tags badgerdb) 114 db_backend = "{{ .BaseConfig.DBBackend }}" 115 116 # Database directory 117 db_dir = "{{ js .BaseConfig.DBPath }}" 118 119 # Output level for logging, including package level options 120 log_level = "{{ .BaseConfig.LogLevel }}" 121 122 # Output format: 'plain' (colored text) or 'json' 123 log_format = "{{ .BaseConfig.LogFormat }}" 124 125 ##### additional base config options ##### 126 127 # Path to the JSON file containing the initial validator set and other meta data 128 genesis_file = "{{ js .BaseConfig.Genesis }}" 129 130 # Path to the JSON file containing the private key to use as a validator in the consensus protocol 131 priv_validator_key_file = "{{ js .BaseConfig.PrivValidatorKey }}" 132 133 # Path to the JSON file containing the last sign state of a validator 134 priv_validator_state_file = "{{ js .BaseConfig.PrivValidatorState }}" 135 136 # TCP or UNIX socket address for CometBFT to listen on for 137 # connections from an external PrivValidator process 138 priv_validator_laddr = "{{ .BaseConfig.PrivValidatorListenAddr }}" 139 140 # Path to the JSON file containing the private key to use for node authentication in the p2p protocol 141 node_key_file = "{{ js .BaseConfig.NodeKey }}" 142 143 # Mechanism to connect to the ABCI application: socket | grpc 144 abci = "{{ .BaseConfig.ABCI }}" 145 146 # If true, query the ABCI app on connecting to a new peer 147 # so the app can decide if we should keep the connection or not 148 filter_peers = {{ .BaseConfig.FilterPeers }} 149 150 151 ####################################################################### 152 ### Advanced Configuration Options ### 153 ####################################################################### 154 155 ####################################################### 156 ### RPC Server Configuration Options ### 157 ####################################################### 158 [rpc] 159 160 # TCP or UNIX socket address for the RPC server to listen on 161 laddr = "{{ .RPC.ListenAddress }}" 162 163 # A list of origins a cross-domain request can be executed from 164 # Default value '[]' disables cors support 165 # Use '["*"]' to allow any origin 166 cors_allowed_origins = [{{ range .RPC.CORSAllowedOrigins }}{{ printf "%q, " . }}{{end}}] 167 168 # A list of methods the client is allowed to use with cross-domain requests 169 cors_allowed_methods = [{{ range .RPC.CORSAllowedMethods }}{{ printf "%q, " . }}{{end}}] 170 171 # A list of non simple headers the client is allowed to use with cross-domain requests 172 cors_allowed_headers = [{{ range .RPC.CORSAllowedHeaders }}{{ printf "%q, " . }}{{end}}] 173 174 # TCP or UNIX socket address for the gRPC server to listen on 175 # NOTE: This server only supports /broadcast_tx_commit 176 grpc_laddr = "{{ .RPC.GRPCListenAddress }}" 177 178 # Maximum number of simultaneous connections. 179 # Does not include RPC (HTTP&WebSocket) connections. See max_open_connections 180 # If you want to accept a larger number than the default, make sure 181 # you increase your OS limits. 182 # 0 - unlimited. 183 # Should be < {ulimit -Sn} - {MaxNumInboundPeers} - {MaxNumOutboundPeers} - {N of wal, db and other open files} 184 # 1024 - 40 - 10 - 50 = 924 = ~900 185 grpc_max_open_connections = {{ .RPC.GRPCMaxOpenConnections }} 186 187 # Activate unsafe RPC commands like /dial_seeds and /unsafe_flush_mempool 188 unsafe = {{ .RPC.Unsafe }} 189 190 # Maximum number of simultaneous connections (including WebSocket). 191 # Does not include gRPC connections. See grpc_max_open_connections 192 # If you want to accept a larger number than the default, make sure 193 # you increase your OS limits. 194 # 0 - unlimited. 195 # Should be < {ulimit -Sn} - {MaxNumInboundPeers} - {MaxNumOutboundPeers} - {N of wal, db and other open files} 196 # 1024 - 40 - 10 - 50 = 924 = ~900 197 max_open_connections = {{ .RPC.MaxOpenConnections }} 198 199 # Maximum number of unique clientIDs that can /subscribe 200 # If you're using /broadcast_tx_commit, set to the estimated maximum number 201 # of broadcast_tx_commit calls per block. 202 max_subscription_clients = {{ .RPC.MaxSubscriptionClients }} 203 204 # Maximum number of unique queries a given client can /subscribe to 205 # If you're using GRPC (or Local RPC client) and /broadcast_tx_commit, set to 206 # the estimated # maximum number of broadcast_tx_commit calls per block. 207 max_subscriptions_per_client = {{ .RPC.MaxSubscriptionsPerClient }} 208 209 # Experimental parameter to specify the maximum number of events a node will 210 # buffer, per subscription, before returning an error and closing the 211 # subscription. Must be set to at least 100, but higher values will accommodate 212 # higher event throughput rates (and will use more memory). 213 experimental_subscription_buffer_size = {{ .RPC.SubscriptionBufferSize }} 214 215 # Experimental parameter to specify the maximum number of RPC responses that 216 # can be buffered per WebSocket client. If clients cannot read from the 217 # WebSocket endpoint fast enough, they will be disconnected, so increasing this 218 # parameter may reduce the chances of them being disconnected (but will cause 219 # the node to use more memory). 220 # 221 # Must be at least the same as "experimental_subscription_buffer_size", 222 # otherwise connections could be dropped unnecessarily. This value should 223 # ideally be somewhat higher than "experimental_subscription_buffer_size" to 224 # accommodate non-subscription-related RPC responses. 225 experimental_websocket_write_buffer_size = {{ .RPC.WebSocketWriteBufferSize }} 226 227 # If a WebSocket client cannot read fast enough, at present we may 228 # silently drop events instead of generating an error or disconnecting the 229 # client. 230 # 231 # Enabling this experimental parameter will cause the WebSocket connection to 232 # be closed instead if it cannot read fast enough, allowing for greater 233 # predictability in subscription behaviour. 234 experimental_close_on_slow_client = {{ .RPC.CloseOnSlowClient }} 235 236 # How long to wait for a tx to be committed during /broadcast_tx_commit. 237 # WARNING: Using a value larger than 10s will result in increasing the 238 # global HTTP write timeout, which applies to all connections and endpoints. 239 # See https://github.com/tendermint/tendermint/issues/3435 240 timeout_broadcast_tx_commit = "{{ .RPC.TimeoutBroadcastTxCommit }}" 241 242 # Maximum size of request body, in bytes 243 max_body_bytes = {{ .RPC.MaxBodyBytes }} 244 245 # Maximum size of request header, in bytes 246 max_header_bytes = {{ .RPC.MaxHeaderBytes }} 247 248 # The path to a file containing certificate that is used to create the HTTPS server. 249 # Might be either absolute path or path related to CometBFT's config directory. 250 # If the certificate is signed by a certificate authority, 251 # the certFile should be the concatenation of the server's certificate, any intermediates, 252 # and the CA's certificate. 253 # NOTE: both tls_cert_file and tls_key_file must be present for CometBFT to create HTTPS server. 254 # Otherwise, HTTP server is run. 255 tls_cert_file = "{{ .RPC.TLSCertFile }}" 256 257 # The path to a file containing matching private key that is used to create the HTTPS server. 258 # Might be either absolute path or path related to CometBFT's config directory. 259 # NOTE: both tls-cert-file and tls-key-file must be present for CometBFT to create HTTPS server. 260 # Otherwise, HTTP server is run. 261 tls_key_file = "{{ .RPC.TLSKeyFile }}" 262 263 # pprof listen address (https://golang.org/pkg/net/http/pprof) 264 pprof_laddr = "{{ .RPC.PprofListenAddress }}" 265 266 ####################################################### 267 ### P2P Configuration Options ### 268 ####################################################### 269 [p2p] 270 271 # Address to listen for incoming connections 272 laddr = "{{ .P2P.ListenAddress }}" 273 274 # Address to advertise to peers for them to dial 275 # If empty, will use the same port as the laddr, 276 # and will introspect on the listener or use UPnP 277 # to figure out the address. ip and port are required 278 # example: 159.89.10.97:26656 279 external_address = "{{ .P2P.ExternalAddress }}" 280 281 # Comma separated list of seed nodes to connect to 282 seeds = "{{ .P2P.Seeds }}" 283 284 # Comma separated list of nodes to keep persistent connections to 285 persistent_peers = "{{ .P2P.PersistentPeers }}" 286 287 # UPNP port forwarding 288 upnp = {{ .P2P.UPNP }} 289 290 # Path to address book 291 addr_book_file = "{{ js .P2P.AddrBook }}" 292 293 # Set true for strict address routability rules 294 # Set false for private or local networks 295 addr_book_strict = {{ .P2P.AddrBookStrict }} 296 297 # Maximum number of inbound peers 298 max_num_inbound_peers = {{ .P2P.MaxNumInboundPeers }} 299 300 # Maximum number of outbound peers to connect to, excluding persistent peers 301 max_num_outbound_peers = {{ .P2P.MaxNumOutboundPeers }} 302 303 # List of node IDs, to which a connection will be (re)established ignoring any existing limits 304 unconditional_peer_ids = "{{ .P2P.UnconditionalPeerIDs }}" 305 306 # Maximum pause when redialing a persistent peer (if zero, exponential backoff is used) 307 persistent_peers_max_dial_period = "{{ .P2P.PersistentPeersMaxDialPeriod }}" 308 309 # Time to wait before flushing messages out on the connection 310 flush_throttle_timeout = "{{ .P2P.FlushThrottleTimeout }}" 311 312 # Maximum size of a message packet payload, in bytes 313 max_packet_msg_payload_size = {{ .P2P.MaxPacketMsgPayloadSize }} 314 315 # Rate at which packets can be sent, in bytes/second 316 send_rate = {{ .P2P.SendRate }} 317 318 # Rate at which packets can be received, in bytes/second 319 recv_rate = {{ .P2P.RecvRate }} 320 321 # Set true to enable the peer-exchange reactor 322 pex = {{ .P2P.PexReactor }} 323 324 # Seed mode, in which node constantly crawls the network and looks for 325 # peers. If another node asks it for addresses, it responds and disconnects. 326 # 327 # Does not work if the peer-exchange reactor is disabled. 328 seed_mode = {{ .P2P.SeedMode }} 329 330 # Comma separated list of peer IDs to keep private (will not be gossiped to other peers) 331 private_peer_ids = "{{ .P2P.PrivatePeerIDs }}" 332 333 # Toggle to disable guard against peers connecting from the same ip. 334 allow_duplicate_ip = {{ .P2P.AllowDuplicateIP }} 335 336 # Peer connection configuration. 337 handshake_timeout = "{{ .P2P.HandshakeTimeout }}" 338 dial_timeout = "{{ .P2P.DialTimeout }}" 339 340 ####################################################### 341 ### Mempool Configuration Option ### 342 ####################################################### 343 [mempool] 344 345 # Mempool version to use: 346 # 1) "v0" - (default) FIFO mempool. 347 # 2) "v1" - prioritized mempool. 348 version = "{{ .Mempool.Version }}" 349 350 # Recheck (default: true) defines whether CometBFT should recheck the 351 # validity for all remaining transaction in the mempool after a block. 352 # Since a block affects the application state, some transactions in the 353 # mempool may become invalid. If this does not apply to your application, 354 # you can disable rechecking. 355 recheck = {{ .Mempool.Recheck }} 356 broadcast = {{ .Mempool.Broadcast }} 357 wal_dir = "{{ js .Mempool.WalPath }}" 358 359 # Maximum number of transactions in the mempool 360 size = {{ .Mempool.Size }} 361 362 # Limit the total size of all txs in the mempool. 363 # This only accounts for raw transactions (e.g. given 1MB transactions and 364 # max_txs_bytes=5MB, mempool will only accept 5 transactions). 365 max_txs_bytes = {{ .Mempool.MaxTxsBytes }} 366 367 # Size of the cache (used to filter transactions we saw earlier) in transactions 368 cache_size = {{ .Mempool.CacheSize }} 369 370 # Do not remove invalid transactions from the cache (default: false) 371 # Set to true if it's not possible for any invalid transaction to become valid 372 # again in the future. 373 keep-invalid-txs-in-cache = {{ .Mempool.KeepInvalidTxsInCache }} 374 375 # Maximum size of a single transaction. 376 # NOTE: the max size of a tx transmitted over the network is {max_tx_bytes}. 377 max_tx_bytes = {{ .Mempool.MaxTxBytes }} 378 379 # Maximum size of a batch of transactions to send to a peer 380 # Including space needed by encoding (one varint per transaction). 381 # XXX: Unused due to https://github.com/tendermint/tendermint/issues/5796 382 max_batch_bytes = {{ .Mempool.MaxBatchBytes }} 383 384 # ttl-duration, if non-zero, defines the maximum amount of time a transaction 385 # can exist for in the mempool. 386 # 387 # Note, if ttl-num-blocks is also defined, a transaction will be removed if it 388 # has existed in the mempool at least ttl-num-blocks number of blocks or if it's 389 # insertion time into the mempool is beyond ttl-duration. 390 ttl-duration = "{{ .Mempool.TTLDuration }}" 391 392 # ttl-num-blocks, if non-zero, defines the maximum number of blocks a transaction 393 # can exist for in the mempool. 394 # 395 # Note, if ttl-duration is also defined, a transaction will be removed if it 396 # has existed in the mempool at least ttl-num-blocks number of blocks or if 397 # it's insertion time into the mempool is beyond ttl-duration. 398 ttl-num-blocks = {{ .Mempool.TTLNumBlocks }} 399 400 ####################################################### 401 ### State Sync Configuration Options ### 402 ####################################################### 403 [statesync] 404 # State sync rapidly bootstraps a new node by discovering, fetching, and restoring a state machine 405 # snapshot from peers instead of fetching and replaying historical blocks. Requires some peers in 406 # the network to take and serve state machine snapshots. State sync is not attempted if the node 407 # has any local state (LastBlockHeight > 0). The node will have a truncated block history, 408 # starting from the height of the snapshot. 409 enable = {{ .StateSync.Enable }} 410 411 # RPC servers (comma-separated) for light client verification of the synced state machine and 412 # retrieval of state data for node bootstrapping. Also needs a trusted height and corresponding 413 # header hash obtained from a trusted source, and a period during which validators can be trusted. 414 # 415 # For Cosmos SDK-based chains, trust_period should usually be about 2/3 of the unbonding time (~2 416 # weeks) during which they can be financially punished (slashed) for misbehavior. 417 rpc_servers = "{{ StringsJoin .StateSync.RPCServers "," }}" 418 trust_height = {{ .StateSync.TrustHeight }} 419 trust_hash = "{{ .StateSync.TrustHash }}" 420 trust_period = "{{ .StateSync.TrustPeriod }}" 421 422 # Time to spend discovering snapshots before initiating a restore. 423 discovery_time = "{{ .StateSync.DiscoveryTime }}" 424 425 # Temporary directory for state sync snapshot chunks, defaults to the OS tempdir (typically /tmp). 426 # Will create a new, randomly named directory within, and remove it when done. 427 temp_dir = "{{ .StateSync.TempDir }}" 428 429 # The timeout duration before re-requesting a chunk, possibly from a different 430 # peer (default: 1 minute). 431 chunk_request_timeout = "{{ .StateSync.ChunkRequestTimeout }}" 432 433 # The number of concurrent chunk fetchers to run (default: 1). 434 chunk_fetchers = "{{ .StateSync.ChunkFetchers }}" 435 436 ####################################################### 437 ### Fast Sync Configuration Connections ### 438 ####################################################### 439 [fastsync] 440 441 # Fast Sync version to use: 442 # 1) "v0" (default) - the legacy fast sync implementation 443 # 2) "v1" - refactor of v0 version for better testability 444 # 2) "v2" - complete redesign of v0, optimized for testability & readability 445 version = "{{ .FastSync.Version }}" 446 447 ####################################################### 448 ### Consensus Configuration Options ### 449 ####################################################### 450 [consensus] 451 452 wal_file = "{{ js .Consensus.WalPath }}" 453 454 # How long we wait for a proposal block before prevoting nil 455 timeout_propose = "{{ .Consensus.TimeoutPropose }}" 456 # How much timeout_propose increases with each round 457 timeout_propose_delta = "{{ .Consensus.TimeoutProposeDelta }}" 458 # How long we wait after receiving +2/3 prevotes for “anything” (ie. not a single block or nil) 459 timeout_prevote = "{{ .Consensus.TimeoutPrevote }}" 460 # How much the timeout_prevote increases with each round 461 timeout_prevote_delta = "{{ .Consensus.TimeoutPrevoteDelta }}" 462 # How long we wait after receiving +2/3 precommits for “anything” (ie. not a single block or nil) 463 timeout_precommit = "{{ .Consensus.TimeoutPrecommit }}" 464 # How much the timeout_precommit increases with each round 465 timeout_precommit_delta = "{{ .Consensus.TimeoutPrecommitDelta }}" 466 # How long we wait after committing a block, before starting on the new 467 # height (this gives us a chance to receive some more precommits, even 468 # though we already have +2/3). 469 timeout_commit = "{{ .Consensus.TimeoutCommit }}" 470 471 # How many blocks to look back to check existence of the node's consensus votes before joining consensus 472 # When non-zero, the node will panic upon restart 473 # if the same consensus key was used to sign {double_sign_check_height} last blocks. 474 # So, validators should stop the state machine, wait for some blocks, and then restart the state machine to avoid panic. 475 double_sign_check_height = {{ .Consensus.DoubleSignCheckHeight }} 476 477 # Make progress as soon as we have all the precommits (as if TimeoutCommit = 0) 478 skip_timeout_commit = {{ .Consensus.SkipTimeoutCommit }} 479 480 # EmptyBlocks mode and possible interval between empty blocks 481 create_empty_blocks = {{ .Consensus.CreateEmptyBlocks }} 482 create_empty_blocks_interval = "{{ .Consensus.CreateEmptyBlocksInterval }}" 483 484 # Reactor sleep duration parameters 485 peer_gossip_sleep_duration = "{{ .Consensus.PeerGossipSleepDuration }}" 486 peer_query_maj23_sleep_duration = "{{ .Consensus.PeerQueryMaj23SleepDuration }}" 487 488 ####################################################### 489 ### Storage Configuration Options ### 490 ####################################################### 491 [storage] 492 493 # Set to true to discard ABCI responses from the state store, which can save a 494 # considerable amount of disk space. Set to false to ensure ABCI responses are 495 # persisted. ABCI responses are required for /block_results RPC queries, and to 496 # reindex events in the command-line tool. 497 discard_abci_responses = {{ .Storage.DiscardABCIResponses}} 498 499 ####################################################### 500 ### Transaction Indexer Configuration Options ### 501 ####################################################### 502 [tx_index] 503 504 # What indexer to use for transactions 505 # 506 # The application will set which txs to index. In some cases a node operator will be able 507 # to decide which txs to index based on configuration set in the application. 508 # 509 # Options: 510 # 1) "null" 511 # 2) "kv" (default) - the simplest possible indexer, backed by key-value storage (defaults to levelDB; see DBBackend). 512 # - When "kv" is chosen "tx.height" and "tx.hash" will always be indexed. 513 # 3) "psql" - the indexer services backed by PostgreSQL. 514 # When "kv" or "psql" is chosen "tx.height" and "tx.hash" will always be indexed. 515 indexer = "{{ .TxIndex.Indexer }}" 516 517 # The PostgreSQL connection configuration, the connection format: 518 # postgresql://<user>:<password>@<host>:<port>/<db>?<opts> 519 psql-conn = "{{ .TxIndex.PsqlConn }}" 520 521 ####################################################### 522 ### Instrumentation Configuration Options ### 523 ####################################################### 524 [instrumentation] 525 526 # When true, Prometheus metrics are served under /metrics on 527 # PrometheusListenAddr. 528 # Check out the documentation for the list of available metrics. 529 prometheus = {{ .Instrumentation.Prometheus }} 530 531 # Address to listen for Prometheus collector(s) connections 532 prometheus_listen_addr = "{{ .Instrumentation.PrometheusListenAddr }}" 533 534 # Maximum number of simultaneous connections. 535 # If you want to accept a larger number than the default, make sure 536 # you increase your OS limits. 537 # 0 - unlimited. 538 max_open_connections = {{ .Instrumentation.MaxOpenConnections }} 539 540 # Instrumentation namespace 541 namespace = "{{ .Instrumentation.Namespace }}" 542 ` 543 544 /****** these are for test settings ***********/ 545 546 func ResetTestRoot(testName string) *Config { 547 return ResetTestRootWithChainID(testName, "") 548 } 549 550 func ResetTestRootWithChainID(testName string, chainID string) *Config { 551 // create a unique, concurrency-safe test directory under os.TempDir() 552 rootDir, err := os.MkdirTemp("", fmt.Sprintf("%s-%s_", chainID, testName)) 553 if err != nil { 554 panic(err) 555 } 556 // ensure config and data subdirs are created 557 if err := cmtos.EnsureDir(filepath.Join(rootDir, defaultConfigDir), DefaultDirPerm); err != nil { 558 panic(err) 559 } 560 if err := cmtos.EnsureDir(filepath.Join(rootDir, defaultDataDir), DefaultDirPerm); err != nil { 561 panic(err) 562 } 563 564 baseConfig := DefaultBaseConfig() 565 configFilePath := filepath.Join(rootDir, defaultConfigFilePath) 566 genesisFilePath := filepath.Join(rootDir, baseConfig.Genesis) 567 privKeyFilePath := filepath.Join(rootDir, baseConfig.PrivValidatorKey) 568 privStateFilePath := filepath.Join(rootDir, baseConfig.PrivValidatorState) 569 570 // Write default config file if missing. 571 if !cmtos.FileExists(configFilePath) { 572 writeDefaultConfigFile(configFilePath) 573 } 574 if !cmtos.FileExists(genesisFilePath) { 575 if chainID == "" { 576 chainID = "cometbft_test" 577 } 578 testGenesis := fmt.Sprintf(testGenesisFmt, chainID) 579 cmtos.MustWriteFile(genesisFilePath, []byte(testGenesis), 0o644) 580 } 581 // we always overwrite the priv val 582 cmtos.MustWriteFile(privKeyFilePath, []byte(testPrivValidatorKey), 0o644) 583 cmtos.MustWriteFile(privStateFilePath, []byte(testPrivValidatorState), 0o644) 584 585 config := TestConfig().SetRoot(rootDir) 586 return config 587 } 588 589 var testGenesisFmt = `{ 590 "genesis_time": "2018-10-10T08:20:13.695936996Z", 591 "chain_id": "%s", 592 "initial_height": "1", 593 "consensus_params": { 594 "block": { 595 "max_bytes": "22020096", 596 "max_gas": "-1", 597 "time_iota_ms": "10" 598 }, 599 "evidence": { 600 "max_age_num_blocks": "100000", 601 "max_age_duration": "172800000000000", 602 "max_bytes": "1048576" 603 }, 604 "validator": { 605 "pub_key_types": [ 606 "ed25519" 607 ] 608 }, 609 "version": {} 610 }, 611 "validators": [ 612 { 613 "pub_key": { 614 "type": "tendermint/PubKeyEd25519", 615 "value":"AT/+aaL1eB0477Mud9JMm8Sh8BIvOYlPGC9KkIUmFaE=" 616 }, 617 "power": "10", 618 "name": "" 619 } 620 ], 621 "app_hash": "" 622 }` 623 624 var testPrivValidatorKey = `{ 625 "address": "A3258DCBF45DCA0DF052981870F2D1441A36D145", 626 "pub_key": { 627 "type": "tendermint/PubKeyEd25519", 628 "value": "AT/+aaL1eB0477Mud9JMm8Sh8BIvOYlPGC9KkIUmFaE=" 629 }, 630 "priv_key": { 631 "type": "tendermint/PrivKeyEd25519", 632 "value": "EVkqJO/jIXp3rkASXfh9YnyToYXRXhBr6g9cQVxPFnQBP/5povV4HTjvsy530kybxKHwEi85iU8YL0qQhSYVoQ==" 633 } 634 }` 635 636 var testPrivValidatorState = `{ 637 "height": "0", 638 "round": 0, 639 "step": 0 640 }`