github.com/vipernet-xyz/tm@v0.34.24/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 tmos "github.com/vipernet-xyz/tm/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 := tmos.EnsureDir(rootDir, DefaultDirPerm); err != nil { 35 panic(err.Error()) 36 } 37 if err := tmos.EnsureDir(filepath.Join(rootDir, defaultConfigDir), DefaultDirPerm); err != nil { 38 panic(err.Error()) 39 } 40 if err := tmos.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 !tmos.FileExists(configFilePath) { 48 writeDefaultConfigFile(configFilePath) 49 } 50 } 51 52 // XXX: this func should probably be called by cmd/tendermint/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 tmos.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/.tendermint" by default, but could be changed via $TMHOME 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 Tendermint 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 Tendermint 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/vipernet-xyz/tm/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 Tendermint'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 Tendermint 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 Tendermint's config directory. 259 # NOTE: both tls-cert-file and tls-key-file must be present for Tendermint 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 = {{ .Mempool.Recheck }} 351 broadcast = {{ .Mempool.Broadcast }} 352 wal_dir = "{{ js .Mempool.WalPath }}" 353 354 # Maximum number of transactions in the mempool 355 size = {{ .Mempool.Size }} 356 357 # Limit the total size of all txs in the mempool. 358 # This only accounts for raw transactions (e.g. given 1MB transactions and 359 # max_txs_bytes=5MB, mempool will only accept 5 transactions). 360 max_txs_bytes = {{ .Mempool.MaxTxsBytes }} 361 362 # Size of the cache (used to filter transactions we saw earlier) in transactions 363 cache_size = {{ .Mempool.CacheSize }} 364 365 # Do not remove invalid transactions from the cache (default: false) 366 # Set to true if it's not possible for any invalid transaction to become valid 367 # again in the future. 368 keep-invalid-txs-in-cache = {{ .Mempool.KeepInvalidTxsInCache }} 369 370 # Maximum size of a single transaction. 371 # NOTE: the max size of a tx transmitted over the network is {max_tx_bytes}. 372 max_tx_bytes = {{ .Mempool.MaxTxBytes }} 373 374 # Maximum size of a batch of transactions to send to a peer 375 # Including space needed by encoding (one varint per transaction). 376 # XXX: Unused due to https://github.com/vipernet-xyz/tm/issues/5796 377 max_batch_bytes = {{ .Mempool.MaxBatchBytes }} 378 379 # ttl-duration, if non-zero, defines the maximum amount of time a transaction 380 # can exist for in the mempool. 381 # 382 # Note, if ttl-num-blocks is also defined, a transaction will be removed if it 383 # has existed in the mempool at least ttl-num-blocks number of blocks or if it's 384 # insertion time into the mempool is beyond ttl-duration. 385 ttl-duration = "{{ .Mempool.TTLDuration }}" 386 387 # ttl-num-blocks, if non-zero, defines the maximum number of blocks a transaction 388 # can exist for in the mempool. 389 # 390 # Note, if ttl-duration is also defined, a transaction will be removed if it 391 # has existed in the mempool at least ttl-num-blocks number of blocks or if 392 # it's insertion time into the mempool is beyond ttl-duration. 393 ttl-num-blocks = {{ .Mempool.TTLNumBlocks }} 394 395 ####################################################### 396 ### State Sync Configuration Options ### 397 ####################################################### 398 [statesync] 399 # State sync rapidly bootstraps a new node by discovering, fetching, and restoring a state machine 400 # snapshot from peers instead of fetching and replaying historical blocks. Requires some peers in 401 # the network to take and serve state machine snapshots. State sync is not attempted if the node 402 # has any local state (LastBlockHeight > 0). The node will have a truncated block history, 403 # starting from the height of the snapshot. 404 enable = {{ .StateSync.Enable }} 405 406 # RPC servers (comma-separated) for light client verification of the synced state machine and 407 # retrieval of state data for node bootstrapping. Also needs a trusted height and corresponding 408 # header hash obtained from a trusted source, and a period during which validators can be trusted. 409 # 410 # For Cosmos SDK-based chains, trust_period should usually be about 2/3 of the unbonding time (~2 411 # weeks) during which they can be financially punished (slashed) for misbehavior. 412 rpc_servers = "{{ StringsJoin .StateSync.RPCServers "," }}" 413 trust_height = {{ .StateSync.TrustHeight }} 414 trust_hash = "{{ .StateSync.TrustHash }}" 415 trust_period = "{{ .StateSync.TrustPeriod }}" 416 417 # Time to spend discovering snapshots before initiating a restore. 418 discovery_time = "{{ .StateSync.DiscoveryTime }}" 419 420 # Temporary directory for state sync snapshot chunks, defaults to the OS tempdir (typically /tmp). 421 # Will create a new, randomly named directory within, and remove it when done. 422 temp_dir = "{{ .StateSync.TempDir }}" 423 424 # The timeout duration before re-requesting a chunk, possibly from a different 425 # peer (default: 1 minute). 426 chunk_request_timeout = "{{ .StateSync.ChunkRequestTimeout }}" 427 428 # The number of concurrent chunk fetchers to run (default: 1). 429 chunk_fetchers = "{{ .StateSync.ChunkFetchers }}" 430 431 ####################################################### 432 ### Fast Sync Configuration Connections ### 433 ####################################################### 434 [fastsync] 435 436 # Fast Sync version to use: 437 # 1) "v0" (default) - the legacy fast sync implementation 438 # 2) "v1" - refactor of v0 version for better testability 439 # 2) "v2" - complete redesign of v0, optimized for testability & readability 440 version = "{{ .FastSync.Version }}" 441 442 ####################################################### 443 ### Consensus Configuration Options ### 444 ####################################################### 445 [consensus] 446 447 wal_file = "{{ js .Consensus.WalPath }}" 448 449 # How long we wait for a proposal block before prevoting nil 450 timeout_propose = "{{ .Consensus.TimeoutPropose }}" 451 # How much timeout_propose increases with each round 452 timeout_propose_delta = "{{ .Consensus.TimeoutProposeDelta }}" 453 # How long we wait after receiving +2/3 prevotes for “anything” (ie. not a single block or nil) 454 timeout_prevote = "{{ .Consensus.TimeoutPrevote }}" 455 # How much the timeout_prevote increases with each round 456 timeout_prevote_delta = "{{ .Consensus.TimeoutPrevoteDelta }}" 457 # How long we wait after receiving +2/3 precommits for “anything” (ie. not a single block or nil) 458 timeout_precommit = "{{ .Consensus.TimeoutPrecommit }}" 459 # How much the timeout_precommit increases with each round 460 timeout_precommit_delta = "{{ .Consensus.TimeoutPrecommitDelta }}" 461 # How long we wait after committing a block, before starting on the new 462 # height (this gives us a chance to receive some more precommits, even 463 # though we already have +2/3). 464 timeout_commit = "{{ .Consensus.TimeoutCommit }}" 465 466 # How many blocks to look back to check existence of the node's consensus votes before joining consensus 467 # When non-zero, the node will panic upon restart 468 # if the same consensus key was used to sign {double_sign_check_height} last blocks. 469 # So, validators should stop the state machine, wait for some blocks, and then restart the state machine to avoid panic. 470 double_sign_check_height = {{ .Consensus.DoubleSignCheckHeight }} 471 472 # Make progress as soon as we have all the precommits (as if TimeoutCommit = 0) 473 skip_timeout_commit = {{ .Consensus.SkipTimeoutCommit }} 474 475 # EmptyBlocks mode and possible interval between empty blocks 476 create_empty_blocks = {{ .Consensus.CreateEmptyBlocks }} 477 create_empty_blocks_interval = "{{ .Consensus.CreateEmptyBlocksInterval }}" 478 479 # Reactor sleep duration parameters 480 peer_gossip_sleep_duration = "{{ .Consensus.PeerGossipSleepDuration }}" 481 peer_query_maj23_sleep_duration = "{{ .Consensus.PeerQueryMaj23SleepDuration }}" 482 483 ####################################################### 484 ### Storage Configuration Options ### 485 ####################################################### 486 [storage] 487 488 # Set to true to discard ABCI responses from the state store, which can save a 489 # considerable amount of disk space. Set to false to ensure ABCI responses are 490 # persisted. ABCI responses are required for /block_results RPC queries, and to 491 # reindex events in the command-line tool. 492 discard_abci_responses = {{ .Storage.DiscardABCIResponses}} 493 494 ####################################################### 495 ### Transaction Indexer Configuration Options ### 496 ####################################################### 497 [tx_index] 498 499 # What indexer to use for transactions 500 # 501 # The application will set which txs to index. In some cases a node operator will be able 502 # to decide which txs to index based on configuration set in the application. 503 # 504 # Options: 505 # 1) "null" 506 # 2) "kv" (default) - the simplest possible indexer, backed by key-value storage (defaults to levelDB; see DBBackend). 507 # - When "kv" is chosen "tx.height" and "tx.hash" will always be indexed. 508 # 3) "psql" - the indexer services backed by PostgreSQL. 509 # When "kv" or "psql" is chosen "tx.height" and "tx.hash" will always be indexed. 510 indexer = "{{ .TxIndex.Indexer }}" 511 512 # The PostgreSQL connection configuration, the connection format: 513 # postgresql://<user>:<password>@<host>:<port>/<db>?<opts> 514 psql-conn = "{{ .TxIndex.PsqlConn }}" 515 516 ####################################################### 517 ### Instrumentation Configuration Options ### 518 ####################################################### 519 [instrumentation] 520 521 # When true, Prometheus metrics are served under /metrics on 522 # PrometheusListenAddr. 523 # Check out the documentation for the list of available metrics. 524 prometheus = {{ .Instrumentation.Prometheus }} 525 526 # Address to listen for Prometheus collector(s) connections 527 prometheus_listen_addr = "{{ .Instrumentation.PrometheusListenAddr }}" 528 529 # Maximum number of simultaneous connections. 530 # If you want to accept a larger number than the default, make sure 531 # you increase your OS limits. 532 # 0 - unlimited. 533 max_open_connections = {{ .Instrumentation.MaxOpenConnections }} 534 535 # Instrumentation namespace 536 namespace = "{{ .Instrumentation.Namespace }}" 537 ` 538 539 /****** these are for test settings ***********/ 540 541 func ResetTestRoot(testName string) *Config { 542 return ResetTestRootWithChainID(testName, "") 543 } 544 545 func ResetTestRootWithChainID(testName string, chainID string) *Config { 546 // create a unique, concurrency-safe test directory under os.TempDir() 547 rootDir, err := os.MkdirTemp("", fmt.Sprintf("%s-%s_", chainID, testName)) 548 if err != nil { 549 panic(err) 550 } 551 // ensure config and data subdirs are created 552 if err := tmos.EnsureDir(filepath.Join(rootDir, defaultConfigDir), DefaultDirPerm); err != nil { 553 panic(err) 554 } 555 if err := tmos.EnsureDir(filepath.Join(rootDir, defaultDataDir), DefaultDirPerm); err != nil { 556 panic(err) 557 } 558 559 baseConfig := DefaultBaseConfig() 560 configFilePath := filepath.Join(rootDir, defaultConfigFilePath) 561 genesisFilePath := filepath.Join(rootDir, baseConfig.Genesis) 562 privKeyFilePath := filepath.Join(rootDir, baseConfig.PrivValidatorKey) 563 privStateFilePath := filepath.Join(rootDir, baseConfig.PrivValidatorState) 564 565 // Write default config file if missing. 566 if !tmos.FileExists(configFilePath) { 567 writeDefaultConfigFile(configFilePath) 568 } 569 if !tmos.FileExists(genesisFilePath) { 570 if chainID == "" { 571 chainID = "tendermint_test" 572 } 573 testGenesis := fmt.Sprintf(testGenesisFmt, chainID) 574 tmos.MustWriteFile(genesisFilePath, []byte(testGenesis), 0o644) 575 } 576 // we always overwrite the priv val 577 tmos.MustWriteFile(privKeyFilePath, []byte(testPrivValidatorKey), 0o644) 578 tmos.MustWriteFile(privStateFilePath, []byte(testPrivValidatorState), 0o644) 579 580 config := TestConfig().SetRoot(rootDir) 581 return config 582 } 583 584 var testGenesisFmt = `{ 585 "genesis_time": "2018-10-10T08:20:13.695936996Z", 586 "chain_id": "%s", 587 "initial_height": "1", 588 "consensus_params": { 589 "block": { 590 "max_bytes": "22020096", 591 "max_gas": "-1", 592 "time_iota_ms": "10" 593 }, 594 "evidence": { 595 "max_age_num_blocks": "100000", 596 "max_age_duration": "172800000000000", 597 "max_bytes": "1048576" 598 }, 599 "validator": { 600 "pub_key_types": [ 601 "ed25519" 602 ] 603 }, 604 "version": {} 605 }, 606 "validators": [ 607 { 608 "pub_key": { 609 "type": "tendermint/PubKeyEd25519", 610 "value":"AT/+aaL1eB0477Mud9JMm8Sh8BIvOYlPGC9KkIUmFaE=" 611 }, 612 "power": "10", 613 "name": "" 614 } 615 ], 616 "app_hash": "" 617 }` 618 619 var testPrivValidatorKey = `{ 620 "address": "A3258DCBF45DCA0DF052981870F2D1441A36D145", 621 "pub_key": { 622 "type": "tendermint/PubKeyEd25519", 623 "value": "AT/+aaL1eB0477Mud9JMm8Sh8BIvOYlPGC9KkIUmFaE=" 624 }, 625 "priv_key": { 626 "type": "tendermint/PrivKeyEd25519", 627 "value": "EVkqJO/jIXp3rkASXfh9YnyToYXRXhBr6g9cQVxPFnQBP/5povV4HTjvsy530kybxKHwEi85iU8YL0qQhSYVoQ==" 628 } 629 }` 630 631 var testPrivValidatorState = `{ 632 "height": "0", 633 "round": 0, 634 "step": 0 635 }`