How to use AssetTypeEnabled method of asset Package

Best Syzkaller code snippet using asset.AssetTypeEnabled

config.go

Source:config.go Github

copy

Full Screen

...433 atLeastOneEnabled = true434 continue435 }436 var enabled bool437 enabled, err = c.AssetTypeEnabled(assetTypes[x], exchName)438 if err != nil {439 return err440 }441 if !enabled {442 continue443 }444 var availPairs currency.Pairs445 availPairs, err = c.GetAvailablePairs(exchName, assetTypes[x])446 if err != nil {447 return err448 }449 err = c.SetPairs(exchName,450 assetTypes[x],451 true,452 currency.Pairs{availPairs.GetRandomPair()})453 if err != nil {454 return err455 }456 atLeastOneEnabled = true457 continue458 }459 // On error an enabled pair is not found in the available pairs list460 // so remove and report461 availPairs, err := c.GetAvailablePairs(exchName, assetTypes[x])462 if err != nil {463 return err464 }465 var pairs, pairsRemoved currency.Pairs466 for x := range enabledPairs {467 if !availPairs.Contains(enabledPairs[x], true) {468 pairsRemoved = append(pairsRemoved, enabledPairs[x])469 continue470 }471 pairs = append(pairs, enabledPairs[x])472 }473 if len(pairsRemoved) == 0 {474 return fmt.Errorf("check pair consistency fault for asset %s, conflict found but no pairs removed",475 assetTypes[x])476 }477 // Flush corrupted/misspelled enabled pairs in config478 err = c.SetPairs(exchName, assetTypes[x], true, pairs)479 if err != nil {480 return err481 }482 log.Warnf(log.ConfigMgr,483 "Exchange %s: [%v] Removing enabled pair(s) %v from enabled pairs list, as it isn't located in the available pairs list.\n",484 exchName,485 assetTypes[x],486 pairsRemoved.Strings())487 if len(pairs) != 0 {488 atLeastOneEnabled = true489 continue490 }491 enabled, err := c.AssetTypeEnabled(assetTypes[x], exchName)492 if err != nil {493 return err494 }495 if !enabled {496 continue497 }498 err = c.SetPairs(exchName,499 assetTypes[x],500 true,501 currency.Pairs{availPairs.GetRandomPair()})502 if err != nil {503 return err504 }505 atLeastOneEnabled = true506 }507 // If no pair is enabled across the entire range of assets, then atleast508 // enable one and turn on the asset type509 if !atLeastOneEnabled {510 avail, err := c.GetAvailablePairs(exchName, assetTypes[0])511 if err != nil {512 return err513 }514 newPair := avail.GetRandomPair()515 err = c.SetPairs(exchName, assetTypes[0], true, currency.Pairs{newPair})516 if err != nil {517 return err518 }519 log.Warnf(log.ConfigMgr,520 "Exchange %s: [%v] No enabled pairs found in available pairs list, randomly added %v pair.\n",521 exchName,522 assetTypes[0],523 newPair)524 }525 return nil526}527// SupportsPair returns true or not whether the exchange supports the supplied528// pair529func (c *Config) SupportsPair(exchName string, p currency.Pair, assetType asset.Item) bool {530 pairs, err := c.GetAvailablePairs(exchName, assetType)531 if err != nil {532 return false533 }534 return pairs.Contains(p, false)535}536// GetPairFormat returns the exchanges pair config storage format537func (c *Config) GetPairFormat(exchName string, assetType asset.Item) (currency.PairFormat, error) {538 exchCfg, err := c.GetExchangeConfig(exchName)539 if err != nil {540 return currency.PairFormat{}, err541 }542 err = c.SupportsExchangeAssetType(exchName, assetType)543 if err != nil {544 return currency.PairFormat{}, err545 }546 if exchCfg.CurrencyPairs.UseGlobalFormat {547 return *exchCfg.CurrencyPairs.ConfigFormat, nil548 }549 p, err := exchCfg.CurrencyPairs.Get(assetType)550 if err != nil {551 return currency.PairFormat{}, err552 }553 if p == nil {554 return currency.PairFormat{},555 fmt.Errorf("exchange %s pair store for asset type %s is nil",556 exchName,557 assetType)558 }559 if p.ConfigFormat == nil {560 return currency.PairFormat{},561 fmt.Errorf("exchange %s pair config format for asset type %s is nil",562 exchName,563 assetType)564 }565 return *p.ConfigFormat, nil566}567// GetAvailablePairs returns a list of currency pairs for a specifc exchange568func (c *Config) GetAvailablePairs(exchName string, assetType asset.Item) (currency.Pairs, error) {569 exchCfg, err := c.GetExchangeConfig(exchName)570 if err != nil {571 return nil, err572 }573 pairFormat, err := c.GetPairFormat(exchName, assetType)574 if err != nil {575 return nil, err576 }577 pairs, err := exchCfg.CurrencyPairs.GetPairs(assetType, false)578 if err != nil {579 return nil, err580 }581 if pairs == nil {582 return nil, nil583 }584 return pairs.Format(pairFormat.Delimiter, pairFormat.Index,585 pairFormat.Uppercase), nil586}587// GetEnabledPairs returns a list of currency pairs for a specifc exchange588func (c *Config) GetEnabledPairs(exchName string, assetType asset.Item) (currency.Pairs, error) {589 exchCfg, err := c.GetExchangeConfig(exchName)590 if err != nil {591 return nil, err592 }593 pairFormat, err := c.GetPairFormat(exchName, assetType)594 if err != nil {595 return nil, err596 }597 pairs, err := exchCfg.CurrencyPairs.GetPairs(assetType, true)598 if err != nil {599 return pairs, err600 }601 if pairs == nil {602 return nil, nil603 }604 return pairs.Format(pairFormat.Delimiter,605 pairFormat.Index,606 pairFormat.Uppercase),607 nil608}609// GetEnabledExchanges returns a list of enabled exchanges610func (c *Config) GetEnabledExchanges() []string {611 var enabledExchs []string612 for i := range c.Exchanges {613 if c.Exchanges[i].Enabled {614 enabledExchs = append(enabledExchs, c.Exchanges[i].Name)615 }616 }617 return enabledExchs618}619// GetDisabledExchanges returns a list of disabled exchanges620func (c *Config) GetDisabledExchanges() []string {621 var disabledExchs []string622 for i := range c.Exchanges {623 if !c.Exchanges[i].Enabled {624 disabledExchs = append(disabledExchs, c.Exchanges[i].Name)625 }626 }627 return disabledExchs628}629// CountEnabledExchanges returns the number of exchanges that are enabled.630func (c *Config) CountEnabledExchanges() int {631 counter := 0632 for i := range c.Exchanges {633 if c.Exchanges[i].Enabled {634 counter++635 }636 }637 return counter638}639// GetCurrencyPairDisplayConfig retrieves the currency pair display preference640func (c *Config) GetCurrencyPairDisplayConfig() *currency.PairFormat {641 return c.Currency.CurrencyPairFormat642}643// GetAllExchangeConfigs returns all exchange configurations644func (c *Config) GetAllExchangeConfigs() []Exchange {645 m.Lock()646 configs := c.Exchanges647 m.Unlock()648 return configs649}650// GetExchangeConfig returns exchange configurations by its indivdual name651func (c *Config) GetExchangeConfig(name string) (*Exchange, error) {652 m.Lock()653 defer m.Unlock()654 for i := range c.Exchanges {655 if strings.EqualFold(c.Exchanges[i].Name, name) {656 return &c.Exchanges[i], nil657 }658 }659 return nil, fmt.Errorf("%s %w", name, ErrExchangeNotFound)660}661// UpdateExchangeConfig updates exchange configurations662func (c *Config) UpdateExchangeConfig(e *Exchange) error {663 m.Lock()664 defer m.Unlock()665 for i := range c.Exchanges {666 if strings.EqualFold(c.Exchanges[i].Name, e.Name) {667 c.Exchanges[i] = *e668 return nil669 }670 }671 return fmt.Errorf("%s %w", e.Name, ErrExchangeNotFound)672}673// CheckExchangeConfigValues returns configuation values for all enabled674// exchanges675func (c *Config) CheckExchangeConfigValues() error {676 if len(c.Exchanges) == 0 {677 return errors.New("no exchange configs found")678 }679 exchanges := 0680 for i := range c.Exchanges {681 if strings.EqualFold(c.Exchanges[i].Name, "GDAX") {682 c.Exchanges[i].Name = "CoinbasePro"683 }684 // Check to see if the old API storage format is used685 if c.Exchanges[i].APIKey != nil {686 // It is, migrate settings to new format687 c.Exchanges[i].API.AuthenticatedSupport = *c.Exchanges[i].AuthenticatedAPISupport688 if c.Exchanges[i].AuthenticatedWebsocketAPISupport != nil {689 c.Exchanges[i].API.AuthenticatedWebsocketSupport = *c.Exchanges[i].AuthenticatedWebsocketAPISupport690 }691 c.Exchanges[i].API.Credentials.Key = *c.Exchanges[i].APIKey692 c.Exchanges[i].API.Credentials.Secret = *c.Exchanges[i].APISecret693 if c.Exchanges[i].APIAuthPEMKey != nil {694 c.Exchanges[i].API.Credentials.PEMKey = *c.Exchanges[i].APIAuthPEMKey695 }696 if c.Exchanges[i].APIAuthPEMKeySupport != nil {697 c.Exchanges[i].API.PEMKeySupport = *c.Exchanges[i].APIAuthPEMKeySupport698 }699 if c.Exchanges[i].ClientID != nil {700 c.Exchanges[i].API.Credentials.ClientID = *c.Exchanges[i].ClientID701 }702 // Flush settings703 c.Exchanges[i].AuthenticatedAPISupport = nil704 c.Exchanges[i].AuthenticatedWebsocketAPISupport = nil705 c.Exchanges[i].APIKey = nil706 c.Exchanges[i].APISecret = nil707 c.Exchanges[i].ClientID = nil708 c.Exchanges[i].APIAuthPEMKeySupport = nil709 c.Exchanges[i].APIAuthPEMKey = nil710 c.Exchanges[i].APIURL = nil711 c.Exchanges[i].APIURLSecondary = nil712 c.Exchanges[i].WebsocketURL = nil713 }714 if c.Exchanges[i].Features == nil {715 c.Exchanges[i].Features = &FeaturesConfig{}716 }717 if c.Exchanges[i].SupportsAutoPairUpdates != nil {718 c.Exchanges[i].Features.Supports.RESTCapabilities.AutoPairUpdates = *c.Exchanges[i].SupportsAutoPairUpdates719 c.Exchanges[i].Features.Enabled.AutoPairUpdates = *c.Exchanges[i].SupportsAutoPairUpdates720 c.Exchanges[i].SupportsAutoPairUpdates = nil721 }722 if c.Exchanges[i].Websocket != nil {723 c.Exchanges[i].Features.Enabled.Websocket = *c.Exchanges[i].Websocket724 c.Exchanges[i].Websocket = nil725 }726 // Check if see if the new currency pairs format is empty and flesh it out if so727 if c.Exchanges[i].CurrencyPairs == nil {728 c.Exchanges[i].CurrencyPairs = new(currency.PairsManager)729 c.Exchanges[i].CurrencyPairs.Pairs = make(map[asset.Item]*currency.PairStore)730 if c.Exchanges[i].PairsLastUpdated != nil {731 c.Exchanges[i].CurrencyPairs.LastUpdated = *c.Exchanges[i].PairsLastUpdated732 }733 c.Exchanges[i].CurrencyPairs.ConfigFormat = c.Exchanges[i].ConfigCurrencyPairFormat734 c.Exchanges[i].CurrencyPairs.RequestFormat = c.Exchanges[i].RequestCurrencyPairFormat735 var availPairs, enabledPairs currency.Pairs736 if c.Exchanges[i].AvailablePairs != nil {737 availPairs = *c.Exchanges[i].AvailablePairs738 }739 if c.Exchanges[i].EnabledPairs != nil {740 enabledPairs = *c.Exchanges[i].EnabledPairs741 }742 c.Exchanges[i].CurrencyPairs.UseGlobalFormat = true743 c.Exchanges[i].CurrencyPairs.Store(asset.Spot,744 currency.PairStore{745 AssetEnabled: convert.BoolPtr(true),746 Available: availPairs,747 Enabled: enabledPairs,748 },749 )750 // flush old values751 c.Exchanges[i].PairsLastUpdated = nil752 c.Exchanges[i].ConfigCurrencyPairFormat = nil753 c.Exchanges[i].RequestCurrencyPairFormat = nil754 c.Exchanges[i].AssetTypes = nil755 c.Exchanges[i].AvailablePairs = nil756 c.Exchanges[i].EnabledPairs = nil757 } else {758 assets := c.Exchanges[i].CurrencyPairs.GetAssetTypes(false)759 if len(assets) == 0 {760 c.Exchanges[i].Enabled = false761 log.Warnf(log.ConfigMgr, "%s no assets found, disabling...", c.Exchanges[i].Name)762 continue763 }764 var atLeastOne bool765 for index := range assets {766 err := c.Exchanges[i].CurrencyPairs.IsAssetEnabled(assets[index])767 if err != nil {768 if errors.Is(err, currency.ErrAssetIsNil) {769 // Checks if we have an old config without the ability to770 // enable disable the entire asset771 log.Warnf(log.ConfigMgr,772 "Exchange %s: upgrading config for asset type %s and setting enabled.\n",773 c.Exchanges[i].Name,774 assets[index])775 err = c.Exchanges[i].CurrencyPairs.SetAssetEnabled(assets[index], true)776 if err != nil {777 return err778 }779 atLeastOne = true780 }781 continue782 }783 atLeastOne = true784 }785 if !atLeastOne {786 // turn on an asset if all disabled787 log.Warnf(log.ConfigMgr,788 "%s assets disabled, turning on asset %s",789 c.Exchanges[i].Name,790 assets[0])791 err := c.Exchanges[i].CurrencyPairs.SetAssetEnabled(assets[0], true)792 if err != nil {793 return err794 }795 }796 }797 if c.Exchanges[i].Enabled {798 if c.Exchanges[i].Name == "" {799 log.Errorf(log.ConfigMgr, ErrExchangeNameEmpty, i)800 c.Exchanges[i].Enabled = false801 continue802 }803 if (c.Exchanges[i].API.AuthenticatedSupport || c.Exchanges[i].API.AuthenticatedWebsocketSupport) &&804 c.Exchanges[i].API.CredentialsValidator != nil {805 var failed bool806 if c.Exchanges[i].API.CredentialsValidator.RequiresKey &&807 (c.Exchanges[i].API.Credentials.Key == "" || c.Exchanges[i].API.Credentials.Key == DefaultAPIKey) {808 failed = true809 }810 if c.Exchanges[i].API.CredentialsValidator.RequiresSecret &&811 (c.Exchanges[i].API.Credentials.Secret == "" || c.Exchanges[i].API.Credentials.Secret == DefaultAPISecret) {812 failed = true813 }814 if c.Exchanges[i].API.CredentialsValidator.RequiresClientID &&815 (c.Exchanges[i].API.Credentials.ClientID == DefaultAPIClientID || c.Exchanges[i].API.Credentials.ClientID == "") {816 failed = true817 }818 if failed {819 c.Exchanges[i].API.AuthenticatedSupport = false820 c.Exchanges[i].API.AuthenticatedWebsocketSupport = false821 log.Warnf(log.ConfigMgr, WarningExchangeAuthAPIDefaultOrEmptyValues, c.Exchanges[i].Name)822 }823 }824 if !c.Exchanges[i].Features.Supports.RESTCapabilities.AutoPairUpdates &&825 !c.Exchanges[i].Features.Supports.WebsocketCapabilities.AutoPairUpdates {826 lastUpdated := convert.UnixTimestampToTime(c.Exchanges[i].CurrencyPairs.LastUpdated)827 lastUpdated = lastUpdated.AddDate(0, 0, pairsLastUpdatedWarningThreshold)828 if lastUpdated.Unix() <= time.Now().Unix() {829 log.Warnf(log.ConfigMgr,830 WarningPairsLastUpdatedThresholdExceeded,831 c.Exchanges[i].Name,832 pairsLastUpdatedWarningThreshold)833 }834 }835 if c.Exchanges[i].HTTPTimeout <= 0 {836 log.Warnf(log.ConfigMgr,837 "Exchange %s HTTP Timeout value not set, defaulting to %v.\n",838 c.Exchanges[i].Name,839 defaultHTTPTimeout)840 c.Exchanges[i].HTTPTimeout = defaultHTTPTimeout841 }842 if c.Exchanges[i].WebsocketResponseCheckTimeout <= 0 {843 log.Warnf(log.ConfigMgr,844 "Exchange %s Websocket response check timeout value not set, defaulting to %v.",845 c.Exchanges[i].Name,846 defaultWebsocketResponseCheckTimeout)847 c.Exchanges[i].WebsocketResponseCheckTimeout = defaultWebsocketResponseCheckTimeout848 }849 if c.Exchanges[i].WebsocketResponseMaxLimit <= 0 {850 log.Warnf(log.ConfigMgr,851 "Exchange %s Websocket response max limit value not set, defaulting to %v.",852 c.Exchanges[i].Name,853 defaultWebsocketResponseMaxLimit)854 c.Exchanges[i].WebsocketResponseMaxLimit = defaultWebsocketResponseMaxLimit855 }856 if c.Exchanges[i].WebsocketTrafficTimeout <= 0 {857 log.Warnf(log.ConfigMgr,858 "Exchange %s Websocket response traffic timeout value not set, defaulting to %v.",859 c.Exchanges[i].Name,860 defaultWebsocketTrafficTimeout)861 c.Exchanges[i].WebsocketTrafficTimeout = defaultWebsocketTrafficTimeout862 }863 if c.Exchanges[i].Orderbook.WebsocketBufferLimit <= 0 {864 log.Warnf(log.ConfigMgr,865 "Exchange %s Websocket orderbook buffer limit value not set, defaulting to %v.",866 c.Exchanges[i].Name,867 defaultWebsocketOrderbookBufferLimit)868 c.Exchanges[i].Orderbook.WebsocketBufferLimit = defaultWebsocketOrderbookBufferLimit869 }870 if c.Exchanges[i].Orderbook.PublishPeriod == nil || c.Exchanges[i].Orderbook.PublishPeriod.Nanoseconds() < 0 {871 log.Warnf(log.ConfigMgr,872 "Exchange %s Websocket orderbook publish period value not set, defaulting to %v.",873 c.Exchanges[i].Name,874 DefaultOrderbookPublishPeriod)875 publishPeriod := DefaultOrderbookPublishPeriod876 c.Exchanges[i].Orderbook.PublishPeriod = &publishPeriod877 }878 err := c.CheckPairConsistency(c.Exchanges[i].Name)879 if err != nil {880 log.Errorf(log.ConfigMgr,881 "Exchange %s: CheckPairConsistency error: %s\n",882 c.Exchanges[i].Name,883 err)884 c.Exchanges[i].Enabled = false885 continue886 }887 for x := range c.Exchanges[i].BankAccounts {888 if !c.Exchanges[i].BankAccounts[x].Enabled {889 continue890 }891 err := c.Exchanges[i].BankAccounts[x].Validate()892 if err != nil {893 c.Exchanges[i].BankAccounts[x].Enabled = false894 log.Warnln(log.ConfigMgr, err.Error())895 }896 }897 exchanges++898 }899 }900 if exchanges == 0 {901 return errors.New(ErrNoEnabledExchanges)902 }903 return nil904}905// CheckBankAccountConfig checks all bank accounts to see if they are valid906func (c *Config) CheckBankAccountConfig() {907 for x := range c.BankAccounts {908 if c.BankAccounts[x].Enabled {909 err := c.BankAccounts[x].Validate()910 if err != nil {911 c.BankAccounts[x].Enabled = false912 log.Warn(log.ConfigMgr, err.Error())913 }914 }915 }916 banking.SetAccounts(c.BankAccounts...)917}918// GetForexProviders returns a list of available forex providers919func (c *Config) GetForexProviders() []currency.FXSettings {920 m.Lock()921 fxProviders := c.Currency.ForexProviders922 m.Unlock()923 return fxProviders924}925// GetPrimaryForexProvider returns the primary forex provider926func (c *Config) GetPrimaryForexProvider() string {927 m.Lock()928 defer m.Unlock()929 for i := range c.Currency.ForexProviders {930 if c.Currency.ForexProviders[i].PrimaryProvider {931 return c.Currency.ForexProviders[i].Name932 }933 }934 return ""935}936// forexProviderExists checks to see if the provider exist.937func (c *Config) forexProviderExists(name string) bool {938 for i := range c.Currency.ForexProviders {939 if strings.EqualFold(c.Currency.ForexProviders[i].Name, name) {940 return true941 }942 }943 return false944}945// CheckCurrencyConfigValues checks to see if the currency config values are946// correct or not947func (c *Config) CheckCurrencyConfigValues() error {948 supported := forexprovider.GetSupportedForexProviders()949 for x := range supported {950 if !c.forexProviderExists(supported[x]) {951 log.Warnf(log.ConfigMgr, "%s forex provider not found, adding to config...\n", supported[x])952 c.Currency.ForexProviders = append(c.Currency.ForexProviders,953 currency.FXSettings{954 Name: supported[x],955 APIKey: DefaultUnsetAPIKey,956 APIKeyLvl: -1,957 })958 }959 }960 for i := range c.Currency.ForexProviders {961 if !common.StringDataContainsInsensitive(supported, c.Currency.ForexProviders[i].Name) {962 log.Warnf(log.ConfigMgr,963 "%s forex provider not supported, please remove from config.\n",964 c.Currency.ForexProviders[i].Name)965 c.Currency.ForexProviders[i].Enabled = false966 }967 }968 if c.Currency.CryptocurrencyProvider == (currency.Provider{}) {969 c.Currency.CryptocurrencyProvider.Name = "CoinMarketCap"970 c.Currency.CryptocurrencyProvider.Enabled = false971 c.Currency.CryptocurrencyProvider.Verbose = false972 c.Currency.CryptocurrencyProvider.AccountPlan = DefaultUnsetAccountPlan973 c.Currency.CryptocurrencyProvider.APIKey = DefaultUnsetAPIKey974 }975 if c.Currency.CryptocurrencyProvider.APIKey == "" {976 c.Currency.CryptocurrencyProvider.APIKey = DefaultUnsetAPIKey977 }978 if c.Currency.CryptocurrencyProvider.AccountPlan == "" {979 c.Currency.CryptocurrencyProvider.AccountPlan = DefaultUnsetAccountPlan980 }981 if c.Currency.CurrencyPairFormat == nil {982 if c.CurrencyPairFormat != nil {983 c.Currency.CurrencyPairFormat = c.CurrencyPairFormat984 c.CurrencyPairFormat = nil985 } else {986 c.Currency.CurrencyPairFormat = &currency.PairFormat{987 Delimiter: "-",988 Uppercase: true,989 }990 }991 }992 if c.Currency.FiatDisplayCurrency.IsEmpty() {993 if c.FiatDisplayCurrency != nil {994 c.Currency.FiatDisplayCurrency = *c.FiatDisplayCurrency995 c.FiatDisplayCurrency = nil996 } else {997 c.Currency.FiatDisplayCurrency = currency.USD998 }999 }1000 // Flush old setting which still exists1001 if c.FiatDisplayCurrency != nil {1002 c.FiatDisplayCurrency = nil1003 }1004 if c.Currency.CurrencyFileUpdateDuration <= 0 {1005 log.Warnf(log.ConfigMgr, "Currency file update duration invalid, defaulting to %s", currency.DefaultCurrencyFileDelay)1006 c.Currency.CurrencyFileUpdateDuration = currency.DefaultCurrencyFileDelay1007 }1008 if c.Currency.ForeignExchangeUpdateDuration <= 0 {1009 log.Warnf(log.ConfigMgr, "Currency foreign exchange update duration invalid, defaulting to %s", currency.DefaultForeignExchangeDelay)1010 c.Currency.ForeignExchangeUpdateDuration = currency.DefaultForeignExchangeDelay1011 }1012 return nil1013}1014// CheckLoggerConfig checks to see logger values are present and valid in config1015// if not creates a default instance of the logger1016func (c *Config) CheckLoggerConfig() error {1017 m.Lock()1018 defer m.Unlock()1019 if c.Logging.Enabled == nil || c.Logging.Output == "" {1020 c.Logging = *log.GenDefaultSettings()1021 }1022 if c.Logging.AdvancedSettings.ShowLogSystemName == nil {1023 c.Logging.AdvancedSettings.ShowLogSystemName = convert.BoolPtr(false)1024 }1025 if c.Logging.LoggerFileConfig != nil {1026 if c.Logging.LoggerFileConfig.FileName == "" {1027 c.Logging.LoggerFileConfig.FileName = "log.txt"1028 }1029 if c.Logging.LoggerFileConfig.Rotate == nil {1030 c.Logging.LoggerFileConfig.Rotate = convert.BoolPtr(false)1031 }1032 if c.Logging.LoggerFileConfig.MaxSize <= 0 {1033 log.Warnf(log.ConfigMgr, "Logger rotation size invalid, defaulting to %v", log.DefaultMaxFileSize)1034 c.Logging.LoggerFileConfig.MaxSize = log.DefaultMaxFileSize1035 }1036 log.FileLoggingConfiguredCorrectly = true1037 }1038 log.RWM.Lock()1039 log.GlobalLogConfig = &c.Logging1040 log.RWM.Unlock()1041 logPath := c.GetDataPath("logs")1042 err := common.CreateDir(logPath)1043 if err != nil {1044 return err1045 }1046 log.LogPath = logPath1047 return nil1048}1049func (c *Config) checkGCTScriptConfig() error {1050 m.Lock()1051 defer m.Unlock()1052 if c.GCTScript.ScriptTimeout <= 0 {1053 c.GCTScript.ScriptTimeout = gctscript.DefaultTimeoutValue1054 }1055 if c.GCTScript.MaxVirtualMachines == 0 {1056 c.GCTScript.MaxVirtualMachines = gctscript.DefaultMaxVirtualMachines1057 }1058 scriptPath := c.GetDataPath("scripts")1059 err := common.CreateDir(scriptPath)1060 if err != nil {1061 return err1062 }1063 outputPath := filepath.Join(scriptPath, "output")1064 err = common.CreateDir(outputPath)1065 if err != nil {1066 return err1067 }1068 gctscript.ScriptPath = scriptPath1069 return nil1070}1071func (c *Config) checkDatabaseConfig() error {1072 m.Lock()1073 defer m.Unlock()1074 if (c.Database == database.Config{}) {1075 c.Database.Driver = database.DBSQLite31076 c.Database.Database = database.DefaultSQLiteDatabase1077 }1078 if !c.Database.Enabled {1079 return nil1080 }1081 if !common.StringDataCompare(database.SupportedDrivers, c.Database.Driver) {1082 c.Database.Enabled = false1083 return fmt.Errorf("unsupported database driver %v, database disabled", c.Database.Driver)1084 }1085 if c.Database.Driver == database.DBSQLite || c.Database.Driver == database.DBSQLite3 {1086 databaseDir := c.GetDataPath("database")1087 err := common.CreateDir(databaseDir)1088 if err != nil {1089 return err1090 }1091 database.DB.DataPath = databaseDir1092 }1093 return database.DB.SetConfig(&c.Database)1094}1095// CheckNTPConfig checks for missing or incorrectly configured NTPClient and recreates with known safe defaults1096func (c *Config) CheckNTPConfig() {1097 m.Lock()1098 defer m.Unlock()1099 if c.NTPClient.AllowedDifference == nil || *c.NTPClient.AllowedDifference == 0 {1100 c.NTPClient.AllowedDifference = new(time.Duration)1101 *c.NTPClient.AllowedDifference = defaultNTPAllowedDifference1102 }1103 if c.NTPClient.AllowedNegativeDifference == nil || *c.NTPClient.AllowedNegativeDifference <= 0 {1104 c.NTPClient.AllowedNegativeDifference = new(time.Duration)1105 *c.NTPClient.AllowedNegativeDifference = defaultNTPAllowedNegativeDifference1106 }1107 if len(c.NTPClient.Pool) < 1 {1108 log.Warnln(log.ConfigMgr, "NTPClient enabled with no servers configured, enabling default pool.")1109 c.NTPClient.Pool = []string{"pool.ntp.org:123"}1110 }1111}1112// SetNTPCheck allows the user to change how they are prompted for timesync alerts1113func (c *Config) SetNTPCheck(input io.Reader) (string, error) {1114 m.Lock()1115 defer m.Unlock()1116 reader := bufio.NewReader(input)1117 log.Warnln(log.ConfigMgr, "Your system time is out of sync, this may cause issues with trading")1118 log.Warnln(log.ConfigMgr, "How would you like to show future notifications? (a)lert at startup / (w)arn periodically / (d)isable")1119 var resp string1120 answered := false1121 for !answered {1122 answer, err := reader.ReadString('\n')1123 if err != nil {1124 return resp, err1125 }1126 answer = strings.TrimRight(answer, "\r\n")1127 switch answer {1128 case "a":1129 c.NTPClient.Level = 01130 resp = "Time sync has been set to alert"1131 answered = true1132 case "w":1133 c.NTPClient.Level = 11134 resp = "Time sync has been set to warn only"1135 answered = true1136 case "d":1137 c.NTPClient.Level = -11138 resp = "Future notifications for out of time sync has been disabled"1139 answered = true1140 default:1141 log.Warnln(log.ConfigMgr,1142 "Invalid option selected, please try again (a)lert / (w)arn / (d)isable")1143 }1144 }1145 return resp, nil1146}1147// CheckDataHistoryMonitorConfig ensures the data history config is1148// valid, or sets default values1149func (c *Config) CheckDataHistoryMonitorConfig() {1150 m.Lock()1151 defer m.Unlock()1152 if c.DataHistoryManager.CheckInterval <= 0 {1153 c.DataHistoryManager.CheckInterval = defaultDataHistoryMonitorCheckTimer1154 }1155 if c.DataHistoryManager.MaxJobsPerCycle == 0 {1156 c.DataHistoryManager.MaxJobsPerCycle = defaultMaxJobsPerCycle1157 }1158}1159// CheckCurrencyStateManager ensures the currency state config is valid, or sets1160// default values1161func (c *Config) CheckCurrencyStateManager() {1162 m.Lock()1163 defer m.Unlock()1164 if c.CurrencyStateManager.Delay <= 0 {1165 c.CurrencyStateManager.Delay = defaultCurrencyStateManagerDelay1166 }1167 if c.CurrencyStateManager.Enabled == nil { // default on, when being upgraded1168 c.CurrencyStateManager.Enabled = convert.BoolPtr(true)1169 }1170}1171// CheckConnectionMonitorConfig checks and if zero value assigns default values1172func (c *Config) CheckConnectionMonitorConfig() {1173 m.Lock()1174 defer m.Unlock()1175 if c.ConnectionMonitor.CheckInterval == 0 {1176 c.ConnectionMonitor.CheckInterval = connchecker.DefaultCheckInterval1177 }1178 if len(c.ConnectionMonitor.DNSList) == 0 {1179 c.ConnectionMonitor.DNSList = connchecker.DefaultDNSList1180 }1181 if len(c.ConnectionMonitor.PublicDomainList) == 0 {1182 c.ConnectionMonitor.PublicDomainList = connchecker.DefaultDomainList1183 }1184}1185// DefaultFilePath returns the default config file path1186// MacOS/Linux: $HOME/.gocryptotrader/config.json or config.dat1187// Windows: %APPDATA%\GoCryptoTrader\config.json or config.dat1188// Helpful for printing application usage1189func DefaultFilePath() string {1190 foundConfig, _, err := GetFilePath("")1191 if err != nil {1192 // If there was no config file, show default location for .json1193 return filepath.Join(common.GetDefaultDataDir(runtime.GOOS), File)1194 }1195 return foundConfig1196}1197// GetAndMigrateDefaultPath returns the target config file1198// migrating it from the old default location to new one,1199// if it was implicitly loaded from a default location and1200// wasn't already in the correct 'new' default location1201func GetAndMigrateDefaultPath(configFile string) (string, error) {1202 filePath, wasDefault, err := GetFilePath(configFile)1203 if err != nil {1204 return "", err1205 }1206 if wasDefault {1207 return migrateConfig(filePath, common.GetDefaultDataDir(runtime.GOOS))1208 }1209 return filePath, nil1210}1211// GetFilePath returns the desired config file or the default config file name1212// and whether it was loaded from a default location (rather than explicitly specified)1213func GetFilePath(configFile string) (configPath string, isImplicitDefaultPath bool, err error) {1214 if configFile != "" {1215 return configFile, false, nil1216 }1217 exePath, err := common.GetExecutablePath()1218 if err != nil {1219 return "", false, err1220 }1221 newDir := common.GetDefaultDataDir(runtime.GOOS)1222 defaultPaths := []string{1223 filepath.Join(exePath, File),1224 filepath.Join(exePath, EncryptedFile),1225 filepath.Join(newDir, File),1226 filepath.Join(newDir, EncryptedFile),1227 }1228 for _, p := range defaultPaths {1229 if file.Exists(p) {1230 configFile = p1231 break1232 }1233 }1234 if configFile == "" {1235 return "", false, fmt.Errorf("config.json file not found in %s, please follow README.md in root dir for config generation",1236 newDir)1237 }1238 return configFile, true, nil1239}1240// migrateConfig will move the config file to the target1241// config directory as `File` or `EncryptedFile` depending on whether the config1242// is encrypted1243func migrateConfig(configFile, targetDir string) (string, error) {1244 data, err := ioutil.ReadFile(configFile)1245 if err != nil {1246 return "", err1247 }1248 var target string1249 if ConfirmECS(data) {1250 target = EncryptedFile1251 } else {1252 target = File1253 }1254 target = filepath.Join(targetDir, target)1255 if configFile == target {1256 return configFile, nil1257 }1258 if file.Exists(target) {1259 log.Warnf(log.ConfigMgr, "config file already found in '%s'; not overwriting, defaulting to %s", target, configFile)1260 return configFile, nil1261 }1262 err = file.Move(configFile, target)1263 if err != nil {1264 return "", err1265 }1266 return target, nil1267}1268// ReadConfigFromFile reads the configuration from the given file1269// if target file is encrypted, prompts for encryption key1270// Also - if not in dryrun mode - it checks if the configuration needs to be encrypted1271// and stores the file as encrypted, if necessary (prompting for enryption key)1272func (c *Config) ReadConfigFromFile(configPath string, dryrun bool) error {1273 defaultPath, _, err := GetFilePath(configPath)1274 if err != nil {1275 return err1276 }1277 confFile, err := os.Open(defaultPath)1278 if err != nil {1279 return err1280 }1281 defer confFile.Close()1282 result, wasEncrypted, err := ReadConfig(confFile, func() ([]byte, error) { return PromptForConfigKey(false) })1283 if err != nil {1284 return fmt.Errorf("error reading config %w", err)1285 }1286 // Override values in the current config1287 *c = *result1288 if dryrun || wasEncrypted || c.EncryptConfig == fileEncryptionDisabled {1289 return nil1290 }1291 if c.EncryptConfig == fileEncryptionPrompt {1292 confirm, err := promptForConfigEncryption()1293 if err != nil {1294 log.Errorf(log.ConfigMgr, "The encryption prompt failed, ignoring for now, next time we will prompt again. Error: %s\n", err)1295 return nil1296 }1297 if confirm {1298 c.EncryptConfig = fileEncryptionEnabled1299 return c.SaveConfigToFile(defaultPath)1300 }1301 c.EncryptConfig = fileEncryptionDisabled1302 err = c.SaveConfigToFile(defaultPath)1303 if err != nil {1304 log.Errorf(log.ConfigMgr, "Cannot save config. Error: %s\n", err)1305 }1306 }1307 return nil1308}1309// ReadConfig verifies and checks for encryption and loads the config from a JSON object.1310// Prompts for decryption key, if target data is encrypted.1311// Returns the loaded configuration and whether it was encrypted.1312func ReadConfig(configReader io.Reader, keyProvider func() ([]byte, error)) (*Config, bool, error) {1313 reader := bufio.NewReader(configReader)1314 pref, err := reader.Peek(len(EncryptConfirmString))1315 if err != nil {1316 return nil, false, err1317 }1318 if !ConfirmECS(pref) {1319 // Read unencrypted configuration1320 decoder := json.NewDecoder(reader)1321 c := &Config{}1322 err = decoder.Decode(c)1323 return c, false, err1324 }1325 conf, err := readEncryptedConfWithKey(reader, keyProvider)1326 return conf, true, err1327}1328// readEncryptedConf reads encrypted configuration and requests key from provider1329func readEncryptedConfWithKey(reader *bufio.Reader, keyProvider func() ([]byte, error)) (*Config, error) {1330 fileData, err := ioutil.ReadAll(reader)1331 if err != nil {1332 return nil, err1333 }1334 for errCounter := 0; errCounter < maxAuthFailures; errCounter++ {1335 key, err := keyProvider()1336 if err != nil {1337 log.Errorf(log.ConfigMgr, "PromptForConfigKey err: %s", err)1338 continue1339 }1340 var c *Config1341 c, err = readEncryptedConf(bytes.NewReader(fileData), key)1342 if err != nil {1343 log.Error(log.ConfigMgr, "Could not decrypt and deserialise data with given key. Invalid password?", err)1344 continue1345 }1346 return c, nil1347 }1348 return nil, errors.New("failed to decrypt config after 3 attempts")1349}1350func readEncryptedConf(reader io.Reader, key []byte) (*Config, error) {1351 c := &Config{}1352 data, err := c.decryptConfigData(reader, key)1353 if err != nil {1354 return nil, err1355 }1356 err = json.Unmarshal(data, c)1357 return c, err1358}1359// SaveConfigToFile saves your configuration to your desired path as a JSON object.1360// The function encrypts the data and prompts for encryption key, if necessary1361func (c *Config) SaveConfigToFile(configPath string) error {1362 defaultPath, _, err := GetFilePath(configPath)1363 if err != nil {1364 return err1365 }1366 var writer *os.File1367 provider := func() (io.Writer, error) {1368 writer, err = file.Writer(defaultPath)1369 return writer, err1370 }1371 defer func() {1372 if writer != nil {1373 err = writer.Close()1374 if err != nil {1375 log.Error(log.ConfigMgr, err)1376 }1377 }1378 }()1379 return c.Save(provider, func() ([]byte, error) { return PromptForConfigKey(true) })1380}1381// Save saves your configuration to the writer as a JSON object1382// with encryption, if configured1383// If there is an error when preparing the data to store, the writer is never requested1384func (c *Config) Save(writerProvider func() (io.Writer, error), keyProvider func() ([]byte, error)) error {1385 payload, err := json.MarshalIndent(c, "", " ")1386 if err != nil {1387 return err1388 }1389 if c.EncryptConfig == fileEncryptionEnabled {1390 // Ensure we have the key from session or from user1391 if len(c.sessionDK) == 0 {1392 var key []byte1393 key, err = keyProvider()1394 if err != nil {1395 return err1396 }1397 var sessionDK, storedSalt []byte1398 sessionDK, storedSalt, err = makeNewSessionDK(key)1399 if err != nil {1400 return err1401 }1402 c.sessionDK, c.storedSalt = sessionDK, storedSalt1403 }1404 payload, err = c.encryptConfigFile(payload)1405 if err != nil {1406 return err1407 }1408 }1409 configWriter, err := writerProvider()1410 if err != nil {1411 return err1412 }1413 _, err = io.Copy(configWriter, bytes.NewReader(payload))1414 return err1415}1416// CheckRemoteControlConfig checks to see if the old c.Webserver field is used1417// and migrates the existing settings to the new RemoteControl struct1418func (c *Config) CheckRemoteControlConfig() {1419 m.Lock()1420 defer m.Unlock()1421 if c.Webserver != nil {1422 port := common.ExtractPort(c.Webserver.ListenAddress)1423 host := common.ExtractHost(c.Webserver.ListenAddress)1424 c.RemoteControl = RemoteControlConfig{1425 Username: c.Webserver.AdminUsername,1426 Password: c.Webserver.AdminPassword,1427 DeprecatedRPC: DepcrecatedRPCConfig{1428 Enabled: c.Webserver.Enabled,1429 ListenAddress: host + ":" + strconv.Itoa(port),1430 },1431 }1432 port++1433 c.RemoteControl.WebsocketRPC = WebsocketRPCConfig{1434 Enabled: c.Webserver.Enabled,1435 ListenAddress: host + ":" + strconv.Itoa(port),1436 ConnectionLimit: c.Webserver.WebsocketConnectionLimit,1437 MaxAuthFailures: c.Webserver.WebsocketMaxAuthFailures,1438 AllowInsecureOrigin: c.Webserver.WebsocketAllowInsecureOrigin,1439 }1440 port++1441 gRPCProxyPort := port + 11442 c.RemoteControl.GRPC = GRPCConfig{1443 Enabled: c.Webserver.Enabled,1444 ListenAddress: host + ":" + strconv.Itoa(port),1445 GRPCProxyEnabled: c.Webserver.Enabled,1446 GRPCProxyListenAddress: host + ":" + strconv.Itoa(gRPCProxyPort),1447 }1448 // Then flush the old webserver settings1449 c.Webserver = nil1450 }1451}1452// CheckConfig checks all config settings1453func (c *Config) CheckConfig() error {1454 err := c.CheckLoggerConfig()1455 if err != nil {1456 log.Errorf(log.ConfigMgr,1457 "Failed to configure logger, some logging features unavailable: %s\n",1458 err)1459 }1460 err = c.checkDatabaseConfig()1461 if err != nil {1462 log.Errorf(log.DatabaseMgr,1463 "Failed to configure database: %v",1464 err)1465 }1466 err = c.CheckExchangeConfigValues()1467 if err != nil {1468 return fmt.Errorf(ErrCheckingConfigValues, err)1469 }1470 err = c.checkGCTScriptConfig()1471 if err != nil {1472 log.Errorf(log.ConfigMgr,1473 "Failed to configure gctscript, feature has been disabled: %s\n",1474 err)1475 }1476 c.CheckConnectionMonitorConfig()1477 c.CheckDataHistoryMonitorConfig()1478 c.CheckCurrencyStateManager()1479 c.CheckCommunicationsConfig()1480 c.CheckClientBankAccounts()1481 c.CheckBankAccountConfig()1482 c.CheckRemoteControlConfig()1483 err = c.CheckCurrencyConfigValues()1484 if err != nil {1485 return err1486 }1487 if c.GlobalHTTPTimeout <= 0 {1488 log.Warnf(log.ConfigMgr,1489 "Global HTTP Timeout value not set, defaulting to %v.\n",1490 defaultHTTPTimeout)1491 c.GlobalHTTPTimeout = defaultHTTPTimeout1492 }1493 if c.NTPClient.Level != 0 {1494 c.CheckNTPConfig()1495 }1496 return nil1497}1498// LoadConfig loads your configuration file into your configuration object1499func (c *Config) LoadConfig(configPath string, dryrun bool) error {1500 err := c.ReadConfigFromFile(configPath, dryrun)1501 if err != nil {1502 return fmt.Errorf(ErrFailureOpeningConfig, configPath, err)1503 }1504 return c.CheckConfig()1505}1506// UpdateConfig updates the config with a supplied config file1507func (c *Config) UpdateConfig(configPath string, newCfg *Config, dryrun bool) error {1508 err := newCfg.CheckConfig()1509 if err != nil {1510 return err1511 }1512 c.Name = newCfg.Name1513 c.EncryptConfig = newCfg.EncryptConfig1514 c.Currency = newCfg.Currency1515 c.GlobalHTTPTimeout = newCfg.GlobalHTTPTimeout1516 c.Portfolio = newCfg.Portfolio1517 c.Communications = newCfg.Communications1518 c.Webserver = newCfg.Webserver1519 c.Exchanges = newCfg.Exchanges1520 if !dryrun {1521 err = c.SaveConfigToFile(configPath)1522 if err != nil {1523 return err1524 }1525 }1526 return c.LoadConfig(configPath, dryrun)1527}1528// GetConfig returns a pointer to a configuration object1529func GetConfig() *Config {1530 return &Cfg1531}1532// RemoveExchange removes an exchange config1533func (c *Config) RemoveExchange(exchName string) bool {1534 m.Lock()1535 defer m.Unlock()1536 for x := range c.Exchanges {1537 if strings.EqualFold(c.Exchanges[x].Name, exchName) {1538 c.Exchanges = append(c.Exchanges[:x], c.Exchanges[x+1:]...)1539 return true1540 }1541 }1542 return false1543}1544// AssetTypeEnabled checks to see if the asset type is enabled in configuration1545func (c *Config) AssetTypeEnabled(a asset.Item, exch string) (bool, error) {1546 cfg, err := c.GetExchangeConfig(exch)1547 if err != nil {1548 return false, err1549 }1550 err = cfg.CurrencyPairs.IsAssetEnabled(a)1551 if err != nil {1552 return false, nil // nolint:nilerr // non-fatal error1553 }1554 return true, nil1555}1556// GetDataPath gets the data path for the given subpath1557func (c *Config) GetDataPath(elem ...string) string {1558 var baseDir string1559 if c.DataDirectory != "" {...

Full Screen

Full Screen

storage.go

Source:storage.go Github

copy

Full Screen

...51 dash: dash,52 tracer: tracer,53 }, nil54}55func (storage *Storage) AssetTypeEnabled(assetType dashapi.AssetType) bool {56 return storage.cfg.IsEnabled(assetType)57}58func (storage *Storage) getDefaultCompressor() Compressor {59 return xzCompressor60}61type ExtraUploadArg struct {62 // It is assumed that paths constructed with same UniqueTag values63 // always correspond to an asset having the same content.64 UniqueTag string65 // If the asset being uploaded already exists (see above), don't return66 // an error, abort uploading and return the download URL.67 SkipIfExists bool68}69var ErrAssetTypeDisabled = errors.New("uploading assets of this type is disabled")70func (storage *Storage) assetPath(name string, extra *ExtraUploadArg) string {71 folderName := ""72 if extra != nil && extra.UniqueTag != "" {73 folderName = extra.UniqueTag74 } else {75 // The idea is to make a file name useful and yet unique.76 // So we put a file to a pseudo-unique "folder".77 folderNameBytes := sha256.Sum256([]byte(fmt.Sprintf("%v", time.Now().UnixNano())))78 folderName = fmt.Sprintf("%x", folderNameBytes)79 }80 const folderPrefix = 1281 if len(folderName) > folderPrefix {82 folderName = folderName[0:folderPrefix]83 }84 return fmt.Sprintf("%s/%s", folderName, name)85}86func (storage *Storage) uploadFileStream(reader io.Reader, assetType dashapi.AssetType,87 name string, extra *ExtraUploadArg) (string, error) {88 if name == "" {89 return "", fmt.Errorf("file name is not specified")90 }91 typeDescr := GetTypeDescription(assetType)92 if typeDescr == nil {93 return "", fmt.Errorf("asset type %s is unknown", assetType)94 }95 if !storage.AssetTypeEnabled(assetType) {96 return "", fmt.Errorf("not allowed to upload an asset of type %s: %w",97 assetType, ErrAssetTypeDisabled)98 }99 path := storage.assetPath(name, extra)100 req := &uploadRequest{101 savePath: path,102 contentType: typeDescr.ContentType,103 contentEncoding: typeDescr.ContentEncoding,104 preserveExtension: typeDescr.preserveExtension,105 }106 if req.contentType == "" {107 req.contentType = "application/octet-stream"108 }109 compressor := storage.getDefaultCompressor()...

Full Screen

Full Screen

AssetTypeEnabled

Using AI Code Generation

copy

Full Screen

1import (2type SimpleAsset struct {3}4func (s *SimpleAsset) Init(APIstub shim.ChaincodeStubInterface) peer.Response {5 return shim.Success(nil)6}7func (s *SimpleAsset) Invoke(APIstub shim.ChaincodeStubInterface) peer.Response {8 function, args := APIstub.GetFunctionAndParameters()9 if function == "createAsset" {10 return s.createAsset(APIstub, args)11 } else if function == "transferAsset" {12 return s.transferAsset(APIstub, args)13 }14 return shim.Error("Invalid Smart Contract function name.")15}16func (s *SimpleAsset) createAsset(APIstub shim.ChaincodeStubInterface, args []string) peer.Response {17 if len(args) != 2 {18 return shim.Error("Incorrect number of arguments. Expecting 2")19 }20 asset := map[string]interface{}{21 }22 assetBytes, err := json.Marshal(asset)23 if err != nil {24 return shim.Error(err.Error())25 }26 err = APIstub.PutState(assetKey, assetBytes)27 if err != nil {28 return shim.Error(err.Error())29 }30 stateEP, err := statebased.NewStateEP(nil)31 if err != nil {32 return shim.Error(err.Error())33 }34 err = stateEP.AddOrgs(statebased.RoleTypePeer, owner)35 if err != nil {36 return shim.Error(err.Error())37 }38 stateEPBytes, err := stateEP.Policy()39 if err != nil {40 return shim.Error(err.Error())41 }42 err = APIstub.SetStateValidationParameter(assetKey, stateEPBytes)43 if err != nil {44 return shim.Error(err

Full Screen

Full Screen

AssetTypeEnabled

Using AI Code Generation

copy

Full Screen

1import (2type AssetTypeEnabled struct {3}4func (t *AssetTypeEnabled) Init(stub shim.ChaincodeStubInterface) peer.Response {5 return shim.Success(nil)6}7func (t *AssetTypeEnabled) Invoke(stub shim.ChaincodeStubInterface) peer.Response {8 function, args := stub.GetFunctionAndParameters()9 if function == "getAssetTypeEnabled" {10 return t.getAssetTypeEnabled(stub, args)11 }12 return shim.Error("Invalid invoke function name.")13}14func (t *AssetTypeEnabled) getAssetTypeEnabled(stub shim.ChaincodeStubInterface, args []string) peer.Response {15 if len(args) != 1 {16 return shim.Error("Incorrect number of arguments. Expecting 1")17 }18 assetTypeEnabled, err := stub.GetStateValidationParameter(args[0])19 if err != nil {20 return shim.Error(err.Error())21 }22 return shim.Success(assetTypeEnabled)23}24func main() {25 err := shim.Start(new(AssetTypeEnabled))26 if err != nil {27 fmt.Printf("Error starting AssetTypeEnabled chaincode: %s", err)28 }29}30import (31func TestAssetTypeEnabled(t *testing.T) {32 scc := new(AssetTypeEnabled)33 stub := shim.NewMockStub("ex02", scc)34 stub.MockTransactionStart("t01")35 _, err := stub.MockInit("1", [][]byte{[]byte("init")})36 assert.NoError(t, err)37 stub.MockTransactionEnd("t01")38 stub.MockTransactionStart("t02")39 res := stub.MockInvoke("2", [][]byte{[]byte("getAssetTypeEnabled"), []byte("asset1")})40 assert.Equal(t, 200, int(res.Status))41 stub.MockTransactionEnd("t02")42}

Full Screen

Full Screen

AssetTypeEnabled

Using AI Code Generation

copy

Full Screen

1import (2type SimpleChaincode struct {3}4func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) peer.Response {5 return shim.Success(nil)6}7func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) peer.Response {8 function, args := stub.GetFunctionAndParameters()9 if function == "assetTypeEnabled" {10 return t.assetTypeEnabled(stub, args)11 }12 return shim.Error("Invalid invoke function name. Expecting \"assetTypeEnabled\"")13}14func (t *SimpleChaincode) assetTypeEnabled(stub shim.ChaincodeStubInterface, args []string) peer.Response {15 if len(args) != 1 {16 return shim.Error("Incorrect number of arguments. Expecting 1")17 }18 assetTypeEnabled, err := stub.AssetTypeEnabled(assetType)19 if err != nil {20 return shim.Error(err.Error())21 }22 fmt.Println("Asset Type Enabled", assetTypeEnabled)23 return shim.Success(nil)24}25func main() {26 err := shim.Start(new(SimpleChaincode))27 if err != nil {28 fmt.Printf("Error starting Simple chaincode: %s", err)29 }30}

Full Screen

Full Screen

AssetTypeEnabled

Using AI Code Generation

copy

Full Screen

1import (2type AssetManagement struct {3}4func (t *AssetManagement) Init(stub shim.ChaincodeStubInterface) peer.Response {5 return shim.Success(nil)6}7func (t *AssetManagement) Invoke(stub shim.ChaincodeStubInterface) peer.Response {8 fn, args := stub.GetFunctionAndParameters()9 if fn == "createAsset" {10 result, err = createAsset(stub, args)11 } else if fn == "updateAsset" {12 result, err = updateAsset(stub, args)13 } else if fn == "readAsset" {14 result, err = readAsset(stub, args)15 } else if fn == "deleteAsset" {16 result, err = deleteAsset(stub, args)17 } else if fn == "readAssetPrivateDetails" {18 result, err = readAssetPrivateDetails(stub, args)19 } else if fn == "readAssetPrivateDetailsHash" {20 result, err = readAssetPrivateDetailsHash(stub, args)21 } else if fn == "transferAsset" {22 result, err = transferAsset(stub, args)23 } else if fn == "getAssetHistory" {24 result, err = getAssetHistory(stub, args)25 } else if fn == "getAssetByRange" {26 result, err = getAssetByRange(stub, args)27 } else if fn == "getAssetByPartialCompositeKey" {28 result, err = getAssetByPartialCompositeKey(stub, args)29 } else if fn == "getAssetByPartialCompositeKeyWithPagination" {30 result, err = getAssetByPartialCompositeKeyWithPagination(stub, args)31 } else if fn == "getAssetByRangeWithPagination" {32 result, err = getAssetByRangeWithPagination(stub, args)33 } else if fn == "getAssetQueryResult"

Full Screen

Full Screen

AssetTypeEnabled

Using AI Code Generation

copy

Full Screen

1import (2type AssetChaincode struct {3}4func (t *AssetChaincode) Init(stub shim.ChaincodeStubInterface) peer.Response {5 fmt.Println("Asset Init")6 return shim.Success(nil)7}8func (t *AssetChaincode) Invoke(stub shim.ChaincodeStubInterface) peer.Response {9 fmt.Println("Asset Invoke")10 return shim.Success(nil)11}12func main() {13 err := shim.Start(new(AssetChaincode))14 if err != nil {15 fmt.Printf("Error starting Asset chaincode: %s", err)16 }17}18import (19type AssetChaincode struct {20}21func (t *AssetChaincode) Init(stub shim.ChaincodeStubInterface) peer.Response {22 fmt.Println("Asset Init")23 return shim.Success(nil)24}25func (t *AssetChaincode) Invoke(stub shim.ChaincodeStubInterface) peer.Response {26 fmt.Println("Asset Invoke")27 return shim.Success(nil)28}29func main() {30 err := shim.Start(new(AssetChaincode))31 if err != nil {32 fmt.Printf("Error starting Asset chaincode: %s", err)33 }34}35import (36type AssetChaincode struct {37}38func (t *AssetChaincode) Init(st

Full Screen

Full Screen

AssetTypeEnabled

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Println(err)5 }6 asset := types.NewAsset("0x89d24a6b4ccb1b6faa2625fe562bdd9a23260359", client)7 isAssetEnabled, err := asset.AssetTypeEnabled(nil)8 if err != nil {9 fmt.Println(err)10 }11 fmt.Println(isAssetEnabled)12}

Full Screen

Full Screen

AssetTypeEnabled

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 err := shim.Start(new(SmartContract))4 if err != nil {5 fmt.Printf("Error creating new Smart Contract: %s", err)6 }7}8type SmartContract struct {9}10func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) sc.Response {11 return shim.Success(nil)12}13func (s *SmartContract) Invoke(APIstub shim.ChaincodeStubInterface) sc.Response {14 function, args := APIstub.GetFunctionAndParameters()15 if function == "queryAsset" {16 return s.queryAsset(APIstub, args)17 } else if function == "createAsset" {18 return s.createAsset(APIstub, args)19 } else if function == "updateAsset" {20 return s.updateAsset(APIstub, args)21 } else if function == "deleteAsset" {22 return s.deleteAsset(APIstub, args)23 }24 return shim.Error("Invalid Smart Contract function name.")25}26func (s *SmartContract) queryAsset(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {27 if len(args) != 1 {28 return shim.Error("Incorrect number of arguments. Expecting 1")29 }30 assetAsBytes, _ := APIstub.GetState(args[0])31 return shim.Success(assetAsBytes)32}33func (s *SmartContract) createAsset(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {34 if len(args) != 2 {35 return shim.Error("Incorrect number of arguments. Expecting 2")36 }37 var asset = Asset{Type: args[1]}38 assetAsBytes, _ := json.Marshal(asset)39 APIstub.PutState(args[0], assetAsBytes)40 return shim.Success(nil)41}42func (s *SmartContract) updateAsset(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {43 if len(args) != 2 {

Full Screen

Full Screen

AssetTypeEnabled

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 stub := shim.NewMockStub("ex02", nil)4 stub.MockTransactionStart("tx1")5 stub.MockInvoke("tx1", [][]byte{[]byte("createAsset"), []byte("asset1"), []byte("100")})6 stub.MockTransactionEnd("tx1")7 stub.MockTransactionStart("tx2")8 stub.MockInvoke("tx2", [][]byte{[]byte("enableAsset"), []byte("asset1")})9 stub.MockTransactionEnd("tx2")10 assetType, _ := stub.GetState("asset1")11 fmt.Println("Asset type: ", assetType)12}

Full Screen

Full Screen

AssetTypeEnabled

Using AI Code Generation

copy

Full Screen

1func main() {2 asset := asset.NewAsset()3 assetTypeEnabled := asset.NewAssetTypeEnabled()4 assetTypeEnabled.SetAssetTypeEnabled("true")5 asset.SetAssetTypeEnabled(assetTypeEnabled)6 fmt.Println("AssetTypeEnabled: " + asset.GetAssetTypeEnabled().GetAssetTypeEnabled())7}8import (9func main() {10 asset := asset.NewAsset()11 assetTypeEnabled := asset.NewAssetTypeEnabled()12 assetTypeEnabled.SetAssetTypeEnabled("false")13 asset.SetAssetTypeEnabled(assetTypeEnabled)14 fmt.Println("AssetTypeEnabled: " + asset.GetAssetTypeEnabled().GetAssetTypeEnabled())15}16import (17func main() {18 asset := asset.NewAsset()19 assetTypeEnabled := asset.NewAssetTypeEnabled()20 assetTypeEnabled.SetAssetTypeEnabled("true")21 asset.SetAssetTypeEnabled(assetTypeEnabled)22 fmt.Println("AssetTypeEnabled: " + asset.GetAssetTypeEnabled().GetAssetTypeEnabled())23}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful