Implement gRPC Simulate endpoint (#7035)

* Implement simulate endpoint

* Add GetProtoTx()

* Add signing in test

* Add txBuilderFromProto

* Remove stray println

* Update to master

* Merge master

* Fix tests

* Make tests pass

* Integrate in router

* Make proto-gen

* Fix lint

* Really fix lint

* Refactor to fix import cycles

* Rename builder -> wrapper

* Update proto/cosmos/base/reflection/v1beta1/reflection.proto

* Fix after merge

* t->w

Co-authored-by: Alexander Bezobchuk <alexanderbez@users.noreply.github.com>
This commit is contained in:
Amaury Martiny 2020-08-24 16:41:08 +02:00 committed by GitHub
parent b6760ff1a9
commit 3d969a1ffd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
26 changed files with 937 additions and 286 deletions

View File

@ -10,7 +10,9 @@ import (
"google.golang.org/grpc/encoding/proto"
"github.com/cosmos/cosmos-sdk/client/grpc/reflection"
"github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/client/grpc/simulate"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
)
@ -19,7 +21,7 @@ var protoCodec = encoding.GetCodec(proto.Name)
// GRPCQueryRouter routes ABCI Query requests to GRPC handlers
type GRPCQueryRouter struct {
routes map[string]GRPCQueryHandler
interfaceRegistry types.InterfaceRegistry
interfaceRegistry codectypes.InterfaceRegistry
serviceData []serviceData
}
@ -69,7 +71,7 @@ func (qrt *GRPCQueryRouter) RegisterService(sd *grpc.ServiceDesc, handler interf
return err
}
if qrt.interfaceRegistry != nil {
return types.UnpackInterfaces(i, qrt.interfaceRegistry)
return codectypes.UnpackInterfaces(i, qrt.interfaceRegistry)
}
return nil
}, nil)
@ -97,14 +99,27 @@ func (qrt *GRPCQueryRouter) RegisterService(sd *grpc.ServiceDesc, handler interf
})
}
// SetInterfaceRegistry sets the interface registry for the router.
func (qrt *GRPCQueryRouter) SetInterfaceRegistry(interfaceRegistry types.InterfaceRegistry) {
// SetInterfaceRegistry sets the interface registry for the router. This will
// also register the interface reflection gRPC service.
func (qrt *GRPCQueryRouter) SetInterfaceRegistry(interfaceRegistry codectypes.InterfaceRegistry) {
qrt.interfaceRegistry = interfaceRegistry
// Once we have an interface registry, we can register the interface
// registry reflection gRPC service.
reflection.RegisterReflectionServiceServer(
qrt,
reflection.NewReflectionServiceServer(qrt.interfaceRegistry),
reflection.NewReflectionServiceServer(interfaceRegistry),
)
}
// RegisterSimulateService registers the simulate service on the gRPC router.
func (qrt *GRPCQueryRouter) RegisterSimulateService(
simulateFn simulate.BaseAppSimulateFn,
interfaceRegistry codectypes.InterfaceRegistry,
pubkeyCodec cryptotypes.PublicKeyCodec,
) {
simulate.RegisterSimulateServiceServer(
qrt,
simulate.NewSimulateServer(simulateFn, qrt.interfaceRegistry, pubkeyCodec),
)
}

View File

@ -8,6 +8,7 @@ import (
fmt "fmt"
grpc1 "github.com/gogo/protobuf/grpc"
proto "github.com/gogo/protobuf/proto"
_ "google.golang.org/genproto/googleapis/api/annotations"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
@ -213,29 +214,32 @@ func init() {
}
var fileDescriptor_d48c054165687f5c = []byte{
// 339 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x52, 0x4d, 0x4b, 0xc3, 0x40,
0x14, 0xcc, 0x2a, 0x08, 0x5d, 0xb0, 0xd2, 0xf5, 0x52, 0xa3, 0x2c, 0x25, 0x20, 0xf6, 0x62, 0x42,
0xed, 0xc5, 0x8f, 0x8b, 0x5f, 0x97, 0x82, 0xf5, 0x10, 0x6f, 0x5e, 0x4a, 0xb2, 0xbe, 0xd6, 0xc5,
0x24, 0x1b, 0xf3, 0xb6, 0xfd, 0x11, 0x9e, 0xfa, 0x5f, 0xfc, 0x13, 0x1e, 0x7b, 0xf4, 0x28, 0xed,
0x1f, 0x91, 0x34, 0x4d, 0x69, 0x30, 0x8a, 0xf4, 0xb4, 0x30, 0xef, 0xcd, 0xbc, 0xd9, 0x61, 0xa8,
0x23, 0x14, 0x86, 0x0a, 0x1d, 0xdf, 0x43, 0x70, 0x12, 0xe8, 0x07, 0x20, 0xb4, 0x54, 0x91, 0x33,
0x6a, 0xf9, 0xa0, 0xbd, 0xd6, 0x0a, 0x64, 0xc7, 0x89, 0xd2, 0x8a, 0xf1, 0x8c, 0x60, 0xa7, 0x04,
0x7b, 0x65, 0xba, 0x20, 0x58, 0x26, 0xad, 0xdf, 0x49, 0xd4, 0x57, 0x41, 0xd0, 0x89, 0x34, 0x24,
0x7d, 0x4f, 0x00, 0xba, 0xf0, 0x3a, 0x04, 0xd4, 0xd6, 0x2d, 0xdd, 0x2b, 0x99, 0x61, 0xac, 0x22,
0x04, 0x76, 0x44, 0x77, 0x64, 0x8e, 0xf6, 0x22, 0x2f, 0x04, 0xac, 0x93, 0xc6, 0x66, 0xb3, 0xe2,
0x56, 0x97, 0xf0, 0x7d, 0x8a, 0x5a, 0x37, 0xd4, 0x4c, 0x55, 0x3a, 0x61, 0x1c, 0x40, 0x08, 0x91,
0xf6, 0xd2, 0xfb, 0xf9, 0x0d, 0x76, 0x48, 0xab, 0x45, 0x99, 0x3a, 0x69, 0x90, 0x66, 0xc5, 0xdd,
0x2e, 0xa8, 0x58, 0x3d, 0xba, 0x5f, 0x2a, 0xb2, 0x30, 0x73, 0x49, 0x0f, 0x64, 0x61, 0xd4, 0x0b,
0x01, 0xd1, 0x1b, 0x14, 0x9d, 0x99, 0xc5, 0x9d, 0x6e, 0xb6, 0x32, 0x77, 0x79, 0xf2, 0xbe, 0x41,
0x6b, 0xee, 0x32, 0x9e, 0x07, 0x48, 0x46, 0x52, 0x00, 0x7b, 0x23, 0xb4, 0xf6, 0x23, 0x02, 0x76,
0x6a, 0xff, 0x1d, 0xaa, 0xfd, 0x5b, 0xa2, 0xe6, 0xd9, 0x1a, 0xcc, 0xec, 0x8b, 0x96, 0xc1, 0xc6,
0x84, 0xee, 0x96, 0x84, 0xc0, 0xce, 0xff, 0x23, 0x5a, 0x1e, 0xbf, 0x79, 0xb1, 0x16, 0x37, 0xb7,
0x74, 0xdd, 0xfd, 0x98, 0x72, 0x32, 0x99, 0x72, 0xf2, 0x35, 0xe5, 0x64, 0x3c, 0xe3, 0xc6, 0x64,
0xc6, 0x8d, 0xcf, 0x19, 0x37, 0x1e, 0xdb, 0x03, 0xa9, 0x9f, 0x87, 0xbe, 0x2d, 0x54, 0x98, 0x77,
0x36, 0x7b, 0x8e, 0xf1, 0xe9, 0xc5, 0x11, 0x81, 0x84, 0x48, 0x3b, 0x83, 0x24, 0x16, 0x2b, 0x95,
0xf5, 0xb7, 0xe6, 0x9d, 0x6d, 0x7f, 0x07, 0x00, 0x00, 0xff, 0xff, 0x2d, 0x13, 0x9d, 0x10, 0xe6,
0x02, 0x00, 0x00,
// 393 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xd2, 0x4f, 0xce, 0x2f, 0xce,
0xcd, 0x2f, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0x2f, 0x4a, 0x4d, 0xcb, 0x49, 0x4d, 0x2e, 0xc9,
0xcc, 0xcf, 0xd3, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0x44, 0x12, 0xd2, 0x2b, 0x28, 0xca,
0x2f, 0xc9, 0x17, 0x92, 0x83, 0x68, 0xd0, 0x03, 0x69, 0xd0, 0x43, 0x92, 0x85, 0x6a, 0x90, 0x92,
0x49, 0xcf, 0xcf, 0x4f, 0xcf, 0x49, 0xd5, 0x4f, 0x2c, 0xc8, 0xd4, 0x4f, 0xcc, 0xcb, 0xcb, 0x2f,
0x49, 0x04, 0x49, 0x17, 0x43, 0x74, 0x2b, 0x49, 0x71, 0x49, 0xf8, 0x64, 0x16, 0x97, 0x38, 0xe6,
0xe4, 0x78, 0xe6, 0x95, 0xa4, 0x16, 0xa5, 0x25, 0x26, 0xa7, 0x16, 0x07, 0xa5, 0x16, 0x96, 0xa6,
0x16, 0x97, 0x28, 0xb9, 0x70, 0x49, 0x62, 0x91, 0x2b, 0x2e, 0xc8, 0xcf, 0x2b, 0x4e, 0x15, 0x52,
0xe7, 0xe2, 0xcf, 0x84, 0x89, 0xc6, 0xe7, 0x25, 0xe6, 0xa6, 0x16, 0x4b, 0x30, 0x2a, 0x30, 0x6b,
0x70, 0x06, 0xf1, 0xc1, 0x85, 0xfd, 0x40, 0xa2, 0x4a, 0xce, 0x5c, 0x52, 0x20, 0x53, 0x3c, 0x73,
0x0b, 0x72, 0x52, 0x73, 0x53, 0xf3, 0xa0, 0xd6, 0x43, 0xed, 0x10, 0x52, 0xe5, 0xe2, 0x43, 0x35,
0x46, 0x82, 0x51, 0x81, 0x51, 0x83, 0x33, 0x88, 0x17, 0xc5, 0x14, 0xa5, 0x78, 0x2e, 0x69, 0xac,
0x86, 0x40, 0x1d, 0xe3, 0xc0, 0x25, 0x93, 0x89, 0x22, 0x15, 0x9f, 0x9b, 0x5a, 0x5c, 0x9c, 0x98,
0x8e, 0xea, 0x32, 0x29, 0x54, 0x35, 0xbe, 0x10, 0x25, 0x60, 0x57, 0x1a, 0xad, 0x65, 0xe6, 0x12,
0x0c, 0x82, 0x07, 0x5e, 0x70, 0x6a, 0x51, 0x59, 0x66, 0x72, 0xaa, 0xd0, 0x1e, 0x46, 0x2e, 0x41,
0x8c, 0x20, 0x10, 0xb2, 0xd0, 0xc3, 0x1f, 0xe4, 0x7a, 0xb8, 0x42, 0x54, 0xca, 0x92, 0x0c, 0x9d,
0x10, 0x2f, 0x2a, 0x19, 0x35, 0x5d, 0x7e, 0x32, 0x99, 0x49, 0x47, 0x48, 0x8b, 0x50, 0x02, 0xc9,
0x44, 0x38, 0xf4, 0x06, 0x23, 0x97, 0x30, 0x96, 0x60, 0x13, 0xb2, 0x22, 0xc6, 0x19, 0xd8, 0x23,
0x4c, 0xca, 0x9a, 0x2c, 0xbd, 0x50, 0x4f, 0x78, 0x80, 0x3d, 0xe1, 0x24, 0xe4, 0x40, 0xd0, 0x13,
0xa8, 0x06, 0xe8, 0x57, 0xa3, 0x26, 0x92, 0x5a, 0x27, 0xdf, 0x13, 0x8f, 0xe4, 0x18, 0x2f, 0x3c,
0x92, 0x63, 0x7c, 0xf0, 0x48, 0x8e, 0x71, 0xc2, 0x63, 0x39, 0x86, 0x0b, 0x8f, 0xe5, 0x18, 0x6e,
0x3c, 0x96, 0x63, 0x88, 0x32, 0x4e, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0x85,
0xd9, 0x02, 0xa1, 0x74, 0x8b, 0x53, 0xb2, 0xf5, 0x93, 0x73, 0x32, 0x53, 0xf3, 0x4a, 0xf4, 0xd3,
0x8b, 0x0a, 0x92, 0x91, 0xec, 0x4d, 0x62, 0x03, 0xe7, 0x06, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff,
0xff, 0xd2, 0xbf, 0x07, 0xa6, 0x7e, 0x03, 0x00, 0x00,
}
// Reference imports to suppress errors if they are not otherwise used.

View File

@ -0,0 +1,245 @@
// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
// source: cosmos/base/reflection/v1beta1/reflection.proto
/*
Package reflection is a reverse proxy.
It translates gRPC into RESTful JSON APIs.
*/
package reflection
import (
"context"
"io"
"net/http"
"github.com/golang/protobuf/descriptor"
"github.com/golang/protobuf/proto"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/grpc-ecosystem/grpc-gateway/utilities"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/status"
)
// Suppress "imported and not used" errors
var _ codes.Code
var _ io.Reader
var _ status.Status
var _ = runtime.String
var _ = utilities.NewDoubleArray
var _ = descriptor.ForMessage
func request_ReflectionService_ListAllInterfaces_0(ctx context.Context, marshaler runtime.Marshaler, client ReflectionServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ListAllInterfacesRequest
var metadata runtime.ServerMetadata
msg, err := client.ListAllInterfaces(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_ReflectionService_ListAllInterfaces_0(ctx context.Context, marshaler runtime.Marshaler, server ReflectionServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ListAllInterfacesRequest
var metadata runtime.ServerMetadata
msg, err := server.ListAllInterfaces(ctx, &protoReq)
return msg, metadata, err
}
func request_ReflectionService_ListImplementations_0(ctx context.Context, marshaler runtime.Marshaler, client ReflectionServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ListImplementationsRequest
var metadata runtime.ServerMetadata
var (
val string
ok bool
err error
_ = err
)
val, ok = pathParams["interface_name"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "interface_name")
}
protoReq.InterfaceName, err = runtime.String(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "interface_name", err)
}
msg, err := client.ListImplementations(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_ReflectionService_ListImplementations_0(ctx context.Context, marshaler runtime.Marshaler, server ReflectionServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ListImplementationsRequest
var metadata runtime.ServerMetadata
var (
val string
ok bool
err error
_ = err
)
val, ok = pathParams["interface_name"]
if !ok {
return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "interface_name")
}
protoReq.InterfaceName, err = runtime.String(val)
if err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "interface_name", err)
}
msg, err := server.ListImplementations(ctx, &protoReq)
return msg, metadata, err
}
// RegisterReflectionServiceHandlerServer registers the http handlers for service ReflectionService to "mux".
// UnaryRPC :call ReflectionServiceServer directly.
// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906.
func RegisterReflectionServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server ReflectionServiceServer) error {
mux.Handle("GET", pattern_ReflectionService_ListAllInterfaces_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_ReflectionService_ListAllInterfaces_0(rctx, inboundMarshaler, server, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_ReflectionService_ListAllInterfaces_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_ReflectionService_ListImplementations_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_ReflectionService_ListImplementations_0(rctx, inboundMarshaler, server, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_ReflectionService_ListImplementations_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
// RegisterReflectionServiceHandlerFromEndpoint is same as RegisterReflectionServiceHandler but
// automatically dials to "endpoint" and closes the connection when "ctx" gets done.
func RegisterReflectionServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) {
conn, err := grpc.Dial(endpoint, opts...)
if err != nil {
return err
}
defer func() {
if err != nil {
if cerr := conn.Close(); cerr != nil {
grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr)
}
return
}
go func() {
<-ctx.Done()
if cerr := conn.Close(); cerr != nil {
grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr)
}
}()
}()
return RegisterReflectionServiceHandler(ctx, mux, conn)
}
// RegisterReflectionServiceHandler registers the http handlers for service ReflectionService to "mux".
// The handlers forward requests to the grpc endpoint over "conn".
func RegisterReflectionServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
return RegisterReflectionServiceHandlerClient(ctx, mux, NewReflectionServiceClient(conn))
}
// RegisterReflectionServiceHandlerClient registers the http handlers for service ReflectionService
// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "ReflectionServiceClient".
// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "ReflectionServiceClient"
// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in
// "ReflectionServiceClient" to call the correct interceptors.
func RegisterReflectionServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client ReflectionServiceClient) error {
mux.Handle("GET", pattern_ReflectionService_ListAllInterfaces_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_ReflectionService_ListAllInterfaces_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_ReflectionService_ListAllInterfaces_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_ReflectionService_ListImplementations_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_ReflectionService_ListImplementations_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_ReflectionService_ListImplementations_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
var (
pattern_ReflectionService_ListAllInterfaces_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"cosmos", "base", "reflection", "v1beta1", "interfaces"}, "", runtime.AssumeColonVerbOpt(true)))
pattern_ReflectionService_ListImplementations_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4, 1, 0, 4, 1, 5, 5}, []string{"cosmos", "base", "reflection", "v1beta1", "implementations", "interface_name"}, "", runtime.AssumeColonVerbOpt(true)))
)
var (
forward_ReflectionService_ListAllInterfaces_0 = runtime.ForwardResponseMessage
forward_ReflectionService_ListImplementations_0 = runtime.ForwardResponseMessage
)

View File

@ -0,0 +1,61 @@
package simulate
import (
"context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
authtx "github.com/cosmos/cosmos-sdk/x/auth/tx"
)
// BaseAppSimulateFn is the signature of the Baseapp#Simulate function.
type BaseAppSimulateFn func(txBytes []byte, txtypes sdk.Tx) (sdk.GasInfo, *sdk.Result, error)
type simulateServer struct {
simulate BaseAppSimulateFn
interfaceRegistry codectypes.InterfaceRegistry
pubkeyCodec cryptotypes.PublicKeyCodec
}
// NewSimulateServer creates a new SimulateServer.
func NewSimulateServer(simulate BaseAppSimulateFn, interfaceRegistry codectypes.InterfaceRegistry, pubkeyCodec cryptotypes.PublicKeyCodec) SimulateServiceServer {
return simulateServer{
simulate: simulate,
interfaceRegistry: interfaceRegistry,
pubkeyCodec: pubkeyCodec,
}
}
var _ SimulateServiceServer = simulateServer{}
// Simulate implements the SimulateService.Simulate RPC method.
func (s simulateServer) Simulate(ctx context.Context, req *SimulateRequest) (*SimulateResponse, error) {
if req.Tx == nil {
return nil, status.Error(codes.InvalidArgument, "invalid empty tx")
}
err := req.Tx.UnpackInterfaces(s.interfaceRegistry)
if err != nil {
return nil, err
}
txBuilder := authtx.WrapTx(req.Tx, s.pubkeyCodec)
txBytes, err := req.Tx.Marshal()
if err != nil {
return nil, err
}
gasInfo, result, err := s.simulate(txBytes, txBuilder.GetTx())
if err != nil {
return nil, err
}
return &SimulateResponse{
GasInfo: &gasInfo,
Result: result,
}, nil
}

View File

@ -1,14 +1,16 @@
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: cosmos/tx/v1beta1/service.proto
// source: cosmos/base/simulate/v1beta1/simulate.proto
package tx
package simulate
import (
context "context"
fmt "fmt"
types "github.com/cosmos/cosmos-sdk/types"
tx "github.com/cosmos/cosmos-sdk/types/tx"
grpc1 "github.com/gogo/protobuf/grpc"
proto "github.com/gogo/protobuf/proto"
_ "google.golang.org/genproto/googleapis/api/annotations"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
@ -28,16 +30,18 @@ var _ = math.Inf
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
// SimulateRequest is the request type for the Service.Simulate RPC method.
// SimulateRequest is the request type for the SimulateServiceService.Simulate
// RPC method.
type SimulateRequest struct {
Tx *Tx `protobuf:"bytes,1,opt,name=tx,proto3" json:"tx,omitempty"`
// tx is the transaction to simulate.
Tx *tx.Tx `protobuf:"bytes,1,opt,name=tx,proto3" json:"tx,omitempty"`
}
func (m *SimulateRequest) Reset() { *m = SimulateRequest{} }
func (m *SimulateRequest) String() string { return proto.CompactTextString(m) }
func (*SimulateRequest) ProtoMessage() {}
func (*SimulateRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_e0b00a618705eca7, []int{0}
return fileDescriptor_503c836d80bb2d47, []int{0}
}
func (m *SimulateRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
@ -66,24 +70,27 @@ func (m *SimulateRequest) XXX_DiscardUnknown() {
var xxx_messageInfo_SimulateRequest proto.InternalMessageInfo
func (m *SimulateRequest) GetTx() *Tx {
func (m *SimulateRequest) GetTx() *tx.Tx {
if m != nil {
return m.Tx
}
return nil
}
// SimulateResponse is the response type for the Service.Simulate RPC method.
// SimulateResponse is the response type for the
// SimulateServiceService.SimulateRPC method.
type SimulateResponse struct {
// gas_info is the information about gas used in the simulation.
GasInfo *types.GasInfo `protobuf:"bytes,1,opt,name=gas_info,json=gasInfo,proto3" json:"gas_info,omitempty"`
Result *types.Result `protobuf:"bytes,2,opt,name=result,proto3" json:"result,omitempty"`
// result is the result of the simulation.
Result *types.Result `protobuf:"bytes,2,opt,name=result,proto3" json:"result,omitempty"`
}
func (m *SimulateResponse) Reset() { *m = SimulateResponse{} }
func (m *SimulateResponse) String() string { return proto.CompactTextString(m) }
func (*SimulateResponse) ProtoMessage() {}
func (*SimulateResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_e0b00a618705eca7, []int{1}
return fileDescriptor_503c836d80bb2d47, []int{1}
}
func (m *SimulateResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
@ -127,33 +134,38 @@ func (m *SimulateResponse) GetResult() *types.Result {
}
func init() {
proto.RegisterType((*SimulateRequest)(nil), "cosmos.tx.v1beta1.SimulateRequest")
proto.RegisterType((*SimulateResponse)(nil), "cosmos.tx.v1beta1.SimulateResponse")
proto.RegisterType((*SimulateRequest)(nil), "cosmos.base.simulate.v1beta1.SimulateRequest")
proto.RegisterType((*SimulateResponse)(nil), "cosmos.base.simulate.v1beta1.SimulateResponse")
}
func init() { proto.RegisterFile("cosmos/tx/v1beta1/service.proto", fileDescriptor_e0b00a618705eca7) }
func init() {
proto.RegisterFile("cosmos/base/simulate/v1beta1/simulate.proto", fileDescriptor_503c836d80bb2d47)
}
var fileDescriptor_e0b00a618705eca7 = []byte{
// 300 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4f, 0xce, 0x2f, 0xce,
0xcd, 0x2f, 0xd6, 0x2f, 0xa9, 0xd0, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x2f, 0x4e,
0x2d, 0x2a, 0xcb, 0x4c, 0x4e, 0xd5, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x84, 0x28, 0xd0,
0x2b, 0xa9, 0xd0, 0x83, 0x2a, 0x90, 0x52, 0x86, 0xea, 0x49, 0x4a, 0x2c, 0x4e, 0xd5, 0x4f, 0x4c,
0x4a, 0xce, 0x84, 0x6b, 0x05, 0x71, 0x20, 0xfa, 0xa4, 0xa4, 0x30, 0x0d, 0x2e, 0xa9, 0x80, 0xc8,
0x29, 0x59, 0x70, 0xf1, 0x07, 0x67, 0xe6, 0x96, 0xe6, 0x24, 0x96, 0xa4, 0x06, 0xa5, 0x16, 0x96,
0xa6, 0x16, 0x97, 0x08, 0xa9, 0x72, 0x31, 0x95, 0x54, 0x48, 0x30, 0x2a, 0x30, 0x6a, 0x70, 0x1b,
0x89, 0xea, 0x61, 0xd8, 0xa9, 0x17, 0x52, 0x11, 0xc4, 0x54, 0x52, 0xa1, 0xd4, 0xc5, 0xc8, 0x25,
0x80, 0xd0, 0x5a, 0x5c, 0x90, 0x9f, 0x57, 0x9c, 0x2a, 0x64, 0xc3, 0xc5, 0x91, 0x9e, 0x58, 0x1c,
0x9f, 0x99, 0x97, 0x96, 0x0f, 0x35, 0x41, 0x11, 0x66, 0x02, 0xc8, 0x89, 0x7a, 0x60, 0x57, 0xc1,
0x0c, 0x72, 0x4f, 0x2c, 0xf6, 0xcc, 0x4b, 0xcb, 0x0f, 0x62, 0x4f, 0x87, 0x30, 0x84, 0x2c, 0xb8,
0xd8, 0x8a, 0x52, 0x8b, 0x4b, 0x73, 0x4a, 0x24, 0x98, 0xc0, 0x7a, 0x15, 0x70, 0xeb, 0x0d, 0x02,
0xab, 0x0b, 0x82, 0xaa, 0x37, 0x4a, 0xe0, 0x62, 0x0f, 0x86, 0x84, 0x95, 0x50, 0x28, 0x17, 0x07,
0xcc, 0x59, 0x42, 0x4a, 0x58, 0x9c, 0x8f, 0xe6, 0x5d, 0x29, 0x65, 0xbc, 0x6a, 0x20, 0xfe, 0x52,
0x62, 0x70, 0xb2, 0x3f, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18,
0x27, 0x3c, 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, 0x39, 0x86, 0x28, 0xd5, 0xf4,
0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, 0x7d, 0x68, 0x48, 0x43, 0x28, 0xdd, 0xe2,
0x94, 0x6c, 0xfd, 0x92, 0xca, 0x82, 0x54, 0x50, 0xd0, 0x27, 0xb1, 0x81, 0x03, 0xdc, 0x18, 0x10,
0x00, 0x00, 0xff, 0xff, 0x16, 0x0a, 0x0d, 0x78, 0xe7, 0x01, 0x00, 0x00,
var fileDescriptor_503c836d80bb2d47 = []byte{
// 351 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x91, 0xbf, 0x4b, 0xf3, 0x40,
0x18, 0xc7, 0x7b, 0x19, 0xfa, 0x96, 0x7b, 0x87, 0xf7, 0x25, 0x20, 0x94, 0x50, 0x42, 0x8d, 0x28,
0x05, 0xe9, 0x1d, 0xad, 0x4b, 0x07, 0x27, 0x17, 0x11, 0xb7, 0xd4, 0xc9, 0x45, 0x2e, 0xf1, 0x1a,
0x0f, 0xd3, 0xbb, 0x98, 0x7b, 0x52, 0x32, 0x3b, 0x3a, 0x09, 0x4e, 0xfe, 0x11, 0xfe, 0x1f, 0x8e,
0x05, 0x17, 0x47, 0x69, 0xfd, 0x43, 0xa4, 0xc9, 0x25, 0x2d, 0x82, 0xd2, 0x29, 0xb9, 0xe7, 0xf9,
0x7c, 0xbf, 0xcf, 0x2f, 0x7c, 0x18, 0x2a, 0x3d, 0x55, 0x9a, 0x06, 0x4c, 0x73, 0xaa, 0xc5, 0x34,
0x8b, 0x19, 0x70, 0x3a, 0x1b, 0x04, 0x1c, 0xd8, 0xa0, 0x0e, 0x90, 0x24, 0x55, 0xa0, 0xec, 0x4e,
0x09, 0x93, 0x15, 0x4c, 0xea, 0x9c, 0x81, 0x9d, 0x4e, 0xa4, 0x54, 0x14, 0x73, 0xca, 0x12, 0x41,
0x99, 0x94, 0x0a, 0x18, 0x08, 0x25, 0x75, 0xa9, 0x75, 0xf6, 0x36, 0x0b, 0xb1, 0x20, 0x14, 0x75,
0x91, 0xd5, 0xc3, 0x40, 0x8e, 0x81, 0x20, 0xaf, 0xb3, 0x90, 0x97, 0x39, 0x6f, 0x84, 0xff, 0x8d,
0x4d, 0x49, 0x9f, 0xdf, 0x65, 0x5c, 0x83, 0xbd, 0x8f, 0x2d, 0xc8, 0xdb, 0xa8, 0x8b, 0x7a, 0x7f,
0x87, 0x3b, 0xc4, 0x34, 0x07, 0x79, 0xd5, 0x11, 0xb9, 0xc8, 0x7d, 0x0b, 0x72, 0xef, 0x01, 0xe1,
0xff, 0x6b, 0xa9, 0x4e, 0x94, 0xd4, 0xdc, 0x3e, 0xc6, 0xad, 0x88, 0xe9, 0x2b, 0x21, 0x27, 0xca,
0x38, 0xec, 0x92, 0xcd, 0xf1, 0x8a, 0xae, 0x2a, 0xa3, 0x53, 0xa6, 0xcf, 0xe4, 0x44, 0xf9, 0x7f,
0xa2, 0xf2, 0xc7, 0x1e, 0xe1, 0x66, 0xca, 0x75, 0x16, 0x43, 0xdb, 0x2a, 0xb4, 0xdd, 0x9f, 0xb5,
0x7e, 0xc1, 0xf9, 0x86, 0x1f, 0xbe, 0xa0, 0xf5, 0x1c, 0x63, 0x9e, 0xce, 0x44, 0xc8, 0xed, 0x67,
0x84, 0x5b, 0x55, 0xcc, 0xee, 0x93, 0xdf, 0xb6, 0x4c, 0xbe, 0xed, 0xc0, 0x21, 0xdb, 0xe2, 0xe5,
0xdc, 0x1e, 0xb9, 0x7f, 0xfb, 0x7c, 0xb2, 0x7a, 0xde, 0x01, 0xdd, 0xea, 0xf2, 0x27, 0xe7, 0xaf,
0x0b, 0x17, 0xcd, 0x17, 0x2e, 0xfa, 0x58, 0xb8, 0xe8, 0x71, 0xe9, 0x36, 0xe6, 0x4b, 0xb7, 0xf1,
0xbe, 0x74, 0x1b, 0x97, 0x83, 0x48, 0xc0, 0x4d, 0x16, 0x90, 0x50, 0x4d, 0x2b, 0xaf, 0xf2, 0xd3,
0xd7, 0xd7, 0xb7, 0x34, 0x8c, 0x05, 0x97, 0x40, 0xa3, 0x34, 0x09, 0x6b, 0xb3, 0xa0, 0x59, 0x9c,
0xf2, 0xe8, 0x2b, 0x00, 0x00, 0xff, 0xff, 0x7d, 0x16, 0xed, 0x90, 0x76, 0x02, 0x00, 0x00,
}
// Reference imports to suppress errors if they are not otherwise used.
@ -164,78 +176,78 @@ var _ grpc.ClientConn
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion4
// ServiceClient is the client API for Service service.
// SimulateServiceClient is the client API for SimulateService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type ServiceClient interface {
type SimulateServiceClient interface {
// Simulate simulates executing a transaction for estimating gas usage.
Simulate(ctx context.Context, in *SimulateRequest, opts ...grpc.CallOption) (*SimulateResponse, error)
}
type serviceClient struct {
type simulateServiceClient struct {
cc grpc1.ClientConn
}
func NewServiceClient(cc grpc1.ClientConn) ServiceClient {
return &serviceClient{cc}
func NewSimulateServiceClient(cc grpc1.ClientConn) SimulateServiceClient {
return &simulateServiceClient{cc}
}
func (c *serviceClient) Simulate(ctx context.Context, in *SimulateRequest, opts ...grpc.CallOption) (*SimulateResponse, error) {
func (c *simulateServiceClient) Simulate(ctx context.Context, in *SimulateRequest, opts ...grpc.CallOption) (*SimulateResponse, error) {
out := new(SimulateResponse)
err := c.cc.Invoke(ctx, "/cosmos.tx.v1beta1.Service/Simulate", in, out, opts...)
err := c.cc.Invoke(ctx, "/cosmos.base.simulate.v1beta1.SimulateService/Simulate", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// ServiceServer is the server API for Service service.
type ServiceServer interface {
// SimulateServiceServer is the server API for SimulateService service.
type SimulateServiceServer interface {
// Simulate simulates executing a transaction for estimating gas usage.
Simulate(context.Context, *SimulateRequest) (*SimulateResponse, error)
}
// UnimplementedServiceServer can be embedded to have forward compatible implementations.
type UnimplementedServiceServer struct {
// UnimplementedSimulateServiceServer can be embedded to have forward compatible implementations.
type UnimplementedSimulateServiceServer struct {
}
func (*UnimplementedServiceServer) Simulate(ctx context.Context, req *SimulateRequest) (*SimulateResponse, error) {
func (*UnimplementedSimulateServiceServer) Simulate(ctx context.Context, req *SimulateRequest) (*SimulateResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Simulate not implemented")
}
func RegisterServiceServer(s grpc1.Server, srv ServiceServer) {
s.RegisterService(&_Service_serviceDesc, srv)
func RegisterSimulateServiceServer(s grpc1.Server, srv SimulateServiceServer) {
s.RegisterService(&_SimulateService_serviceDesc, srv)
}
func _Service_Simulate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
func _SimulateService_Simulate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SimulateRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ServiceServer).Simulate(ctx, in)
return srv.(SimulateServiceServer).Simulate(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/cosmos.tx.v1beta1.Service/Simulate",
FullMethod: "/cosmos.base.simulate.v1beta1.SimulateService/Simulate",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ServiceServer).Simulate(ctx, req.(*SimulateRequest))
return srv.(SimulateServiceServer).Simulate(ctx, req.(*SimulateRequest))
}
return interceptor(ctx, in, info, handler)
}
var _Service_serviceDesc = grpc.ServiceDesc{
ServiceName: "cosmos.tx.v1beta1.Service",
HandlerType: (*ServiceServer)(nil),
var _SimulateService_serviceDesc = grpc.ServiceDesc{
ServiceName: "cosmos.base.simulate.v1beta1.SimulateService",
HandlerType: (*SimulateServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Simulate",
Handler: _Service_Simulate_Handler,
Handler: _SimulateService_Simulate_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "cosmos/tx/v1beta1/service.proto",
Metadata: "cosmos/base/simulate/v1beta1/simulate.proto",
}
func (m *SimulateRequest) Marshal() (dAtA []byte, err error) {
@ -265,7 +277,7 @@ func (m *SimulateRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
return 0, err
}
i -= size
i = encodeVarintService(dAtA, i, uint64(size))
i = encodeVarintSimulate(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
@ -300,7 +312,7 @@ func (m *SimulateResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
return 0, err
}
i -= size
i = encodeVarintService(dAtA, i, uint64(size))
i = encodeVarintSimulate(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x12
@ -312,7 +324,7 @@ func (m *SimulateResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
return 0, err
}
i -= size
i = encodeVarintService(dAtA, i, uint64(size))
i = encodeVarintSimulate(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0xa
@ -320,8 +332,8 @@ func (m *SimulateResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
return len(dAtA) - i, nil
}
func encodeVarintService(dAtA []byte, offset int, v uint64) int {
offset -= sovService(v)
func encodeVarintSimulate(dAtA []byte, offset int, v uint64) int {
offset -= sovSimulate(v)
base := offset
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
@ -339,7 +351,7 @@ func (m *SimulateRequest) Size() (n int) {
_ = l
if m.Tx != nil {
l = m.Tx.Size()
n += 1 + l + sovService(uint64(l))
n += 1 + l + sovSimulate(uint64(l))
}
return n
}
@ -352,20 +364,20 @@ func (m *SimulateResponse) Size() (n int) {
_ = l
if m.GasInfo != nil {
l = m.GasInfo.Size()
n += 1 + l + sovService(uint64(l))
n += 1 + l + sovSimulate(uint64(l))
}
if m.Result != nil {
l = m.Result.Size()
n += 1 + l + sovService(uint64(l))
n += 1 + l + sovSimulate(uint64(l))
}
return n
}
func sovService(x uint64) (n int) {
func sovSimulate(x uint64) (n int) {
return (math_bits.Len64(x|1) + 6) / 7
}
func sozService(x uint64) (n int) {
return sovService(uint64((x << 1) ^ uint64((int64(x) >> 63))))
func sozSimulate(x uint64) (n int) {
return sovSimulate(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *SimulateRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
@ -375,7 +387,7 @@ func (m *SimulateRequest) Unmarshal(dAtA []byte) error {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
return ErrIntOverflowSimulate
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
@ -403,7 +415,7 @@ func (m *SimulateRequest) Unmarshal(dAtA []byte) error {
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
return ErrIntOverflowSimulate
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
@ -416,17 +428,17 @@ func (m *SimulateRequest) Unmarshal(dAtA []byte) error {
}
}
if msglen < 0 {
return ErrInvalidLengthService
return ErrInvalidLengthSimulate
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthService
return ErrInvalidLengthSimulate
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Tx == nil {
m.Tx = &Tx{}
m.Tx = &tx.Tx{}
}
if err := m.Tx.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
@ -434,15 +446,15 @@ func (m *SimulateRequest) Unmarshal(dAtA []byte) error {
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipService(dAtA[iNdEx:])
skippy, err := skipSimulate(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthService
return ErrInvalidLengthSimulate
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthService
return ErrInvalidLengthSimulate
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
@ -464,7 +476,7 @@ func (m *SimulateResponse) Unmarshal(dAtA []byte) error {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
return ErrIntOverflowSimulate
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
@ -492,7 +504,7 @@ func (m *SimulateResponse) Unmarshal(dAtA []byte) error {
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
return ErrIntOverflowSimulate
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
@ -505,11 +517,11 @@ func (m *SimulateResponse) Unmarshal(dAtA []byte) error {
}
}
if msglen < 0 {
return ErrInvalidLengthService
return ErrInvalidLengthSimulate
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthService
return ErrInvalidLengthSimulate
}
if postIndex > l {
return io.ErrUnexpectedEOF
@ -528,7 +540,7 @@ func (m *SimulateResponse) Unmarshal(dAtA []byte) error {
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowService
return ErrIntOverflowSimulate
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
@ -541,11 +553,11 @@ func (m *SimulateResponse) Unmarshal(dAtA []byte) error {
}
}
if msglen < 0 {
return ErrInvalidLengthService
return ErrInvalidLengthSimulate
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthService
return ErrInvalidLengthSimulate
}
if postIndex > l {
return io.ErrUnexpectedEOF
@ -559,15 +571,15 @@ func (m *SimulateResponse) Unmarshal(dAtA []byte) error {
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipService(dAtA[iNdEx:])
skippy, err := skipSimulate(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthService
return ErrInvalidLengthSimulate
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthService
return ErrInvalidLengthSimulate
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
@ -581,7 +593,7 @@ func (m *SimulateResponse) Unmarshal(dAtA []byte) error {
}
return nil
}
func skipService(dAtA []byte) (n int, err error) {
func skipSimulate(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
depth := 0
@ -589,7 +601,7 @@ func skipService(dAtA []byte) (n int, err error) {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowService
return 0, ErrIntOverflowSimulate
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
@ -606,7 +618,7 @@ func skipService(dAtA []byte) (n int, err error) {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowService
return 0, ErrIntOverflowSimulate
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
@ -622,7 +634,7 @@ func skipService(dAtA []byte) (n int, err error) {
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowService
return 0, ErrIntOverflowSimulate
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
@ -635,14 +647,14 @@ func skipService(dAtA []byte) (n int, err error) {
}
}
if length < 0 {
return 0, ErrInvalidLengthService
return 0, ErrInvalidLengthSimulate
}
iNdEx += length
case 3:
depth++
case 4:
if depth == 0 {
return 0, ErrUnexpectedEndOfGroupService
return 0, ErrUnexpectedEndOfGroupSimulate
}
depth--
case 5:
@ -651,7 +663,7 @@ func skipService(dAtA []byte) (n int, err error) {
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
if iNdEx < 0 {
return 0, ErrInvalidLengthService
return 0, ErrInvalidLengthSimulate
}
if depth == 0 {
return iNdEx, nil
@ -661,7 +673,7 @@ func skipService(dAtA []byte) (n int, err error) {
}
var (
ErrInvalidLengthService = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowService = fmt.Errorf("proto: integer overflow")
ErrUnexpectedEndOfGroupService = fmt.Errorf("proto: unexpected end of group")
ErrInvalidLengthSimulate = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowSimulate = fmt.Errorf("proto: integer overflow")
ErrUnexpectedEndOfGroupSimulate = fmt.Errorf("proto: unexpected end of group")
)

View File

@ -0,0 +1,165 @@
// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
// source: cosmos/base/simulate/v1beta1/simulate.proto
/*
Package simulate is a reverse proxy.
It translates gRPC into RESTful JSON APIs.
*/
package simulate
import (
"context"
"io"
"net/http"
"github.com/golang/protobuf/descriptor"
"github.com/golang/protobuf/proto"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/grpc-ecosystem/grpc-gateway/utilities"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/status"
)
// Suppress "imported and not used" errors
var _ codes.Code
var _ io.Reader
var _ status.Status
var _ = runtime.String
var _ = utilities.NewDoubleArray
var _ = descriptor.ForMessage
var (
filter_SimulateService_Simulate_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)}
)
func request_SimulateService_Simulate_0(ctx context.Context, marshaler runtime.Marshaler, client SimulateServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq SimulateRequest
var metadata runtime.ServerMetadata
if err := req.ParseForm(); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_SimulateService_Simulate_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.Simulate(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_SimulateService_Simulate_0(ctx context.Context, marshaler runtime.Marshaler, server SimulateServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq SimulateRequest
var metadata runtime.ServerMetadata
if err := req.ParseForm(); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_SimulateService_Simulate_0); err != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.Simulate(ctx, &protoReq)
return msg, metadata, err
}
// RegisterSimulateServiceHandlerServer registers the http handlers for service SimulateService to "mux".
// UnaryRPC :call SimulateServiceServer directly.
// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906.
func RegisterSimulateServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server SimulateServiceServer) error {
mux.Handle("POST", pattern_SimulateService_Simulate_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_SimulateService_Simulate_0(rctx, inboundMarshaler, server, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SimulateService_Simulate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
// RegisterSimulateServiceHandlerFromEndpoint is same as RegisterSimulateServiceHandler but
// automatically dials to "endpoint" and closes the connection when "ctx" gets done.
func RegisterSimulateServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) {
conn, err := grpc.Dial(endpoint, opts...)
if err != nil {
return err
}
defer func() {
if err != nil {
if cerr := conn.Close(); cerr != nil {
grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr)
}
return
}
go func() {
<-ctx.Done()
if cerr := conn.Close(); cerr != nil {
grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr)
}
}()
}()
return RegisterSimulateServiceHandler(ctx, mux, conn)
}
// RegisterSimulateServiceHandler registers the http handlers for service SimulateService to "mux".
// The handlers forward requests to the grpc endpoint over "conn".
func RegisterSimulateServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
return RegisterSimulateServiceHandlerClient(ctx, mux, NewSimulateServiceClient(conn))
}
// RegisterSimulateServiceHandlerClient registers the http handlers for service SimulateService
// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "SimulateServiceClient".
// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "SimulateServiceClient"
// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in
// "SimulateServiceClient" to call the correct interceptors.
func RegisterSimulateServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client SimulateServiceClient) error {
mux.Handle("POST", pattern_SimulateService_Simulate_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SimulateService_Simulate_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SimulateService_Simulate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
var (
pattern_SimulateService_Simulate_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 2}, []string{"cosmos", "base", "simulate", "v1beta1"}, "", runtime.AssumeColonVerbOpt(true)))
)
var (
forward_SimulateService_Simulate_0 = runtime.ForwardResponseMessage
)

View File

@ -0,0 +1,114 @@
package simulate_test
import (
"context"
"testing"
"github.com/stretchr/testify/suite"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/grpc/simulate"
"github.com/cosmos/cosmos-sdk/client/tx"
"github.com/cosmos/cosmos-sdk/simapp"
"github.com/cosmos/cosmos-sdk/std"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/tx/signing"
authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
)
type IntegrationTestSuite struct {
suite.Suite
app *simapp.SimApp
clientCtx client.Context
queryClient simulate.SimulateServiceClient
sdkCtx sdk.Context
}
func (s *IntegrationTestSuite) SetupSuite() {
app := simapp.Setup(true)
sdkCtx := app.BaseApp.NewContext(true, tmproto.Header{})
app.AccountKeeper.SetParams(sdkCtx, authtypes.DefaultParams())
app.BankKeeper.SetParams(sdkCtx, banktypes.DefaultParams())
// Set up TxConfig.
encodingConfig := simapp.MakeEncodingConfig()
pubKeyCodec := std.DefaultPublicKeyCodec{}
clientCtx := client.Context{}.WithTxConfig(encodingConfig.TxConfig)
// Create new simulation server.
srv := simulate.NewSimulateServer(app.BaseApp.Simulate, encodingConfig.InterfaceRegistry, pubKeyCodec)
queryHelper := baseapp.NewQueryServerTestHelper(sdkCtx, app.InterfaceRegistry())
simulate.RegisterSimulateServiceServer(queryHelper, srv)
queryClient := simulate.NewSimulateServiceClient(queryHelper)
s.app = app
s.clientCtx = clientCtx
s.queryClient = queryClient
s.sdkCtx = sdkCtx
}
func (s IntegrationTestSuite) TestSimulateService() {
// Create an account with some funds.
priv1, _, addr1 := testdata.KeyTestPubAddr()
acc1 := s.app.AccountKeeper.NewAccountWithAddress(s.sdkCtx, addr1)
err := acc1.SetAccountNumber(0)
s.Require().NoError(err)
s.app.AccountKeeper.SetAccount(s.sdkCtx, acc1)
s.app.BankKeeper.SetBalances(s.sdkCtx, addr1, sdk.Coins{
sdk.NewInt64Coin("atom", 10000000),
})
// Create a test x/bank MsgSend.
coins := sdk.NewCoins(sdk.NewInt64Coin("atom", 10))
_, _, addr2 := testdata.KeyTestPubAddr()
msg := banktypes.NewMsgSend(addr1, addr2, coins)
feeAmount := testdata.NewTestFeeAmount()
gasLimit := testdata.NewTestGasLimit()
memo := "foo"
accSeq, accNum := uint64(0), uint64(0)
// Create a txBuilder.
txBuilder := s.clientCtx.TxConfig.NewTxBuilder()
txBuilder.SetMsgs(msg)
txBuilder.SetMemo(memo)
txBuilder.SetFeeAmount(feeAmount)
txBuilder.SetGasLimit(gasLimit)
// 1st round: set empty signature
sigV2 := signing.SignatureV2{
PubKey: priv1.PubKey(),
Data: &signing.SingleSignatureData{
SignMode: s.clientCtx.TxConfig.SignModeHandler().DefaultMode(),
Signature: nil,
},
}
txBuilder.SetSignatures(sigV2)
// 2nd round: actually sign
sigV2, err = tx.SignWithPrivKey(
s.clientCtx.TxConfig.SignModeHandler().DefaultMode(),
authsigning.SignerData{ChainID: s.sdkCtx.ChainID(), AccountNumber: accNum, Sequence: accSeq},
txBuilder, priv1, s.clientCtx.TxConfig, accSeq,
)
txBuilder.SetSignatures(sigV2)
res, err := s.queryClient.Simulate(
context.Background(),
&simulate.SimulateRequest{Tx: txBuilder.GetProtoTx()},
)
s.Require().NoError(err)
// Check the result and gas used are correct.
s.Require().Equal(len(res.GetResult().GetEvents()), 4) // 1 transfer, 3 messages.
s.Require().True(res.GetGasInfo().GetGasUsed() > 0) // Gas used sometimes change, just check it's not empty.
}
func TestSimulateTestSuite(t *testing.T) {
suite.Run(t, new(IntegrationTestSuite))
}

View File

@ -2,6 +2,7 @@ package client
import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/tx"
signingtypes "github.com/cosmos/cosmos-sdk/types/tx/signing"
"github.com/cosmos/cosmos-sdk/x/auth/signing"
)
@ -35,6 +36,8 @@ type (
// also know how to encode itself.
TxBuilder interface {
GetTx() signing.Tx
// GetProtoTx returns the tx as a proto.Message.
GetProtoTx() *tx.Tx
SetMsgs(msgs ...sdk.Msg) error
SetSignatures(signatures ...signingtypes.SignatureV2) error

View File

@ -59,7 +59,7 @@ type UnpackInterfacesMessage interface {
// Any's using the AnyUnpacker. It should generally be implemented as
// follows:
// func (s *MyStruct) UnpackInterfaces(unpacker AnyUnpacker) error {
// var x AnInterface
// var x AnyInterface
// // where X is an Any field on MyStruct
// err := unpacker.UnpackAny(s.X, &x)
// if err != nil {

View File

@ -1,17 +1,23 @@
syntax = "proto3";
package cosmos.base.reflection.v1beta1;
import "google/api/annotations.proto";
option go_package = "github.com/cosmos/cosmos-sdk/client/grpc/reflection";
// ReflectionService defines a service for interface reflection.
service ReflectionService {
// ListAllInterfaces lists all the interfaces registered in the interface
// registry.
rpc ListAllInterfaces(ListAllInterfacesRequest) returns (ListAllInterfacesResponse) {};
rpc ListAllInterfaces(ListAllInterfacesRequest) returns (ListAllInterfacesResponse) {
option (google.api.http).get = "/cosmos/base/reflection/v1beta1/interfaces";
};
// ListImplementations list all the concrete types that implement a given
// interface.
rpc ListImplementations(ListImplementationsRequest) returns (ListImplementationsResponse) {};
rpc ListImplementations(ListImplementationsRequest) returns (ListImplementationsResponse) {
option (google.api.http).get = "/cosmos/base/reflection/v1beta1/interfaces/{interface_name}/implementations";
};
}
// ListAllInterfacesRequest is the request type of the ListAllInterfaces RPC.

View File

@ -0,0 +1,33 @@
syntax = "proto3";
package cosmos.base.simulate.v1beta1;
import "google/api/annotations.proto";
import "cosmos/base/abci/v1beta1/abci.proto";
import "cosmos/tx/v1beta1/tx.proto";
option go_package = "github.com/cosmos/cosmos-sdk/client/grpc/simulate";
// SimulateService defines a gRPC service for simulating transactions.
// It may also support querying and broadcasting in the future.
service SimulateService {
// Simulate simulates executing a transaction for estimating gas usage.
rpc Simulate(SimulateRequest) returns (SimulateResponse) {
option (google.api.http).post = "/cosmos/base/simulate/v1beta1/simulate";
}
}
// SimulateRequest is the request type for the SimulateServiceService.Simulate
// RPC method.
message SimulateRequest {
// tx is the transaction to simulate.
cosmos.tx.v1beta1.Tx tx = 1;
}
// SimulateResponse is the response type for the
// SimulateServiceService.SimulateRPC method.
message SimulateResponse {
// gas_info is the information about gas used in the simulation.
cosmos.base.abci.v1beta1.GasInfo gas_info = 1;
// result is the result of the simulation.
cosmos.base.abci.v1beta1.Result result = 2;
}

View File

@ -1,25 +0,0 @@
syntax = "proto3";
package cosmos.tx.v1beta1;
import "cosmos/base/abci/v1beta1/abci.proto";
import "cosmos/tx/v1beta1/tx.proto";
option go_package = "github.com/cosmos/cosmos-sdk/types/tx";
// Service defines a gRPC service for simulating transactions.
// It may also support querying and broadcasting in the future.
service Service {
// Simulate simulates executing a transaction for estimating gas usage.
rpc Simulate(SimulateRequest) returns (SimulateResponse) {}
}
// SimulateRequest is the request type for the Service.Simulate RPC method.
message SimulateRequest {
Tx tx = 1;
}
// SimulateResponse is the response type for the Service.Simulate RPC method.
message SimulateResponse {
cosmos.base.abci.v1beta1.GasInfo gas_info = 1;
cosmos.base.abci.v1beta1.Result result = 2;
}

View File

@ -183,6 +183,7 @@ func NewSimApp(
bApp.SetCommitMultiStoreTracer(traceStore)
bApp.SetAppVersion(version.Version)
bApp.GRPCQueryRouter().SetInterfaceRegistry(interfaceRegistry)
bApp.GRPCQueryRouter().RegisterSimulateService(bApp.Simulate, interfaceRegistry, std.DefaultPublicKeyCodec{})
keys := sdk.NewKVStoreKeys(
authtypes.StoreKey, banktypes.StoreKey, stakingtypes.StoreKey,
@ -207,7 +208,7 @@ func NewSimApp(
app.ParamsKeeper = initParamsKeeper(appCodec, cdc, keys[paramstypes.StoreKey], tkeys[paramstypes.TStoreKey])
// set the BaseApp's parameter store
bApp.SetParamStore(app.ParamsKeeper.Subspace(baseapp.Paramspace).WithKeyTable(std.ConsensusParamsKeyTable()))
bApp.SetParamStore(app.ParamsKeeper.Subspace(baseapp.Paramspace).WithKeyTable(paramskeeper.ConsensusParamsKeyTable()))
// add capability keeper and ScopeToModule for ibc module
app.CapabilityKeeper = capabilitykeeper.NewKeeper(appCodec, keys[capabilitytypes.StoreKey], memKeys[capabilitytypes.MemStoreKey])

View File

@ -6,14 +6,25 @@ import (
"github.com/stretchr/testify/require"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/std"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/kv"
"github.com/cosmos/cosmos-sdk/types/module"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
)
func makeCodec(bm module.BasicManager) *codec.LegacyAmino {
cdc := codec.New()
bm.RegisterCodec(cdc)
std.RegisterCodec(cdc)
return cdc
}
func TestGetSimulationLog(t *testing.T) {
cdc := std.MakeCodec(ModuleBasics)
cdc := makeCodec(ModuleBasics)
decoders := make(sdk.StoreDecoderRegistry)
decoders[authtypes.StoreKey] = func(kvAs, kvBs kv.Pair) string { return "10" }

View File

@ -5,25 +5,9 @@ import (
"github.com/cosmos/cosmos-sdk/codec/types"
cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
vesting "github.com/cosmos/cosmos-sdk/x/auth/vesting/types"
)
// ----------------------------------------------------------------------------
// necessary types and interfaces registered. This codec is provided to all the
// modules the application depends on.
//
// NOTE: This codec will be deprecated in favor of AppCodec once all modules are
// migrated.
func MakeCodec(bm module.BasicManager) *codec.LegacyAmino {
cdc := codec.New()
bm.RegisterCodec(cdc)
RegisterCodec(cdc)
return cdc
}
func RegisterCodec(cdc *codec.LegacyAmino) {
vesting.RegisterCodec(cdc)
sdk.RegisterCodec(cdc)

View File

@ -3,13 +3,13 @@ package std
import (
"fmt"
"github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/crypto/types/multisig"
"github.com/tendermint/tendermint/crypto"
ed255192 "github.com/tendermint/tendermint/crypto/ed25519"
"github.com/tendermint/tendermint/crypto/secp256k1"
"github.com/tendermint/tendermint/crypto/sr25519"
"github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/crypto/types/multisig"
)
// DefaultPublicKeyCodec implements the standard PublicKeyCodec for the SDK which

View File

@ -17,7 +17,9 @@ import (
authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing"
)
type builder struct {
// wrapper is a wrapper around the tx.Tx proto.Message which retain the raw
// body and auth_info bytes.
type wrapper struct {
tx *tx.Tx
// bodyBz represents the protobuf encoding of TxBody. This should be encoding
@ -38,12 +40,13 @@ type builder struct {
}
var (
_ authsigning.Tx = &builder{}
_ client.TxBuilder = &builder{}
_ ante.HasExtensionOptionsTx = &builder{}
_ ExtensionOptionsTxBuilder = &builder{}
_ authsigning.Tx = &wrapper{}
_ client.TxBuilder = &wrapper{}
_ ante.HasExtensionOptionsTx = &wrapper{}
_ ExtensionOptionsTxBuilder = &wrapper{}
)
// ExtensionOptionsTxBuilder defines a TxBuilder that can also set extensions.
type ExtensionOptionsTxBuilder interface {
client.TxBuilder
@ -51,8 +54,8 @@ type ExtensionOptionsTxBuilder interface {
SetNonCriticalExtensionOptions(...*codectypes.Any)
}
func newBuilder(pubkeyCodec types.PublicKeyCodec) *builder {
return &builder{
func newBuilder(pubkeyCodec types.PublicKeyCodec) *wrapper {
return &wrapper{
tx: &tx.Tx{
Body: &tx.TxBody{},
AuthInfo: &tx.AuthInfo{
@ -63,12 +66,12 @@ func newBuilder(pubkeyCodec types.PublicKeyCodec) *builder {
}
}
func (t *builder) GetMsgs() []sdk.Msg {
if t.tx == nil || t.tx.Body == nil {
func (w *wrapper) GetMsgs() []sdk.Msg {
if w.tx == nil || w.tx.Body == nil {
return nil
}
anys := t.tx.Body.Messages
anys := w.tx.Body.Messages
res := make([]sdk.Msg, len(anys))
for i, any := range anys {
msg := any.GetCachedValue().(sdk.Msg)
@ -80,18 +83,18 @@ func (t *builder) GetMsgs() []sdk.Msg {
// MaxGasWanted defines the max gas allowed.
const MaxGasWanted = uint64((1 << 63) - 1)
func (t *builder) ValidateBasic() error {
theTx := t.tx
func (w *wrapper) ValidateBasic() error {
theTx := w.tx
if theTx == nil {
return fmt.Errorf("bad Tx")
}
body := t.tx.Body
body := w.tx.Body
if body == nil {
return fmt.Errorf("missing TxBody")
}
authInfo := t.tx.AuthInfo
authInfo := w.tx.AuthInfo
if authInfo == nil {
return fmt.Errorf("missing AuthInfo")
}
@ -121,53 +124,53 @@ func (t *builder) ValidateBasic() error {
return sdkerrors.ErrNoSignatures
}
if len(sigs) != len(t.GetSigners()) {
if len(sigs) != len(w.GetSigners()) {
return sdkerrors.Wrapf(
sdkerrors.ErrUnauthorized,
"wrong number of signers; expected %d, got %d", t.GetSigners(), len(sigs),
"wrong number of signers; expected %d, got %d", w.GetSigners(), len(sigs),
)
}
return nil
}
func (t *builder) getBodyBytes() []byte {
if len(t.bodyBz) == 0 {
func (w *wrapper) getBodyBytes() []byte {
if len(w.bodyBz) == 0 {
// if bodyBz is empty, then marshal the body. bodyBz will generally
// be set to nil whenever SetBody is called so the result of calling
// this method should always return the correct bytes. Note that after
// decoding bodyBz is derived from TxRaw so that it matches what was
// transmitted over the wire
var err error
t.bodyBz, err = proto.Marshal(t.tx.Body)
w.bodyBz, err = proto.Marshal(w.tx.Body)
if err != nil {
panic(err)
}
}
return t.bodyBz
return w.bodyBz
}
func (t *builder) getAuthInfoBytes() []byte {
if len(t.authInfoBz) == 0 {
func (w *wrapper) getAuthInfoBytes() []byte {
if len(w.authInfoBz) == 0 {
// if authInfoBz is empty, then marshal the body. authInfoBz will generally
// be set to nil whenever SetAuthInfo is called so the result of calling
// this method should always return the correct bytes. Note that after
// decoding authInfoBz is derived from TxRaw so that it matches what was
// transmitted over the wire
var err error
t.authInfoBz, err = proto.Marshal(t.tx.AuthInfo)
w.authInfoBz, err = proto.Marshal(w.tx.AuthInfo)
if err != nil {
panic(err)
}
}
return t.authInfoBz
return w.authInfoBz
}
func (t *builder) GetSigners() []sdk.AccAddress {
func (w *wrapper) GetSigners() []sdk.AccAddress {
var signers []sdk.AccAddress
seen := map[string]bool{}
for _, msg := range t.GetMsgs() {
for _, msg := range w.GetMsgs() {
for _, addr := range msg.GetSigners() {
if !seen[addr.String()] {
signers = append(signers, addr)
@ -179,57 +182,57 @@ func (t *builder) GetSigners() []sdk.AccAddress {
return signers
}
func (t *builder) GetPubKeys() []crypto.PubKey {
if t.pubKeys == nil {
signerInfos := t.tx.AuthInfo.SignerInfos
func (w *wrapper) GetPubKeys() []crypto.PubKey {
if w.pubKeys == nil {
signerInfos := w.tx.AuthInfo.SignerInfos
pubKeys := make([]crypto.PubKey, len(signerInfos))
for i, si := range signerInfos {
var err error
pk := si.PublicKey
if pk != nil {
pubKeys[i], err = t.pubkeyCodec.Decode(si.PublicKey)
pubKeys[i], err = w.pubkeyCodec.Decode(si.PublicKey)
if err != nil {
panic(err)
}
}
}
t.pubKeys = pubKeys
w.pubKeys = pubKeys
}
return t.pubKeys
return w.pubKeys
}
func (t *builder) GetGas() uint64 {
return t.tx.AuthInfo.Fee.GasLimit
func (w *wrapper) GetGas() uint64 {
return w.tx.AuthInfo.Fee.GasLimit
}
func (t *builder) GetFee() sdk.Coins {
return t.tx.AuthInfo.Fee.Amount
func (w *wrapper) GetFee() sdk.Coins {
return w.tx.AuthInfo.Fee.Amount
}
func (t *builder) FeePayer() sdk.AccAddress {
return t.GetSigners()[0]
func (w *wrapper) FeePayer() sdk.AccAddress {
return w.GetSigners()[0]
}
func (t *builder) GetMemo() string {
return t.tx.Body.Memo
func (w *wrapper) GetMemo() string {
return w.tx.Body.Memo
}
func (t *builder) GetSignatures() [][]byte {
return t.tx.Signatures
func (w *wrapper) GetSignatures() [][]byte {
return w.tx.Signatures
}
// GetTimeoutHeight returns the transaction's timeout height (if set).
func (t *builder) GetTimeoutHeight() uint64 {
return t.tx.Body.TimeoutHeight
func (w *wrapper) GetTimeoutHeight() uint64 {
return w.tx.Body.TimeoutHeight
}
func (t *builder) GetSignaturesV2() ([]signing.SignatureV2, error) {
signerInfos := t.tx.AuthInfo.SignerInfos
sigs := t.tx.Signatures
pubKeys := t.GetPubKeys()
func (w *wrapper) GetSignaturesV2() ([]signing.SignatureV2, error) {
signerInfos := w.tx.AuthInfo.SignerInfos
sigs := w.tx.Signatures
pubKeys := w.GetPubKeys()
n := len(signerInfos)
res := make([]signing.SignatureV2, n)
@ -249,7 +252,7 @@ func (t *builder) GetSignaturesV2() ([]signing.SignatureV2, error) {
return res, nil
}
func (t *builder) SetMsgs(msgs ...sdk.Msg) error {
func (w *wrapper) SetMsgs(msgs ...sdk.Msg) error {
anys := make([]*codectypes.Any, len(msgs))
for i, msg := range msgs {
@ -260,52 +263,52 @@ func (t *builder) SetMsgs(msgs ...sdk.Msg) error {
}
}
t.tx.Body.Messages = anys
w.tx.Body.Messages = anys
// set bodyBz to nil because the cached bodyBz no longer matches tx.Body
t.bodyBz = nil
w.bodyBz = nil
return nil
}
// SetTimeoutHeight sets the transaction's height timeout.
func (t *builder) SetTimeoutHeight(height uint64) {
t.tx.Body.TimeoutHeight = height
func (w *wrapper) SetTimeoutHeight(height uint64) {
w.tx.Body.TimeoutHeight = height
// set bodyBz to nil because the cached bodyBz no longer matches tx.Body
t.bodyBz = nil
w.bodyBz = nil
}
func (t *builder) SetMemo(memo string) {
t.tx.Body.Memo = memo
func (w *wrapper) SetMemo(memo string) {
w.tx.Body.Memo = memo
// set bodyBz to nil because the cached bodyBz no longer matches tx.Body
t.bodyBz = nil
w.bodyBz = nil
}
func (t *builder) SetGasLimit(limit uint64) {
if t.tx.AuthInfo.Fee == nil {
t.tx.AuthInfo.Fee = &tx.Fee{}
func (w *wrapper) SetGasLimit(limit uint64) {
if w.tx.AuthInfo.Fee == nil {
w.tx.AuthInfo.Fee = &tx.Fee{}
}
t.tx.AuthInfo.Fee.GasLimit = limit
w.tx.AuthInfo.Fee.GasLimit = limit
// set authInfoBz to nil because the cached authInfoBz no longer matches tx.AuthInfo
t.authInfoBz = nil
w.authInfoBz = nil
}
func (t *builder) SetFeeAmount(coins sdk.Coins) {
if t.tx.AuthInfo.Fee == nil {
t.tx.AuthInfo.Fee = &tx.Fee{}
func (w *wrapper) SetFeeAmount(coins sdk.Coins) {
if w.tx.AuthInfo.Fee == nil {
w.tx.AuthInfo.Fee = &tx.Fee{}
}
t.tx.AuthInfo.Fee.Amount = coins
w.tx.AuthInfo.Fee.Amount = coins
// set authInfoBz to nil because the cached authInfoBz no longer matches tx.AuthInfo
t.authInfoBz = nil
w.authInfoBz = nil
}
func (t *builder) SetSignatures(signatures ...signing.SignatureV2) error {
func (w *wrapper) SetSignatures(signatures ...signing.SignatureV2) error {
n := len(signatures)
signerInfos := make([]*tx.SignerInfo, n)
rawSigs := make([][]byte, n)
@ -313,7 +316,7 @@ func (t *builder) SetSignatures(signatures ...signing.SignatureV2) error {
for i, sig := range signatures {
var modeInfo *tx.ModeInfo
modeInfo, rawSigs[i] = SignatureDataToModeInfoAndSig(sig.Data)
pk, err := t.pubkeyCodec.Encode(sig.PubKey)
pk, err := w.pubkeyCodec.Encode(sig.PubKey)
if err != nil {
return err
}
@ -324,43 +327,55 @@ func (t *builder) SetSignatures(signatures ...signing.SignatureV2) error {
}
}
t.setSignerInfos(signerInfos)
t.setSignatures(rawSigs)
w.setSignerInfos(signerInfos)
w.setSignatures(rawSigs)
return nil
}
func (t *builder) setSignerInfos(infos []*tx.SignerInfo) {
t.tx.AuthInfo.SignerInfos = infos
func (w *wrapper) setSignerInfos(infos []*tx.SignerInfo) {
w.tx.AuthInfo.SignerInfos = infos
// set authInfoBz to nil because the cached authInfoBz no longer matches tx.AuthInfo
t.authInfoBz = nil
w.authInfoBz = nil
// set cached pubKeys to nil because they no longer match tx.AuthInfo
t.pubKeys = nil
w.pubKeys = nil
}
func (t *builder) setSignatures(sigs [][]byte) {
t.tx.Signatures = sigs
func (w *wrapper) setSignatures(sigs [][]byte) {
w.tx.Signatures = sigs
}
func (t *builder) GetTx() authsigning.Tx {
return t
func (w *wrapper) GetTx() authsigning.Tx {
return w
}
func (t *builder) GetExtensionOptions() []*codectypes.Any {
return t.tx.Body.ExtensionOptions
// GetProtoTx returns the tx as a proto.Message.
func (w *wrapper) GetProtoTx() *tx.Tx {
return w.tx
}
func (t *builder) GetNonCriticalExtensionOptions() []*codectypes.Any {
return t.tx.Body.NonCriticalExtensionOptions
// WrapTx creates a TxBuilder wrapper around a tx.Tx proto message.
func WrapTx(protoTx *tx.Tx, pubkeyCodec types.PublicKeyCodec) client.TxBuilder {
return &wrapper{
tx: protoTx,
pubkeyCodec: pubkeyCodec,
}
}
func (t *builder) SetExtensionOptions(extOpts ...*codectypes.Any) {
t.tx.Body.ExtensionOptions = extOpts
t.bodyBz = nil
func (w *wrapper) GetExtensionOptions() []*codectypes.Any {
return w.tx.Body.ExtensionOptions
}
func (t *builder) SetNonCriticalExtensionOptions(extOpts ...*codectypes.Any) {
t.tx.Body.NonCriticalExtensionOptions = extOpts
t.bodyBz = nil
func (w *wrapper) GetNonCriticalExtensionOptions() []*codectypes.Any {
return w.tx.Body.NonCriticalExtensionOptions
}
func (w *wrapper) SetExtensionOptions(extOpts ...*codectypes.Any) {
w.tx.Body.ExtensionOptions = extOpts
w.bodyBz = nil
}
func (w *wrapper) SetNonCriticalExtensionOptions(extOpts ...*codectypes.Any) {
w.tx.Body.NonCriticalExtensionOptions = extOpts
w.bodyBz = nil
}

View File

@ -118,7 +118,7 @@ func TestTxBuilder(t *testing.T) {
txBuilder.SetNonCriticalExtensionOptions(any)
require.Equal(t, []*codectypes.Any{any}, txBuilder.GetNonCriticalExtensionOptions())
txBuilder = &builder{}
txBuilder = &wrapper{}
require.NotPanics(t, func() {
_ = txBuilder.GetMsgs()
})

View File

@ -43,9 +43,9 @@ func (g config) NewTxBuilder() client.TxBuilder {
// WrapTxBuilder returns a builder from provided transaction
func (g config) WrapTxBuilder(newTx sdk.Tx) (client.TxBuilder, error) {
newBuilder, ok := newTx.(*builder)
newBuilder, ok := newTx.(*wrapper)
if !ok {
return nil, fmt.Errorf("expected %T, got %T", &builder{}, newTx)
return nil, fmt.Errorf("expected %T, got %T", &wrapper{}, newTx)
}
return newBuilder, nil

View File

@ -64,7 +64,7 @@ func DefaultTxDecoder(cdc *codec.ProtoCodec, keyCodec cryptotypes.PublicKeyCodec
return nil, sdkerrors.Wrap(sdkerrors.ErrTxDecode, err.Error())
}
return &builder{
return &wrapper{
tx: theTx,
bodyBz: raw.BodyBytes,
authInfoBz: raw.AuthInfoBytes,
@ -89,7 +89,7 @@ func DefaultJSONTxDecoder(cdc *codec.ProtoCodec, keyCodec cryptotypes.PublicKeyC
return nil, sdkerrors.Wrap(sdkerrors.ErrTxDecode, err.Error())
}
return &builder{
return &wrapper{
tx: &theTx,
pubKeys: pks,
pubkeyCodec: keyCodec,

View File

@ -31,7 +31,7 @@ func (signModeDirectHandler) GetSignBytes(mode signingtypes.SignMode, data signi
return nil, fmt.Errorf("expected %s, got %s", signingtypes.SignMode_SIGN_MODE_DIRECT, mode)
}
protoTx, ok := tx.(*builder)
protoTx, ok := tx.(*wrapper)
if !ok {
return nil, fmt.Errorf("can only handle a protobuf Tx, got %T", tx)
}

View File

@ -13,15 +13,15 @@ import (
// DefaultTxEncoder returns a default protobuf TxEncoder using the provided Marshaler
func DefaultTxEncoder() types.TxEncoder {
return func(tx types.Tx) ([]byte, error) {
wrapper, ok := tx.(*builder)
txWrapper, ok := tx.(*wrapper)
if !ok {
return nil, fmt.Errorf("expected %T, got %T", &builder{}, tx)
return nil, fmt.Errorf("expected %T, got %T", &wrapper{}, tx)
}
raw := &txtypes.TxRaw{
BodyBytes: wrapper.getBodyBytes(),
AuthInfoBytes: wrapper.getAuthInfoBytes(),
Signatures: wrapper.tx.Signatures,
BodyBytes: txWrapper.getBodyBytes(),
AuthInfoBytes: txWrapper.getAuthInfoBytes(),
Signatures: txWrapper.tx.Signatures,
}
return proto.Marshal(raw)
@ -31,11 +31,11 @@ func DefaultTxEncoder() types.TxEncoder {
// DefaultTxEncoder returns a default protobuf JSON TxEncoder using the provided Marshaler
func DefaultJSONTxEncoder() types.TxEncoder {
return func(tx types.Tx) ([]byte, error) {
wrapper, ok := tx.(*builder)
txWrapper, ok := tx.(*wrapper)
if !ok {
return nil, fmt.Errorf("expected %T, got %T", &builder{}, tx)
return nil, fmt.Errorf("expected %T, got %T", &wrapper{}, tx)
}
return codec.ProtoMarshalJSON(wrapper.tx)
return codec.ProtoMarshalJSON(txWrapper.tx)
}
}

View File

@ -32,7 +32,7 @@ func (s signModeLegacyAminoJSONHandler) GetSignBytes(mode signingtypes.SignMode,
return nil, fmt.Errorf("expected %s, got %s", signingtypes.SignMode_SIGN_MODE_LEGACY_AMINO_JSON, mode)
}
protoTx, ok := tx.(*builder)
protoTx, ok := tx.(*wrapper)
if !ok {
return nil, fmt.Errorf("can only handle a protobuf Tx, got %T", tx)
}

View File

@ -25,7 +25,7 @@ var (
timeout = uint64(10)
)
func buildTx(t *testing.T, bldr *builder) {
func buildTx(t *testing.T, bldr *wrapper) {
bldr.SetFeeAmount(coins)
bldr.SetGasLimit(gas)
bldr.SetMemo(memo)

View File

@ -6,6 +6,7 @@ import (
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
txtypes "github.com/cosmos/cosmos-sdk/types/tx"
"github.com/cosmos/cosmos-sdk/types/tx/signing"
authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing"
)
@ -25,6 +26,12 @@ func (s *StdTxBuilder) GetTx() authsigning.Tx {
return s.StdTx
}
// GetProtoTx implements TxBuilder.GetProtoTx
func (s *StdTxBuilder) GetProtoTx() *txtypes.Tx {
// Stdtx isn't a proto.Message
return nil
}
// SetMsgs implements TxBuilder.SetMsgs
func (s *StdTxBuilder) SetMsgs(msgs ...sdk.Msg) error {
s.Msgs = msgs

View File

@ -1,11 +1,11 @@
package std
package keeper
import (
abci "github.com/tendermint/tendermint/abci/types"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/baseapp"
paramstypes "github.com/cosmos/cosmos-sdk/x/params/types"
"github.com/cosmos/cosmos-sdk/x/params/types"
)
// ConsensusParamsKeyTable returns an x/params module keyTable to be used in
@ -13,15 +13,15 @@ import (
// standard validation functions. Applications can choose to adopt this KeyTable
// or provider their own when the existing validation functions do not suite their
// needs.
func ConsensusParamsKeyTable() paramstypes.KeyTable {
return paramstypes.NewKeyTable(
paramstypes.NewParamSetPair(
func ConsensusParamsKeyTable() types.KeyTable {
return types.NewKeyTable(
types.NewParamSetPair(
baseapp.ParamStoreKeyBlockParams, abci.BlockParams{}, baseapp.ValidateBlockParams,
),
paramstypes.NewParamSetPair(
types.NewParamSetPair(
baseapp.ParamStoreKeyEvidenceParams, tmproto.EvidenceParams{}, baseapp.ValidateEvidenceParams,
),
paramstypes.NewParamSetPair(
types.NewParamSetPair(
baseapp.ParamStoreKeyValidatorParams, tmproto.ValidatorParams{}, baseapp.ValidateValidatorParams,
),
)