Exemplo n.º 1
0
        public CurrencyProvider(ProtocolConfiguration protocolConfiguration)
        {
            _protocolConfiguration = protocolConfiguration;
            _requestHelper         = new RequestHelper(_host);

            _walletClient =
                new Latoken.CurrencyProvider.Protocol.Tron.Grpc.Api.Wallet.WalletClient(_protocolConfiguration.Channel);
        }
        public bool ConnectServer(ProtocolConfiguration protocolConfig, out string error)
        {
            error = "";
            try
            {
                ProtocolManager.Register(protocolConfig);
                ProtocolManager[protocolConfig.Name].Open();
                return(true);
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("Description:"))
                {
                    error = ex.Message.Substring(ex.Message.IndexOf("Description:"));
                }
                else if (ex.Message.Contains("Exception occured during channel opening") ||
                         (ex.InnerException != null && ex.InnerException.ToString().Contains("No such host is known")))
                {
                    error = "Could not connect to ";
                    switch (protocolConfig.Name)
                    {
                    case "Configserver":
                        error += "configuration";
                        break;

                    case "Tserver":
                        error += "voice";
                        break;

                    case "Ixnserver":
                        error += "interaction";
                        break;

                    case "Chatserver":
                        error += "chat";
                        break;

                    case "Ucserver":
                        error += "universal contact";
                        break;

                    case "Statisticsserver":
                    case "ElavonStatisticsserver":
                        error += "stat";
                        break;
                    }
                    error += " server host '" + protocolConfig.Uri.Host + "' on port '" + protocolConfig.Uri.Port;
                }
                else
                {
                    error = ex.Message;
                }
            }
            return(false);
        }
        public void BalanceZero(string adrressBase58, StringType stringType, TypeNet typeNet)
        {
            ProtocolConfiguration protocolConfiguration = new ProtocolConfiguration(typeNet);

            CurrencyProvider.Protocol.Tron.CurrencyProvider currencyProvider = new CurrencyProvider.Protocol.Tron.CurrencyProvider(protocolConfiguration);

            long balance = currencyProvider.balanceByAddress(adrressBase58);

            Console.WriteLine($"{adrressBase58}:{balance}");
            Assert.IsTrue(balance == 0);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Saves a reference to the SessionBase then creates a Timer to send
        /// <see cref="KeepAliveProtocolCommands.KEEP_ALIVE"/>
        /// command packets.
        /// </summary>
        /// <param name="session">A SessionBase that encapsulates the connection
        /// session.</param>
        ///<param name="pc">A ProtocolConfiguration that contains configuration
        /// properties. This parameter is not used.</param>
        /// <param name="userData">An object that may be used by client applications to
        /// pass objects or data to client side protocol implementations. This parameter is
        /// not used.</param>
        public override void Initialize(SessionBase session, ProtocolConfiguration pc, object userData = null)
        {
            base.Initialize(session, pc, userData);

            lock (this)
            {
                CloseTimer();

                timer = new Timer(TimerCallback, null, KeepAliveProtocol.INTERVAL, KeepAliveProtocol.INTERVAL);
            }
        }
Exemplo n.º 5
0
        [DataRow("TRb45eJbLbxCp2WQYQeNt9AoR3iiMKooLqs", -20, false)]                                                                                                             // сумма отрицательная.
        public void ValidateTransactionOptionsTest(string agentPrivateKey, string agentAddress, string credentialsAddress, long amount)
        {
            ProtocolConfiguration protocolConfiguration = new ProtocolConfiguration(TypeNet.Test);

            CurrencyProvider.Protocol.Tron.CurrencyProvider currencyProvider = new CurrencyProvider.Protocol.Tron.CurrencyProvider(protocolConfiguration);

            TransactionOptions generateTransactionOptions = GenerateTransactionOptions(agentPrivateKey, agentAddress, "TPwJS5eC5BPGyMGtYTHNhPTB89sUWjDSSu", 108);

            bool isValidTransactionOptions = currencyProvider.validateTransactionOptions(generateTransactionOptions);

            Assert.IsTrue(isValidTransactionOptions);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Handles command packets.
        /// </summary>
        /// <param name="br">A BinaryReader that contains the command packet.</param>
        protected void OnPacketReceived(BinaryReader br)
        {
            ushort protocolId = br.ReadUInt16();

            if (protocolId == 0)
            {
                capabilitiesProtocol.OnPacketReceived(br);
                return;
            }

            try
            {
                ProtocolBase p;
                lock (protocolImplementations)
                {
                    if (protocolImplementations.ContainsKey(protocolId))
                    {
                        p = protocolImplementations[protocolId];
                    }
                    else
                    {
                        if (!protocolConfigurations.ContainsKey(protocolId))
                        {
                            throw new Exception(string.Format(ErrorTypes.INVALID_PROTOCOL, protocolId));
                        }

                        ProtocolConfiguration pc = protocolConfigurations[protocolId];
                        p = pc.CreateInstance();
                        if (p == null)
                        {
                            throw new Exception(string.Format(ErrorTypes.CLASS_NOT_FOUND, pc));
                        }

                        if (!IsAuthenticated && !(p is AuthenticationProtocolBase))
                        {
                            throw new Exception(string.Format(ErrorTypes.NOT_AUTHENTICATED, pc));
                        }

                        protocolImplementations.Add(protocolId, p);

                        Log(Level.Debug, string.Format("Initializing protocol {0}...", protocolId));
                        p.Initialize(this, pc, userData);
                    }
                    LastActivityAt = DateTime.Now;
                }
                p.OnPacketReceived(br);
            }
            catch (Exception ex)
            {
                capabilitiesProtocol.SendError(protocolId, ex.Message);
            }
        }
Exemplo n.º 7
0
        public static CircuitBreak GetCircuitBreak(ProtocolConfiguration protocolConfiguration, Func <Exception, bool> exceptionPredicate)
        {
            string key = $"{protocolConfiguration.Protocol}_{protocolConfiguration.Name}_{protocolConfiguration.Defalut}";

            if (!circuitBreakers.ContainsKey(key))
            {
                circuitBreakers.Add(key, new CircuitBreak(
                                        protocolConfiguration.ExceptionsAllowedBeforeBreaking,
                                        TimeSpan.FromSeconds(protocolConfiguration.DurationOfBreak),
                                        protocolConfiguration.ReTries,
                                        exceptionPredicate));
            }
            return(circuitBreakers[key]);
        }
Exemplo n.º 8
0
        //    [DataRow("TMy3cNNSZHY5d6F39BUbwUExJR93QDpGeh", StringType.Base58, TypeNet.Main)]
        public void SolidityDockerConnectTest(string addressBase58, StringType stringType, TypeNet typeNet)
        {
            //  ProtocolConfiguration protocolConfiguration = new ProtocolConfiguration(typeNet, "172.17.0.2", 50051);
            // ProtocolConfiguration protocolConfiguration = new ProtocolConfiguration(typeNet);
            //  ProtocolConfiguration protocolConfiguration = new ProtocolConfiguration(typeNet, "10.0.75.1", 50041);
            ProtocolConfiguration protocolConfiguration = new ProtocolConfiguration(typeNet, "10.0.75.1", 50052);
            //  ProtocolConfiguration protocolConfiguration = new ProtocolConfiguration(typeNet, "18.184.238.21", 50051);


            var walletClient = new Latoken.CurrencyProvider.Protocol.Tron.Grpc.Api.WalletSolidity.WalletSolidityClient(protocolConfiguration.Channel);
            var sol          = new Latoken.CurrencyProvider.Protocol.Tron.Grpc.Api.WalletSolidity.WalletSolidityClient(protocolConfiguration.Channel);

            byte[] addressBytes = StringHelper.GetBytesAdressFromString(addressBase58);

            Account account = new Account();

            account.Address = ByteString.CopyFrom(addressBytes.SubArray(0, 21));

            var dddd = sol.GetAccount(account);
            //       NodeList listNodes = walletClient.GetPaginatedAssetIssueList ListNodes(new EmptyMessage());

            var we = new Latoken.CurrencyProvider.Protocol.Tron.Grpc.Api.WalletExtension.WalletExtensionClient(protocolConfiguration.Channel);



            var ap = new AccountPaginated();

            ap.Account = account;
            ap.Offset  = 0;
            ap.Limit   = 100;

            var t = we.GetTransactionsFromThis2(ap);


            CurrencyProvider.Protocol.Tron.CurrencyProvider currencyProvider = new CurrencyProvider.Protocol.Tron.CurrencyProvider(protocolConfiguration);

            var rr = BitConverter.GetBytes(1502948);

            BytesMessage numberMessa = new BytesMessage();

            numberMessa.Value = Google.Protobuf.ByteString.CopyFrom(rr);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Creates a <c>ProtocolConfiguration</c> instance for each protocol in the configuration string
        /// </summary>
        /// <param name="config">The configuration string</param>
        /// <returns>The array of configuration objects</returns>
        private ProtocolConfiguration[] parseConfigurations(string config)
        {
            ProtocolConfiguration[] retval;                     //= new ArrayList();
            string[] component_strings = config.Split(new char[] { ':' });
            String   component_string;
            ProtocolConfiguration protocol_config;

            if (component_strings == null)
            {
                return(null);
            }

            retval = new ProtocolConfiguration[component_strings.Length];

            for (int i = 0; i < component_strings.Length; i++)
            {
                component_string = (String)component_strings.GetValue(i);
                protocol_config  = new ProtocolConfiguration(component_string);
                retval[i]        = protocol_config;
            }
            return(retval);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Creates then initializes the protocol.
        /// </summary>
        /// <param name="protocolId">A UInt16 that specifies the unique protocol
        /// identifier.</param>
        /// <param name="userData">An object that may be used client applications to pass
        /// objects or data to client side protocol implementations.</param>
        /// <returns>A ProtocolBase that implements the protocol layer.</returns>
        public ProtocolBase Initialize(ushort protocolId, object userData = null)
        {
            ProtocolBase p = null;

            lock (protocolImplementations)
            {
                if (!protocolImplementations.ContainsKey(protocolId))
                {
                    if (!protocolConfigurations.ContainsKey(protocolId))
                    {
                        throw new Exception(string.Format(ErrorTypes.INVALID_PROTOCOL, protocolId));
                    }

                    ProtocolConfiguration pc = protocolConfigurations[protocolId];
                    p = pc.CreateInstance();
                    if (p == null)
                    {
                        throw new Exception(string.Format(ErrorTypes.CLASS_NOT_FOUND, pc));
                    }

                    protocolImplementations.Add(protocolId, p);

                    Log(Level.Debug, string.Format("Initializing protocol {0}...", protocolId));
                    if (userData == null)
                    {
                        userData = this.userData;
                    }
                    p.Initialize(this, pc, userData);
                    LastActivityAt = DateTime.Now;
                }
                else
                {
                    p = protocolImplementations[protocolId];
                }
            }
            return(p);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Creates an array of <c>Protocols</c> from the configurations
        /// </summary>
        /// <param name="protocol_configs">Array of <c>ProtocolConfiguration</c> objects</param>
        /// <param name="stack">Instance <c>ProtocolSinkStack</c> which the Protocol layers should reference</param>
        /// <returns>Array of <c>Protocol</c> objects</returns>
        private Protocol[] createProtocols(ProtocolConfiguration[] protocol_configs, ProtocolSinkStack stack)
        {
            Protocol[]             retval = new Protocol[protocol_configs.Length];
            Protocol               layer;

            for(int i=0; i < protocol_configs.Length; i++)
            {
                layer = (Protocol)protocol_configs[i].createLayer(stack); //stack
                if(layer == null)
                    return null;
                retval[i] = layer;
            }

            sanityCheck(retval);
            return retval;
        }
Exemplo n.º 12
0
		/// <summary> Creates a new protocol given the protocol specification. Initializes the properties and starts the
		/// up and down handler threads.
		/// </summary>
		/// <param name="prot_spec">The specification of the protocol. Same convention as for specifying a protocol stack.
		/// An exception will be thrown if the class cannot be created. Example:
		/// <pre>"VERIFY_SUSPECT(timeout=1500)"</pre> Note that no colons (:) have to be
		/// specified
		/// </param>
		/// <param name="stack">The protocol stack
		/// </param>
		/// <returns> Protocol The newly created protocol
		/// </returns>
		/// <exception cref=""> Exception Will be thrown when the new protocol cannot be created
		/// </exception>
		public virtual Protocol createProtocol(string prot_spec, ProtocolStack stack)
		{
			ProtocolConfiguration config;
			Protocol prot;
			
			if (prot_spec == null)
				throw new System.Exception("Configurator.createProtocol(): prot_spec is null");
			
			// parse the configuration for this protocol
			config = new ProtocolConfiguration(this, prot_spec);
			
			// create an instance of the protocol class and configure it
			prot = config.createLayer(stack);
			
			// start the handler threads (unless down_thread or up_thread are set to false)
			prot.startDownHandler();
			prot.startUpHandler();
			
			return prot;
		}
 /// <summary>
 /// Calls the base <see cref="US.OpenServer.Protocols.ProtocolBase.Initialize"/>
 /// function then saves a reference to the Session and WinAuthProtocolConfigurationServer.
 /// </summary>
 /// <param name="session">A SessionBase that encapsulates the connection
 /// session. This value is casted to Session.</param>
 ///<param name="pc">A ProtocolConfiguration that contains configuration
 /// properties. This value is casted to WinAuthProtocolConfigurationServer.</param>
 /// <param name="userData">An object that may be used by client applications to
 /// pass objects or data to client side protocol implementations. This parameter is
 /// not used.</param>
 public override void Initialize(SessionBase session, ProtocolConfiguration pc, object userData = null)
 {
     base.Initialize(session, pc, userData);
     this.sessionEx = (Session)session;
     this.pc        = pc as WinAuthProtocolConfigurationServer;
 }
Exemplo n.º 14
0
		/// <summary> Return a number of ProtocolConfigurations in a vector</summary>
		/// <param name="configuration">protocol-stack configuration string
		/// </param>
		/// <returns> Vector of ProtocolConfigurations
		/// </returns>
		public virtual System.Collections.ArrayList parseConfigurations(string configuration)
		{
			System.Collections.ArrayList retval = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10));
			System.Collections.ArrayList component_strings = parseComponentStrings(configuration, ":");
			string component_string;
			ProtocolConfiguration protocol_config;
			
			if (component_strings == null)
				return null;
			for (int i = 0; i < component_strings.Count; i++)
			{
				component_string = ((string) component_strings[i]);
				protocol_config = new ProtocolConfiguration(this, component_string);
				retval.Add(protocol_config);
			}
			return retval;
		}
 public IService GetServiceClient <IService>(RegistryInformation registryInformation, ProtocolConfiguration protocolConfiguration)
 {
     return((IService) new WCFRealProxy <IService>(registryInformation, protocolConfiguration).GetTransparentProxy());
 }
Exemplo n.º 16
0
        public TronServiceTrovider()
        {
            ProtocolConfiguration protocolConfiguration = new ProtocolConfiguration(TypeNet.Main, "fullnode", 50051, 30, 5000);

            _currencyProvider = new Protocol.Tron.CurrencyProvider(protocolConfiguration);
        }
 /// <summary>
 /// Calls the base <see cref="US.OpenServer.Protocols.ProtocolBase.Initialize"/>
 /// function then saves a reference to the Session and WinAuthProtocolConfigurationServer.
 /// </summary>
 /// <param name="session">A SessionBase that encapsulates the connection
 /// session. This value is casted to Session.</param>
 ///<param name="pc">A ProtocolConfiguration that contains configuration
 /// properties. This value is casted to WinAuthProtocolConfigurationServer.</param>
 /// <param name="userData">An object that may be used by client applications to
 /// pass objects or data to client side protocol implementations. This parameter is
 /// not used.</param>
 public override void Initialize(SessionBase session, ProtocolConfiguration pc, object userData = null)
 {
     base.Initialize(session, pc, userData);
     this.sessionEx = (Session)session;
     this.pc = pc as WinAuthProtocolConfigurationServer;
 }
Exemplo n.º 18
0
        /// <summary>
        /// The function creates a new instance of the plugin.
        /// </summary>
        /// <param name="dependencies">The implementations of various adapters needed for the plugin to function.</param>
        /// <returns>The instance of the plugin.</returns>
        public IMusicBeeRemotePlugin BootStrap(MusicBeeDependencies dependencies)
        {
            JsonConvert.DefaultSettings = () =>
            {
                var settings = new JsonSerializerSettings
                {
                    DateTimeZoneHandling = DateTimeZoneHandling.Local,
                    NullValueHandling    = NullValueHandling.Ignore,
                };

                settings.Converters.Add(new StringEnumConverter {
                    NamingStrategy = new SnakeCaseNamingStrategy()
                });
                return(settings);
            };

            // Bson serialization for client IP addresses
            BsonMapper.Global.RegisterType(
                ipAddress => ipAddress.ToString(),
                bson => IPAddress.Parse(bson.AsString));

            // Bson serialization for client Physical Addresses
            BsonMapper.Global.RegisterType(
                mac => mac.ToString(),
                bson =>
            {
                var newAddress = PhysicalAddress.Parse(bson);
                return(PhysicalAddress.None.Equals(newAddress) ? null : newAddress);
            });

            _container.Configure(c =>
            {
                c.For <ILibraryApiAdapter>().Use(() => dependencies.LibraryAdapter).Singleton();
                c.For <INowPlayingApiAdapter>().Use(() => dependencies.NowPlayingAdapter).Singleton();
                c.For <IOutputApiAdapter>().Use(() => dependencies.OutputAdapter).Singleton();
                c.For <IPlayerApiAdapter>().Use(() => dependencies.PlayerAdapter).Singleton();
                c.For <IQueueAdapter>().Use(() => dependencies.QueueAdapter).Singleton();
                c.For <ITrackApiAdapter>().Use(() => dependencies.TrackAdapter).Singleton();
                c.For <IInvokeHandler>().Use(() => dependencies.InvokeHandler).Singleton();

                c.For <IWindowManager>().Use <WindowManager>().Singleton();

                c.For <IPluginLogManager>().Use <PluginLogManager>().Singleton();
                c.For <IPlayerStateMonitor>().Use <PlayerStateMonitor>().Singleton();
                c.For <ITrackStateMonitor>().Use <TrackStateMonitor>().Singleton();

                c.For <CommandExecutor>().Use <CommandExecutor>().Singleton();

                c.For <SocketServer>().Use <SocketServer>().Singleton();
                c.For <HttpSupport>().Use <HttpSupport>().Singleton();
                c.For <IPluginNetworking>().Use <PluginNetworking>().Singleton();
                c.For <LyricCoverModel>().Use <LyricCoverModel>().Singleton();
                c.For <ServiceDiscovery>().Use <ServiceDiscovery>().Singleton();

                c.For <PersistenceManager>().Use <PersistenceManager>().Singleton();
                c.For <IJsonSettingsFileManager>().Use <JsonSettingsFileManager>().Singleton();

                c.For <IStorageLocationProvider>()
                .Use <StorageLocationProvider>()
                .Ctor <string>()
                .Is(dependencies.BaseStoragePath)
                .Singleton();

                c.For <IVersionProvider>()
                .Use <VersionProvider>()
                .Ctor <string>()
                .Is(dependencies.CurrentVersion)
                .Singleton();

                c.For <Authenticator>().Use <Authenticator>().Singleton();
                c.For <ITrackRepository>().Use <TrackRepository>().Singleton();
                c.For <ICacheInfoRepository>().Use <CacheInfoRepository>().Singleton();
                c.For <ILibraryScanner>().Use <LibraryScanner>().Singleton();
                c.For <ITinyMessengerHub>().Use <TinyMessengerHub>().Singleton();
                c.For <IMusicBeeRemotePlugin>().Use <MusicBeeRemotePlugin>().Singleton();

                c.For <OpenHelpCommand>().Use <OpenHelpCommand>();
                c.For <OpenLogDirectoryCommand>().Use <OpenLogDirectoryCommand>();
                c.For <SaveConfigurationCommand>().Use <SaveConfigurationCommand>();
                c.For <ConfigurationPanel>().Use <ConfigurationPanel>();
                c.For <ConfigurationPanelViewModel>().Use <ConfigurationPanelViewModel>();
                c.For <IConfigurationPanelPresenter>().Use <ConfigurationPanelPresenter>();

                c.For <PartyModePanel>().Use <PartyModePanel>();

                c.For <IWhitelistManagementPresenter>().Use <WhitelistManagementPresenter>();
                c.For <WhitelistManagementControl>().Use <WhitelistManagementControl>();

                c.For <PodcastHttpApi>().Use <PodcastHttpApi>().Singleton();
                c.For <ClientRepository>().Singleton();
                c.For <LogRepository>().Singleton();
                c.For <ClientManager>().Singleton();
            });

            var controller = _container.GetInstance <CommandExecutor>();

            ProtocolConfiguration.Register(controller, _container);

            return(_container.GetInstance <IMusicBeeRemotePlugin>());
        }
 public WCFRealProxy(RegistryInformation registryInformation, ProtocolConfiguration protocolConfiguration) : base(typeof(IService))
 {
     this.registryInformation   = registryInformation;
     this.protocolConfiguration = protocolConfiguration;
 }
Exemplo n.º 20
0
        /// <summary>
        /// Creates a <c>ProtocolConfiguration</c> instance for each protocol in the configuration string
        /// </summary>
        /// <param name="config">The configuration string</param>
        /// <returns>The array of configuration objects</returns>
        private ProtocolConfiguration[] parseConfigurations(string config)
        {
            ProtocolConfiguration[]		retval; //= new ArrayList();
            string[]					component_strings = config.Split(new char[] {':'});
            String						component_string;
            ProtocolConfiguration		protocol_config;

            if(component_strings == null)
                return null;

            retval = new ProtocolConfiguration[component_strings.Length];

            for(int i=0; i < component_strings.Length; i++)
            {
                component_string = (String)component_strings.GetValue(i);
                protocol_config = new ProtocolConfiguration(component_string);
                retval[i] = protocol_config;
            }
            return retval;
        }
Exemplo n.º 21
0
        /// <summary>
        /// Saves a reference to the SessionBase then creates a Timer to send
        /// <see cref="KeepAliveProtocolCommands.KEEP_ALIVE"/>
        /// command packets.
        /// </summary>
        /// <param name="session">A SessionBase that encapsulates the connection
        /// session.</param>
        ///<param name="pc">A ProtocolConfiguration that contains configuration
        /// properties. This parameter is not used.</param>
        /// <param name="userData">An object that may be used by client applications to
        /// pass objects or data to client side protocol implementations. This parameter is
        /// not used.</param>
        public override void Initialize(SessionBase session, ProtocolConfiguration pc, object userData = null)
        {
            base.Initialize(session, pc, userData);

            lock (this)
            {
                if (timer != null)
                    timer.Dispose();

                timer = new Timer(TimerCallback, null, KeepAliveProtocol.INTERVAL, KeepAliveProtocol.INTERVAL);
            }
        }
        public async Task <RegistryInformation> RegisterServiceAsync(ServiceConfiguration serviceConfiguration, ProtocolConfiguration protocolConfiguration, Uri healthCheckUri = null, IEnumerable <string> tags = null)
        {
            var serviceId   = ServiceDiscoveryHelper.GetServiceId(serviceConfiguration.Interface, serviceConfiguration.Port.ToString());
            var serviceName = ServiceDiscoveryHelper.GetServiceName(protocolConfiguration.Protocol, serviceConfiguration.Interface);

            string versionLabel = $"{ServiceDiscoveryHelper.VERSION_PREFIX}{serviceConfiguration.Version}";
            var    tagList      = (tags ?? Enumerable.Empty <string>()).ToList();

            tagList.Add(protocolConfiguration.Protocol);
            tagList.Add(protocolConfiguration.Transmit);
            tagList.Add(versionLabel);

            var instance = new RegistryInformation
            {
                Name    = serviceName,
                Id      = serviceId,
                Address = await DnsUtil.GetIpAddressAsync(),
                Port    = serviceConfiguration.Port,
                Version = serviceConfiguration.Version,
                Tags    = tagList
            };

            ServiceInstances.Add(instance);
            return(instance);
        }
        public async Task <RegistryInformation> RegisterServiceAsync(ServiceConfiguration serviceConfiguration, ProtocolConfiguration protocolConfiguration, Uri healthCheckUri = null, IEnumerable <string> tags = null)
        {
            var serviceId   = ServiceDiscoveryHelper.GetServiceId(serviceConfiguration.Interface, serviceConfiguration.Port.ToString());
            var serviceName = ServiceDiscoveryHelper.GetServiceName(protocolConfiguration.Protocol, serviceConfiguration.Interface);

            string versionLabel = $"{ServiceDiscoveryHelper.VERSION_PREFIX}{serviceConfiguration.Version}";
            var    tagList      = (tags ?? Enumerable.Empty <string>()).ToList();

            tagList.Add(protocolConfiguration.Protocol);
            tagList.Add(protocolConfiguration.Transmit);
            tagList.Add(versionLabel);

            string check             = healthCheckUri?.ToString() ?? $"";
            var    agentServiceCheck = protocolConfiguration.Transmit == "tcp" ?
                                       new AgentServiceCheck {
                TCP = check, Interval = TimeSpan.FromSeconds(2)
            }
                                                    : new AgentServiceCheck {
                HTTP = check, Interval = TimeSpan.FromSeconds(2)
            };

            var registration = new AgentServiceRegistration
            {
                ID      = serviceId,
                Name    = serviceName,
                Tags    = tagList.ToArray(),
                Address = await DnsUtil.GetIpAddressAsync(),
                Port    = serviceConfiguration.Port,
                Check   = new AgentServiceCheck
                {
                    HTTP = check, Interval = TimeSpan.FromSeconds(2)
                }
            };

            await _consul.Agent.ServiceRegister(registration);

            return(new RegistryInformation
            {
                Name = registration.Name,
                Id = registration.ID,
                Address = registration.Address,
                Port = registration.Port,
                Version = serviceConfiguration.Version,
                Tags = tagList
            });
        }
Exemplo n.º 24
0
        //    [DataRow("TMy3cNNSZHY5d6F39BUbwUExJR93QDpGeh", StringType.Base58, TypeNet.Main)]
        public void DockerConnectTest(string addressBase58, StringType stringType, TypeNet typeNet)
        {
            //  ProtocolConfiguration protocolConfiguration = new ProtocolConfiguration(typeNet, "172.17.0.2", 50051);
            // ProtocolConfiguration protocolConfiguration = new ProtocolConfiguration(typeNet);
            //  ProtocolConfiguration protocolConfiguration = new ProtocolConfiguration(typeNet, "10.0.75.1", 50041);
            ProtocolConfiguration protocolConfiguration = new ProtocolConfiguration(typeNet, "10.0.75.1", 50051);

            //  ProtocolConfiguration protocolConfiguration = new ProtocolConfiguration(typeNet, "18.184.238.21", 50051);


            Wallet.WalletClient walletClient = new Latoken.CurrencyProvider.Protocol.Tron.Grpc.Api.Wallet.WalletClient(protocolConfiguration.Channel);
            NodeList            listNodes    = walletClient.ListNodes(new EmptyMessage());


            CurrencyProvider.Protocol.Tron.CurrencyProvider currencyProvider = new CurrencyProvider.Protocol.Tron.CurrencyProvider(protocolConfiguration);

            var rr  = BitConverter.GetBytes(152948);
            var ddd = rr.ToHexString2();

            BytesMessage numberMessa = new BytesMessage();

            numberMessa.Value = Google.Protobuf.ByteString.CopyFrom(ddd.FromHexToByteArray2());
            var dd = walletClient.GetBlockById(numberMessa);


            var block = walletClient.GetNowBlock(new EmptyMessage());

            //    long balance = currencyProvider.balanceByAddress(addressBase58);
            //   Console.WriteLine($"{addressBase58}:{balance}");
            //  Assert.IsTrue(balance > 0);
            List <TransactionAtom> transferContractList = new List <TransactionAtom>();

            int startPosition   = 1;
            int endPosition     = 1600000;
            int step            = 100;
            int currentPosition = startPosition;

            while (currentPosition <= endPosition)
            {
                int currentStartPosition = currentPosition;
                int currentEndPosition   = currentStartPosition + step;

                var blocklimit = new BlockLimit();
                blocklimit.StartNum = currentStartPosition;
                blocklimit.EndNum   = currentEndPosition;
                BlockList qqqq = walletClient.GetBlockByLimitNext(blocklimit);

                foreach (Block block1 in qqqq.Block)
                {
                    foreach (Transaction transaction in block1.Transactions)
                    {
                        foreach (Transaction.Types.Contract contract1 in transaction.RawData.Contract)
                        {
                            if (contract1.Type == Transaction.Types.Contract.Types.ContractType.TransferContract)
                            {
                                ByteString       parameterValue   = contract1.Parameter.Value;
                                TransferContract transferContract = TransferContract.Parser.ParseFrom(parameterValue.ToByteArray());

                                TronAddress     fromAccount = new TronAddress(transferContract.OwnerAddress.ToByteArray());
                                TronAddress     toAccount   = new TronAddress(transferContract.ToAddress.ToByteArray());
                                TransactionAtom ta          = new TransactionAtom(fromAccount, toAccount, transferContract.Amount, new TransactionHelper().GetTransactionHash(transaction));

                                transferContractList.Add(ta);
                            }
                        }
                    }
                }

                currentPosition = currentEndPosition;
            }

            //          var eeede = qqqq.Block[0].Transactions[0];
            //        var contract = eeede.RawData.Contract[0].Parameter;
        }