Пример #1
0
    // Get's the contract as an object
    async Task <EvmContract> GetContract(byte[] privateKey, byte[] publicKey)
    {
        var writer = RpcClientFactory.Configure()
                     .WithLogger(Debug.unityLogger)
                     .WithHTTP("http://127.0.0.1:46658/rpc")
                     .Create();

        var reader = RpcClientFactory.Configure()
                     .WithLogger(Debug.unityLogger)
                     .WithHTTP("http://127.0.0.1:46658/query")
                     .Create();

        var client = new DAppChainClient(writer, reader)
        {
            Logger = Debug.unityLogger
        };

        // Required middleware
        client.TxMiddleware = new TxMiddleware(new ITxMiddlewareHandler[] {
            new NonceTxMiddleware(publicKey, client),
            new SignedTxMiddleware(privateKey)
        });

        // ABI of the Solidity contract
        string abi = simpleStoreABI.ToString();

        var contractAddr = new Address(simpleStoreAddress.ToString());
        var callerAddr   = Address.FromPublicKey(publicKey);

        return(new EvmContract(client, contractAddr, callerAddr, abi));
    }
Пример #2
0
Файл: Rpc.cs Проект: Sholtee/rpc
            static async Task Invoke()
            {
                using var factory = new RpcClientFactory(Host);
                IModule proxy = await factory.CreateClient <IModule>();

                Assert.That(proxy.Add(1, 2), Is.EqualTo(3));
            }
Пример #3
0
        public NamingGrpcClientProxy(
            ILogger logger,
            string namespaceId,
            SecurityProxy securityProxy,
            IServerListFactory serverListFactory,
            NacosSdkOptions options,
            ServiceInfoHolder serviceInfoHolder)
        {
            this._logger        = logger;
            this.namespaceId    = namespaceId;
            this.uuid           = Guid.NewGuid().ToString();
            this._options       = options;
            this._securityProxy = securityProxy;

            this.requestTimeout = options.DefaultTimeOut > 0 ? options.DefaultTimeOut : 3000L;

            Dictionary <string, string> labels = new Dictionary <string, string>()
            {
                { RemoteConstants.LABEL_SOURCE, RemoteConstants.LABEL_SOURCE_SDK },
                { RemoteConstants.LABEL_MODULE, RemoteConstants.LABEL_MODULE_NAMING },
            };

            this.rpcClient = RpcClientFactory.CreateClient(uuid, RemoteConnectionType.GRPC, labels);

            this.namingGrpcConnectionEventListener = new NamingGrpcConnectionEventListener(_logger, this);

            Start(serverListFactory, serviceInfoHolder);
        }
    async Task <EvmContract> GetContract(byte[] privateKey, byte[] publicKey)
    {
        var writer = RpcClientFactory.Configure()
                     .WithLogger(Debug.unityLogger)
                     .WithWebSocket("ws://127.0.0.1:46658/websocket")
                     .Create();

        var reader = RpcClientFactory.Configure()
                     .WithLogger(Debug.unityLogger)
                     .WithWebSocket("ws://127.0.0.1:46658/queryws")
                     .Create();

        var client = new DAppChainClient(writer, reader)
        {
            Logger = Debug.unityLogger
        };

        // required middleware
        client.TxMiddleware = new TxMiddleware(new ITxMiddlewareHandler[]
        {
            new NonceTxMiddleware(publicKey, client),
            new SignedTxMiddleware(privateKey)
        });

        // ABI of the Solidity contract
        const string abi          = "[{\"constant\":false,\"inputs\":[{\"name\":\"_tileState\",\"type\":\"string\"}],\"name\":\"SetTileMapState\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"GetTileMapState\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"state\",\"type\":\"string\"}],\"name\":\"OnTileMapStateUpdate\",\"type\":\"event\"}]\r\n";
        var          contractAddr = await client.ResolveContractAddressAsync("TilesChain");

        var callerAddr = Address.FromPublicKey(publicKey);

        return(new EvmContract(client, contractAddr, callerAddr, abi));
    }
Пример #5
0
        public async Task CreateContract(byte[] privateKey)
        {
            byte[]  publicKey  = CryptoUtils.PublicKeyFromPrivateKey(privateKey);
            Address callerAddr = Address.FromPublicKey(publicKey);

            IRpcClient writer = RpcClientFactory.Configure().WithLogger(Debug.unityLogger).WithWebSocket(WriterHost)
                                .Create();

            IRpcClient reader = RpcClientFactory.Configure().WithLogger(Debug.unityLogger).WithWebSocket(ReaderHost)
                                .Create();

            DAppChainClient client = new DAppChainClient(writer, reader)
            {
                Logger = Debug.unityLogger
            };

            client.TxMiddleware = new TxMiddleware(new ITxMiddlewareHandler[]
            {
                new NonceTxMiddleware(publicKey, client), new SignedTxMiddleware(privateKey)
            });

            client.AutoReconnect = false;

            await client.ReadClient.ConnectAsync();

            await client.WriteClient.ConnectAsync();

            Address contractAddr = await client.ResolveContractAddressAsync("ZombieBattleground");

            Contract oldContract = Contract;

            Contract = new Contract(client, contractAddr, callerAddr);
            ContractCreated?.Invoke(oldContract, Contract);
        }
Пример #6
0
        /// <summary>
        /// 
        /// </summary>
        public AppHost(RpcConfig config)
        {
            if (config == null)
                throw new ArgumentNullException(nameof(config));

            Config = config;

            AppId = config.AppId;
            Registry = RegistryHelper.GetRegistry(this, config);
            ServiceHost = new ServiceHost(this, config);
            FormatterManager = new FormatterManager(config);
            ClientFactory = new RpcClientFactory(this, config);

            if (!string.IsNullOrWhiteSpace(config.Monitor?.Type))
            {
                var monitorFactory = ReflectHelper.CreateInstanceByIdentifier<IMonitorFactory>(config.Monitor.Type);
                Monitor = monitorFactory.CreateMonitor(this, config);
            }

            if (config.Filter?.Filters.Count > 0)
            {
                foreach (var item in config.Filter.Filters)
                {
                    var factory = ReflectHelper.CreateInstanceByIdentifier<IFilterFactory>(item.Type);
                    var filters = factory.CreateFilters();
                    if (filters == null) continue;
                    foreach (var filter in filters)
                    {
                        AddFilter(filter);
                    }
                }
            }
        }
    async Task <Contract> GetContract(byte[] privateKey, byte[] publicKey)
    {
        var writer = RpcClientFactory.Configure()
                     .WithLogger(Debug.unityLogger)
                     .WithHTTP("http://127.0.0.1:46658/rpc")
                     //.WithWebSocket("ws://127.0.0.1:46657/websocket")
                     .Create();

        var reader = RpcClientFactory.Configure()
                     .WithLogger(Debug.unityLogger)
                     .WithHTTP("http://127.0.0.1:46658/query")
                     //.WithWebSocket("ws://127.0.0.1:9999/queryws")
                     .Create();

        var client = new DAppChainClient(writer, reader)
        {
            Logger = Debug.unityLogger
        };

        // required middleware
        client.TxMiddleware = new TxMiddleware(new ITxMiddlewareHandler[] {
            new NonceTxMiddleware(publicKey, client),
            new SignedTxMiddleware(privateKey)
        });

        var contractAddr = await client.ResolveContractAddressAsync("BluePrint");

        var callerAddr = Address.FromPublicKey(publicKey);

        return(new Contract(client, contractAddr, callerAddr));
    }
Пример #8
0
    public async Task <EvmContract> GetContract()
    {
        this.writer = RpcClientFactory.Configure()
                      .WithLogger(Debug.unityLogger)
                      .WithWebSocket("ws://extdev-plasma-us1.dappchains.com:80/websocket")
                      .Create();
        this.reader = RpcClientFactory.Configure()
                      .WithLogger(Debug.unityLogger)
                      .WithWebSocket("ws://extdev-plasma-us1.dappchains.com:80/queryws")
                      .Create();

        this.client = new DAppChainClient(this.writer, this.reader)
        {
            Logger = this.logger
        };

        this.client.TxMiddleware = new TxMiddleware(new ITxMiddlewareHandler[]
        {
            new NonceTxMiddleware(this.publicKey, this.client),
            new SignedTxMiddleware(this.privateKey)
        });
        await this.client.ReadClient.ConnectAsync();

        await this.client.WriteClient.ConnectAsync();

        var         calller     = Address.FromPublicKey(this.publicKey);
        EvmContract evmContract = new EvmContract(this.client, this.contractAddress, calller, GetAbi());

        //evmContract.EventReceived += this.EventReceiveHandler;
        await evmContract.Client.SubscribeToAllEvents();

        return(evmContract);
    }
Пример #9
0
        private async Task <EvmContract> GetContract()
        {
            this.writer = RpcClientFactory.Configure()
                          .WithLogger(this.logger)
                          .WithWebSocket("ws://" + this.backendHost + ":46657/websocket")
                          .Create();

            this.reader = RpcClientFactory.Configure()
                          .WithLogger(this.logger)
                          .WithWebSocket("ws://" + this.backendHost + ":9999/queryws")
                          .Create();

            this.client = new DAppChainClient(this.writer, this.reader)
            {
                Logger = this.logger
            };

            // required middleware
            this.client.TxMiddleware = new TxMiddleware(new ITxMiddlewareHandler[]
            {
                new NonceTxMiddleware(this.publicKey, this.client),
                new SignedTxMiddleware(this.privateKey)
            });

            Address contractAddr = await this.client.ResolveContractAddressAsync("BlackJack");

            Address     callerAddr  = Address.FromPublicKey(this.publicKey);
            EvmContract evmContract = new EvmContract(this.client, contractAddr, callerAddr, this.abi);

            evmContract.EventReceived += EventReceivedHandler;
            return(evmContract);
        }
Пример #10
0
        private async Task <EvmContract> GetContract(byte[] privateKey, byte[] publicKey, string abi)
        {
            ILogger    logger = NullLogger.Instance;
            IRpcClient writer = RpcClientFactory.Configure()
                                .WithLogger(logger)
                                .WithWebSocket("ws://127.0.0.1:46657/websocket")
                                .Create();

            IRpcClient reader = RpcClientFactory.Configure()
                                .WithLogger(logger)
                                .WithWebSocket("ws://127.0.0.1:9999/queryws")
                                .Create();

            DAppChainClient client = new DAppChainClient(writer, reader)
            {
                Logger = logger
            };

            // required middleware
            client.TxMiddleware = new TxMiddleware(new ITxMiddlewareHandler[]
            {
                new NonceTxMiddleware(publicKey, client),
                new SignedTxMiddleware(privateKey)
            });

            Address contractAddr = await client.ResolveContractAddressAsync("Tests");

            Address callerAddr = Address.FromPublicKey(publicKey);

            return(new EvmContract(client, contractAddr, callerAddr, abi));
        }
    /// <summary>
    /// Connects to the DAppChain and returns an instance of a contract.
    /// </summary>
    /// <returns></returns>
    private async Task <EvmContract> GetContract()
    {
        this.writer = RpcClientFactory.Configure()
                      .WithLogger(this.logger)
                      .WithWebSocket("ws://" + this.backendHost + ":46657/websocket")
                      .Create();

        this.reader = RpcClientFactory.Configure()
                      .WithLogger(this.logger)
                      .WithWebSocket("ws://" + this.backendHost + ":9999/queryws")
                      .Create();

        this.client = new DAppChainClient(this.writer, this.reader)
        {
            Logger = this.logger
        };

        // required middleware
        this.client.TxMiddleware = new TxMiddleware(new ITxMiddlewareHandler[]
        {
            new NonceTxMiddleware(this.publicKey, this.client),
            new SignedTxMiddleware(this.privateKey)
        });

        // If 'truffle deploy' was used to deploy the contract,
        // you will have to use the contract address directly
        // instead of resolving it from contract name
        Address contractAddr = await this.client.ResolveContractAddressAsync("Blueprint");

        EvmContract evmContract = new EvmContract(this.client, contractAddr, this.address, this.abi);

        return(evmContract);
    }
Пример #12
0
        public RpcClientFactoryTest()
        {
            var rpcClient = new Mock <IRpcClient>();

            rpcClient.SetupGet(i => i.Protocol).Returns(RpcProtocol.Tcp);
            var clients = new IRpcClient[] { rpcClient.Object };
            var config  = new RpcConfiguration()
            {
                ClientConfig = new Dictionary <string, ClientConfiguration>()
                {
                    { "NoUdp", new ClientConfiguration()
                      {
                          Protocol = RpcProtocol.Udp
                      } },
                    { "Tcp", new ClientConfiguration()
                      {
                          Protocol = RpcProtocol.Tcp, Host = "127.0.0.1", Port = 3333, Timeout = 30
                      } }
                }
            };
            var calback = new Mock <IClientCallBack>();

            calback.Setup(i => i.NewCallBackTask(0, 30, "Tcp", "ReturnParametersNull"))
            .ReturnsAsync(new Response()
            {
                RequestId        = 2,
                Timeout          = 2,
                ReturnParameters = null
            });
            sut = new RpcClientFactory(clients, config, calback.Object);
        }
Пример #13
0
        public RpcClientFactoryTests()
        {
            var channelFactory = Substitute.For <ITcpClientChannelFactory>();
            var clientEventLoopGroupFactory = Substitute.For <ITcpClientEventLoopGroupFactory>();

            _rpcClientFactory = new RpcClientFactory(channelFactory, clientEventLoopGroupFactory,
                                                     new List <IRpcResponseObserver>());
        }
Пример #14
0
Файл: Rpc.cs Проект: Sholtee/rpc
        public void Teardown()
        {
            Server.Dispose();
            Server.Container.Dispose();
            Server = null;

            ClientFactory.Dispose();
            ClientFactory = null;
        }
Пример #15
0
        public SimpleRpcClient(IUserOutput userOutput,
                               IPasswordRegistry passwordRegistry,
                               X509Certificate2 certificate,
                               ILogger logger,
                               SigningContext signingContextProvider)
        {
            _logger      = logger;
            _certificate = certificate;

            var fileSystem = new FileSystem();

            var consolePasswordReader = new ConsolePasswordReader(userOutput, new ConsoleUserInput());
            var passwordManager       = new PasswordManager(consolePasswordReader, passwordRegistry);

            var cryptoContext = new FfiWrapper();

            var hashProvider = new HashProvider(HashingAlgorithm.GetAlgorithmMetadata("keccak-256"));

            var peerSettings = Substitute.For <IPeerSettings>();

            peerSettings.NetworkType.Returns(signingContextProvider.NetworkType);

            var localKeyStore = new LocalKeyStore(passwordManager, cryptoContext, fileSystem, hashProvider, _logger);

            var keyRegistry = new KeyRegistry();
            var keySigner   = new KeySigner(localKeyStore, cryptoContext, keyRegistry);

            var memoryCacheOptions        = new MemoryCacheOptions();
            var memoryCache               = new MemoryCache(memoryCacheOptions);
            var changeTokenProvider       = new TtlChangeTokenProvider(10000);
            var messageCorrelationManager = new RpcMessageCorrelationManager(memoryCache, _logger, changeTokenProvider);
            var peerIdValidator           = new PeerIdValidator(cryptoContext);

            var nodeRpcClientChannelFactory =
                new RpcClientChannelFactory(keySigner, messageCorrelationManager, peerIdValidator, peerSettings);

            var eventLoopGroupFactoryConfiguration = new EventLoopGroupFactoryConfiguration
            {
                TcpClientHandlerWorkerThreads = 4
            };

            var tcpClientEventLoopGroupFactory = new TcpClientEventLoopGroupFactory(eventLoopGroupFactoryConfiguration);

            var handlers = new List <IRpcResponseObserver>
            {
                new BroadcastRawTransactionResponseObserver(_logger),
                new GetVersionResponseObserver(_logger)
            };

            _rpcClientFactory =
                new RpcClientFactory(nodeRpcClientChannelFactory, tcpClientEventLoopGroupFactory, handlers);

            //PeerId for RPC/TCP is currently redundant.
            var publicKey = keyRegistry.GetItemFromRegistry(KeyRegistryTypes.DefaultKey).GetPublicKey().Bytes;

            _senderPeerId = publicKey.BuildPeerIdFromPublicKey(IPAddress.Any, 1026);
        }
Пример #16
0
        public async Task InstalledService_ShouldRun() 
        {
            if (Environment.OSVersion.Platform != PlatformID.Win32NT) Assert.Ignore("The related feature is Windows exclusive.");

            using var factory = new RpcClientFactory(HOST);
            ICalculator calculator = await factory.CreateClient<ICalculator>();

            Assert.That(await calculator.AddAsync(1, 1), Is.EqualTo(2));
        }
Пример #17
0
    public async void SignIn()
    {
        var privateKey = CryptoUtils.GeneratePrivateKey();
        var publicKey  = CryptoUtils.PublicKeyFromPrivateKey(privateKey);
        var callerAddr = Address.FromPublicKey(publicKey);

        this.statusTextRef.text = "Signed in as " + callerAddr.QualifiedAddress;

        var writer = RpcClientFactory.Configure()
                     .WithLogger(Debug.unityLogger)
                     //.WithHTTP("http://127.0.0.1:46658/rpc")
                     .WithWebSocket("ws://127.0.0.1:46658/websocket")
                     .Create();

        var reader = RpcClientFactory.Configure()
                     .WithLogger(Debug.unityLogger)
                     //.WithHTTP("http://127.0.0.1:46658/query")
                     .WithWebSocket("ws://127.0.0.1:46658/queryws")
                     .Create();

        var client = new DAppChainClient(writer, reader)
        {
            Logger = Debug.unityLogger
        };

        client.TxMiddleware = new TxMiddleware(new ITxMiddlewareHandler[] {
            new NonceTxMiddleware(publicKey, client),
            new SignedTxMiddleware(privateKey)
        });

        var contractAddr = await client.ResolveContractAddressAsync("BluePrint");

        this.contract = new Contract(client, contractAddr, callerAddr);

        // Subscribe to DAppChainClient.OnChainEvent to receive all events

        /*
         * client.OnChainEvent += (sender, e) =>
         * {
         *  var jsonStr = System.Text.Encoding.UTF8.GetString(e.Data);
         *  var data = JsonConvert.DeserializeObject<SampleEvent>(jsonStr);
         *  Debug.Log(string.Format("Chain Event: {0}, {1}, {2} from block {3}", data.Method, data.Key, data.Value, e.BlockHeight));
         * };
         */

        // Subscribe to DAppChainClient.ChainEventReceived to receive events from a specific smart contract
        await this.contract.Client.SubscribeToAllEvents();

        this.contract.EventReceived += (sender, e) =>
        {
            var jsonStr = System.Text.Encoding.UTF8.GetString(e.Data);
            var data    = JsonConvert.DeserializeObject <SampleEvent>(jsonStr);
            Debug.Log(string.Format("Contract Event: {0}, {1}, {2} from block {3}", data.Method, data.Key, data.Value, e.BlockHeight));
        };
    }
Пример #18
0
 public PropertyIssuer(RpcClientFactory factory)
 {
     this.factory     = factory;
     this.Type        = PropertyType.Production;
     this.TokenType   = TokenType.Indivisible;
     this.Category    = "Company";
     this.Subcategory = "Private";
     this.Name        = "Satang Corporation";
     this.Description = "Provides cryptocurrency solutions.";
     this.Url         = "https://satang.com";
 }
Пример #19
0
            static async Task Invoke()
            {
                using var factory = new RpcClientFactory(Host)
                      {
                          Timeout = TimeSpan.FromSeconds(5)
                      };

                ICalculator proxy = await factory.CreateClient <ICalculator>();

                Assert.That(proxy.Add(1, 2), Is.EqualTo(3));
            }
Пример #20
0
        public virtual void TestFactoryProvider()
        {
            Configuration    conf          = new Configuration();
            RpcClientFactory clientFactory = null;
            RpcServerFactory serverFactory = null;

            clientFactory = RpcFactoryProvider.GetClientFactory(conf);
            serverFactory = RpcFactoryProvider.GetServerFactory(conf);
            NUnit.Framework.Assert.AreEqual(typeof(RpcClientFactoryPBImpl), clientFactory.GetType
                                                ());
            NUnit.Framework.Assert.AreEqual(typeof(RpcServerFactoryPBImpl), serverFactory.GetType
                                                ());
            conf.Set(YarnConfiguration.IpcClientFactoryClass, "unknown");
            conf.Set(YarnConfiguration.IpcServerFactoryClass, "unknown");
            conf.Set(YarnConfiguration.IpcRecordFactoryClass, "unknown");
            try
            {
                clientFactory = RpcFactoryProvider.GetClientFactory(conf);
                NUnit.Framework.Assert.Fail("Expected an exception - unknown serializer");
            }
            catch (YarnRuntimeException)
            {
            }
            try
            {
                serverFactory = RpcFactoryProvider.GetServerFactory(conf);
                NUnit.Framework.Assert.Fail("Expected an exception - unknown serializer");
            }
            catch (YarnRuntimeException)
            {
            }
            conf = new Configuration();
            conf.Set(YarnConfiguration.IpcClientFactoryClass, "NonExistantClass");
            conf.Set(YarnConfiguration.IpcServerFactoryClass, typeof(RpcServerFactoryPBImpl).
                     FullName);
            try
            {
                clientFactory = RpcFactoryProvider.GetClientFactory(conf);
                NUnit.Framework.Assert.Fail("Expected an exception - unknown class");
            }
            catch (YarnRuntimeException)
            {
            }
            try
            {
                serverFactory = RpcFactoryProvider.GetServerFactory(conf);
            }
            catch (YarnRuntimeException)
            {
                NUnit.Framework.Assert.Fail("Error while loading factory using reflection: [" + typeof(
                                                RpcServerFactoryPBImpl).FullName + "]");
            }
        }
Пример #21
0
        public async Task Client_MayGetTheServiceVersion()
        {
            using var clientFactory = new RpcClientFactory(Host);

            //
            // Mivel a kiszolgalo "dotnet.exe"-vel lett inditva es a verzioinfo mindig a host exe verzioja
            // ezert ez most it gyakorlatilag a runtime verziojat kene visszaadja.
            //

            Version
                serverVer = await clientFactory.ServiceVersion,
                corVer    = HostProcess.MainModule.FileVersionInfo;

            Assert.That(serverVer, Is.EqualTo(corVer));
        }
Пример #22
0
        /// <summary>
        /// 开启远程调用
        /// </summary>
        /// <param name="arrMethodArgs">方法参数</param>
        /// <param name="methodInfo">方法名字</param>
        /// <returns></returns>
        private object DoMethodCall(object[] arrMethodArgs, Type[] argmentTypes, MethodInfo methodInfo)
        {
            var methodCallInfo = new MethodCallInfo()
            {
                ClassName     = _proxyType.FullName,
                MethodName    = methodInfo.Name,
                Parameters    = arrMethodArgs,
                TypeHandle    = _proxyType.TypeHandle,
                ArgumentTypes = argmentTypes
            };
            var client         = RpcClientFactory.GetClient(_proxyType.Name);
            var requestMessage = new RequestMessage()
            {
                MethodCallInfo = methodCallInfo
            };
            var responseMessage = client.Send(requestMessage);

            return(responseMessage);
        }
Пример #23
0
    public async void SignIn()
    {
        var privateKey = CryptoUtils.GeneratePrivateKey();
        var publicKey  = CryptoUtils.PublicKeyFromPrivateKey(privateKey);
        var callerAddr = Address.FromPublicKey(publicKey);

        this.statusTextRef.text = "Signed in as " + callerAddr.QualifiedAddress;

        var writer = RpcClientFactory.Configure()
                     .WithLogger(Debug.unityLogger)
                     .WithWebSocket("ws://127.0.0.1:46658/websocket")
                     .Create();

        var reader = RpcClientFactory.Configure()
                     .WithLogger(Debug.unityLogger)
                     .WithWebSocket("ws://127.0.0.1:46658/queryws")
                     .Create();

        var client = new DAppChainClient(writer, reader)
        {
            Logger = Debug.unityLogger
        };

        // required middleware
        client.TxMiddleware = new TxMiddleware(new ITxMiddlewareHandler[]
        {
            new NonceTxMiddleware(publicKey, client),
            new SignedTxMiddleware(privateKey)
        });

        const string abi          = "[{\"constant\":false,\"inputs\":[{\"name\":\"_tileState\",\"type\":\"string\"}],\"name\":\"SetTileMapState\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"GetTileMapState\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"state\",\"type\":\"string\"}],\"name\":\"OnTileMapStateUpdate\",\"type\":\"event\"}]\r\n";
        var          contractAddr = await client.ResolveContractAddressAsync("TilesChain");

        contract = new EvmContract(client, contractAddr, callerAddr, abi);

        // Subscribe to DAppChainClient.ChainEventReceived to receive events from a specific smart contract
        this.contract.EventReceived += (sender, e) =>
        {
            OnTileMapStateUpdateEvent tileMapStateUpdateEvent = e.DecodeEventDto <OnTileMapStateUpdateEvent>();
            Debug.Log(string.Format("Contract Event: {0}, {1}, from block {2}", e.EventName, tileMapStateUpdateEvent.State, e.BlockHeight));
        };
    }
Пример #24
0
        public async Task SubscribeToResponse_Without_Response_Handler_Should_Throw_Exception()
        {
            var nodeRpcClientFactory = new RpcClientFactory(_channelFactory, _clientEventLoopGroupFactory,
                                                            new List <IRpcResponseObserver>());
            var nodeRpcClient = await nodeRpcClientFactory.GetClientAsync(null, _rpcClientConfig);

            var targetVersionResponse = new VersionResponse {
                Version = "1.2.3.4"
            };
            var protocolMessage =
                targetVersionResponse.ToProtocolMessage(_peerIdentifier, CorrelationId.GenerateCorrelationId());
            var observerDto = new ObserverDto(_channelHandlerContext, protocolMessage);

            Assert.Throws <ResponseHandlerDoesNotExistException>(() =>
            {
                _mockSocketReplySubject.OnNext(observerDto);
                nodeRpcClient.SubscribeToResponse <VersionResponse>(response => { });
                _testScheduler.Start();
            });
        }
Пример #25
0
        private RpcClient EnsureRpcClient(string taskId)
        {
            Dictionary <string, string> labels    = GetLabels();
            Dictionary <string, string> newlabels = new Dictionary <string, string>(labels);

            newlabels["taskId"] = taskId;

            RpcClient rpcClient = RpcClientFactory
                                  .CreateClient("config-" + taskId + "-" + uuid, RemoteConnectionType.GRPC, newlabels);

            if (rpcClient.IsWaitInited())
            {
                InitHandlerRpcClient(rpcClient);
                rpcClient.SetTenant(GetTenant());
                rpcClient.SetClientAbilities(InitAbilities());
                rpcClient.Start();
            }

            return(rpcClient);
        }
Пример #26
0
        public RpcClientFactoryTests()
        {
            this.nodeBuilder = NodeBuilderFactory.CreateNodeBuilder(GetType());

            try
            {
                var node = this.nodeBuilder.CreateNode(true);

                this.network           = node.Network;
                this.server            = node.RPCUri;
                this.credential        = RPCCredentialString.Parse(node.GetRPCAuth());
                this.elysiumSerializer = new Mock <ITransactionSerializer>();
                this.subject           = new RpcClientFactory(this.network, this.server, this.credential, this.elysiumSerializer.Object);
            }
            catch
            {
                this.nodeBuilder.Dispose();
                throw;
            }
        }
Пример #27
0
        public static async Task <EvmContract> GetEvmContract(byte[] privateKey, byte[] publicKey, string abi, CustomTxMiddlewareFunc customTxMiddlewareFunc = null)
        {
            ILogger    logger = Debug.unityLogger;
            IRpcClient writer = RpcClientFactory.Configure()
                                .WithLogger(logger)
                                .WithWebSocket("ws://127.0.0.1:46658/websocket")
                                .Create();

            IRpcClient reader = RpcClientFactory.Configure()
                                .WithLogger(logger)
                                .WithWebSocket("ws://127.0.0.1:46658/queryws")
                                .Create();

            DAppChainClient client = new DAppChainClient(writer, reader)
            {
                Logger = logger
            };

            // required middleware
            ITxMiddlewareHandler[] txMiddlewareHandlers;
            if (customTxMiddlewareFunc != null)
            {
                txMiddlewareHandlers = customTxMiddlewareFunc(client, privateKey, publicKey);
            }
            else
            {
                txMiddlewareHandlers = new ITxMiddlewareHandler[]
                {
                    new NonceTxMiddleware(publicKey, client),
                    new SignedTxMiddleware(privateKey)
                };
            }

            client.TxMiddleware = new TxMiddleware(txMiddlewareHandlers);

            Address contractAddress = await client.ResolveContractAddressAsync("Tests");

            Address callerAddress = Address.FromPublicKey(publicKey);

            return(new EvmContract(client, contractAddress, callerAddress, abi));
        }
Пример #28
0
        public async Task SubscribeToResponse_Should_Not_Return_Invalid_Response()
        {
            var nodeRpcClientFactory = new RpcClientFactory(_channelFactory, _clientEventLoopGroupFactory,
                                                            new List <IRpcResponseObserver> {
                new GetVersionResponseObserver(_logger)
            });
            var nodeRpcClient = await nodeRpcClientFactory.GetClientAsync(null, _rpcClientConfig);

            var receivedResponse      = false;
            var targetVersionResponse = new VersionResponse {
                Version = "1.2.3.4"
            };
            var protocolMessage =
                targetVersionResponse.ToProtocolMessage(_peerIdentifier, CorrelationId.GenerateCorrelationId());
            var observerDto = new ObserverDto(_channelHandlerContext, protocolMessage);

            _mockSocketReplySubject.OnNext(observerDto);
            nodeRpcClient.SubscribeToResponse <GetDeltaResponse>(response => receivedResponse = true);
            _testScheduler.Start();

            receivedResponse.Should().BeFalse();
        }
Пример #29
0
        /// <summary>
        ///
        /// </summary>
        public AppHost(RpcConfig config)
        {
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            Config = config;

            AppId            = config.AppId;
            Registry         = RegistryHelper.GetRegistry(this, config);
            ServiceHost      = new ServiceHost(this, config);
            FormatterManager = new FormatterManager(config);
            ClientFactory    = new RpcClientFactory(this, config);

            if (!string.IsNullOrWhiteSpace(config.Monitor?.Type))
            {
                var monitorFactory = ReflectHelper.CreateInstanceByIdentifier <IMonitorFactory>(config.Monitor.Type);
                Monitor = monitorFactory.CreateMonitor(this, config);
            }

            if (config.Filter?.Filters.Count > 0)
            {
                foreach (var item in config.Filter.Filters)
                {
                    var factory = ReflectHelper.CreateInstanceByIdentifier <IFilterFactory>(item.Type);
                    var filters = factory.CreateFilters();
                    if (filters == null)
                    {
                        continue;
                    }
                    foreach (var filter in filters)
                    {
                        AddFilter(filter);
                    }
                }
            }
        }
Пример #30
0
        public async Task Setup()
        {
            if (Environment.OSVersion.Platform != PlatformID.Win32NT) return;

            Invoke(EXE_PATCH, "-install");
            Invoke("sc", "start Calculator");

            using var factory = new RpcClientFactory(HOST);
            int attempts = 0;
            do
            {
                try
                {
                    await factory.ServiceVersion;
                    break;          
                }
                catch 
                {
                    if (++attempts == 5) throw;
                    Thread.Sleep(50);
                }
            }
            while (true);
        }
        /// <summary>
        /// Deletes node data directory (if exists) and start new instance of bitcoind
        /// </summary>
        public BitcoindProcess(string hostIp, string bitcoindFullPath, string dataDir, int p2pPort, int rpcPort, string zmqIp, int zmqPort, ILoggerFactory loggerFactory, bool emptyDataDir = true)
        {
            this.Host        = hostIp;
            this.P2Port      = p2pPort;
            this.RpcPort     = rpcPort;
            this.RpcUser     = "******";
            this.RpcPassword = "******";
            this.ZmqIp       = zmqIp;
            this.ZmqPort     = zmqPort;
            this.logger      = loggerFactory.CreateLogger <BitcoindProcess>();


            if (!ArePortsAvailable(p2pPort, rpcPort))
            {
                throw new Exception(
                          "Can not start a new instance of bitcoind. Specified ports are already in use. There might be an old version of bitcoind still running. Terminate it manually and try again-");
            }

            if (emptyDataDir)
            {
                if (Directory.Exists(dataDir))
                {
                    var regtest = Path.Combine(dataDir, "regtest");
                    if (Directory.Exists(regtest))
                    {
                        logger.LogInformation($"Old regtest directory exists. Removing it: {regtest}");
                        Directory.Delete(regtest, true);
                    }
                }
                else
                {
                    Directory.CreateDirectory(dataDir);
                }
            }
            else
            {
                if (!Directory.Exists(dataDir))
                {
                    throw new Exception("Data directory does not exists. Can not start new instance of bitcoind");
                }
            }


            // use StartupInfo.ArgumentList instead of StartupInfo.Arguments to avoid problems with spaces in data dir
            var argumentList = new List <string>(defaultParams.Split(" ").ToList());

            argumentList.Add($"-port={p2pPort}");
            argumentList.Add($"-rpcport={rpcPort}");
            argumentList.Add($"-datadir={dataDir}");
            argumentList.Add($"-rpcuser={RpcUser}");
            argumentList.Add($"-rpcpassword={RpcPassword}");
            argumentList.Add($"-zmqpubhashblock=tcp://{ZmqIp}:{zmqPort}");
            argumentList.Add($"-zmqpubinvalidtx=tcp://{ZmqIp}:{zmqPort}");
            argumentList.Add($"-zmqpubdiscardedfrommempool=tcp://{ZmqIp}:{zmqPort}");
            argumentList.Add($"-invalidtxsink=ZMQ");

            logger.LogInformation($"Starting {bitcoindFullPath} {string.Join(" ",argumentList.ToArray())}");

            var localProcess = new Process();
            var startInfo    = new ProcessStartInfo(bitcoindFullPath);

            foreach (var arg in argumentList)
            {
                startInfo.ArgumentList.Add(arg);
            }

            localProcess.StartInfo = startInfo;
            try
            {
                if (!localProcess.Start())
                {
                    throw new Exception($"Can not invoke {bitcoindFullPath}");
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"Can not invoke {bitcoindFullPath}. {ex.Message}", ex);
            }

            this.process = localProcess;
            string bestBlockhash = null;


            var rpcClient = new RpcClient(RpcClientFactory.CreateAddress(Host, rpcPort),
                                          new System.Net.NetworkCredential(RpcUser, RpcPassword), loggerFactory.CreateLogger <RpcClient>());

            try
            {
                RetryUtils.Exec(() => { bestBlockhash = rpcClient.GetBestBlockHashAsync().Result; }, 10, 100);
            }
            catch (Exception e)
            {
                logger.LogError($"Can not connect to test node {e.Message}");
                throw new Exception($"Can not connect to test node", e);
            }

            this.RpcClient = rpcClient;
            if (emptyDataDir)
            {
                var height = rpcClient.GetBlockHeaderAsync(bestBlockhash).Result.Height;
                if (height != 0)
                {
                    throw new Exception(
                              "The node that was just started does not have an empty chain. Can not proceed. Terminate the instance manually. ");
                }
            }

            logger.LogInformation($"Started bitcoind process pid={localProcess.Id } rpcPort={rpcPort}, p2pPort={P2Port}, dataDir={dataDir}");
        }