首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Tendermint,GRPC和C# - RST_STREAM终止的流和错误代码: PROTOCOL_ERROR

Tendermint,GRPC和C# - RST_STREAM终止的流和错误代码: PROTOCOL_ERROR
EN

Stack Overflow用户
提问于 2021-08-31 21:12:38
回答 1查看 2.7K关注 0票数 2

我在我的一个项目中需要Tendermint,但以前从未使用过它,所以我首先尝试实现一个非常简单的示例:https://docs.tendermint.com/master/tutorials/java.html,但在C# (.NET 5.0)中。

(下载:极小例子)

我创建了一个简单的GRPC服务,试图尽可能地遵循指南:

Startup.cs:

代码语言:javascript
运行
复制
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddGrpc();
    }
    
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IConfiguration conf)
    {
        if (env.IsDevelopment())
            app.UseDeveloperExceptionPage();

        app.UseRouting();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapGrpcService<KVStoreService>();
            endpoints.MapGet("/", async context =>
            {
                await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
            });
        });

        app.UseGlobalHostEnvironemnt(env); // These are for tests and are irrelevant for the problem
        app.UseGlobalConfiguration(conf);
        app.UseGlobalLogger();
        app.UseTendermint(); // This starts tendermint process
    }
}

启动招标造币厂使用基本的Process.Start调用。我在.toml配置文件中保留了默认值,是的,文档中有一个错误,--proxy_app标志应该使用下划线(错误是详细的):

代码语言:javascript
运行
复制
public static void ConfigureTendermint()
{
    var tendermint = Process.Start(new ProcessStartInfo
    {
        FileName = @"Tendermint\tendermint.exe",
        Arguments = "init validator --home=Tendermint"
    });
    tendermint?.WaitForExit();

    Process.Start(new ProcessStartInfo
    {
        FileName = @"Tendermint\tendermint.exe",
        Arguments = @"node --abci grpc --proxy_app tcp://127.0.0.1:5020 --home=Tendermint --log_level debug"
    });
}

这是正在处理.proto文件的项目文件,它们都成功地生成并工作:

代码语言:javascript
运行
复制
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Grpc" Version="2.39.1" />
    <PackageReference Include="Grpc.AspNetCore" Version="2.39.0" />
    <PackageReference Include="Grpc.Tools" Version="2.39.1">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="LiteDB" Version="5.0.11" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\..\CommonLib.AspNet\CommonLib.AspNet\CommonLib.AspNet.csproj" />
    <ProjectReference Include="..\..\CommonLib\CommonLib\CommonLib.csproj" />
  </ItemGroup>

  <ItemGroup>
    <Protobuf Include="Source\Protos\gogoproto\gogo.proto" GrpcServices="Server" ProtoRoot="Source/Protos" />
    <Protobuf Include="Source\Protos\tendermint\crypto\keys.proto" GrpcServices="Server" ProtoRoot="Source/Protos" />
    <Protobuf Include="Source\Protos\tendermint\crypto\proof.proto" GrpcServices="Server" ProtoRoot="Source/Protos" />
    <Protobuf Include="Source\Protos\tendermint\types\block.proto" GrpcServices="Server" ProtoRoot="Source/Protos" />
    <Protobuf Include="Source\Protos\tendermint\types\canonical.proto" GrpcServices="Server" ProtoRoot="Source/Protos" />
    <Protobuf Include="Source\Protos\tendermint\types\events.proto" GrpcServices="Server" ProtoRoot="Source/Protos" />
    <Protobuf Include="Source\Protos\tendermint\types\evidence.proto" GrpcServices="Server" ProtoRoot="Source/Protos" />
    <Protobuf Include="Source\Protos\tendermint\types\params.proto" GrpcServices="Server" ProtoRoot="Source/Protos" />
    <Protobuf Include="Source\Protos\tendermint\types\types.proto" GrpcServices="Server" ProtoRoot="Source/Protos" />
    <Protobuf Include="Source\Protos\tendermint\types\validator.proto" GrpcServices="Server" ProtoRoot="Source/Protos" />
    <Protobuf Include="Source\Protos\tendermint\version\types.proto" GrpcServices="Server" ProtoRoot="Source/Protos" />
    <Protobuf Include="Source\Protos\tendermint\abci\types.proto" GrpcServices="Server" ProtoRoot="Source/Protos" />
  </ItemGroup>

  <ItemGroup>
    <Folder Include="Source\Database\" />
  </ItemGroup>

</Project>

下面是服务本身,它包含转换为C#的示例(链接)

代码语言:javascript
运行
复制
public class KVStoreService : ABCIApplication.ABCIApplicationBase
{
    private static LiteDatabase _env;
    private static ILiteCollection<KV> _store;

    public LiteDatabase Env => _env ??= new LiteDatabase(WebUtils.Configuration?.GetConnectionString("LiteDb"));
    public ILiteCollection<KV> Store => _store ??= Env.GetCollection<KV>("kvs");

    public override Task<ResponseEcho> Echo(RequestEcho request, ServerCallContext context)
    {
        return Task.FromResult(new ResponseEcho { Message = $"Validator is Running: {DateTime.Now:dd-MM-yyyy HH:mm}" });
    }

    public override Task<ResponseCheckTx> CheckTx(RequestCheckTx request, ServerCallContext context)
    {
        var (code, _) = Validate(request.Tx);
        return Task.FromResult(new ResponseCheckTx { Code = code, GasWanted = 1 });
    }
    
    public override Task<ResponseBeginBlock> BeginBlock(RequestBeginBlock request, ServerCallContext context)
    {
        Env.BeginTrans();
        Store.EnsureIndex(x => x.Key, true);
        return Task.FromResult(new ResponseBeginBlock());
    }
    
    public override Task<ResponseDeliverTx> DeliverTx(RequestDeliverTx request, ServerCallContext context)
    {
        var (code, kv) = Validate(request.Tx);
        if (code == 0)
            Store.Insert(kv);
        return Task.FromResult(new ResponseDeliverTx { Code = code });
    }

    public override Task<ResponseCommit> Commit(RequestCommit request, ServerCallContext context)
    {
        Env.Commit();
        return Task.FromResult(new ResponseCommit { Data = ByteString.CopyFrom(new byte[8]) });
    }

    public override Task<ResponseQuery> Query(RequestQuery request, ServerCallContext context)
    {
        var k = request.Data.ToBase64();
        var v = Store.FindOne(x => x.Key == k)?.Value;
        var resp = new ResponseQuery();
        if (v == null)
            resp.Log = $"There is no value for \"{k}\" key";
        else 
        {
            resp.Log = "KVP:";
            resp.Key = ByteString.FromBase64(k);
            resp.Value = ByteString.FromBase64(v);
        }

        return Task.FromResult(resp);
    }

    private (uint, KV) Validate(ByteString tx) 
    {
        var kv = tx.ToStringUtf8().Split('=').Select(kv => kv.UTF8ToBase64()).ToKV();
        if (kv.Key.IsNullOrWhiteSpace() || kv.Value.IsNullOrWhiteSpace())
            return (1, kv);
        
        var stored = Store.FindOne(x => x.Key == kv.Key)?.Value;
        if (stored != null && stored == kv.Value)
            return (2, kv);

        return (0, kv);
    }
}

现在,如果我为我的服务创建一个简单的客户端,同时启动两个项目,它们都将完美地工作:

代码语言:javascript
运行
复制
public class Program
{
    public static async Task Main()
    {
        LoggerUtils.Logger.Log(LogLevel.Info, $@"Log Path: {LoggerUtils.LogPath}");
        using var channel = GrpcChannel.ForAddress("http://localhost:5020");
        var client = new ABCIApplication.ABCIApplicationClient(channel);

        var echo = string.Empty;
        while (echo.IsNullOrWhiteSpace())
        {
            try
            {
                echo = client.Echo(new RequestEcho()).Message;
            }
            catch (Exception ex) when (ex is HttpRequestException or RpcException)
            {
                await Task.Delay(1000);
                LoggerUtils.Logger.Log(LogLevel.Info, "Server not Ready, retrying...");
            }
        }
        
        var beginBlock = await client.BeginBlockAsync(new RequestBeginBlock());
        var deliver = await client.DeliverTxAsync(new RequestDeliverTx { Tx = ByteString.CopyFromUtf8("tendermint=rocks") });
        var commit = await client.CommitAsync(new RequestCommit());
        var checkTx = await client.CheckTxAsync(new RequestCheckTx { Tx = ByteString.CopyFromUtf8("tendermint=rocks") });
        var query = await client.QueryAsync(new RequestQuery { Data = ByteString.CopyFromUtf8("tendermint") });

        System.Console.WriteLine($"Echo Status: {echo}");
        System.Console.WriteLine($"Begin Block Status: {(beginBlock != null ? "Success" : "Failure")}");
        System.Console.WriteLine($"Delivery Status: {deliver.Code switch { 0 => "Success", 1 => "Invalid Data", 2 => "Already Exists", _ => "Failure" }}");
        System.Console.WriteLine($"Commit Status: {(commit.Data.ToByteArray().SequenceEqual(new byte[8]) ? "Success" : "Failure")}");
        System.Console.WriteLine($"CheckTx Status: {checkTx.Code switch { 0 => "Success", 1 => "Invalid Data", 2 => "Already Exists", _ => "Failure" }}");
        System.Console.WriteLine($"Query Status: {query.Log} {query.Key.ToStringUtf8()}{(query.Key == ByteString.Empty || query.Value == ByteString.Empty ? "" : "=")}{query.Value.ToStringUtf8()}");

        System.Console.ReadKey();
    }
}

服务器工作:

客户工作:

但是,到目前为止,只要我将Tendermint插入管道(这样客户端就可以通过它调用我的应用程序),出于某种原因,我得到了以下信息:

代码语言:javascript
运行
复制
Echo failed - module=abci-client connection=query err="rpc error: code = Internal desc = stream terminated by RST_STREAM with error code: PROTOCOL_ERROR"`

无论我如何启动进程并重复错误,都会发生这种情况。显然,由于Tendermint无法连接到代理应用程序,因此也不能调用它:

上面发布的错误是设置为调试的日志(包括GRPC日志)所得到的全部错误。

代码语言:javascript
运行
复制
"Logging": {
  "LogLevel": {
    "Default": "Debug",
    "Microsoft": "Debug",
    "Microsoft.Hosting.Lifetime": "Debug",
    "Grpc": "Debug"
  }

类似的线程指出了元数据的问题(比如\n中的元数据),但我不知道这与我的特定问题有什么关系,您可以使用这里作为参考。

我很确定这是一个简单的错误配置的情况,阻止Tendermint与实际应用程序交谈,但我无法弄清楚。任何帮助都将不胜感激。

EN

Stack Overflow用户

回答已采纳

发布于 2021-09-06 19:18:11

@artur的评论让我思考,我终于明白了。实际上,甚至在我发布这个问题之前,我的第一个想法是,这确实应该是http,尽管文档中有这样的说法,但是不,http://127.0.0.1:5020是行不通的。所以我试着把它放在.toml文件中,我甚至尝试过使用https,但也没有成功。尝试使用http不会引发任何错误,与使用tcp之前的地址不同,它只是挂在Waiting for Echo消息上(与指向错误地址时类似,这很奇怪)。我一直,最终回到了tcp版本。解决方案很简单,完全删除协议.

这些文档并没有给出任何线索,所以为了完成这些工作,至少在使用C# (.NET 5)时,您必须做3件事情才能使它正常工作,所有这些都是微不足道的,但是您必须首先自己解决它们:

  1. 当指向代理应用程序时,从配置中删除协议:tcp://127.0.0.1:<port>应该是127.0.0.1:<port>,是的,不管您在.toml文件中指定了协议还是作为控制台中的标志,它都会抛出。
  2. 标志是--proxy_app而不是--proxy-app
  3. 除了遵循本教程,您还必须显式地覆盖和实现Info()Echo()InitChain(),否则它将抛出一个Unimplemented Exception

由于我对Tendermint的理解仍然很少,所以最初的方法存在一些设计问题。以下是任何面临类似问题的人的代码:

https://github.com/rvnlord/TendermintAbciGrpcCSharp

票数 2
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69005348

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档