Last active
July 24, 2019 07:09
-
-
Save gz-c/1bd8325644ac08fdc59bf937d9d0aa54 to your computer and use it in GitHub Desktop.
SublimeText GoSublime GoImports issue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package skycoin | |
import ( | |
"fmt" | |
"log" | |
"path/filepath" | |
"strings" | |
"github.com/skycoin/skycoin/src/api" | |
"github.com/skycoin/skycoin/src/cipher/bip44" | |
"github.com/skycoin/skycoin/src/util/file" | |
"github.com/spf13/cobra" | |
) | |
var ( | |
cfgFile string | |
) | |
func initConfig() { | |
// Lookup order: | |
// 1. Use packr/hardcoded defaults | |
// 2. Read config file from disk | |
// 3. Apply CLI options | |
viper.SetConfigType("toml") | |
// Load default config | |
// TODO -- this MUST be packed with packr for distribution | |
// This MUST be "hardcoded" somehow - or we can use a struct? | |
// TODO -- use viper.SetDefault for defaults instead | |
if cfgFile != "" { | |
// Use config file from the root command | |
viper.SetConfigFile(cfgFile) | |
} else { | |
dataDir, err := file.BuildDataDir(".skycoin") | |
if err != nil { | |
log.Fatal(err) | |
} | |
viper.SetConfigName("skyfiber") | |
// Search for the config file in local directory, ./config, then in ~/.skycoin/config/ | |
// Search paths are in reverse order of priority | |
viper.AddConfigPath(filepath.Join(dataDir, "config/")) | |
viper.AddConfigPath("./config/") | |
viper.AddConfigPath(".") | |
} | |
// viper.SetEnvPrefix("SKY") | |
// viper.AutomaticEnv() // read in environment variables that match | |
// If a config file is found, read it in | |
// Note: use MergeInConfig() if you want to "stack" configs on top of each other | |
if err := viper.ReadInConfig(); err != nil { | |
if _, ok := err.(viper.ConfigFileNotFoundError); ok { | |
if cfgFile != "" { | |
log.Fatal(err) | |
} | |
} else { | |
log.Fatal(err) | |
} | |
} | |
} | |
func setupRootCommand(cfg *NodeConfig) { | |
setDefaults() | |
// Setup global root command | |
var rootCmd = &cobra.Command{ | |
Use: "root", | |
Short: "root command", | |
Long: `root command`, | |
Run: func(cmd *cobra.Command, args []string) { | |
fmt.Printf("Inside rootCmd Run with args: %v\n", args) | |
}, | |
} | |
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file") | |
// Below is an example of how to use a cmd flag that mixes with a config file setting | |
// rootCmd.PersistentFlags().String("log", "knights.of.ni", "Syslog host") | |
// if err := viper.BindPFlag("log", rootCmd.PersistentFlags().Lookup("log")); err != nil { | |
// log.Fatal("Unable to bind flag:", err) | |
// } | |
registerFlags(rootCmd, cfg) | |
cobra.OnInitialize(initConfig) | |
if err := rootCmd.Execute(); err != nil { | |
log.Fatal(err) | |
} | |
} | |
func bindConfigFlag(cmd *cobra.Command, configKey, flagKey string) { | |
if err := viper.BindPFlag(configKey, cmd.Flags().Lookup(flagKey)); err != nil { | |
log.Fatalf("Unable to bind flag configKey=%s flagKey=%s err=%v", configKey, flagKey, err) | |
} | |
} | |
func registerFlags(cmd *cobra.Command, c *NodeConfig) { | |
// cmd.Flags().BoolVar(&help, "help", false, "Show help") | |
cmd.Flags().BoolVar(&c.DisablePEX, "disable-pex", c.DisablePEX, "disable PEX peer discovery") | |
cmd.Flags().BoolVar(&c.DownloadPeerList, "download-peerlist", c.DownloadPeerList, "download a peers.txt from -peerlist-url") | |
cmd.Flags().StringVar(&c.PeerListURL, "peerlist-url", c.PeerListURL, "with -download-peerlist=true, download a peers.txt file from this url") | |
cmd.Flags().BoolVar(&c.DisableOutgoingConnections, "disable-outgoing", c.DisableOutgoingConnections, "Don't make outgoing connections") | |
cmd.Flags().BoolVar(&c.DisableIncomingConnections, "disable-incoming", c.DisableIncomingConnections, "Don't allow incoming connections") | |
cmd.Flags().BoolVar(&c.DisableNetworking, "disable-networking", c.DisableNetworking, "Disable all network activity") | |
cmd.Flags().BoolVar(&c.EnableGUI, "enable-gui", c.EnableGUI, "Enable GUI") | |
cmd.Flags().BoolVar(&c.DisableCSRF, "disable-csrf", c.DisableCSRF, "disable CSRF check") | |
cmd.Flags().BoolVar(&c.DisableHeaderCheck, "disable-header-check", c.DisableHeaderCheck, "disables the host, origin and referer header checks.") | |
cmd.Flags().BoolVar(&c.DisableCSP, "disable-csp", c.DisableCSP, "disable content-security-policy in http response") | |
cmd.Flags().StringVar(&c.Address, "address", c.Address, "IP Address to run application on. Leave empty to default to a public interface") | |
cmd.Flags().IntVar(&c.Port, "port", c.Port, "Port to run application on") | |
cmd.Flags().BoolVar(&c.WebInterface, "web-interface", c.WebInterface, "enable the web interface") | |
cmd.Flags().IntVar(&c.WebInterfacePort, "web-interface-port", c.WebInterfacePort, "port to serve web interface on") | |
cmd.Flags().StringVar(&c.WebInterfaceAddr, "web-interface-addr", c.WebInterfaceAddr, "addr to serve web interface on") | |
cmd.Flags().StringVar(&c.WebInterfaceCert, "web-interface-cert", c.WebInterfaceCert, "skycoind.cert file for web interface HTTPS. If not provided, will autogenerate or use skycoind.cert in --data-dir") | |
cmd.Flags().StringVar(&c.WebInterfaceKey, "web-interface-key", c.WebInterfaceKey, "skycoind.key file for web interface HTTPS. If not provided, will autogenerate or use skycoind.key in --data-dir") | |
cmd.Flags().BoolVar(&c.WebInterfaceHTTPS, "web-interface-https", c.WebInterfaceHTTPS, "enable HTTPS for web interface") | |
cmd.Flags().StringVar(&c.HostWhitelist, "host-whitelist", c.HostWhitelist, "Hostnames to whitelist in the Host header check. Only applies when the web interface is bound to localhost.") | |
allAPISets := []string{ | |
api.EndpointsRead, | |
api.EndpointsStatus, | |
api.EndpointsWallet, | |
api.EndpointsTransaction, | |
api.EndpointsPrometheus, | |
api.EndpointsNetCtrl, | |
api.EndpointsInsecureWalletSeed, | |
api.EndpointsStorage, | |
} | |
cmd.Flags().StringVar(&c.EnabledAPISets, "enable-api-sets", c.EnabledAPISets, fmt.Sprintf("enable API set. Options are %s. Multiple values should be separated by comma", strings.Join(allAPISets, ", "))) | |
cmd.Flags().StringVar(&c.DisabledAPISets, "disable-api-sets", c.DisabledAPISets, fmt.Sprintf("disable API set. Options are %s. Multiple values should be separated by comma", strings.Join(allAPISets, ", "))) | |
cmd.Flags().BoolVar(&c.EnableAllAPISets, "enable-all-api-sets", c.EnableAllAPISets, "enable all API sets, except for deprecated or insecure sets. This option is applied before --disable-api-sets.") | |
cmd.Flags().StringVar(&c.WebInterfaceUsername, "web-interface-username", c.WebInterfaceUsername, "username for the web interface") | |
cmd.Flags().StringVar(&c.WebInterfacePassword, "web-interface-password", c.WebInterfacePassword, "password for the web interface") | |
cmd.Flags().BoolVar(&c.WebInterfacePlaintextAuth, "web-interface-plaintext-auth", c.WebInterfacePlaintextAuth, "allow web interface auth without https") | |
cmd.Flags().BoolVar(&c.LaunchBrowser, "launch-browser", c.LaunchBrowser, "launch system default webbrowser at client startup") | |
cmd.Flags().StringVar(&c.DataDirectory, "data-dir", c.DataDirectory, "directory to store app data (defaults to ~/.skycoin)") | |
cmd.Flags().StringVar(&c.DBPath, "db-path", c.DBPath, "path of database file (defaults to ~/.skycoin/data.db)") | |
cmd.Flags().BoolVar(&c.DBReadOnly, "db-read-only", c.DBReadOnly, "open bolt db read-only") | |
cmd.Flags().BoolVar(&c.ProfileCPU, "profile-cpu", c.ProfileCPU, "enable cpu profiling") | |
cmd.Flags().StringVar(&c.ProfileCPUFile, "profile-cpu-file", c.ProfileCPUFile, "where to write the cpu profile file") | |
cmd.Flags().BoolVar(&c.HTTPProf, "http-prof", c.HTTPProf, "run the HTTP profiling interface") | |
cmd.Flags().StringVar(&c.HTTPProfHost, "http-prof-host", c.HTTPProfHost, "hostname to bind the HTTP profiling interface to") | |
cmd.Flags().StringVar(&c.LogLevel, "log-level", c.LogLevel, "Choices are: debug, info, warn, error, fatal, panic") | |
cmd.Flags().BoolVar(&c.ColorLog, "color-log", c.ColorLog, "Add terminal colors to log output") | |
cmd.Flags().BoolVar(&c.DisablePingPong, "no-ping-log", c.DisablePingPong, `disable "reply to ping" and "received pong" debug log messages`) | |
cmd.Flags().BoolVar(&c.LogToFile, "logtofile", c.LogToFile, "log to file") | |
cmd.Flags().StringVar(&c.GUIDirectory, "gui-dir", c.GUIDirectory, "static content directory for the HTML interface") | |
cmd.Flags().BoolVar(&c.VerifyDB, "verify-db", c.VerifyDB, "check the database for corruption") | |
cmd.Flags().BoolVar(&c.ResetCorruptDB, "reset-corrupt-db", c.ResetCorruptDB, "reset the database if corrupted, and continue running instead of exiting") | |
cmd.Flags().BoolVar(&c.DisableDefaultPeers, "disable-default-peers", c.DisableDefaultPeers, "disable the hardcoded default peers") | |
cmd.Flags().StringVar(&c.CustomPeersFile, "custom-peers-file", c.CustomPeersFile, "load custom peers from a newline separate list of ip:port in a file. Note that this is different from the peers.json file in the data directory") | |
cmd.Flags().StringVar(&c.UserAgentRemark, "user-agent-remark", c.UserAgentRemark, "additional remark to include in the user agent sent over the wire protocol") | |
cmd.Flags().Uint64Var(&c.maxUnconfirmedTransactionSize, "max-txn-size-unconfirmed", uint64(c.UnconfirmedVerifyTxn.MaxTransactionSize), "maximum size of an unconfirmed transaction") | |
cmd.Flags().Uint64Var(&c.unconfirmedBurnFactor, "burn-factor-unconfirmed", uint64(c.UnconfirmedVerifyTxn.BurnFactor), "coinhour burn factor applied to unconfirmed transactions") | |
cmd.Flags().Uint64Var(&c.unconfirmedMaxDropletPrecision, "max-decimals-unconfirmed", uint64(c.UnconfirmedVerifyTxn.MaxDropletPrecision), "max number of decimal places applied to unconfirmed transactions") | |
cmd.Flags().Uint64Var(&c.createBlockBurnFactor, "burn-factor-create-block", uint64(c.CreateBlockVerifyTxn.BurnFactor), "coinhour burn factor applied when creating blocks") | |
cmd.Flags().Uint64Var(&c.createBlockMaxTransactionSize, "max-txn-size-create-block", uint64(c.CreateBlockVerifyTxn.MaxTransactionSize), "maximum size of a transaction applied when creating blocks") | |
cmd.Flags().Uint64Var(&c.createBlockMaxDropletPrecision, "max-decimals-create-block", uint64(c.CreateBlockVerifyTxn.MaxDropletPrecision), "max number of decimal places applied when creating blocks") | |
cmd.Flags().Uint64Var(&c.maxBlockSize, "max-block-size", uint64(c.MaxBlockTransactionsSize), "maximum total size of transactions in a block") | |
cmd.Flags().BoolVar(&c.RunBlockPublisher, "block-publisher", c.RunBlockPublisher, "run the daemon as a block publisher") | |
cmd.Flags().StringVar(&c.BlockchainPubkeyStr, "blockchain-public-key", c.BlockchainPubkeyStr, "public key of the blockchain") | |
cmd.Flags().StringVar(&c.BlockchainSeckeyStr, "blockchain-secret-key", c.BlockchainSeckeyStr, "secret key of the blockchain") | |
cmd.Flags().StringVar(&c.GenesisAddressStr, "genesis-address", c.GenesisAddressStr, "genesis address") | |
cmd.Flags().StringVar(&c.GenesisSignatureStr, "genesis-signature", c.GenesisSignatureStr, "genesis block signature") | |
cmd.Flags().Uint64Var(&c.GenesisTimestamp, "genesis-timestamp", c.GenesisTimestamp, "genesis block timestamp") | |
cmd.Flags().StringVar(&c.WalletDirectory, "wallet-dir", c.WalletDirectory, "location of the wallet files. Defaults to ~/.skycoin/wallet/") | |
cmd.Flags().StringVar(&c.KVStorageDirectory, "storage-dir", c.KVStorageDirectory, "location of the storage data files. Defaults to ~/.skycoin/data/") | |
cmd.Flags().IntVar(&c.MaxConnections, "max-connections", c.MaxConnections, "Maximum number of total connections allowed") | |
cmd.Flags().IntVar(&c.MaxOutgoingConnections, "max-outgoing-connections", c.MaxOutgoingConnections, "Maximum number of outgoing connections allowed") | |
cmd.Flags().IntVar(&c.MaxDefaultPeerOutgoingConnections, "max-default-peer-outgoing-connections", c.MaxDefaultPeerOutgoingConnections, "The maximum default peer outgoing connections allowed") | |
cmd.Flags().IntVar(&c.PeerlistSize, "peerlist-size", c.PeerlistSize, "Max number of peers to track in peerlist") | |
cmd.Flags().DurationVar(&c.OutgoingConnectionsRate, "connection-rate", c.OutgoingConnectionsRate, "How often to make an outgoing connection") | |
cmd.Flags().IntVar(&c.MaxOutgoingMessageLength, "max-out-msg-len", c.MaxOutgoingMessageLength, "Maximum length of outgoing wire messages") | |
cmd.Flags().IntVar(&c.MaxIncomingMessageLength, "max-in-msg-len", c.MaxIncomingMessageLength, "Maximum length of incoming wire messages") | |
cmd.Flags().BoolVar(&c.LocalhostOnly, "localhost-only", c.LocalhostOnly, "Run on localhost and only connect to localhost peers") | |
cmd.Flags().StringVar(&c.WalletCryptoType, "wallet-crypto-type", c.WalletCryptoType, "wallet crypto type. Can be sha256-xor or scrypt-chacha20poly1305") | |
cmd.Flags().BoolVar(&c.Version, "version", false, "show node version") | |
bindConfigFlag(cmd, "port", "port") | |
bindConfigFlag(cmd, "web_interface_port", "web-interface-port") | |
bindConfigFlag(cmd, "unconfirmed_burn_factor", "burn-factor-unconfirmed") | |
bindConfigFlag(cmd, "unconfirmed_max_transaction_size", "max-txn-size-unconfirmed") | |
bindConfigFlag(cmd, "unconfirmed_max_decimals", "max-decimals-unconfirmed") | |
bindConfigFlag(cmd, "create_block_burn_factor", "burn-factor-create-block") | |
bindConfigFlag(cmd, "create_block_max_transaction_size", "max-txn-size-create-block") | |
bindConfigFlag(cmd, "create_block_max_decimals", "max-decimals-create-block") | |
bindConfigFlag(cmd, "max_block_transactions_size", "max-block-size") | |
// TODO -- not defined in CLI yet, but are in skyfiber.toml | |
// bindConfigFlag(cmd, "display_name", "display-name") | |
// bindConfigFlag(cmd, "ticker", "ticker") | |
// bindConfigFlag(cmd, "coin_hours_display_name", "coin-hours-display-name") | |
// bindConfigFlag(cmd, "coin_hours_display_name_singular", "coin-hours-display-name-singular") | |
// bindConfigFlag(cmd, "coin_hours_ticker", "coin-hours-ticker") | |
// bindConfigFlag(cmd, "explorer_url", "explorer-url") | |
// bindConfigFlag(cmd, "bip44_coin", "bip44-coin") | |
// distribution params | |
// bindConfigFlag(cmd, "max_coin_supply", "max-coin-supply") | |
// bindConfigFlag(cmd, "initial_unlocked_count", "initial-unlocked-count") | |
// bindConfigFlag(cmd, "unlock_address_rate", "unlock-address-rate") | |
// bindConfigFlag(cmd, "unlock_time_interval", "unlock-time-interval") | |
// TODO -- a distribution addresses flag would need special parsing? | |
// Doesn't really belong as a CLI flag, but for consistency... | |
// bindConfigFlag(cmd, "distribution_addresses", "distribution-addresses") | |
// user verifyTxnParams | |
bindConfigFlag(cmd, "user_burn_factor", "burn-factor-user") | |
bindConfigFlag(cmd, "user_max_decimals", "max-decimals-user") | |
bindConfigFlag(cmd, "user_max_transaction_size", "max-txn-size-user") | |
bindConfigFlag(cmd, "genesis_signature_str", "genesis-signature") | |
bindConfigFlag(cmd, "genesis_address_str", "genesis-address") | |
bindConfigFlag(cmd, "blockchain_pubkey", "blockchain-public-key") | |
bindConfigFlag(cmd, "blockchain_seckey", "blockchain-secret-key") | |
bindConfigFlag(cmd, "genesis_timestamp", "genesis-timestamp") | |
// TODO - this flag is a duplicate of max_coin_supply except measured in droplets | |
// instead of in coins. We can remove it. | |
// bindConfigFlag(cmd, "genesis_coin_volume", "genesis-coin-volume") | |
// TODO -- would need special parsing (array) | |
// bindConfigFlag(cmd, "default_connections", "default-connections") | |
bindConfigFlag(cmd, "peer_list_url", "peerlist-url") | |
} | |
func setDefaults() { | |
// node defaults | |
// viper.SetDefault("genesis_coin_volume", 100e12) | |
viper.SetDefault("port", 6000) | |
viper.SetDefault("web_interface_port", 6420) | |
viper.SetDefault("unconfirmed_burn_factor", 10) | |
viper.SetDefault("unconfirmed_max_transaction_size", 32*1024) | |
viper.SetDefault("unconfirmed_max_decimals", 3) | |
viper.SetDefault("create_block_burn_factor", 10) | |
viper.SetDefault("create_block_max_transaction_size", 32*1024) | |
viper.SetDefault("create_block_max_decimals", 3) | |
viper.SetDefault("max_block_transactions_size", 32*1024) | |
viper.SetDefault("display_name", "Skycoin") | |
viper.SetDefault("ticker", "SKY") | |
viper.SetDefault("coin_hours_display_name", "Coin Hours") | |
viper.SetDefault("coin_hours_display_name_singular", "Coin Hour") | |
viper.SetDefault("coin_hours_ticker", "SCH") | |
viper.SetDefault("explorer_url", "https://explorer.skycoin.net") | |
viper.SetDefault("bip44_coin", bip44.CoinTypeSkycoin) | |
viper.SetDefault("max_coin_supply", 1e8) | |
viper.SetDefault("initial_unlocked_count", 25) | |
viper.SetDefault("unlock_address_rate", 5) | |
viper.SetDefault("unlock_time_interval", 60*60*24*365) | |
viper.SetDefault("user_max_decimals", 3) | |
viper.SetDefault("user_burn_factor", 10) | |
viper.SetDefault("user_max_transaction_size", 32*1024) | |
} | |
// SetupConfig sets up the root command | |
func SetupConfig(cfg *NodeConfig) { | |
setupRootCommand(cfg) | |
// This line allows test binary flags to cooperate with our own flags | |
// pflag.CommandLine.AddGoFlagSet(flag.CommandLine) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment