add 0g code

This commit is contained in:
Solovyov1796 2024-05-01 14:08:58 +08:00 committed by 0g-wh
parent 14a0b2c99f
commit cf502b61e7
61 changed files with 10037 additions and 43 deletions

View File

@ -118,6 +118,12 @@ import (
committeeclient "github.com/0glabs/0g-chain/x/committee/client" committeeclient "github.com/0glabs/0g-chain/x/committee/client"
committeekeeper "github.com/0glabs/0g-chain/x/committee/keeper" committeekeeper "github.com/0glabs/0g-chain/x/committee/keeper"
committeetypes "github.com/0glabs/0g-chain/x/committee/types" committeetypes "github.com/0glabs/0g-chain/x/committee/types"
council "github.com/0glabs/0g-chain/x/council/v1"
councilkeeper "github.com/0glabs/0g-chain/x/council/v1/keeper"
counciltypes "github.com/0glabs/0g-chain/x/council/v1/types"
das "github.com/0glabs/0g-chain/x/das/v1"
daskeeper "github.com/0glabs/0g-chain/x/das/v1/keeper"
dastypes "github.com/0glabs/0g-chain/x/das/v1/types"
evmutil "github.com/0glabs/0g-chain/x/evmutil" evmutil "github.com/0glabs/0g-chain/x/evmutil"
evmutilkeeper "github.com/0glabs/0g-chain/x/evmutil/keeper" evmutilkeeper "github.com/0glabs/0g-chain/x/evmutil/keeper"
evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types" evmutiltypes "github.com/0glabs/0g-chain/x/evmutil/types"
@ -171,6 +177,8 @@ var (
validatorvesting.AppModuleBasic{}, validatorvesting.AppModuleBasic{},
evmutil.AppModuleBasic{}, evmutil.AppModuleBasic{},
mint.AppModuleBasic{}, mint.AppModuleBasic{},
council.AppModuleBasic{},
das.AppModuleBasic{},
) )
// module account permissions // module account permissions
@ -715,6 +723,11 @@ func NewApp(
) )
app.govKeeper.SetTallyHandler(tallyHandler) app.govKeeper.SetTallyHandler(tallyHandler)
app.CouncilKeeper = councilkeeper.NewKeeper(
keys[counciltypes.StoreKey], appCodec, app.stakingKeeper,
)
app.DasKeeper = daskeeper.NewKeeper(keys[dastypes.StoreKey], appCodec, app.stakingKeeper)
// create the module manager (Note: Any module instantiated in the module manager that is later modified // create the module manager (Note: Any module instantiated in the module manager that is later modified
// must be passed by reference here.) // must be passed by reference here.)
app.mm = module.NewManager( app.mm = module.NewManager(
@ -1029,7 +1042,7 @@ func RegisterAPIRouteRewrites(router *mux.Router) {
// Eg: querying /cosmos/distribution/v1beta1/community_pool will return // Eg: querying /cosmos/distribution/v1beta1/community_pool will return
// the same response as querying /kava/community/v1beta1/total_balance // the same response as querying /kava/community/v1beta1/total_balance
routeMap := map[string]string{ routeMap := map[string]string{
"/cosmos/distribution/v1beta1/community_pool": "/kava/community/v1beta1/total_balance", "/cosmos/distribution/v1beta1/community_pool": "/0g-chain/community/v1beta1/total_balance",
} }
for clientPath, backendPath := range routeMap { for clientPath, backendPath := range routeMap {

View File

@ -1,41 +0,0 @@
package app
import sdk "github.com/cosmos/cosmos-sdk/types"
const (
// Bech32MainPrefix defines the Bech32 prefix for account addresses
Bech32MainPrefix = "kava"
// Bech32PrefixAccPub defines the Bech32 prefix of an account's public key
Bech32PrefixAccPub = Bech32MainPrefix + "pub"
// Bech32PrefixValAddr defines the Bech32 prefix of a validator's operator address
Bech32PrefixValAddr = Bech32MainPrefix + "val" + "oper"
// Bech32PrefixValPub defines the Bech32 prefix of a validator's operator public key
Bech32PrefixValPub = Bech32MainPrefix + "val" + "oper" + "pub"
// Bech32PrefixConsAddr defines the Bech32 prefix of a consensus node address
Bech32PrefixConsAddr = Bech32MainPrefix + "val" + "cons"
// Bech32PrefixConsPub defines the Bech32 prefix of a consensus node public key
Bech32PrefixConsPub = Bech32MainPrefix + "val" + "cons" + "pub"
Bip44CoinType = 459 // see https://github.com/satoshilabs/slips/blob/master/slip-0044.md
)
// SetSDKConfig configures the global config with kava app specific parameters.
// It does not seal the config to allow modification in tests.
func SetSDKConfig() *sdk.Config {
config := sdk.GetConfig()
SetBech32AddressPrefixes(config)
SetBip44CoinType(config)
return config
}
// SetBech32AddressPrefixes sets the global prefix to be used when serializing addresses to bech32 strings.
func SetBech32AddressPrefixes(config *sdk.Config) {
config.SetBech32PrefixForAccount(Bech32MainPrefix, Bech32PrefixAccPub)
config.SetBech32PrefixForValidator(Bech32PrefixValAddr, Bech32PrefixValPub)
config.SetBech32PrefixForConsensusNode(Bech32PrefixConsAddr, Bech32PrefixConsPub)
}
// SetBip44CoinType sets the global coin type to be used in hierarchical deterministic wallets.
func SetBip44CoinType(config *sdk.Config) {
config.SetCoinType(Bip44CoinType)
}

View File

@ -79,7 +79,7 @@ type TestApp struct {
// //
// Note, it also sets the sdk config with the app's address prefix, coin type, etc. // Note, it also sets the sdk config with the app's address prefix, coin type, etc.
func NewTestApp() TestApp { func NewTestApp() TestApp {
SetSDKConfig() chaincfg.SetSDKConfig()
return NewTestAppFromSealed() return NewTestAppFromSealed()
} }

View File

@ -0,0 +1,61 @@
package client
import (
"context"
"time"
"github.com/0glabs/0g-chain/helper/da/light"
"github.com/pkg/errors"
)
type DaLightRpcClient interface {
Sample(ctx context.Context, streamId, headerHash []byte, blobIdx, times uint32) (bool, error)
Destroy()
GetInstanceCount() int
}
type daLightClient struct {
maxInstance int
pool ConnectionPool
}
func NewDaLightClient(address string, instanceLimit int) DaLightRpcClient {
return &daLightClient{
maxInstance: instanceLimit,
pool: NewConnectionPool(address, instanceLimit, 10*time.Minute),
}
}
func (c *daLightClient) Sample(ctx context.Context, streamId, headerHash []byte, blobIdx, times uint32) (bool, error) {
connection, err := c.pool.GetConnection()
if err != nil {
return false, errors.Wrap(err, "failed to connect to da light server")
}
defer c.pool.ReleaseConnection(connection)
req := &light.SampleRequest{
StreamId: streamId,
BatchHeaderHash: headerHash,
BlobIndex: blobIdx,
Times: times,
}
client := light.NewLightClient(connection)
reply, err := client.Sample(ctx, req)
if err != nil {
return false, errors.Wrap(err, "failed to sample from da light server")
}
return reply.Success, nil
}
func (c *daLightClient) Destroy() {
if c.pool != nil {
c.pool.Close()
c.pool = nil
}
}
func (c *daLightClient) GetInstanceCount() int {
return c.maxInstance
}

101
helper/da/client/pool.go Normal file
View File

@ -0,0 +1,101 @@
package client
import (
"errors"
"sync"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/backoff"
"google.golang.org/grpc/credentials/insecure"
)
type ConnectionPool interface {
GetConnection() (*grpc.ClientConn, error)
ReleaseConnection(*grpc.ClientConn)
Close()
}
type connectionPoolImpl struct {
address string
maxSize int
timeout time.Duration
param grpc.ConnectParams
mu sync.Mutex
pool []*grpc.ClientConn
}
func NewConnectionPool(address string, maxSize int, timeout time.Duration) ConnectionPool {
return &connectionPoolImpl{
address: address,
maxSize: maxSize,
timeout: timeout,
param: grpc.ConnectParams{
Backoff: backoff.Config{
BaseDelay: 1.0 * time.Second,
Multiplier: 1.5,
Jitter: 0.2,
MaxDelay: 30 * time.Second,
},
MinConnectTimeout: 30 * time.Second,
},
pool: make([]*grpc.ClientConn, 0, maxSize),
}
}
func (p *connectionPoolImpl) GetConnection() (*grpc.ClientConn, error) {
p.mu.Lock()
defer p.mu.Unlock()
if p.pool == nil {
return nil, errors.New("connection pool is closed")
}
// Check if there's any available connection in the pool
if len(p.pool) > 0 {
conn := p.pool[0]
p.pool = p.pool[1:]
return conn, nil
}
// If the pool is empty, create a new connection
conn, err := grpc.Dial(p.address, grpc.WithBlock(),
grpc.WithConnectParams(p.param),
grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
return nil, err
}
return conn, nil
}
func (p *connectionPoolImpl) ReleaseConnection(conn *grpc.ClientConn) {
p.mu.Lock()
defer p.mu.Unlock()
if p.pool != nil {
// If the pool is full, close the connection
if len(p.pool) >= p.maxSize {
conn.Close()
return
}
// Add the connection back to the pool
p.pool = append(p.pool, conn)
} else {
conn.Close()
}
}
func (p *connectionPoolImpl) Close() {
p.mu.Lock()
defer p.mu.Unlock()
if p.pool != nil {
for _, conn := range p.pool {
conn.Close()
}
p.pool = nil
}
}

26
helper/da/go.mod Normal file
View File

@ -0,0 +1,26 @@
module github.com/0glabs/0g-chain/helper/da
go 1.20
require (
github.com/json-iterator/go v1.1.12
github.com/lesismal/nbio v1.5.4
github.com/pkg/errors v0.9.1
github.com/rs/zerolog v1.32.0
google.golang.org/grpc v1.63.2
google.golang.org/protobuf v1.33.0
)
require (
github.com/lesismal/llib v1.1.13 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/stretchr/testify v1.8.4 // indirect
golang.org/x/crypto v0.19.0 // indirect
golang.org/x/net v0.21.0 // indirect
golang.org/x/sys v0.17.0 // indirect
golang.org/x/text v0.14.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240227224415-6ceb2ff114de // indirect
)

60
helper/da/go.sum Normal file
View File

@ -0,0 +1,60 @@
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/lesismal/llib v1.1.13 h1:+w1+t0PykXpj2dXQck0+p6vdC9/mnbEXHgUy/HXDGfE=
github.com/lesismal/llib v1.1.13/go.mod h1:70tFXXe7P1FZ02AU9l8LgSOK7d7sRrpnkUr3rd3gKSg=
github.com/lesismal/nbio v1.5.4 h1:fZ6FOVZOBm7nFuudYsq+WyHJuM2UNuPdlvF/1LVa6lo=
github.com/lesismal/nbio v1.5.4/go.mod h1:mvfYBAA1jmrafXf2XvkM28jWkMTfA5jGks+HKDBMmOc=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.32.0 h1:keLypqrlIjaFsbmJOBdB/qvyF8KEtCWHwobLp5l/mQ0=
github.com/rs/zerolog v1.32.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
golang.org/x/crypto v0.0.0-20210513122933-cd7d49e622d5/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8=
golang.org/x/crypto v0.19.0 h1:ENy+Az/9Y1vSrlrvBSyna3PITt4tiZLf7sgCjZBX7Wo=
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210510120150-4163338589ed/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240227224415-6ceb2ff114de h1:cZGRis4/ot9uVm639a+rHCUaG0JJHEsdyzSQTMX+suY=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240227224415-6ceb2ff114de/go.mod h1:H4O17MA/PE9BsGx3w+a+W2VOLLD1Qf7oJneAoU6WktY=
google.golang.org/grpc v1.63.2 h1:MUeiw1B2maTVZthpU5xvASfTh3LDbxHd6IJ6QQVU+xM=
google.golang.org/grpc v1.63.2/go.mod h1:WAX/8DgncnokcFUldAxq7GeB5DXHDbMF+lLvDomNkRA=
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=

397
helper/da/light/light.pb.go Normal file
View File

@ -0,0 +1,397 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.28.1
// protoc v4.25.3
// source: light/light.proto
package light
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
// SampleRequest contains the blob to sample (by batch and blob index) and required sample times
type SampleRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
StreamId []byte `protobuf:"bytes,1,opt,name=stream_id,json=streamId,proto3" json:"stream_id,omitempty"`
BatchHeaderHash []byte `protobuf:"bytes,2,opt,name=batch_header_hash,json=batchHeaderHash,proto3" json:"batch_header_hash,omitempty"`
BlobIndex uint32 `protobuf:"varint,3,opt,name=blob_index,json=blobIndex,proto3" json:"blob_index,omitempty"`
Times uint32 `protobuf:"varint,4,opt,name=times,proto3" json:"times,omitempty"`
}
func (x *SampleRequest) Reset() {
*x = SampleRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_light_light_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *SampleRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SampleRequest) ProtoMessage() {}
func (x *SampleRequest) ProtoReflect() protoreflect.Message {
mi := &file_light_light_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use SampleRequest.ProtoReflect.Descriptor instead.
func (*SampleRequest) Descriptor() ([]byte, []int) {
return file_light_light_proto_rawDescGZIP(), []int{0}
}
func (x *SampleRequest) GetStreamId() []byte {
if x != nil {
return x.StreamId
}
return nil
}
func (x *SampleRequest) GetBatchHeaderHash() []byte {
if x != nil {
return x.BatchHeaderHash
}
return nil
}
func (x *SampleRequest) GetBlobIndex() uint32 {
if x != nil {
return x.BlobIndex
}
return 0
}
func (x *SampleRequest) GetTimes() uint32 {
if x != nil {
return x.Times
}
return 0
}
// SampleReply contains the sample result
type SampleReply struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"`
}
func (x *SampleReply) Reset() {
*x = SampleReply{}
if protoimpl.UnsafeEnabled {
mi := &file_light_light_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *SampleReply) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SampleReply) ProtoMessage() {}
func (x *SampleReply) ProtoReflect() protoreflect.Message {
mi := &file_light_light_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use SampleReply.ProtoReflect.Descriptor instead.
func (*SampleReply) Descriptor() ([]byte, []int) {
return file_light_light_proto_rawDescGZIP(), []int{1}
}
func (x *SampleReply) GetSuccess() bool {
if x != nil {
return x.Success
}
return false
}
type RetrieveRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
BatchHeaderHash []byte `protobuf:"bytes,1,opt,name=batch_header_hash,json=batchHeaderHash,proto3" json:"batch_header_hash,omitempty"`
BlobIndex uint32 `protobuf:"varint,2,opt,name=blob_index,json=blobIndex,proto3" json:"blob_index,omitempty"`
}
func (x *RetrieveRequest) Reset() {
*x = RetrieveRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_light_light_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RetrieveRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RetrieveRequest) ProtoMessage() {}
func (x *RetrieveRequest) ProtoReflect() protoreflect.Message {
mi := &file_light_light_proto_msgTypes[2]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RetrieveRequest.ProtoReflect.Descriptor instead.
func (*RetrieveRequest) Descriptor() ([]byte, []int) {
return file_light_light_proto_rawDescGZIP(), []int{2}
}
func (x *RetrieveRequest) GetBatchHeaderHash() []byte {
if x != nil {
return x.BatchHeaderHash
}
return nil
}
func (x *RetrieveRequest) GetBlobIndex() uint32 {
if x != nil {
return x.BlobIndex
}
return 0
}
type RetrieveReply struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Status bool `protobuf:"varint,1,opt,name=status,proto3" json:"status,omitempty"`
Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"`
}
func (x *RetrieveReply) Reset() {
*x = RetrieveReply{}
if protoimpl.UnsafeEnabled {
mi := &file_light_light_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RetrieveReply) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RetrieveReply) ProtoMessage() {}
func (x *RetrieveReply) ProtoReflect() protoreflect.Message {
mi := &file_light_light_proto_msgTypes[3]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RetrieveReply.ProtoReflect.Descriptor instead.
func (*RetrieveReply) Descriptor() ([]byte, []int) {
return file_light_light_proto_rawDescGZIP(), []int{3}
}
func (x *RetrieveReply) GetStatus() bool {
if x != nil {
return x.Status
}
return false
}
func (x *RetrieveReply) GetData() []byte {
if x != nil {
return x.Data
}
return nil
}
var File_light_light_proto protoreflect.FileDescriptor
var file_light_light_proto_rawDesc = []byte{
0x0a, 0x11, 0x6c, 0x69, 0x67, 0x68, 0x74, 0x2f, 0x6c, 0x69, 0x67, 0x68, 0x74, 0x2e, 0x70, 0x72,
0x6f, 0x74, 0x6f, 0x12, 0x05, 0x6c, 0x69, 0x67, 0x68, 0x74, 0x22, 0x8d, 0x01, 0x0a, 0x0d, 0x53,
0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09,
0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52,
0x08, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x49, 0x64, 0x12, 0x2a, 0x0a, 0x11, 0x62, 0x61, 0x74,
0x63, 0x68, 0x5f, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x5f, 0x68, 0x61, 0x73, 0x68, 0x18, 0x02,
0x20, 0x01, 0x28, 0x0c, 0x52, 0x0f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x48, 0x65, 0x61, 0x64, 0x65,
0x72, 0x48, 0x61, 0x73, 0x68, 0x12, 0x1d, 0x0a, 0x0a, 0x62, 0x6c, 0x6f, 0x62, 0x5f, 0x69, 0x6e,
0x64, 0x65, 0x78, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x62, 0x6c, 0x6f, 0x62, 0x49,
0x6e, 0x64, 0x65, 0x78, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x18, 0x04, 0x20,
0x01, 0x28, 0x0d, 0x52, 0x05, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x22, 0x27, 0x0a, 0x0b, 0x53, 0x61,
0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x12, 0x18, 0x0a, 0x07, 0x73, 0x75, 0x63,
0x63, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x73, 0x75, 0x63, 0x63,
0x65, 0x73, 0x73, 0x22, 0x5c, 0x0a, 0x0f, 0x52, 0x65, 0x74, 0x72, 0x69, 0x65, 0x76, 0x65, 0x52,
0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x2a, 0x0a, 0x11, 0x62, 0x61, 0x74, 0x63, 0x68, 0x5f,
0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x5f, 0x68, 0x61, 0x73, 0x68, 0x18, 0x01, 0x20, 0x01, 0x28,
0x0c, 0x52, 0x0f, 0x62, 0x61, 0x74, 0x63, 0x68, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x48, 0x61,
0x73, 0x68, 0x12, 0x1d, 0x0a, 0x0a, 0x62, 0x6c, 0x6f, 0x62, 0x5f, 0x69, 0x6e, 0x64, 0x65, 0x78,
0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x62, 0x6c, 0x6f, 0x62, 0x49, 0x6e, 0x64, 0x65,
0x78, 0x22, 0x3b, 0x0a, 0x0d, 0x52, 0x65, 0x74, 0x72, 0x69, 0x65, 0x76, 0x65, 0x52, 0x65, 0x70,
0x6c, 0x79, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01,
0x28, 0x08, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61,
0x74, 0x61, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x32, 0x79,
0x0a, 0x05, 0x4c, 0x69, 0x67, 0x68, 0x74, 0x12, 0x34, 0x0a, 0x06, 0x53, 0x61, 0x6d, 0x70, 0x6c,
0x65, 0x12, 0x14, 0x2e, 0x6c, 0x69, 0x67, 0x68, 0x74, 0x2e, 0x53, 0x61, 0x6d, 0x70, 0x6c, 0x65,
0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x12, 0x2e, 0x6c, 0x69, 0x67, 0x68, 0x74, 0x2e,
0x53, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x22, 0x00, 0x12, 0x3a, 0x0a,
0x08, 0x52, 0x65, 0x74, 0x72, 0x69, 0x65, 0x76, 0x65, 0x12, 0x16, 0x2e, 0x6c, 0x69, 0x67, 0x68,
0x74, 0x2e, 0x52, 0x65, 0x74, 0x72, 0x69, 0x65, 0x76, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73,
0x74, 0x1a, 0x14, 0x2e, 0x6c, 0x69, 0x67, 0x68, 0x74, 0x2e, 0x52, 0x65, 0x74, 0x72, 0x69, 0x65,
0x76, 0x65, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x22, 0x00, 0x42, 0x30, 0x5a, 0x2e, 0x67, 0x69, 0x74,
0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x30, 0x67, 0x6c, 0x61, 0x62, 0x73, 0x2f, 0x30,
0x67, 0x2d, 0x64, 0x61, 0x74, 0x61, 0x2d, 0x61, 0x76, 0x61, 0x69, 0x6c, 0x2f, 0x72, 0x75, 0x6e,
0x2f, 0x67, 0x72, 0x70, 0x63, 0x2f, 0x6c, 0x69, 0x67, 0x68, 0x74, 0x62, 0x06, 0x70, 0x72, 0x6f,
0x74, 0x6f, 0x33,
}
var (
file_light_light_proto_rawDescOnce sync.Once
file_light_light_proto_rawDescData = file_light_light_proto_rawDesc
)
func file_light_light_proto_rawDescGZIP() []byte {
file_light_light_proto_rawDescOnce.Do(func() {
file_light_light_proto_rawDescData = protoimpl.X.CompressGZIP(file_light_light_proto_rawDescData)
})
return file_light_light_proto_rawDescData
}
var file_light_light_proto_msgTypes = make([]protoimpl.MessageInfo, 4)
var file_light_light_proto_goTypes = []interface{}{
(*SampleRequest)(nil), // 0: light.SampleRequest
(*SampleReply)(nil), // 1: light.SampleReply
(*RetrieveRequest)(nil), // 2: light.RetrieveRequest
(*RetrieveReply)(nil), // 3: light.RetrieveReply
}
var file_light_light_proto_depIdxs = []int32{
0, // 0: light.Light.Sample:input_type -> light.SampleRequest
2, // 1: light.Light.Retrieve:input_type -> light.RetrieveRequest
1, // 2: light.Light.Sample:output_type -> light.SampleReply
3, // 3: light.Light.Retrieve:output_type -> light.RetrieveReply
2, // [2:4] is the sub-list for method output_type
0, // [0:2] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_light_light_proto_init() }
func file_light_light_proto_init() {
if File_light_light_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_light_light_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*SampleRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_light_light_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*SampleReply); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_light_light_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RetrieveRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_light_light_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RetrieveReply); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_light_light_proto_rawDesc,
NumEnums: 0,
NumMessages: 4,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_light_light_proto_goTypes,
DependencyIndexes: file_light_light_proto_depIdxs,
MessageInfos: file_light_light_proto_msgTypes,
}.Build()
File_light_light_proto = out.File
file_light_light_proto_rawDesc = nil
file_light_light_proto_goTypes = nil
file_light_light_proto_depIdxs = nil
}

View File

@ -0,0 +1,141 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.2.0
// - protoc v4.25.3
// source: light/light.proto
package light
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.32.0 or later.
const _ = grpc.SupportPackageIsVersion7
// LightClient is the client API for Light service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type LightClient interface {
Sample(ctx context.Context, in *SampleRequest, opts ...grpc.CallOption) (*SampleReply, error)
Retrieve(ctx context.Context, in *RetrieveRequest, opts ...grpc.CallOption) (*RetrieveReply, error)
}
type lightClient struct {
cc grpc.ClientConnInterface
}
func NewLightClient(cc grpc.ClientConnInterface) LightClient {
return &lightClient{cc}
}
func (c *lightClient) Sample(ctx context.Context, in *SampleRequest, opts ...grpc.CallOption) (*SampleReply, error) {
out := new(SampleReply)
err := c.cc.Invoke(ctx, "/light.Light/Sample", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *lightClient) Retrieve(ctx context.Context, in *RetrieveRequest, opts ...grpc.CallOption) (*RetrieveReply, error) {
out := new(RetrieveReply)
err := c.cc.Invoke(ctx, "/light.Light/Retrieve", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// LightServer is the server API for Light service.
// All implementations must embed UnimplementedLightServer
// for forward compatibility
type LightServer interface {
Sample(context.Context, *SampleRequest) (*SampleReply, error)
Retrieve(context.Context, *RetrieveRequest) (*RetrieveReply, error)
mustEmbedUnimplementedLightServer()
}
// UnimplementedLightServer must be embedded to have forward compatible implementations.
type UnimplementedLightServer struct {
}
func (UnimplementedLightServer) Sample(context.Context, *SampleRequest) (*SampleReply, error) {
return nil, status.Errorf(codes.Unimplemented, "method Sample not implemented")
}
func (UnimplementedLightServer) Retrieve(context.Context, *RetrieveRequest) (*RetrieveReply, error) {
return nil, status.Errorf(codes.Unimplemented, "method Retrieve not implemented")
}
func (UnimplementedLightServer) mustEmbedUnimplementedLightServer() {}
// UnsafeLightServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to LightServer will
// result in compilation errors.
type UnsafeLightServer interface {
mustEmbedUnimplementedLightServer()
}
func RegisterLightServer(s grpc.ServiceRegistrar, srv LightServer) {
s.RegisterService(&Light_ServiceDesc, srv)
}
func _Light_Sample_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SampleRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(LightServer).Sample(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/light.Light/Sample",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(LightServer).Sample(ctx, req.(*SampleRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Light_Retrieve_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RetrieveRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(LightServer).Retrieve(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/light.Light/Retrieve",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(LightServer).Retrieve(ctx, req.(*RetrieveRequest))
}
return interceptor(ctx, in, info, handler)
}
// Light_ServiceDesc is the grpc.ServiceDesc for Light service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var Light_ServiceDesc = grpc.ServiceDesc{
ServiceName: "light.Light",
HandlerType: (*LightServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Sample",
Handler: _Light_Sample_Handler,
},
{
MethodName: "Retrieve",
Handler: _Light_Retrieve_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "light/light.proto",
}

89
helper/da/main.go Normal file
View File

@ -0,0 +1,89 @@
package main
import (
"context"
"flag"
"fmt"
"io"
"log"
"net/url"
"os"
"os/signal"
"time"
"github.com/0glabs/0g-chain/helper/da/service"
"github.com/0glabs/0g-chain/helper/da/types"
"github.com/lesismal/nbio/nbhttp"
"github.com/lesismal/nbio/nbhttp/websocket"
)
const (
subscribeMsg = "{\"jsonrpc\":\"2.0\",\"method\":\"subscribe\",\"id\":1,\"params\":{\"query\":\"tm.event='Tx'\"}}"
)
var (
rpcAddress = flag.String("rpc-address", "34.214.2.28:32001", "address of da-light rpc server")
wsAddress = flag.String("ws-address", "127.0.0.1:26657", "address of emvos ws server")
relativePath = flag.String("relative-path", "", "relative path of evmosd")
account = flag.String("account", "", "account to run evmosd cli")
keyring = flag.String("keyring", "", "keyring to run evmosd cli")
homePath = flag.String("home", "", "home path of evmosd node")
)
func newUpgrader() *websocket.Upgrader {
u := websocket.NewUpgrader()
u.OnMessage(func(c *websocket.Conn, messageType websocket.MessageType, data []byte) {
log.Println("onEcho:", string(data))
ctx := context.WithValue(context.Background(), types.DA_RPC_ADDRESS, *rpcAddress)
ctx = context.WithValue(ctx, types.NODE_CLI_RELATIVE_PATH, *relativePath)
ctx = context.WithValue(ctx, types.NODE_CLI_EXEC_ACCOUNT, *account)
ctx = context.WithValue(ctx, types.NODE_CLI_EXEC_KEYRING, *keyring)
ctx = context.WithValue(ctx, types.NODE_HOME_PATH, *homePath)
go func() { service.OnMessage(ctx, c, messageType, data) }()
})
u.OnClose(func(c *websocket.Conn, err error) {
fmt.Println("OnClose:", c.RemoteAddr().String(), err)
service.OnClose()
})
return u
}
func main() {
flag.Parse()
engine := nbhttp.NewEngine(nbhttp.Config{})
err := engine.Start()
if err != nil {
fmt.Printf("nbio.Start failed: %v\n", err)
return
}
go func() {
u := url.URL{Scheme: "ws", Host: *wsAddress, Path: "/websocket"}
dialer := &websocket.Dialer{
Engine: engine,
Upgrader: newUpgrader(),
DialTimeout: time.Second * 3,
}
c, res, err := dialer.Dial(u.String(), nil)
if err != nil {
if res != nil && res.Body != nil {
bReason, _ := io.ReadAll(res.Body)
fmt.Printf("dial failed: %v, reason: %v\n", err, string(bReason))
} else {
fmt.Printf("dial failed: %v\n", err)
}
return
}
c.WriteMessage(websocket.TextMessage, []byte(subscribeMsg))
}()
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
<-interrupt
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
engine.Shutdown(ctx)
}

View File

@ -0,0 +1,33 @@
syntax = "proto3";
package light;
option go_package = "proto/light";
service Light {
rpc Sample(SampleRequest) returns (SampleReply) {}
rpc Retrieve(RetrieveRequest) returns (RetrieveReply) {}
}
// SampleRequest contains the blob to sample (by batch and blob index) and required sample times
message SampleRequest {
bytes stream_id = 1;
bytes batch_header_hash = 2;
uint32 blob_index = 3;
uint32 times = 4;
}
// SampleReply contains the sample result
message SampleReply {
bool success = 1;
}
message RetrieveRequest {
bytes batch_header_hash = 1;
uint32 blob_index = 2;
}
message RetrieveReply {
bool status = 1;
bytes data = 2;
}

View File

@ -0,0 +1,186 @@
package service
import (
"context"
"encoding/hex"
"os"
"os/exec"
"strconv"
"strings"
"github.com/0glabs/0g-chain/helper/da/client"
"github.com/0glabs/0g-chain/helper/da/types"
"github.com/0glabs/0g-chain/helper/da/utils/sizedw8grp"
jsoniter "github.com/json-iterator/go"
"github.com/lesismal/nbio/nbhttp/websocket"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
)
const (
defaultClientInstance = 10
)
var rpcClient client.DaLightRpcClient
func OnMessage(ctx context.Context, c *websocket.Conn, messageType websocket.MessageType, data []byte) {
if messageType == websocket.TextMessage {
rawMsg := unwrapJsonRpc(data)
if verifyQuery(rawMsg) {
eventStr := jsoniter.Get(rawMsg, "events").ToString()
events := map[string][]string{}
if err := jsoniter.UnmarshalFromString(eventStr, &events); err == nil {
dasRequestMap := make(map[string]string, 4)
for key, val := range events {
if strings.HasPrefix(key, "das_request.") {
dasRequestMap[strings.ReplaceAll(key, "das_request.", "")] = val[0]
}
}
if len(dasRequestMap) == 4 {
rid, _ := strconv.ParseUint(dasRequestMap["request_id"], 10, 64)
numBlobs, _ := strconv.ParseUint(dasRequestMap["num_blobs"], 10, 64)
req := types.DASRequest{
RequestId: rid,
StreamId: dasRequestMap["stream_id"],
BatchHeaderHash: dasRequestMap["batch_header_hash"],
NumBlobs: numBlobs,
}
err := handleDasRequest(ctx, req)
if err != nil {
log.Err(err).Msgf("failed to handle das request: %v, %v", req, err)
} else {
log.Info().Msgf("successfully handled das request: %v", req)
}
}
}
}
} else {
// TODO: handle other message
}
}
func OnClose() {
if rpcClient != nil {
rpcClient.Destroy()
rpcClient = nil
}
}
func unwrapJsonRpc(data []byte) []byte {
result := jsoniter.Get(data, "result")
if 0 < len(result.Keys()) {
return []byte(result.ToString())
}
return []byte{}
}
func verifyQuery(data []byte) bool {
if len(data) > 0 {
return jsoniter.Get(data, "query").ToString() == "tm.event='Tx'"
}
return false
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func handleDasRequest(ctx context.Context, request types.DASRequest) error {
if rpcClient == nil {
addrVal := ctx.Value(types.DA_RPC_ADDRESS)
if addrVal == nil {
return errors.New("da light service address not found in context")
}
limit := ctx.Value(types.INSTANCE_LIMIT)
if limit == nil {
limit = defaultClientInstance
}
rpcClient = client.NewDaLightClient(addrVal.(string), limit.(int))
}
streamID, err := hex.DecodeString(request.StreamId)
if err != nil {
return err
}
batchHeaderHash, err := hex.DecodeString(request.BatchHeaderHash)
if err != nil {
return err
}
result := make(chan bool, request.NumBlobs)
taskCnt := min(rpcClient.GetInstanceCount(), int(request.NumBlobs))
wg := sizedw8grp.New(taskCnt)
for i := uint64(0); i < request.NumBlobs; i++ {
wg.Add()
go func(idx uint64) {
defer wg.Done()
ret, err := rpcClient.Sample(ctx, streamID, batchHeaderHash, uint32(idx), 1)
if err != nil {
log.Err(err).Msgf("failed to sample data availability with blob index %d", idx)
result <- false
} else {
log.Info().Msgf("sample result for blob index %d: %v", idx, ret)
result <- ret
}
}(i)
}
wg.Wait()
close(result)
finalResult := true
for val := range result {
if !val {
finalResult = false
break
}
}
return runEvmosdCliReportDasResult(ctx, request.RequestId, finalResult)
}
func runEvmosdCliReportDasResult(ctx context.Context, requestId uint64, result bool) error {
relativePath := ctx.Value(types.NODE_CLI_RELATIVE_PATH)
if relativePath == nil {
return errors.New("relativePath not found in context")
}
account := ctx.Value(types.NODE_CLI_EXEC_ACCOUNT)
if account == nil {
return errors.New("account not found in context")
}
args := []string{
"tx",
"das",
"report-das-result",
strconv.FormatUint(requestId, 10),
strconv.FormatBool(result),
"--from", account.(string),
"--gas-prices", "7678500neuron", // TODO: use args to set gas prices
}
homePath := ctx.Value(types.NODE_HOME_PATH)
if len(homePath.(string)) > 0 {
args = append(args, "--home", homePath.(string))
}
keyring := ctx.Value(types.NODE_CLI_EXEC_KEYRING)
if len(keyring.(string)) > 0 {
args = append(args, "--keyring-backend", keyring.(string))
}
cmdStr := relativePath.(string) + "0gchaind"
cmd := exec.Command(cmdStr, append(args, "-y")...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}

View File

@ -0,0 +1,8 @@
package types
type DASRequest struct {
RequestId uint64 `json:"request_id"`
StreamId string `json:"stream_id"`
BatchHeaderHash string `json:"batch_header_hash"`
NumBlobs uint64 `json:"num_blobs"`
}

10
helper/da/types/keys.go Normal file
View File

@ -0,0 +1,10 @@
package types
const (
DA_RPC_ADDRESS = "rpc_address"
INSTANCE_LIMIT = "instance_limit"
NODE_CLI_RELATIVE_PATH = "relative_path"
NODE_CLI_EXEC_ACCOUNT = "node_exec_account"
NODE_CLI_EXEC_KEYRING = "node_exec_keyring"
NODE_HOME_PATH = "home_path"
)

View File

@ -0,0 +1,51 @@
package sizedw8grp
import (
"context"
"math"
"sync"
)
type SizedWaitGroup struct {
Size int
current chan struct{}
wg sync.WaitGroup
}
func New(limit int) SizedWaitGroup {
size := math.MaxInt32
if limit > 0 {
size = limit
}
return SizedWaitGroup{
Size: size,
current: make(chan struct{}, size),
wg: sync.WaitGroup{},
}
}
func (s *SizedWaitGroup) Add() {
_ = s.AddWithContext(context.Background())
}
func (s *SizedWaitGroup) AddWithContext(ctx context.Context) error {
select {
case <-ctx.Done():
return ctx.Err()
case s.current <- struct{}{}:
break
}
s.wg.Add(1)
return nil
}
func (s *SizedWaitGroup) Done() {
<-s.current
s.wg.Done()
}
func (s *SizedWaitGroup) Wait() {
s.wg.Wait()
}

View File

@ -0,0 +1,52 @@
syntax = "proto3";
package zgc.council.v1;
import "cosmos_proto/cosmos.proto";
import "gogoproto/gogo.proto";
import "google/protobuf/any.proto";
import "google/protobuf/timestamp.proto";
option go_package = "github.com/0glabs/0g-chain/x/council/v1/types";
message Params {
uint64 council_size = 1;
}
// GenesisState defines the council module's genesis state.
message GenesisState {
option (gogoproto.goproto_getters) = false;
Params params = 1 [(gogoproto.nullable) = false];
uint64 voting_start_height = 2;
uint64 voting_period = 3;
uint64 current_council_id = 4 [(gogoproto.customname) = "CurrentCouncilID"];
repeated Council councils = 5 [(gogoproto.nullable) = false];
}
message Council {
uint64 id = 1 [(gogoproto.customname) = "ID"];
uint64 voting_start_height = 2;
uint64 start_height = 3;
uint64 end_height = 4;
repeated Vote votes = 5 [(gogoproto.nullable) = false];
repeated bytes members = 6 [
(cosmos_proto.scalar) = "cosmos.AddressBytes",
(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.ValAddress"
];
}
message Vote {
option (gogoproto.goproto_getters) = false;
uint64 council_id = 1 [(gogoproto.customname) = "CouncilID"];
bytes voter = 2 [
(cosmos_proto.scalar) = "cosmos.AddressBytes",
(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.ValAddress"
];
repeated Ballot ballots = 3;
}
message Ballot {
uint64 id = 1 [(gogoproto.customname) = "ID"];
bytes content = 2;
}

View File

@ -0,0 +1,34 @@
syntax = "proto3";
package zgc.council.v1;
import "cosmos_proto/cosmos.proto";
import "gogoproto/gogo.proto";
import "google/api/annotations.proto";
import "google/protobuf/any.proto";
import "google/protobuf/timestamp.proto";
import "zgc/council/v1/genesis.proto";
option go_package = "github.com/0glabs/0g-chain/x/council/v1/types";
option (gogoproto.goproto_getters_all) = false;
// Query defines the gRPC querier service for council module
service Query {
rpc CurrentCouncilID(QueryCurrentCouncilIDRequest) returns (QueryCurrentCouncilIDResponse) {
option (google.api.http).get = "/0gchain/council/v1/current-council-id";
}
rpc RegisteredVoters(QueryRegisteredVotersRequest) returns (QueryRegisteredVotersResponse) {
option (google.api.http).get = "/0gchain/council/v1/registered-voters";
}
}
message QueryCurrentCouncilIDRequest {}
message QueryCurrentCouncilIDResponse {
uint64 current_council_id = 1 [(gogoproto.customname) = "CurrentCouncilID"];
}
message QueryRegisteredVotersRequest {}
message QueryRegisteredVotersResponse {
repeated string voters = 1;
}

View File

@ -0,0 +1,31 @@
syntax = "proto3";
package zgc.council.v1;
import "cosmos_proto/cosmos.proto";
import "gogoproto/gogo.proto";
import "google/protobuf/any.proto";
import "zgc/council/v1/genesis.proto";
option go_package = "github.com/0glabs/0g-chain/x/council/v1/types";
option (gogoproto.goproto_getters_all) = false;
// Msg defines the council Msg service
service Msg {
rpc Register(MsgRegister) returns (MsgRegisterResponse);
rpc Vote(MsgVote) returns (MsgVoteResponse);
}
message MsgRegister {
string voter = 1;
bytes key = 2;
}
message MsgRegisterResponse {}
message MsgVote {
uint64 council_id = 1 [(gogoproto.customname) = "CouncilID"];
string voter = 2;
repeated Ballot ballots = 3;
}
message MsgVoteResponse {}

View File

@ -0,0 +1,37 @@
syntax = "proto3";
package zgc.das.v1;
import "cosmos_proto/cosmos.proto";
import "gogoproto/gogo.proto";
import "google/protobuf/any.proto";
import "google/protobuf/timestamp.proto";
option go_package = "github.com/0glabs/0g-chain/x/das/v1/types";
message Params {}
// GenesisState defines the das module's genesis state.
message GenesisState {
option (gogoproto.goproto_getters) = false;
Params params = 1 [(gogoproto.nullable) = false];
uint64 next_request_id = 2 [(gogoproto.customname) = "NextRequestID"];
repeated DASRequest requests = 3 [(gogoproto.nullable) = false];
repeated DASResponse responses = 4 [(gogoproto.nullable) = false];
}
message DASRequest {
uint64 id = 1 [(gogoproto.customname) = "ID"];
bytes stream_id = 2 [(gogoproto.customname) = "StreamID"];
bytes batch_header_hash = 3;
uint32 num_blobs = 4;
}
message DASResponse {
uint64 id = 1 [(gogoproto.customname) = "ID"];
bytes sampler = 2 [
(cosmos_proto.scalar) = "cosmos.AddressBytes",
(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.ValAddress"
];
repeated bool results = 3;
}

View File

@ -0,0 +1,24 @@
syntax = "proto3";
package zgc.das.v1;
import "cosmos_proto/cosmos.proto";
import "gogoproto/gogo.proto";
import "google/api/annotations.proto";
import "google/protobuf/any.proto";
import "google/protobuf/timestamp.proto";
option go_package = "github.com/0glabs/0g-chain/x/das/v1/types";
option (gogoproto.goproto_getters_all) = false;
// Query defines the gRPC querier service for the das module
service Query {
rpc NextRequestID(QueryNextRequestIDRequest) returns (QueryNextRequestIDResponse) {
option (google.api.http).get = "/0gchain/das/v1/next-request-id";
}
}
message QueryNextRequestIDRequest {}
message QueryNextRequestIDResponse {
uint64 next_request_id = 1 [(gogoproto.customname) = "NextRequestID"];
}

35
proto/zgc/das/v1/tx.proto Normal file
View File

@ -0,0 +1,35 @@
syntax = "proto3";
package zgc.das.v1;
import "cosmos_proto/cosmos.proto";
import "gogoproto/gogo.proto";
import "google/protobuf/any.proto";
import "zgc/das/v1/genesis.proto";
option go_package = "github.com/0glabs/0g-chain/x/das/v1/types";
option (gogoproto.goproto_getters_all) = false;
// Msg defines the das Msg service
service Msg {
rpc RequestDAS(MsgRequestDAS) returns (MsgRequestDASResponse);
rpc ReportDASResult(MsgReportDASResult) returns (MsgReportDASResultResponse);
}
message MsgRequestDAS {
string requester = 1 [(gogoproto.moretags) = "Requester"];
string stream_id = 2 [(gogoproto.customname) = "StreamID"];
string batch_header_hash = 3;
uint32 num_blobs = 4;
}
message MsgRequestDASResponse {
uint64 request_id = 1 [(gogoproto.customname) = "RequestID"];
}
message MsgReportDASResult {
uint64 request_id = 1 [(gogoproto.customname) = "RequestID"];
string sampler = 2;
repeated bool results = 3;
}
message MsgReportDASResultResponse {}

View File

@ -0,0 +1,87 @@
package cli
import (
"context"
"fmt"
"strings"
"github.com/spf13/cobra"
"github.com/0glabs/0g-chain/x/council/v1/types"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
)
// GetQueryCmd returns the cli query commands for the inflation module.
func GetQueryCmd() *cobra.Command {
cmd := &cobra.Command{
Use: types.ModuleName,
Short: "Querying commands for the council module",
DisableFlagParsing: true,
SuggestionsMinimumDistance: 2,
RunE: client.ValidateCmd,
}
cmd.AddCommand(
GetCurrentCouncilID(),
GetRegisteredVoters(),
)
return cmd
}
func GetCurrentCouncilID() *cobra.Command {
cmd := &cobra.Command{
Use: "current-council-id",
Short: "Query the current council ID",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
queryClient := types.NewQueryClient(clientCtx)
params := &types.QueryCurrentCouncilIDRequest{}
res, err := queryClient.CurrentCouncilID(context.Background(), params)
if err != nil {
return err
}
return clientCtx.PrintString(fmt.Sprintf("%v\n", res.CurrentCouncilID))
},
}
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
func GetRegisteredVoters() *cobra.Command {
cmd := &cobra.Command{
Use: "registered-voters",
Short: "Query registered voters",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
queryClient := types.NewQueryClient(clientCtx)
params := &types.QueryRegisteredVotersRequest{}
res, err := queryClient.RegisteredVoters(context.Background(), params)
if err != nil {
return err
}
return clientCtx.PrintString(fmt.Sprintf("%v\n", strings.Join(res.Voters, ",")))
},
}
flags.AddQueryFlagsToCmd(cmd)
return cmd
}

View File

@ -0,0 +1,198 @@
package cli
import (
"bufio"
"bytes"
"encoding/hex"
"errors"
"fmt"
"strconv"
sdkmath "cosmossdk.io/math"
"github.com/0glabs/0g-chain/crypto/vrf"
"github.com/0glabs/0g-chain/x/council/v1/types"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/tx"
sdkkr "github.com/cosmos/cosmos-sdk/crypto/keyring"
sdk "github.com/cosmos/cosmos-sdk/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
vrfalgo "github.com/coniks-sys/coniks-go/crypto/vrf"
"github.com/cosmos/cosmos-sdk/client/input"
"github.com/spf13/cobra"
)
// GetTxCmd returns the transaction commands for this module
func GetTxCmd() *cobra.Command {
cmd := &cobra.Command{
Use: types.ModuleName,
Short: fmt.Sprintf("%s transactions subcommands", types.ModuleName),
DisableFlagParsing: true,
SuggestionsMinimumDistance: 2,
RunE: client.ValidateCmd,
}
cmd.AddCommand(
NewRegisterCmd(),
NewVoteCmd(),
)
return cmd
}
func NewRegisterCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "register",
Short: "Register a voter",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
// bypass the restriction of set keyring options
ctx := client.GetClientContextFromCmd(cmd).WithKeyringOptions(vrf.VrfOption())
client.SetCmdClientContext(cmd, ctx)
clientCtx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
kr := clientCtx.Keyring
// get account name by address
accAddr := clientCtx.GetFromAddress()
accRecord, err := kr.KeyByAddress(accAddr)
if err != nil {
// not found record by address in keyring
return nil
}
// check voter account record exists
voterAccName := accRecord.Name + "-voter"
_, err = kr.Key(voterAccName)
if err == nil {
// account exists, ask for user confirmation
response, err2 := input.GetConfirmation(fmt.Sprintf("override the existing name %s", voterAccName), bufio.NewReader(clientCtx.Input), cmd.ErrOrStderr())
if err2 != nil {
return err2
}
if !response {
return errors.New("aborted")
}
err2 = kr.Delete(voterAccName)
if err2 != nil {
return err2
}
}
keyringAlgos, _ := kr.SupportedAlgorithms()
algo, err := sdkkr.NewSigningAlgoFromString("vrf", keyringAlgos)
if err != nil {
return err
}
newRecord, err := kr.NewAccount(voterAccName, "", "", "", algo)
if err != nil {
return err
}
pubKey, err := newRecord.GetPubKey()
if err != nil {
return err
}
valAddr, err := sdk.ValAddressFromHex(hex.EncodeToString(clientCtx.GetFromAddress().Bytes()))
if err != nil {
return err
}
msg := &types.MsgRegister{
Voter: valAddr.String(),
Key: pubKey.Bytes(),
}
return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg)
},
}
flags.AddTxFlagsToCmd(cmd)
return cmd
}
func NewVoteCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "vote council-id",
Short: "Vote on a proposal",
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
kr := clientCtx.Keyring
// get account name by address
inAddr := clientCtx.GetFromAddress()
valAddr, err := sdk.ValAddressFromHex(hex.EncodeToString(inAddr.Bytes()))
if err != nil {
return err
}
inRecord, err := kr.KeyByAddress(inAddr)
if err != nil {
// not found record by address in keyring
return nil
}
// check voter account record exists
voterAccName := inRecord.Name + "-voter"
voterRecord, err := kr.Key(voterAccName)
if err != nil {
// not found voter account
return err
}
sk := vrfalgo.PrivateKey(voterRecord.GetLocal().PrivKey.Value)
councilID, err := strconv.ParseUint(args[0], 10, 64)
if err != nil {
return err
}
votingStartHeight := types.DefaultVotingStartHeight + (councilID-1)*types.DefaultVotingPeriod
rsp, err := stakingtypes.NewQueryClient(clientCtx).HistoricalInfo(cmd.Context(), &stakingtypes.QueryHistoricalInfoRequest{Height: int64(votingStartHeight)})
if err != nil {
return err
}
var tokens sdkmath.Int
for _, val := range rsp.Hist.Valset {
thisValAddr := val.GetOperator()
if thisValAddr.Equals(valAddr) {
tokens = val.GetTokens()
}
}
// the denom of token is neuron, need to convert to A0GI
a0gi := tokens.Quo(sdk.NewInt(1_000_000_000_000_000_000))
// 1_000 0AGI token / vote
numBallots := a0gi.Quo(sdk.NewInt(1_000)).Uint64()
ballots := make([]*types.Ballot, numBallots)
for i := range ballots {
ballotID := uint64(i)
ballots[i] = &types.Ballot{
ID: ballotID,
Content: sk.Compute(bytes.Join([][]byte{rsp.Hist.Header.LastCommitHash, types.Uint64ToBytes(ballotID)}, nil)),
}
}
msg := &types.MsgVote{
CouncilID: councilID,
Voter: valAddr.String(),
Ballots: ballots,
}
return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg)
},
}
flags.AddTxFlagsToCmd(cmd)
return cmd
}

56
x/council/v1/genesis.go Normal file
View File

@ -0,0 +1,56 @@
package council
import (
"fmt"
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/0glabs/0g-chain/x/council/v1/keeper"
"github.com/0glabs/0g-chain/x/council/v1/types"
)
// InitGenesis initializes the store state from a genesis state.
func InitGenesis(ctx sdk.Context, keeper keeper.Keeper, gs types.GenesisState) {
if err := gs.Validate(); err != nil {
panic(fmt.Sprintf("failed to validate %s genesis state: %s", types.ModuleName, err))
}
params := gs.Params
err := keeper.SetParams(ctx, params)
if err != nil {
panic(errorsmod.Wrapf(err, "error setting params"))
}
keeper.SetCurrentCouncilID(ctx, gs.CurrentCouncilID)
for _, p := range gs.Councils {
keeper.SetCouncil(ctx, p)
}
}
// ExportGenesis returns a GenesisState for a given context and keeper.
func ExportGenesis(ctx sdk.Context, keeper keeper.Keeper) *types.GenesisState {
startHeight, err := keeper.GetVotingStartHeight(ctx)
if err != nil {
panic(err)
}
period, err := keeper.GetVotingPeriod(ctx)
if err != nil {
panic(err)
}
currentID, err := keeper.GetCurrentCouncilID(ctx)
if err != nil {
panic(err)
}
return types.NewGenesisState(
keeper.GetParams(ctx),
startHeight,
period,
currentID,
keeper.GetCouncils(ctx),
)
}

View File

@ -0,0 +1,72 @@
package keeper
import (
"sort"
sdk "github.com/cosmos/cosmos-sdk/types"
abci "github.com/tendermint/tendermint/abci/types"
)
type Ballot struct {
voter sdk.ValAddress
content string
}
func (k *Keeper) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) {
councilID, err := k.GetCurrentCouncilID(ctx)
if err != nil {
// TODO: handle the case where councilID is not available
return
}
council, bz := k.GetCouncil(ctx, councilID)
if !bz {
return
}
if ctx.BlockHeight() >= int64(council.StartHeight) {
// We are ready to accept votes for the next council
if err := k.StoreNewCouncil(ctx, council.StartHeight); err != nil {
return
}
}
if ctx.BlockHeight() < int64(council.EndHeight) {
return
}
k.IncrementCurrentCouncilID(ctx)
council, bz = k.GetCouncil(ctx, councilID+1)
if !bz {
return
}
ballots := []Ballot{}
seen := make(map[string]struct{})
for _, vote := range council.Votes {
for _, ballot := range vote.Ballots {
ballot := Ballot{
voter: vote.Voter,
content: string(ballot.Content),
}
if _, ok := seen[ballot.content]; ok {
continue
}
ballots = append(ballots, ballot)
seen[ballot.content] = struct{}{}
}
}
sort.Slice(ballots, func(i, j int) bool {
return ballots[i].content < ballots[j].content
})
councilSize := k.GetParams(ctx).CouncilSize
council.Members = make([]sdk.ValAddress, councilSize)
for i := 0; i < int(councilSize); i = i + 1 {
council.Members[i] = ballots[i].voter
}
k.SetCouncil(ctx, council)
}
func (k *Keeper) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) {
}

View File

@ -0,0 +1,35 @@
package keeper
import (
"context"
"github.com/0glabs/0g-chain/x/council/v1/types"
sdk "github.com/cosmos/cosmos-sdk/types"
)
var _ types.QueryServer = Keeper{}
func (k Keeper) CurrentCouncilID(
c context.Context,
_ *types.QueryCurrentCouncilIDRequest,
) (*types.QueryCurrentCouncilIDResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
currentCouncilID, err := k.GetCurrentCouncilID(ctx)
if err != nil {
return nil, err
}
return &types.QueryCurrentCouncilIDResponse{CurrentCouncilID: currentCouncilID}, nil
}
func (k Keeper) RegisteredVoters(
c context.Context,
_ *types.QueryRegisteredVotersRequest,
) (*types.QueryRegisteredVotersResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
voterAddrs := k.GetVoters(ctx)
voters := make([]string, len(voterAddrs))
for i, voterAddr := range voterAddrs {
voters[i] = voterAddr.String()
}
return &types.QueryRegisteredVotersResponse{Voters: voters}, nil
}

View File

@ -0,0 +1,323 @@
package keeper
import (
"fmt"
errorsmod "cosmossdk.io/errors"
"github.com/coniks-sys/coniks-go/crypto/vrf"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/store/prefix"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/tendermint/tendermint/libs/log"
"github.com/0glabs/0g-chain/x/council/v1/types"
)
// Keeper of the inflation store
type Keeper struct {
storeKey storetypes.StoreKey
cdc codec.BinaryCodec
stakingKeeper types.StakingKeeper
}
// NewKeeper creates a new mint Keeper instance
func NewKeeper(
storeKey storetypes.StoreKey,
cdc codec.BinaryCodec,
stakingKeeper types.StakingKeeper,
) Keeper {
return Keeper{
storeKey: storeKey,
cdc: cdc,
stakingKeeper: stakingKeeper,
}
}
// Logger returns a module-specific logger.
func (k Keeper) Logger(ctx sdk.Context) log.Logger {
return ctx.Logger().With("module", "x/"+types.ModuleName)
}
// ------------------------------------------
// Councils
// ------------------------------------------
func (k Keeper) SetCurrentCouncilID(ctx sdk.Context, id uint64) {
store := ctx.KVStore(k.storeKey)
store.Set(types.CurrentCouncilIDKey, types.GetKeyFromID(id))
}
func (k Keeper) GetCurrentCouncilID(ctx sdk.Context) (uint64, error) {
store := ctx.KVStore(k.storeKey)
bz := store.Get(types.CurrentCouncilIDKey)
if bz == nil {
return 0, errorsmod.Wrap(types.ErrInvalidGenesis, "current council ID not set at genesis")
}
return types.Uint64FromBytes(bz), nil
}
func (k Keeper) IncrementCurrentCouncilID(ctx sdk.Context) error {
id, err := k.GetCurrentCouncilID(ctx)
if err != nil {
return err
}
k.SetCurrentCouncilID(ctx, id+1)
return nil
}
func (k Keeper) SetVotingStartHeight(ctx sdk.Context, votingStartHeight uint64) {
store := ctx.KVStore(k.storeKey)
store.Set(types.VotingStartHeightKey, types.GetKeyFromID(votingStartHeight))
}
func (k Keeper) GetVotingStartHeight(ctx sdk.Context) (uint64, error) {
store := ctx.KVStore(k.storeKey)
bz := store.Get(types.VotingStartHeightKey)
if bz == nil {
return 0, errorsmod.Wrap(types.ErrInvalidGenesis, "voting start height not set at genesis")
}
return types.Uint64FromBytes(bz), nil
}
func (k Keeper) SetVotingPeriod(ctx sdk.Context, votingPeriod uint64) {
store := ctx.KVStore(k.storeKey)
store.Set(types.VotingPeriodKey, types.GetKeyFromID(votingPeriod))
}
func (k Keeper) GetVotingPeriod(ctx sdk.Context) (uint64, error) {
store := ctx.KVStore(k.storeKey)
bz := store.Get(types.VotingPeriodKey)
if bz == nil {
return 0, errorsmod.Wrap(types.ErrInvalidGenesis, "voting period not set at genesis")
}
return types.Uint64FromBytes(bz), nil
}
// StoreNewCouncil stores a council, adding a new ID
func (k Keeper) StoreNewCouncil(ctx sdk.Context, votingStartHeight uint64) error {
currentCouncilID, err := k.GetCurrentCouncilID(ctx)
if err != nil {
return err
}
votingPeriod, err := k.GetVotingPeriod(ctx)
if err != nil {
return err
}
com := types.Council{
ID: currentCouncilID + 1,
VotingStartHeight: votingStartHeight,
StartHeight: votingStartHeight + votingPeriod,
EndHeight: votingStartHeight + votingPeriod*2,
Votes: []types.Vote{},
Members: []sdk.ValAddress{},
}
k.SetCouncil(ctx, com)
return nil
}
func (k Keeper) GetCouncil(ctx sdk.Context, councilID uint64) (types.Council, bool) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.CouncilKeyPrefix)
bz := store.Get(types.GetKeyFromID(councilID))
if bz == nil {
return types.Council{}, false
}
var com types.Council
k.cdc.MustUnmarshal(bz, &com)
return com, true
}
// SetCouncil puts a council into the store.
func (k Keeper) SetCouncil(ctx sdk.Context, council types.Council) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.CouncilKeyPrefix)
bz := k.cdc.MustMarshal(&council)
store.Set(types.GetKeyFromID(council.ID), bz)
}
// // DeleteProposal removes a proposal from the store.
// func (k Keeper) DeleteProposal(ctx sdk.Context, proposalID uint64) {
// store := prefix.NewStore(ctx.KVStore(k.storeKey), types.ProposalKeyPrefix)
// store.Delete(types.GetKeyFromID(proposalID))
// }
// IterateProposals provides an iterator over all stored proposals.
// For each proposal, cb will be called. If cb returns true, the iterator will close and stop.
func (k Keeper) IterateCouncil(ctx sdk.Context, cb func(proposal types.Council) (stop bool)) {
iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.CouncilKeyPrefix)
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
var council types.Council
k.cdc.MustUnmarshal(iterator.Value(), &council)
if cb(council) {
break
}
}
}
func (k Keeper) GetCouncils(ctx sdk.Context) types.Councils {
results := types.Councils{}
k.IterateCouncil(ctx, func(prop types.Council) bool {
results = append(results, prop)
return false
})
return results
}
// // DeleteProposalAndVotes removes a proposal and its associated votes.
// func (k Keeper) DeleteProposalAndVotes(ctx sdk.Context, proposalID uint64) {
// votes := k.GetVotesByProposal(ctx, proposalID)
// k.DeleteProposal(ctx, proposalID)
// for _, v := range votes {
// k.DeleteVote(ctx, v.ProposalID, v.Voter)
// }
// }
// ------------------------------------------
// Votes
// ------------------------------------------
// GetVote gets a vote from the store.
func (k Keeper) GetVote(ctx sdk.Context, epochID uint64, voter sdk.ValAddress) (types.Vote, bool) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.VoteKeyPrefix)
bz := store.Get(types.GetVoteKey(epochID, voter))
if bz == nil {
return types.Vote{}, false
}
var vote types.Vote
k.cdc.MustUnmarshal(bz, &vote)
return vote, true
}
// SetVote puts a vote into the store.
func (k Keeper) SetVote(ctx sdk.Context, vote types.Vote) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.VoteKeyPrefix)
bz := k.cdc.MustMarshal(&vote)
store.Set(types.GetVoteKey(vote.CouncilID, vote.Voter), bz)
}
// DeleteVote removes a Vote from the store.
func (k Keeper) DeleteVote(ctx sdk.Context, councilID uint64, voter sdk.ValAddress) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.VoteKeyPrefix)
store.Delete(types.GetVoteKey(councilID, voter))
}
// IterateVotes provides an iterator over all stored votes.
// For each vote, cb will be called. If cb returns true, the iterator will close and stop.
func (k Keeper) IterateVotes(ctx sdk.Context, cb func(vote types.Vote) (stop bool)) {
iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.VoteKeyPrefix)
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
var vote types.Vote
k.cdc.MustUnmarshal(iterator.Value(), &vote)
if cb(vote) {
break
}
}
}
// GetVotes returns all stored votes.
func (k Keeper) GetVotes(ctx sdk.Context) []types.Vote {
results := []types.Vote{}
k.IterateVotes(ctx, func(vote types.Vote) bool {
results = append(results, vote)
return false
})
return results
}
// GetVotesByProposal returns all votes for one proposal.
func (k Keeper) GetVotesByCouncil(ctx sdk.Context, councilID uint64) []types.Vote {
results := []types.Vote{}
iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), append(types.VoteKeyPrefix, types.GetKeyFromID(councilID)...))
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
var vote types.Vote
k.cdc.MustUnmarshal(iterator.Value(), &vote)
results = append(results, vote)
}
return results
}
// ------------------------------------------
// Voters
// ------------------------------------------
func (k Keeper) SetVoter(ctx sdk.Context, voter sdk.ValAddress, pk vrf.PublicKey) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.VoterKeyPrefix)
store.Set(types.GetVoterKey(voter), pk)
fmt.Printf("voterStoreKey: %v, publicKey: %v\n", types.GetVoterKey(voter), pk)
}
func (k Keeper) IterateVoters(ctx sdk.Context, cb func(voter sdk.ValAddress, pk vrf.PublicKey) (stop bool)) {
iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.VoterKeyPrefix)
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
if cb(sdk.ValAddress(iterator.Key()[1:]), vrf.PublicKey(iterator.Value())) {
break
}
}
}
// GetVotes returns all stored voters
func (k Keeper) GetVoters(ctx sdk.Context) []sdk.ValAddress {
results := []sdk.ValAddress{}
k.IterateVoters(ctx, func(voter sdk.ValAddress, _ vrf.PublicKey) bool {
results = append(results, voter)
return false
})
return results
}
func (k Keeper) AddVoter(ctx sdk.Context, voter sdk.ValAddress, key []byte) error {
if len(key) != vrf.PublicKeySize {
return types.ErrInvalidPublicKey
}
k.SetVoter(ctx, voter, vrf.PublicKey(key))
ctx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypeRegister,
sdk.NewAttribute(types.AttributeKeyVoter, voter.String()),
// TODO: types.AttributeKeyPublicKey
),
)
return nil
}
func (k Keeper) AddVote(ctx sdk.Context, councilID uint64, voter sdk.ValAddress, ballots []*types.Ballot) error {
// Validate
com, found := k.GetCouncil(ctx, councilID)
if !found {
return errorsmod.Wrapf(types.ErrUnknownCouncil, "%d", councilID)
}
if com.HasVotingEndedBy(ctx.BlockHeight()) {
return errorsmod.Wrapf(types.ErrProposalExpired, "%d ≥ %d", ctx.BlockHeight(), com.StartHeight)
}
// TODO: verify if the voter is registered
// TODO: verify whether ballots are valid or not
// Store vote, overwriting any prior vote
k.SetVote(ctx, types.NewVote(councilID, voter, ballots))
ctx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypeVote,
sdk.NewAttribute(types.AttributeKeyCouncilID, fmt.Sprintf("%d", com.ID)),
sdk.NewAttribute(types.AttributeKeyVoter, voter.String()),
// TODO: types.AttributeKeyBallots
),
)
return nil
}

View File

@ -0,0 +1,51 @@
// Copyright Tharsis Labs Ltd.(Evmos)
// SPDX-License-Identifier:ENCL-1.0(https://github.com/evmos/evmos/blob/main/LICENSE)
package keeper
import (
"context"
"github.com/0glabs/0g-chain/x/council/v1/types"
sdk "github.com/cosmos/cosmos-sdk/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)
var _ types.MsgServer = &Keeper{}
// Register handles MsgRegister messages
func (k Keeper) Register(goCtx context.Context, msg *types.MsgRegister) (*types.MsgRegisterResponse, error) {
ctx := sdk.UnwrapSDKContext(goCtx)
valAddr, err := sdk.ValAddressFromBech32(msg.Voter)
if err != nil {
return nil, err
}
_, found := k.stakingKeeper.GetValidator(ctx, valAddr)
if !found {
return nil, stakingtypes.ErrNoValidatorFound
}
if err := k.AddVoter(ctx, valAddr, msg.Key); err != nil {
return nil, err
}
return &types.MsgRegisterResponse{}, nil
}
// Vote handles MsgVote messages
func (k Keeper) Vote(goCtx context.Context, msg *types.MsgVote) (*types.MsgVoteResponse, error) {
ctx := sdk.UnwrapSDKContext(goCtx)
voter, err := sdk.ValAddressFromBech32(msg.Voter)
if err != nil {
return nil, err
}
if err := k.AddVote(ctx, msg.CouncilID, voter, msg.Ballots); err != nil {
return nil, err
}
return &types.MsgVoteResponse{}, nil
}

View File

@ -0,0 +1,29 @@
package keeper
import (
"github.com/0glabs/0g-chain/x/council/v1/types"
sdk "github.com/cosmos/cosmos-sdk/types"
)
func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) {
store := ctx.KVStore(k.storeKey)
bz := store.Get(types.ParamsKey)
if len(bz) == 0 {
return params
}
k.cdc.MustUnmarshal(bz, &params)
return params
}
func (k Keeper) SetParams(ctx sdk.Context, params types.Params) error {
store := ctx.KVStore(k.storeKey)
bz, err := k.cdc.Marshal(&params)
if err != nil {
return err
}
store.Set(types.ParamsKey, bz)
return nil
}

182
x/council/v1/module.go Normal file
View File

@ -0,0 +1,182 @@
package council
import (
"context"
"encoding/json"
"fmt"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
"github.com/gorilla/mux"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/spf13/cobra"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/0glabs/0g-chain/x/council/v1/client/cli"
"github.com/0glabs/0g-chain/x/council/v1/keeper"
"github.com/0glabs/0g-chain/x/council/v1/types"
)
// consensusVersion defines the current x/council module consensus version.
const consensusVersion = 1
// type check to ensure the interface is properly implemented
var (
_ module.AppModule = AppModule{}
_ module.AppModuleBasic = AppModuleBasic{}
// _ module.AppModuleSimulation = AppModule{}
_ module.BeginBlockAppModule = AppModule{}
_ module.EndBlockAppModule = AppModule{}
)
// app module Basics object
type AppModuleBasic struct{}
// Name returns the inflation module's name.
func (AppModuleBasic) Name() string {
return types.ModuleName
}
// RegisterLegacyAminoCodec registers the inflation module's types on the given LegacyAmino codec.
func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {}
// ConsensusVersion returns the consensus state-breaking version for the module.
func (AppModuleBasic) ConsensusVersion() uint64 {
return consensusVersion
}
// RegisterInterfaces registers interfaces and implementations of the incentives
// module.
func (AppModuleBasic) RegisterInterfaces(interfaceRegistry codectypes.InterfaceRegistry) {
types.RegisterInterfaces(interfaceRegistry)
}
// DefaultGenesis returns default genesis state as raw bytes for the incentives
// module.
func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage {
return cdc.MustMarshalJSON(types.DefaultGenesisState())
}
// ValidateGenesis performs genesis state validation for the inflation module.
func (b AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, _ client.TxEncodingConfig, bz json.RawMessage) error {
var genesisState types.GenesisState
if err := cdc.UnmarshalJSON(bz, &genesisState); err != nil {
return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err)
}
return genesisState.Validate()
}
// RegisterRESTRoutes performs a no-op as the inflation module doesn't expose REST
// endpoints
func (AppModuleBasic) RegisterRESTRoutes(_ client.Context, _ *mux.Router) {}
// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the inflation module.
func (b AppModuleBasic) RegisterGRPCGatewayRoutes(c client.Context, serveMux *runtime.ServeMux) {
if err := types.RegisterQueryHandlerClient(context.Background(), serveMux, types.NewQueryClient(c)); err != nil {
panic(err)
}
}
// GetTxCmd returns the root tx command for the inflation module.
func (AppModuleBasic) GetTxCmd() *cobra.Command { return cli.GetTxCmd() }
// GetQueryCmd returns no root query command for the inflation module.
func (AppModuleBasic) GetQueryCmd() *cobra.Command {
return cli.GetQueryCmd()
}
// ___________________________________________________________________________
// AppModule implements an application module for the inflation module.
type AppModule struct {
AppModuleBasic
keeper keeper.Keeper
sk stakingkeeper.Keeper
}
// NewAppModule creates a new AppModule Object
func NewAppModule(
k keeper.Keeper,
sk stakingkeeper.Keeper,
) AppModule {
return AppModule{
AppModuleBasic: AppModuleBasic{},
keeper: k,
sk: sk,
}
}
// Name returns the inflation module's name.
func (AppModule) Name() string {
return types.ModuleName
}
// Route returns evmutil module's message route.
func (am AppModule) Route() sdk.Route { return sdk.Route{} }
// QuerierRoute returns evmutil module's query routing key.
func (AppModule) QuerierRoute() string { return "" }
// LegacyQuerierHandler returns evmutil module's Querier.
func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier {
return nil
}
// RegisterInvariants registers the inflation module invariants.
func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {}
// RegisterServices registers a gRPC query service to respond to the
// module-specific gRPC queries.
func (am AppModule) RegisterServices(cfg module.Configurator) {
types.RegisterMsgServer(cfg.MsgServer(), am.keeper)
types.RegisterQueryServer(cfg.QueryServer(), am.keeper)
}
func (am AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) {
am.keeper.BeginBlock(ctx, req)
}
func (am AppModule) EndBlock(ctx sdk.Context, req abci.RequestEndBlock) []abci.ValidatorUpdate {
am.keeper.EndBlock(ctx, req)
return []abci.ValidatorUpdate{}
}
// InitGenesis performs genesis initialization for the inflation module. It returns
// no validator updates.
func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate {
var genesisState types.GenesisState
cdc.MustUnmarshalJSON(data, &genesisState)
InitGenesis(ctx, am.keeper, genesisState)
return []abci.ValidatorUpdate{}
}
// ExportGenesis returns the exported genesis state as raw bytes for the inflation
// module.
func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage {
gs := ExportGenesis(ctx, am.keeper)
return cdc.MustMarshalJSON(gs)
}
// ___________________________________________________________________________
// AppModuleSimulation functions
// GenerateGenesisState creates a randomized GenState of the inflation module.
func (am AppModule) GenerateGenesisState(_ *module.SimulationState) {
}
// RegisterStoreDecoder registers a decoder for inflation module's types.
func (am AppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {
}
// WeightedOperations doesn't return any inflation module operation.
func (am AppModule) WeightedOperations(_ module.SimulationState) []simtypes.WeightedOperation {
return []simtypes.WeightedOperation{}
}

View File

@ -0,0 +1,52 @@
package types
import (
"github.com/0glabs/0g-chain/crypto/vrf"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/msgservice"
)
var (
amino = codec.NewLegacyAmino()
// ModuleCdc references the global evm module codec. Note, the codec should
// ONLY be used in certain instances of tests and for JSON encoding.
ModuleCdc = codec.NewProtoCodec(codectypes.NewInterfaceRegistry())
// AminoCdc is a amino codec created to support amino JSON compatible msgs.
AminoCdc = codec.NewAminoCodec(amino)
)
const (
// Amino names
registerName = "evmos/council/MsgRegister"
voteName = "evmos/council/MsgVote"
)
// NOTE: This is required for the GetSignBytes function
func init() {
RegisterLegacyAminoCodec(amino)
amino.Seal()
}
// RegisterInterfaces register implementations
func RegisterInterfaces(registry codectypes.InterfaceRegistry) {
registry.RegisterImplementations(
(*sdk.Msg)(nil),
&MsgRegister{},
&MsgVote{},
)
registry.RegisterImplementations((*cryptotypes.PubKey)(nil), &vrf.PubKey{})
registry.RegisterImplementations((*cryptotypes.PrivKey)(nil), &vrf.PrivKey{})
msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc)
}
// RegisterLegacyAminoCodec required for EIP-712
func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {
cdc.RegisterConcrete(&MsgRegister{}, registerName, nil)
cdc.RegisterConcrete(&MsgVote{}, voteName, nil)
}

View File

@ -0,0 +1,21 @@
package types
import (
sdk "github.com/cosmos/cosmos-sdk/types"
)
type Councils []Council
type Votes []Vote
func (c Council) HasVotingEndedBy(height int64) bool {
return height >= int64(c.StartHeight)
}
// NewVote instantiates a new instance of Vote
func NewVote(councilID uint64, voter sdk.ValAddress, ballots []*Ballot) Vote {
return Vote{
CouncilID: councilID,
Voter: voter,
Ballots: ballots,
}
}

View File

@ -0,0 +1,3 @@
package types
type Epoch struct{}

View File

@ -0,0 +1,19 @@
package types
import errorsmod "cosmossdk.io/errors"
var (
ErrUnknownCouncil = errorsmod.Register(ModuleName, 2, "council not found")
ErrInvalidCouncil = errorsmod.Register(ModuleName, 3, "invalid council")
ErrUnknownProposal = errorsmod.Register(ModuleName, 4, "proposal not found")
ErrProposalExpired = errorsmod.Register(ModuleName, 5, "proposal expired")
ErrInvalidPubProposal = errorsmod.Register(ModuleName, 6, "invalid pubproposal")
ErrUnknownVote = errorsmod.Register(ModuleName, 7, "vote not found")
ErrInvalidGenesis = errorsmod.Register(ModuleName, 8, "invalid genesis")
ErrNoProposalHandlerExists = errorsmod.Register(ModuleName, 9, "pubproposal has no corresponding handler")
ErrUnknownSubspace = errorsmod.Register(ModuleName, 10, "subspace not found")
ErrInvalidVoteType = errorsmod.Register(ModuleName, 11, "invalid vote type")
ErrNotFoundProposalTally = errorsmod.Register(ModuleName, 12, "proposal tally not found")
ErrInvalidPublicKey = errorsmod.Register(ModuleName, 13, "invalid public key")
ErrInvalidValidatorAddress = errorsmod.Register(ModuleName, 14, "invalid validator address")
)

View File

@ -0,0 +1,19 @@
package types
// Module event types
const (
EventTypeRegister = "register"
EventTypeVote = "vote"
AttributeValueCategory = "council"
AttributeKeyCouncilID = "council_id"
AttributeKeyProposalID = "proposal_id"
AttributeKeyVotingStartHeight = "voting_start_height"
AttributeKeyVotingEndHeight = "voting_end_height"
AttributeKeyProposalCloseStatus = "status"
AttributeKeyVoter = "voter"
AttributeKeyBallots = "ballots"
AttributeKeyPublicKey = "public_key"
AttributeKeyProposalOutcome = "proposal_outcome"
AttributeKeyProposalTally = "proposal_tally"
)

View File

@ -0,0 +1,42 @@
package types
const (
DefaultVotingStartHeight = 1
DefaultVotingPeriod = 200
)
// NewGenesisState returns a new genesis state object for the module.
func NewGenesisState(params Params, votingStartHeight uint64, votingPeriod uint64, currentCouncilID uint64, councils Councils) *GenesisState {
return &GenesisState{
Params: params,
VotingStartHeight: votingStartHeight,
VotingPeriod: votingPeriod,
CurrentCouncilID: currentCouncilID,
Councils: councils,
}
}
// DefaultGenesisState returns the default genesis state for the module.
func DefaultGenesisState() *GenesisState {
return NewGenesisState(
Params{
CouncilSize: 1,
},
DefaultVotingStartHeight,
DefaultVotingPeriod,
1,
[]Council{
{
ID: 1,
VotingStartHeight: DefaultVotingStartHeight,
StartHeight: DefaultVotingStartHeight + DefaultVotingPeriod,
EndHeight: DefaultVotingStartHeight + DefaultVotingPeriod*2,
Votes: Votes{},
}},
)
}
// Validate performs basic validation of genesis data.
func (gs GenesisState) Validate() error {
return nil
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,23 @@
package types
import (
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)
// AccountKeeper defines the expected account keeper
type AccountKeeper interface {
GetAccount(sdk.Context, sdk.AccAddress) authtypes.AccountI
}
// BankKeeper defines the expected bank keeper interface
type BankKeeper interface {
GetSupply(ctx sdk.Context, denom string) sdk.Coin
GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin
}
type StakingKeeper interface {
BondDenom(ctx sdk.Context) (res string)
GetValidator(ctx sdk.Context, addr sdk.ValAddress) (validator stakingtypes.Validator, found bool)
}

View File

@ -0,0 +1,52 @@
package types
import (
"encoding/binary"
sdk "github.com/cosmos/cosmos-sdk/types"
)
const (
// ModuleName The name that will be used throughout the module
ModuleName = "council"
// StoreKey Top level store key where all module items will be stored
StoreKey = ModuleName
)
// Key prefixes
var (
CouncilKeyPrefix = []byte{0x00} // prefix for keys that store councils
VoteKeyPrefix = []byte{0x01} // prefix for keys that store votes
VoterKeyPrefix = []byte{0x02} // prefix for keys that store voters
ParamsKey = []byte{0x03}
VotingStartHeightKey = []byte{0x04}
VotingPeriodKey = []byte{0x05}
CurrentCouncilIDKey = []byte{0x06}
)
// GetKeyFromID returns the bytes to use as a key for a uint64 id
func GetKeyFromID(id uint64) []byte {
return Uint64ToBytes(id)
}
func GetVoteKey(councilID uint64, voter sdk.ValAddress) []byte {
return append(GetKeyFromID(councilID), voter.Bytes()...)
}
func GetVoterKey(voter sdk.ValAddress) []byte {
return voter.Bytes()
}
// Uint64ToBytes converts a uint64 into fixed length bytes for use in store keys.
func Uint64ToBytes(id uint64) []byte {
bz := make([]byte, 8)
binary.BigEndian.PutUint64(bz, uint64(id))
return bz
}
// Uint64FromBytes converts some fixed length bytes back into a uint64.
func Uint64FromBytes(bz []byte) uint64 {
return binary.BigEndian.Uint64(bz)
}

65
x/council/v1/types/msg.go Normal file
View File

@ -0,0 +1,65 @@
package types
import (
"encoding/hex"
"github.com/coniks-sys/coniks-go/crypto/vrf"
sdk "github.com/cosmos/cosmos-sdk/types"
)
var _, _ sdk.Msg = &MsgRegister{}, &MsgVote{}
// GetSigners returns the expected signers for a MsgRegister message.
func (msg *MsgRegister) GetSigners() []sdk.AccAddress {
valAddr, err := sdk.ValAddressFromBech32(msg.Voter)
if err != nil {
panic(err)
}
accAddr, err := sdk.AccAddressFromHexUnsafe(hex.EncodeToString(valAddr.Bytes()))
if err != nil {
panic(err)
}
return []sdk.AccAddress{accAddr}
}
// ValidateBasic does a sanity check of the provided data
func (msg *MsgRegister) ValidateBasic() error {
if _, err := sdk.ValAddressFromBech32(msg.Voter); err != nil {
return ErrInvalidValidatorAddress
}
if len(msg.Key) != vrf.PublicKeySize {
return ErrInvalidPublicKey
}
return nil
}
// GetSignBytes implements the LegacyMsg interface.
func (msg MsgRegister) GetSignBytes() []byte {
return sdk.MustSortJSON(AminoCdc.MustMarshalJSON(&msg))
}
// GetSigners returns the expected signers for a MsgVote message.
func (msg *MsgVote) GetSigners() []sdk.AccAddress {
valAddr, err := sdk.ValAddressFromBech32(msg.Voter)
if err != nil {
panic(err)
}
accAddr, err := sdk.AccAddressFromHexUnsafe(hex.EncodeToString(valAddr.Bytes()))
if err != nil {
panic(err)
}
return []sdk.AccAddress{accAddr}
}
// ValidateBasic does a sanity check of the provided data
func (msg *MsgVote) ValidateBasic() error {
if _, err := sdk.ValAddressFromBech32(msg.Voter); err != nil {
return ErrInvalidValidatorAddress
}
return nil
}
// GetSignBytes implements the LegacyMsg interface.
func (msg MsgVote) GetSignBytes() []byte {
return sdk.MustSortJSON(AminoCdc.MustMarshalJSON(&msg))
}

View File

@ -0,0 +1,839 @@
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: zgc/council/v1/query.proto
package types
import (
context "context"
fmt "fmt"
_ "github.com/cosmos/cosmos-proto"
_ "github.com/cosmos/cosmos-sdk/codec/types"
_ "github.com/gogo/protobuf/gogoproto"
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"
_ "google.golang.org/protobuf/types/known/timestamppb"
io "io"
math "math"
math_bits "math/bits"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
type QueryCurrentCouncilIDRequest struct {
}
func (m *QueryCurrentCouncilIDRequest) Reset() { *m = QueryCurrentCouncilIDRequest{} }
func (m *QueryCurrentCouncilIDRequest) String() string { return proto.CompactTextString(m) }
func (*QueryCurrentCouncilIDRequest) ProtoMessage() {}
func (*QueryCurrentCouncilIDRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_eb373abb48fc6ce6, []int{0}
}
func (m *QueryCurrentCouncilIDRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryCurrentCouncilIDRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryCurrentCouncilIDRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryCurrentCouncilIDRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryCurrentCouncilIDRequest.Merge(m, src)
}
func (m *QueryCurrentCouncilIDRequest) XXX_Size() int {
return m.Size()
}
func (m *QueryCurrentCouncilIDRequest) XXX_DiscardUnknown() {
xxx_messageInfo_QueryCurrentCouncilIDRequest.DiscardUnknown(m)
}
var xxx_messageInfo_QueryCurrentCouncilIDRequest proto.InternalMessageInfo
type QueryCurrentCouncilIDResponse struct {
CurrentCouncilID uint64 `protobuf:"varint,1,opt,name=current_council_id,json=currentCouncilId,proto3" json:"current_council_id,omitempty"`
}
func (m *QueryCurrentCouncilIDResponse) Reset() { *m = QueryCurrentCouncilIDResponse{} }
func (m *QueryCurrentCouncilIDResponse) String() string { return proto.CompactTextString(m) }
func (*QueryCurrentCouncilIDResponse) ProtoMessage() {}
func (*QueryCurrentCouncilIDResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_eb373abb48fc6ce6, []int{1}
}
func (m *QueryCurrentCouncilIDResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryCurrentCouncilIDResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryCurrentCouncilIDResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryCurrentCouncilIDResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryCurrentCouncilIDResponse.Merge(m, src)
}
func (m *QueryCurrentCouncilIDResponse) XXX_Size() int {
return m.Size()
}
func (m *QueryCurrentCouncilIDResponse) XXX_DiscardUnknown() {
xxx_messageInfo_QueryCurrentCouncilIDResponse.DiscardUnknown(m)
}
var xxx_messageInfo_QueryCurrentCouncilIDResponse proto.InternalMessageInfo
type QueryRegisteredVotersRequest struct {
}
func (m *QueryRegisteredVotersRequest) Reset() { *m = QueryRegisteredVotersRequest{} }
func (m *QueryRegisteredVotersRequest) String() string { return proto.CompactTextString(m) }
func (*QueryRegisteredVotersRequest) ProtoMessage() {}
func (*QueryRegisteredVotersRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_eb373abb48fc6ce6, []int{2}
}
func (m *QueryRegisteredVotersRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryRegisteredVotersRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryRegisteredVotersRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryRegisteredVotersRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryRegisteredVotersRequest.Merge(m, src)
}
func (m *QueryRegisteredVotersRequest) XXX_Size() int {
return m.Size()
}
func (m *QueryRegisteredVotersRequest) XXX_DiscardUnknown() {
xxx_messageInfo_QueryRegisteredVotersRequest.DiscardUnknown(m)
}
var xxx_messageInfo_QueryRegisteredVotersRequest proto.InternalMessageInfo
type QueryRegisteredVotersResponse struct {
Voters []string `protobuf:"bytes,1,rep,name=voters,proto3" json:"voters,omitempty"`
}
func (m *QueryRegisteredVotersResponse) Reset() { *m = QueryRegisteredVotersResponse{} }
func (m *QueryRegisteredVotersResponse) String() string { return proto.CompactTextString(m) }
func (*QueryRegisteredVotersResponse) ProtoMessage() {}
func (*QueryRegisteredVotersResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_eb373abb48fc6ce6, []int{3}
}
func (m *QueryRegisteredVotersResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryRegisteredVotersResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryRegisteredVotersResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryRegisteredVotersResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryRegisteredVotersResponse.Merge(m, src)
}
func (m *QueryRegisteredVotersResponse) XXX_Size() int {
return m.Size()
}
func (m *QueryRegisteredVotersResponse) XXX_DiscardUnknown() {
xxx_messageInfo_QueryRegisteredVotersResponse.DiscardUnknown(m)
}
var xxx_messageInfo_QueryRegisteredVotersResponse proto.InternalMessageInfo
func init() {
proto.RegisterType((*QueryCurrentCouncilIDRequest)(nil), "zgc.council.v1.QueryCurrentCouncilIDRequest")
proto.RegisterType((*QueryCurrentCouncilIDResponse)(nil), "zgc.council.v1.QueryCurrentCouncilIDResponse")
proto.RegisterType((*QueryRegisteredVotersRequest)(nil), "zgc.council.v1.QueryRegisteredVotersRequest")
proto.RegisterType((*QueryRegisteredVotersResponse)(nil), "zgc.council.v1.QueryRegisteredVotersResponse")
}
func init() { proto.RegisterFile("zgc/council/v1/query.proto", fileDescriptor_eb373abb48fc6ce6) }
var fileDescriptor_eb373abb48fc6ce6 = []byte{
// 418 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x92, 0x3f, 0x8f, 0xd3, 0x30,
0x18, 0xc6, 0xe3, 0x03, 0x4e, 0xc2, 0x03, 0xaa, 0xac, 0x13, 0xba, 0x8b, 0x0e, 0x5f, 0x15, 0x09,
0xe8, 0x40, 0xe2, 0x16, 0x06, 0xf6, 0x96, 0x05, 0x31, 0xd1, 0x81, 0x81, 0xa5, 0x4a, 0x1c, 0xe3,
0x5a, 0x6a, 0xec, 0x34, 0x76, 0x2a, 0xda, 0x91, 0x4f, 0x80, 0xc4, 0x0e, 0x5f, 0xa7, 0x62, 0xaa,
0xc4, 0xc2, 0x84, 0x20, 0xe5, 0x83, 0xa0, 0xc6, 0x6e, 0xd5, 0x3f, 0x04, 0xb1, 0xe5, 0x7d, 0x9e,
0xf7, 0x7d, 0xfd, 0xf3, 0xe3, 0x40, 0x7f, 0xc1, 0x29, 0xa1, 0xaa, 0x94, 0x54, 0x4c, 0xc8, 0xac,
0x47, 0xa6, 0x25, 0x2b, 0xe6, 0x51, 0x5e, 0x28, 0xa3, 0xd0, 0xbd, 0x05, 0xa7, 0x91, 0xf3, 0xa2,
0x59, 0xcf, 0xbf, 0xa2, 0x4a, 0x67, 0x4a, 0x8f, 0x6a, 0x97, 0xd8, 0xc2, 0xb6, 0xfa, 0x17, 0x5c,
0x71, 0x65, 0xf5, 0xcd, 0x97, 0x53, 0xaf, 0xb9, 0x52, 0x7c, 0xc2, 0x48, 0x9c, 0x0b, 0x12, 0x4b,
0xa9, 0x4c, 0x6c, 0x84, 0x92, 0xdb, 0x99, 0x2b, 0xe7, 0xd6, 0x55, 0x52, 0xbe, 0x23, 0xb1, 0x74,
0x27, 0xfb, 0x37, 0xc7, 0x96, 0x11, 0x19, 0xd3, 0x26, 0xce, 0xf2, 0xed, 0xe6, 0x23, 0x6c, 0xce,
0x24, 0xd3, 0xc2, 0x6d, 0x0e, 0x30, 0xbc, 0x7e, 0xbd, 0xb9, 0xc7, 0xa0, 0x2c, 0x0a, 0x26, 0xcd,
0xc0, 0xf6, 0xbd, 0x7c, 0x31, 0x64, 0xd3, 0x92, 0x69, 0x13, 0x50, 0xf8, 0xa0, 0xc1, 0xd7, 0xb9,
0x92, 0x9a, 0xa1, 0x3e, 0x44, 0xd4, 0x7a, 0x23, 0x77, 0xc8, 0x48, 0xa4, 0x97, 0xa0, 0x0d, 0x3a,
0xb7, 0xfb, 0x17, 0xd5, 0x8f, 0x9b, 0xd6, 0xc9, 0x64, 0x8b, 0x1e, 0x2a, 0xe9, 0x0e, 0x62, 0xc8,
0xb8, 0xd0, 0x86, 0x15, 0x2c, 0x7d, 0xa3, 0x0c, 0x2b, 0xf4, 0x16, 0xe2, 0xb9, 0x83, 0x38, 0xf5,
0x1d, 0xc4, 0x7d, 0x78, 0x3e, 0xab, 0x95, 0x4b, 0xd0, 0xbe, 0xd5, 0xb9, 0x3b, 0x74, 0xd5, 0xd3,
0xaf, 0x67, 0xf0, 0x4e, 0x3d, 0x89, 0xbe, 0x00, 0x78, 0x42, 0x82, 0x9e, 0x44, 0x87, 0xcf, 0x16,
0xfd, 0x2b, 0x0a, 0x3f, 0xfc, 0xcf, 0x6e, 0xcb, 0x14, 0x44, 0x1f, 0xbe, 0xfd, 0xfe, 0x74, 0xd6,
0x41, 0x8f, 0x48, 0x97, 0xd3, 0x71, 0x2c, 0xe4, 0xfe, 0x23, 0xb8, 0x08, 0x42, 0x27, 0x85, 0x22,
0x45, 0x9f, 0x01, 0x6c, 0x1d, 0x5f, 0xb0, 0x81, 0xb0, 0x21, 0xa7, 0x06, 0xc2, 0xa6, 0xd4, 0x82,
0xb0, 0x26, 0x7c, 0x8c, 0x1e, 0xfe, 0x8d, 0xb0, 0xd8, 0x4d, 0x85, 0x36, 0xcc, 0xfe, 0xab, 0xe5,
0x2f, 0xec, 0x2d, 0x2b, 0x0c, 0x56, 0x15, 0x06, 0x3f, 0x2b, 0x0c, 0x3e, 0xae, 0xb1, 0xb7, 0x5a,
0x63, 0xef, 0xfb, 0x1a, 0x7b, 0x6f, 0x43, 0x2e, 0xcc, 0xb8, 0x4c, 0x22, 0xaa, 0x32, 0xd2, 0xe5,
0x93, 0x38, 0xd1, 0xa4, 0xcb, 0x43, 0xbb, 0xf6, 0xfd, 0xfe, 0x62, 0x33, 0xcf, 0x99, 0x4e, 0xce,
0xeb, 0xdf, 0xef, 0xd9, 0x9f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x6f, 0x29, 0x40, 0xb9, 0x55, 0x03,
0x00, 0x00,
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion4
// QueryClient is the client API for Query service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type QueryClient interface {
CurrentCouncilID(ctx context.Context, in *QueryCurrentCouncilIDRequest, opts ...grpc.CallOption) (*QueryCurrentCouncilIDResponse, error)
RegisteredVoters(ctx context.Context, in *QueryRegisteredVotersRequest, opts ...grpc.CallOption) (*QueryRegisteredVotersResponse, error)
}
type queryClient struct {
cc grpc1.ClientConn
}
func NewQueryClient(cc grpc1.ClientConn) QueryClient {
return &queryClient{cc}
}
func (c *queryClient) CurrentCouncilID(ctx context.Context, in *QueryCurrentCouncilIDRequest, opts ...grpc.CallOption) (*QueryCurrentCouncilIDResponse, error) {
out := new(QueryCurrentCouncilIDResponse)
err := c.cc.Invoke(ctx, "/zgc.council.v1.Query/CurrentCouncilID", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *queryClient) RegisteredVoters(ctx context.Context, in *QueryRegisteredVotersRequest, opts ...grpc.CallOption) (*QueryRegisteredVotersResponse, error) {
out := new(QueryRegisteredVotersResponse)
err := c.cc.Invoke(ctx, "/zgc.council.v1.Query/RegisteredVoters", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// QueryServer is the server API for Query service.
type QueryServer interface {
CurrentCouncilID(context.Context, *QueryCurrentCouncilIDRequest) (*QueryCurrentCouncilIDResponse, error)
RegisteredVoters(context.Context, *QueryRegisteredVotersRequest) (*QueryRegisteredVotersResponse, error)
}
// UnimplementedQueryServer can be embedded to have forward compatible implementations.
type UnimplementedQueryServer struct {
}
func (*UnimplementedQueryServer) CurrentCouncilID(ctx context.Context, req *QueryCurrentCouncilIDRequest) (*QueryCurrentCouncilIDResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method CurrentCouncilID not implemented")
}
func (*UnimplementedQueryServer) RegisteredVoters(ctx context.Context, req *QueryRegisteredVotersRequest) (*QueryRegisteredVotersResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method RegisteredVoters not implemented")
}
func RegisterQueryServer(s grpc1.Server, srv QueryServer) {
s.RegisterService(&_Query_serviceDesc, srv)
}
func _Query_CurrentCouncilID_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(QueryCurrentCouncilIDRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(QueryServer).CurrentCouncilID(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/zgc.council.v1.Query/CurrentCouncilID",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(QueryServer).CurrentCouncilID(ctx, req.(*QueryCurrentCouncilIDRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Query_RegisteredVoters_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(QueryRegisteredVotersRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(QueryServer).RegisteredVoters(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/zgc.council.v1.Query/RegisteredVoters",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(QueryServer).RegisteredVoters(ctx, req.(*QueryRegisteredVotersRequest))
}
return interceptor(ctx, in, info, handler)
}
var _Query_serviceDesc = grpc.ServiceDesc{
ServiceName: "zgc.council.v1.Query",
HandlerType: (*QueryServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "CurrentCouncilID",
Handler: _Query_CurrentCouncilID_Handler,
},
{
MethodName: "RegisteredVoters",
Handler: _Query_RegisteredVoters_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "zgc/council/v1/query.proto",
}
func (m *QueryCurrentCouncilIDRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryCurrentCouncilIDRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryCurrentCouncilIDRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
return len(dAtA) - i, nil
}
func (m *QueryCurrentCouncilIDResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryCurrentCouncilIDResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryCurrentCouncilIDResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.CurrentCouncilID != 0 {
i = encodeVarintQuery(dAtA, i, uint64(m.CurrentCouncilID))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *QueryRegisteredVotersRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryRegisteredVotersRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryRegisteredVotersRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
return len(dAtA) - i, nil
}
func (m *QueryRegisteredVotersResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryRegisteredVotersResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryRegisteredVotersResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Voters) > 0 {
for iNdEx := len(m.Voters) - 1; iNdEx >= 0; iNdEx-- {
i -= len(m.Voters[iNdEx])
copy(dAtA[i:], m.Voters[iNdEx])
i = encodeVarintQuery(dAtA, i, uint64(len(m.Voters[iNdEx])))
i--
dAtA[i] = 0xa
}
}
return len(dAtA) - i, nil
}
func encodeVarintQuery(dAtA []byte, offset int, v uint64) int {
offset -= sovQuery(v)
base := offset
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return base
}
func (m *QueryCurrentCouncilIDRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
return n
}
func (m *QueryCurrentCouncilIDResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.CurrentCouncilID != 0 {
n += 1 + sovQuery(uint64(m.CurrentCouncilID))
}
return n
}
func (m *QueryRegisteredVotersRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
return n
}
func (m *QueryRegisteredVotersResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if len(m.Voters) > 0 {
for _, s := range m.Voters {
l = len(s)
n += 1 + l + sovQuery(uint64(l))
}
}
return n
}
func sovQuery(x uint64) (n int) {
return (math_bits.Len64(x|1) + 6) / 7
}
func sozQuery(x uint64) (n int) {
return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *QueryCurrentCouncilIDRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryCurrentCouncilIDRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryCurrentCouncilIDRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryCurrentCouncilIDResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryCurrentCouncilIDResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryCurrentCouncilIDResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field CurrentCouncilID", wireType)
}
m.CurrentCouncilID = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.CurrentCouncilID |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryRegisteredVotersRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryRegisteredVotersRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryRegisteredVotersRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryRegisteredVotersResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryRegisteredVotersResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryRegisteredVotersResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Voters", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthQuery
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthQuery
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Voters = append(m.Voters, string(dAtA[iNdEx:postIndex]))
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipQuery(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
depth := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowQuery
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowQuery
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
case 1:
iNdEx += 8
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowQuery
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if length < 0 {
return 0, ErrInvalidLengthQuery
}
iNdEx += length
case 3:
depth++
case 4:
if depth == 0 {
return 0, ErrUnexpectedEndOfGroupQuery
}
depth--
case 5:
iNdEx += 4
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
if iNdEx < 0 {
return 0, ErrInvalidLengthQuery
}
if depth == 0 {
return iNdEx, nil
}
}
return 0, io.ErrUnexpectedEOF
}
var (
ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow")
ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group")
)

View File

@ -0,0 +1,218 @@
// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
// source: zgc/council/v1/query.proto
/*
Package types is a reverse proxy.
It translates gRPC into RESTful JSON APIs.
*/
package types
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/metadata"
"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 _ = metadata.Join
func request_Query_CurrentCouncilID_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq QueryCurrentCouncilIDRequest
var metadata runtime.ServerMetadata
msg, err := client.CurrentCouncilID(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_Query_CurrentCouncilID_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq QueryCurrentCouncilIDRequest
var metadata runtime.ServerMetadata
msg, err := server.CurrentCouncilID(ctx, &protoReq)
return msg, metadata, err
}
func request_Query_RegisteredVoters_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq QueryRegisteredVotersRequest
var metadata runtime.ServerMetadata
msg, err := client.RegisteredVoters(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_Query_RegisteredVoters_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq QueryRegisteredVotersRequest
var metadata runtime.ServerMetadata
msg, err := server.RegisteredVoters(ctx, &protoReq)
return msg, metadata, err
}
// RegisterQueryHandlerServer registers the http handlers for service Query to "mux".
// UnaryRPC :call QueryServer directly.
// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906.
// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead.
func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error {
mux.Handle("GET", pattern_Query_CurrentCouncilID_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
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_Query_CurrentCouncilID_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Query_CurrentCouncilID_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_Query_RegisteredVoters_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
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_Query_RegisteredVoters_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Query_RegisteredVoters_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but
// automatically dials to "endpoint" and closes the connection when "ctx" gets done.
func RegisterQueryHandlerFromEndpoint(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 RegisterQueryHandler(ctx, mux, conn)
}
// RegisterQueryHandler registers the http handlers for service Query to "mux".
// The handlers forward requests to the grpc endpoint over "conn".
func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn))
}
// RegisterQueryHandlerClient registers the http handlers for service Query
// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient".
// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient"
// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in
// "QueryClient" to call the correct interceptors.
func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error {
mux.Handle("GET", pattern_Query_CurrentCouncilID_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_Query_CurrentCouncilID_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Query_CurrentCouncilID_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("GET", pattern_Query_RegisteredVoters_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_Query_RegisteredVoters_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Query_RegisteredVoters_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
var (
pattern_Query_CurrentCouncilID_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"0gchain", "council", "v1", "current-council-id"}, "", runtime.AssumeColonVerbOpt(false)))
pattern_Query_RegisteredVoters_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"0gchain", "council", "v1", "registered-voters"}, "", runtime.AssumeColonVerbOpt(false)))
)
var (
forward_Query_CurrentCouncilID_0 = runtime.ForwardResponseMessage
forward_Query_RegisteredVoters_0 = runtime.ForwardResponseMessage
)

975
x/council/v1/types/tx.pb.go Normal file
View File

@ -0,0 +1,975 @@
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: zgc/council/v1/tx.proto
package types
import (
context "context"
fmt "fmt"
_ "github.com/cosmos/cosmos-proto"
_ "github.com/cosmos/cosmos-sdk/codec/types"
_ "github.com/gogo/protobuf/gogoproto"
grpc1 "github.com/gogo/protobuf/grpc"
proto "github.com/gogo/protobuf/proto"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
io "io"
math "math"
math_bits "math/bits"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
type MsgRegister struct {
Voter string `protobuf:"bytes,1,opt,name=voter,proto3" json:"voter,omitempty"`
Key []byte `protobuf:"bytes,2,opt,name=key,proto3" json:"key,omitempty"`
}
func (m *MsgRegister) Reset() { *m = MsgRegister{} }
func (m *MsgRegister) String() string { return proto.CompactTextString(m) }
func (*MsgRegister) ProtoMessage() {}
func (*MsgRegister) Descriptor() ([]byte, []int) {
return fileDescriptor_3783c1e1bc40f3a1, []int{0}
}
func (m *MsgRegister) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *MsgRegister) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_MsgRegister.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *MsgRegister) XXX_Merge(src proto.Message) {
xxx_messageInfo_MsgRegister.Merge(m, src)
}
func (m *MsgRegister) XXX_Size() int {
return m.Size()
}
func (m *MsgRegister) XXX_DiscardUnknown() {
xxx_messageInfo_MsgRegister.DiscardUnknown(m)
}
var xxx_messageInfo_MsgRegister proto.InternalMessageInfo
type MsgRegisterResponse struct {
}
func (m *MsgRegisterResponse) Reset() { *m = MsgRegisterResponse{} }
func (m *MsgRegisterResponse) String() string { return proto.CompactTextString(m) }
func (*MsgRegisterResponse) ProtoMessage() {}
func (*MsgRegisterResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_3783c1e1bc40f3a1, []int{1}
}
func (m *MsgRegisterResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *MsgRegisterResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_MsgRegisterResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *MsgRegisterResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_MsgRegisterResponse.Merge(m, src)
}
func (m *MsgRegisterResponse) XXX_Size() int {
return m.Size()
}
func (m *MsgRegisterResponse) XXX_DiscardUnknown() {
xxx_messageInfo_MsgRegisterResponse.DiscardUnknown(m)
}
var xxx_messageInfo_MsgRegisterResponse proto.InternalMessageInfo
type MsgVote struct {
CouncilID uint64 `protobuf:"varint,1,opt,name=council_id,json=councilId,proto3" json:"council_id,omitempty"`
Voter string `protobuf:"bytes,2,opt,name=voter,proto3" json:"voter,omitempty"`
Ballots []*Ballot `protobuf:"bytes,3,rep,name=ballots,proto3" json:"ballots,omitempty"`
}
func (m *MsgVote) Reset() { *m = MsgVote{} }
func (m *MsgVote) String() string { return proto.CompactTextString(m) }
func (*MsgVote) ProtoMessage() {}
func (*MsgVote) Descriptor() ([]byte, []int) {
return fileDescriptor_3783c1e1bc40f3a1, []int{2}
}
func (m *MsgVote) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *MsgVote) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_MsgVote.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *MsgVote) XXX_Merge(src proto.Message) {
xxx_messageInfo_MsgVote.Merge(m, src)
}
func (m *MsgVote) XXX_Size() int {
return m.Size()
}
func (m *MsgVote) XXX_DiscardUnknown() {
xxx_messageInfo_MsgVote.DiscardUnknown(m)
}
var xxx_messageInfo_MsgVote proto.InternalMessageInfo
type MsgVoteResponse struct {
}
func (m *MsgVoteResponse) Reset() { *m = MsgVoteResponse{} }
func (m *MsgVoteResponse) String() string { return proto.CompactTextString(m) }
func (*MsgVoteResponse) ProtoMessage() {}
func (*MsgVoteResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_3783c1e1bc40f3a1, []int{3}
}
func (m *MsgVoteResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *MsgVoteResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_MsgVoteResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *MsgVoteResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_MsgVoteResponse.Merge(m, src)
}
func (m *MsgVoteResponse) XXX_Size() int {
return m.Size()
}
func (m *MsgVoteResponse) XXX_DiscardUnknown() {
xxx_messageInfo_MsgVoteResponse.DiscardUnknown(m)
}
var xxx_messageInfo_MsgVoteResponse proto.InternalMessageInfo
func init() {
proto.RegisterType((*MsgRegister)(nil), "zgc.council.v1.MsgRegister")
proto.RegisterType((*MsgRegisterResponse)(nil), "zgc.council.v1.MsgRegisterResponse")
proto.RegisterType((*MsgVote)(nil), "zgc.council.v1.MsgVote")
proto.RegisterType((*MsgVoteResponse)(nil), "zgc.council.v1.MsgVoteResponse")
}
func init() { proto.RegisterFile("zgc/council/v1/tx.proto", fileDescriptor_3783c1e1bc40f3a1) }
var fileDescriptor_3783c1e1bc40f3a1 = []byte{
// 375 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x92, 0xbf, 0x52, 0xea, 0x40,
0x14, 0xc6, 0x13, 0xc2, 0xbd, 0x5c, 0x96, 0xeb, 0xbf, 0x88, 0x02, 0xd1, 0x09, 0x4c, 0x6c, 0x28,
0x24, 0x0b, 0x38, 0xf6, 0x0e, 0xda, 0x30, 0x4a, 0x93, 0xc2, 0xc2, 0x86, 0x49, 0xc2, 0xba, 0x64,
0x0c, 0x39, 0x0c, 0x1b, 0x18, 0xa0, 0xf1, 0x15, 0x6c, 0x7c, 0x27, 0x4a, 0x4a, 0x2b, 0x47, 0xc3,
0x8b, 0x38, 0x24, 0x1b, 0x05, 0x46, 0xed, 0xce, 0x39, 0xbf, 0x2f, 0xdf, 0x77, 0x4e, 0x12, 0x94,
0x9b, 0x52, 0x1b, 0xdb, 0x30, 0xf4, 0x6c, 0xc7, 0xc5, 0xa3, 0x1a, 0xf6, 0xc7, 0x7a, 0x7f, 0x00,
0x3e, 0xc8, 0xdb, 0x53, 0x6a, 0xeb, 0x1c, 0xe8, 0xa3, 0x9a, 0x52, 0xb0, 0x81, 0xf5, 0x80, 0xb5,
0x43, 0x8a, 0xa3, 0x26, 0x92, 0x2a, 0x59, 0x0a, 0x14, 0xa2, 0xf9, 0xb2, 0xe2, 0xd3, 0x02, 0x05,
0xa0, 0x2e, 0xc1, 0x61, 0x67, 0x0d, 0xef, 0xb1, 0xe9, 0x4d, 0x38, 0x3a, 0xde, 0x08, 0xa5, 0xc4,
0x23, 0xcc, 0xe1, 0x76, 0xda, 0x39, 0xca, 0xb4, 0x18, 0x35, 0x08, 0x75, 0x98, 0x4f, 0x06, 0x72,
0x16, 0xfd, 0x19, 0x81, 0x4f, 0x06, 0x79, 0xb1, 0x24, 0x96, 0xd3, 0x46, 0xd4, 0xc8, 0xbb, 0x48,
0x7a, 0x20, 0x93, 0x7c, 0xa2, 0x24, 0x96, 0xff, 0x1b, 0xcb, 0x52, 0x3b, 0x40, 0xfb, 0x2b, 0x8f,
0x19, 0x84, 0xf5, 0xc1, 0x63, 0x44, 0x7b, 0x44, 0xa9, 0x16, 0xa3, 0xb7, 0xe0, 0x13, 0xf9, 0x14,
0x21, 0x1e, 0xda, 0x76, 0x3a, 0xa1, 0x5d, 0xb2, 0xb1, 0x15, 0xbc, 0x16, 0xd3, 0x97, 0xd1, 0xb4,
0x79, 0x65, 0xa4, 0xb9, 0xa0, 0xd9, 0xf9, 0xca, 0x4d, 0xac, 0xe6, 0x56, 0x51, 0xca, 0x32, 0x5d,
0x17, 0x7c, 0x96, 0x97, 0x4a, 0x52, 0x39, 0x53, 0x3f, 0xd4, 0xd7, 0x5f, 0x94, 0xde, 0x08, 0xb1,
0x11, 0xcb, 0xb4, 0x3d, 0xb4, 0xc3, 0x17, 0x88, 0x77, 0xaa, 0x3f, 0x8b, 0x48, 0x6a, 0x31, 0x2a,
0xdf, 0xa0, 0x7f, 0x9f, 0x67, 0x1e, 0x6d, 0xfa, 0xac, 0x1c, 0xa3, 0x9c, 0xfc, 0x02, 0x63, 0x57,
0xf9, 0x02, 0x25, 0xc3, 0x33, 0x73, 0xdf, 0x88, 0x97, 0x40, 0x29, 0xfe, 0x00, 0x62, 0x87, 0xc6,
0xf5, 0xec, 0x5d, 0x15, 0x66, 0x81, 0x2a, 0xce, 0x03, 0x55, 0x7c, 0x0b, 0x54, 0xf1, 0x69, 0xa1,
0x0a, 0xf3, 0x85, 0x2a, 0xbc, 0x2c, 0x54, 0xe1, 0xae, 0x42, 0x1d, 0xbf, 0x3b, 0xb4, 0x74, 0x1b,
0x7a, 0xb8, 0x4a, 0x5d, 0xd3, 0x62, 0xb8, 0x4a, 0x2b, 0x76, 0xd7, 0x74, 0x3c, 0x3c, 0x5e, 0xfb,
0x87, 0x26, 0x7d, 0xc2, 0xac, 0xbf, 0xe1, 0xd7, 0x3c, 0xfb, 0x08, 0x00, 0x00, 0xff, 0xff, 0x2a,
0xc2, 0x71, 0x36, 0x62, 0x02, 0x00, 0x00,
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion4
// MsgClient is the client API for Msg service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type MsgClient interface {
Register(ctx context.Context, in *MsgRegister, opts ...grpc.CallOption) (*MsgRegisterResponse, error)
Vote(ctx context.Context, in *MsgVote, opts ...grpc.CallOption) (*MsgVoteResponse, error)
}
type msgClient struct {
cc grpc1.ClientConn
}
func NewMsgClient(cc grpc1.ClientConn) MsgClient {
return &msgClient{cc}
}
func (c *msgClient) Register(ctx context.Context, in *MsgRegister, opts ...grpc.CallOption) (*MsgRegisterResponse, error) {
out := new(MsgRegisterResponse)
err := c.cc.Invoke(ctx, "/zgc.council.v1.Msg/Register", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *msgClient) Vote(ctx context.Context, in *MsgVote, opts ...grpc.CallOption) (*MsgVoteResponse, error) {
out := new(MsgVoteResponse)
err := c.cc.Invoke(ctx, "/zgc.council.v1.Msg/Vote", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// MsgServer is the server API for Msg service.
type MsgServer interface {
Register(context.Context, *MsgRegister) (*MsgRegisterResponse, error)
Vote(context.Context, *MsgVote) (*MsgVoteResponse, error)
}
// UnimplementedMsgServer can be embedded to have forward compatible implementations.
type UnimplementedMsgServer struct {
}
func (*UnimplementedMsgServer) Register(ctx context.Context, req *MsgRegister) (*MsgRegisterResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Register not implemented")
}
func (*UnimplementedMsgServer) Vote(ctx context.Context, req *MsgVote) (*MsgVoteResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Vote not implemented")
}
func RegisterMsgServer(s grpc1.Server, srv MsgServer) {
s.RegisterService(&_Msg_serviceDesc, srv)
}
func _Msg_Register_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(MsgRegister)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(MsgServer).Register(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/zgc.council.v1.Msg/Register",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(MsgServer).Register(ctx, req.(*MsgRegister))
}
return interceptor(ctx, in, info, handler)
}
func _Msg_Vote_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(MsgVote)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(MsgServer).Vote(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/zgc.council.v1.Msg/Vote",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(MsgServer).Vote(ctx, req.(*MsgVote))
}
return interceptor(ctx, in, info, handler)
}
var _Msg_serviceDesc = grpc.ServiceDesc{
ServiceName: "zgc.council.v1.Msg",
HandlerType: (*MsgServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Register",
Handler: _Msg_Register_Handler,
},
{
MethodName: "Vote",
Handler: _Msg_Vote_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "zgc/council/v1/tx.proto",
}
func (m *MsgRegister) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *MsgRegister) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *MsgRegister) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Key) > 0 {
i -= len(m.Key)
copy(dAtA[i:], m.Key)
i = encodeVarintTx(dAtA, i, uint64(len(m.Key)))
i--
dAtA[i] = 0x12
}
if len(m.Voter) > 0 {
i -= len(m.Voter)
copy(dAtA[i:], m.Voter)
i = encodeVarintTx(dAtA, i, uint64(len(m.Voter)))
i--
dAtA[i] = 0xa
}
return len(dAtA) - i, nil
}
func (m *MsgRegisterResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *MsgRegisterResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *MsgRegisterResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
return len(dAtA) - i, nil
}
func (m *MsgVote) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *MsgVote) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *MsgVote) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if len(m.Ballots) > 0 {
for iNdEx := len(m.Ballots) - 1; iNdEx >= 0; iNdEx-- {
{
size, err := m.Ballots[iNdEx].MarshalToSizedBuffer(dAtA[:i])
if err != nil {
return 0, err
}
i -= size
i = encodeVarintTx(dAtA, i, uint64(size))
}
i--
dAtA[i] = 0x1a
}
}
if len(m.Voter) > 0 {
i -= len(m.Voter)
copy(dAtA[i:], m.Voter)
i = encodeVarintTx(dAtA, i, uint64(len(m.Voter)))
i--
dAtA[i] = 0x12
}
if m.CouncilID != 0 {
i = encodeVarintTx(dAtA, i, uint64(m.CouncilID))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func (m *MsgVoteResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *MsgVoteResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *MsgVoteResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
return len(dAtA) - i, nil
}
func encodeVarintTx(dAtA []byte, offset int, v uint64) int {
offset -= sovTx(v)
base := offset
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return base
}
func (m *MsgRegister) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Voter)
if l > 0 {
n += 1 + l + sovTx(uint64(l))
}
l = len(m.Key)
if l > 0 {
n += 1 + l + sovTx(uint64(l))
}
return n
}
func (m *MsgRegisterResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
return n
}
func (m *MsgVote) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.CouncilID != 0 {
n += 1 + sovTx(uint64(m.CouncilID))
}
l = len(m.Voter)
if l > 0 {
n += 1 + l + sovTx(uint64(l))
}
if len(m.Ballots) > 0 {
for _, e := range m.Ballots {
l = e.Size()
n += 1 + l + sovTx(uint64(l))
}
}
return n
}
func (m *MsgVoteResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
return n
}
func sovTx(x uint64) (n int) {
return (math_bits.Len64(x|1) + 6) / 7
}
func sozTx(x uint64) (n int) {
return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *MsgRegister) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTx
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: MsgRegister: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: MsgRegister: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Voter", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTx
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthTx
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthTx
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Voter = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTx
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthTx
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthTx
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Key = append(m.Key[:0], dAtA[iNdEx:postIndex]...)
if m.Key == nil {
m.Key = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTx(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTx
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *MsgRegisterResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTx
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: MsgRegisterResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: MsgRegisterResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipTx(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTx
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *MsgVote) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTx
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: MsgVote: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: MsgVote: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field CouncilID", wireType)
}
m.CouncilID = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTx
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.CouncilID |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Voter", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTx
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthTx
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthTx
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Voter = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Ballots", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTx
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthTx
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthTx
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Ballots = append(m.Ballots, &Ballot{})
if err := m.Ballots[len(m.Ballots)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipTx(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTx
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *MsgVoteResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowTx
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: MsgVoteResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: MsgVoteResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipTx(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthTx
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipTx(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
depth := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowTx
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowTx
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
case 1:
iNdEx += 8
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowTx
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if length < 0 {
return 0, ErrInvalidLengthTx
}
iNdEx += length
case 3:
depth++
case 4:
if depth == 0 {
return 0, ErrUnexpectedEndOfGroupTx
}
depth--
case 5:
iNdEx += 4
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
if iNdEx < 0 {
return 0, ErrInvalidLengthTx
}
if depth == 0 {
return iNdEx, nil
}
}
return 0, io.ErrUnexpectedEOF
}
var (
ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowTx = fmt.Errorf("proto: integer overflow")
ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group")
)

View File

@ -0,0 +1,57 @@
package cli
import (
"context"
"fmt"
"github.com/spf13/cobra"
"github.com/0glabs/0g-chain/x/das/v1/types"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
)
// GetQueryCmd returns the cli query commands for the inflation module.
func GetQueryCmd() *cobra.Command {
cmd := &cobra.Command{
Use: types.ModuleName,
Short: "Querying commands for the das module",
DisableFlagParsing: true,
SuggestionsMinimumDistance: 2,
RunE: client.ValidateCmd,
}
cmd.AddCommand(
GetNextRequestID(),
)
return cmd
}
func GetNextRequestID() *cobra.Command {
cmd := &cobra.Command{
Use: "next-request-id",
Short: "Query the next request ID",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
queryClient := types.NewQueryClient(clientCtx)
params := &types.QueryNextRequestIDRequest{}
res, err := queryClient.NextRequestID(context.Background(), params)
if err != nil {
return err
}
return clientCtx.PrintString(fmt.Sprintf("%v\n", res.NextRequestID))
},
}
flags.AddQueryFlagsToCmd(cmd)
return cmd
}

103
x/das/v1/client/cli/tx.go Normal file
View File

@ -0,0 +1,103 @@
package cli
import (
"encoding/hex"
"fmt"
"strconv"
"github.com/0glabs/0g-chain/x/das/v1/types"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/tx"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/spf13/cobra"
)
// GetTxCmd returns the transaction commands for this module
func GetTxCmd() *cobra.Command {
cmd := &cobra.Command{
Use: types.ModuleName,
Short: fmt.Sprintf("%s transactions subcommands", types.ModuleName),
DisableFlagParsing: true,
SuggestionsMinimumDistance: 2,
RunE: client.ValidateCmd,
}
cmd.AddCommand(
NewRequestDASCmd(),
NewReportDASResultCmd(),
)
return cmd
}
func NewRequestDASCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "request-das steram-id batch-header-hash num-blobs",
Short: "Request data-availability-sampling",
Args: cobra.ExactArgs(3),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
numBlobs, err := strconv.Atoi(args[2])
if err != nil {
return err
}
msg := types.NewMsgRequestDAS(clientCtx.GetFromAddress(), args[0], args[1], uint32(numBlobs))
return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg)
},
}
flags.AddTxFlagsToCmd(cmd)
return cmd
}
func NewReportDASResultCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "report-das-result request-id results",
Short: "Report data-availability-sampling result",
Args: cobra.MinimumNArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, err := client.GetClientTxContext(cmd)
if err != nil {
return err
}
requestID, err := strconv.ParseUint(args[0], 10, 64)
if err != nil {
return err
}
n := len(args) - 1
results := make([]bool, n)
for i := 0; i < n; i++ {
var err error
results[i], err = strconv.ParseBool(args[i+1])
if err != nil {
return err
}
}
// get account name by address
accAddr := clientCtx.GetFromAddress()
samplerAddr, err := sdk.ValAddressFromHex(hex.EncodeToString(accAddr.Bytes()))
if err != nil {
return err
}
msg := &types.MsgReportDASResult{
RequestID: requestID,
Sampler: samplerAddr.String(),
Results: results,
}
return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg)
},
}
flags.AddTxFlagsToCmd(cmd)
return cmd
}

39
x/das/v1/genesis.go Normal file
View File

@ -0,0 +1,39 @@
package das
import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/0glabs/0g-chain/x/das/v1/keeper"
"github.com/0glabs/0g-chain/x/das/v1/types"
)
// InitGenesis initializes the store state from a genesis state.
func InitGenesis(ctx sdk.Context, keeper keeper.Keeper, gs types.GenesisState) {
if err := gs.Validate(); err != nil {
panic(fmt.Sprintf("failed to validate %s genesis state: %s", types.ModuleName, err))
}
keeper.SetNextRequestID(ctx, gs.NextRequestID)
for _, req := range gs.Requests {
keeper.SetDASRequest(ctx, req)
}
for _, resp := range gs.Responses {
keeper.SetDASResponse(ctx, resp)
}
}
// ExportGenesis returns a GenesisState for a given context and keeper.
func ExportGenesis(ctx sdk.Context, keeper keeper.Keeper) *types.GenesisState {
nextRequestID, err := keeper.GetNextRequestID(ctx)
if err != nil {
panic(err)
}
return types.NewGenesisState(
nextRequestID,
keeper.GetDASRequests(ctx),
keeper.GetDASResponses(ctx),
)
}

View File

@ -0,0 +1,22 @@
package keeper
import (
"context"
"github.com/0glabs/0g-chain/x/das/v1/types"
sdk "github.com/cosmos/cosmos-sdk/types"
)
var _ types.QueryServer = Keeper{}
func (k Keeper) NextRequestID(
c context.Context,
_ *types.QueryNextRequestIDRequest,
) (*types.QueryNextRequestIDResponse, error) {
ctx := sdk.UnwrapSDKContext(c)
nextRequestID, err := k.GetNextRequestID(ctx)
if err != nil {
return nil, err
}
return &types.QueryNextRequestIDResponse{NextRequestID: nextRequestID}, nil
}

198
x/das/v1/keeper/keeper.go Normal file
View File

@ -0,0 +1,198 @@
package keeper
import (
"encoding/hex"
"strconv"
errorsmod "cosmossdk.io/errors"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/store/prefix"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/tendermint/tendermint/libs/log"
"github.com/0glabs/0g-chain/x/das/v1/types"
)
type Keeper struct {
storeKey storetypes.StoreKey
cdc codec.BinaryCodec
stakingKeeperRef types.StakingKeeperRef
}
// NewKeeper creates a new das Keeper instance
func NewKeeper(
storeKey storetypes.StoreKey,
cdc codec.BinaryCodec,
stakingKeeper types.StakingKeeperRef,
) Keeper {
return Keeper{
storeKey: storeKey,
cdc: cdc,
stakingKeeperRef: stakingKeeper,
}
}
// Logger returns a module-specific logger.
func (k Keeper) Logger(ctx sdk.Context) log.Logger {
return ctx.Logger().With("module", "x/"+types.ModuleName)
}
func (k Keeper) SetNextRequestID(ctx sdk.Context, id uint64) {
store := ctx.KVStore(k.storeKey)
store.Set(types.NextRequestIDKey, types.GetKeyFromID(id))
}
func (k Keeper) GetNextRequestID(ctx sdk.Context) (uint64, error) {
store := ctx.KVStore(k.storeKey)
bz := store.Get(types.NextRequestIDKey)
if bz == nil {
return 0, errorsmod.Wrap(types.ErrInvalidGenesis, "next request ID not set at genesis")
}
return types.Uint64FromBytes(bz), nil
}
func (k Keeper) IncrementNextRequestID(ctx sdk.Context) error {
id, err := k.GetNextRequestID(ctx)
if err != nil {
return err
}
k.SetNextRequestID(ctx, id+1)
return nil
}
func (k Keeper) GetDASRequest(ctx sdk.Context, requestID uint64) (types.DASRequest, bool) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.RequestKeyPrefix)
bz := store.Get(types.GetKeyFromID(requestID))
if bz == nil {
return types.DASRequest{}, false
}
var req types.DASRequest
k.cdc.MustUnmarshal(bz, &req)
return req, true
}
func (k Keeper) SetDASRequest(ctx sdk.Context, req types.DASRequest) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.RequestKeyPrefix)
bz := k.cdc.MustMarshal(&req)
store.Set(types.GetKeyFromID(req.ID), bz)
}
func (k Keeper) IterateDASRequest(ctx sdk.Context, cb func(req types.DASRequest) (stop bool)) {
iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.RequestKeyPrefix)
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
var req types.DASRequest
k.cdc.MustUnmarshal(iterator.Value(), &req)
if cb(req) {
break
}
}
}
func (k Keeper) GetDASRequests(ctx sdk.Context) []types.DASRequest {
results := []types.DASRequest{}
k.IterateDASRequest(ctx, func(req types.DASRequest) bool {
results = append(results, req)
return false
})
return results
}
func (k Keeper) StoreNewDASRequest(
ctx sdk.Context,
streamIDHexStr string,
batchHeaderHashHexStr string,
numBlobs uint32) (uint64, error) {
requestID, err := k.GetNextRequestID(ctx)
if err != nil {
return 0, err
}
streamID, err := hex.DecodeString(streamIDHexStr)
if err != nil {
return 0, err
}
batchHeaderHash, err := hex.DecodeString(batchHeaderHashHexStr)
if err != nil {
return 0, err
}
req := types.DASRequest{
ID: requestID,
StreamID: streamID,
BatchHeaderHash: batchHeaderHash,
NumBlobs: numBlobs,
}
k.SetDASRequest(ctx, req)
ctx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypeDASRequest,
sdk.NewAttribute(types.AttributeKeyRequestID, strconv.FormatUint(requestID, 10)),
sdk.NewAttribute(types.AttributeKeyStreamID, streamIDHexStr),
sdk.NewAttribute(types.AttributeKeyBatchHeaderHash, batchHeaderHashHexStr),
sdk.NewAttribute(types.AttributeKeyNumBlobs, strconv.FormatUint(uint64(numBlobs), 10)),
),
)
return requestID, nil
}
func (k Keeper) GetDASResponse(
ctx sdk.Context, requestID uint64, sampler sdk.ValAddress,
) (types.DASResponse, bool) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.ResponseKeyPrefix)
bz := store.Get(types.GetResponseKey(requestID, sampler))
if bz == nil {
return types.DASResponse{}, false
}
var vote types.DASResponse
k.cdc.MustUnmarshal(bz, &vote)
return vote, true
}
func (k Keeper) SetDASResponse(ctx sdk.Context, resp types.DASResponse) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.ResponseKeyPrefix)
bz := k.cdc.MustMarshal(&resp)
store.Set(types.GetResponseKey(resp.ID, resp.Sampler), bz)
}
func (k Keeper) IterateDASResponse(ctx sdk.Context, cb func(resp types.DASResponse) (stop bool)) {
iterator := sdk.KVStorePrefixIterator(ctx.KVStore(k.storeKey), types.ResponseKeyPrefix)
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
var resp types.DASResponse
k.cdc.MustUnmarshal(iterator.Value(), &resp)
if cb(resp) {
break
}
}
}
func (k Keeper) GetDASResponses(ctx sdk.Context) []types.DASResponse {
results := []types.DASResponse{}
k.IterateDASResponse(ctx, func(resp types.DASResponse) bool {
results = append(results, resp)
return false
})
return results
}
func (k Keeper) StoreNewDASResponse(
ctx sdk.Context, requestID uint64, sampler sdk.ValAddress, results []bool) error {
if _, found := k.GetDASRequest(ctx, requestID); !found {
return errorsmod.Wrapf(types.ErrUnknownRequest, "%d", requestID)
}
k.SetDASResponse(ctx, types.DASResponse{
ID: requestID,
Sampler: sampler,
Results: results,
})
return nil
}

View File

@ -0,0 +1,49 @@
package keeper
import (
"context"
"github.com/0glabs/0g-chain/x/das/v1/types"
sdk "github.com/cosmos/cosmos-sdk/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)
var _ types.MsgServer = &Keeper{}
// RequestDAS handles MsgRequestDAS messages
func (k Keeper) RequestDAS(
goCtx context.Context, msg *types.MsgRequestDAS,
) (*types.MsgRequestDASResponse, error) {
ctx := sdk.UnwrapSDKContext(goCtx)
requestID, err := k.StoreNewDASRequest(ctx, msg.StreamID, msg.BatchHeaderHash, msg.NumBlobs)
if err != nil {
return nil, err
}
k.IncrementNextRequestID(ctx)
return &types.MsgRequestDASResponse{
RequestID: requestID,
}, nil
}
// ReportDASResult handles MsgReportDASResult messages
func (k Keeper) ReportDASResult(
goCtx context.Context, msg *types.MsgReportDASResult,
) (*types.MsgReportDASResultResponse, error) {
ctx := sdk.UnwrapSDKContext(goCtx)
sampler, err := sdk.ValAddressFromBech32(msg.Sampler)
if err != nil {
return nil, err
}
if _, found := k.stakingKeeperRef.GetValidator(ctx, sampler); !found {
return nil, stakingtypes.ErrNoValidatorFound
}
if err := k.StoreNewDASResponse(ctx, msg.RequestID, sampler, msg.Results); err != nil {
return nil, err
}
return &types.MsgReportDASResultResponse{}, nil
}

180
x/das/v1/module.go Normal file
View File

@ -0,0 +1,180 @@
package das
import (
"context"
"encoding/json"
"fmt"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
"github.com/gorilla/mux"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/spf13/cobra"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/0glabs/0g-chain/x/das/v1/client/cli"
"github.com/0glabs/0g-chain/x/das/v1/keeper"
"github.com/0glabs/0g-chain/x/das/v1/types"
)
// consensusVersion defines the current x/council module consensus version.
const consensusVersion = 1
// type check to ensure the interface is properly implemented
var (
_ module.AppModule = AppModule{}
_ module.AppModuleBasic = AppModuleBasic{}
// _ module.AppModuleSimulation = AppModule{}
_ module.BeginBlockAppModule = AppModule{}
_ module.EndBlockAppModule = AppModule{}
)
// app module Basics object
type AppModuleBasic struct{}
// Name returns the inflation module's name.
func (AppModuleBasic) Name() string {
return types.ModuleName
}
// RegisterLegacyAminoCodec registers the inflation module's types on the given LegacyAmino codec.
func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {}
// ConsensusVersion returns the consensus state-breaking version for the module.
func (AppModuleBasic) ConsensusVersion() uint64 {
return consensusVersion
}
// RegisterInterfaces registers interfaces and implementations of the incentives
// module.
func (AppModuleBasic) RegisterInterfaces(interfaceRegistry codectypes.InterfaceRegistry) {
types.RegisterInterfaces(interfaceRegistry)
}
// DefaultGenesis returns default genesis state as raw bytes for the incentives
// module.
func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage {
return cdc.MustMarshalJSON(types.DefaultGenesisState())
}
// ValidateGenesis performs genesis state validation for the inflation module.
func (b AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, _ client.TxEncodingConfig, bz json.RawMessage) error {
var genesisState types.GenesisState
if err := cdc.UnmarshalJSON(bz, &genesisState); err != nil {
return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err)
}
return genesisState.Validate()
}
// RegisterRESTRoutes performs a no-op as the inflation module doesn't expose REST
// endpoints
func (AppModuleBasic) RegisterRESTRoutes(_ client.Context, _ *mux.Router) {}
// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the inflation module.
func (b AppModuleBasic) RegisterGRPCGatewayRoutes(c client.Context, serveMux *runtime.ServeMux) {
if err := types.RegisterQueryHandlerClient(context.Background(), serveMux, types.NewQueryClient(c)); err != nil {
panic(err)
}
}
// GetTxCmd returns the root tx command for the inflation module.
func (AppModuleBasic) GetTxCmd() *cobra.Command {
return cli.GetTxCmd()
}
// GetQueryCmd returns no root query command for the inflation module.
func (AppModuleBasic) GetQueryCmd() *cobra.Command {
return cli.GetQueryCmd()
}
// ___________________________________________________________________________
// AppModule implements an application module for the inflation module.
type AppModule struct {
AppModuleBasic
keeper keeper.Keeper
}
// NewAppModule creates a new AppModule Object
func NewAppModule(
k keeper.Keeper,
) AppModule {
return AppModule{
AppModuleBasic: AppModuleBasic{},
keeper: k,
}
}
// Name returns the inflation module's name.
func (AppModule) Name() string {
return types.ModuleName
}
// Route returns evmutil module's message route.
func (am AppModule) Route() sdk.Route { return sdk.Route{} }
// QuerierRoute returns evmutil module's query routing key.
func (AppModule) QuerierRoute() string { return "" }
// LegacyQuerierHandler returns evmutil module's Querier.
func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier {
return nil
}
// RegisterInvariants registers the inflation module invariants.
func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {}
// RegisterServices registers a gRPC query service to respond to the
// module-specific gRPC queries.
func (am AppModule) RegisterServices(cfg module.Configurator) {
types.RegisterMsgServer(cfg.MsgServer(), am.keeper)
types.RegisterQueryServer(cfg.QueryServer(), am.keeper)
}
func (am AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) {
// am.keeper.BeginBlock(ctx, req)
}
func (am AppModule) EndBlock(ctx sdk.Context, req abci.RequestEndBlock) []abci.ValidatorUpdate {
// am.keeper.EndBlock(ctx, req)
return []abci.ValidatorUpdate{}
}
// InitGenesis performs genesis initialization for the inflation module. It returns
// no validator updates.
func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate {
var genesisState types.GenesisState
cdc.MustUnmarshalJSON(data, &genesisState)
InitGenesis(ctx, am.keeper, genesisState)
return []abci.ValidatorUpdate{}
}
// ExportGenesis returns the exported genesis state as raw bytes for the inflation
// module.
func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage {
gs := ExportGenesis(ctx, am.keeper)
return cdc.MustMarshalJSON(gs)
}
// ___________________________________________________________________________
// AppModuleSimulation functions
// GenerateGenesisState creates a randomized GenState of the inflation module.
func (am AppModule) GenerateGenesisState(_ *module.SimulationState) {
}
// RegisterStoreDecoder registers a decoder for inflation module's types.
func (am AppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {
}
// WeightedOperations doesn't return any inflation module operation.
func (am AppModule) WeightedOperations(_ module.SimulationState) []simtypes.WeightedOperation {
return []simtypes.WeightedOperation{}
}

47
x/das/v1/types/codec.go Normal file
View File

@ -0,0 +1,47 @@
package types
import (
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/msgservice"
)
var (
amino = codec.NewLegacyAmino()
// ModuleCdc references the global evm module codec. Note, the codec should
// ONLY be used in certain instances of tests and for JSON encoding.
ModuleCdc = codec.NewProtoCodec(codectypes.NewInterfaceRegistry())
// AminoCdc is a amino codec created to support amino JSON compatible msgs.
AminoCdc = codec.NewAminoCodec(amino)
)
const (
// Amino names
requestDASName = "evmos/das/MsgRequestDAS"
reportDASResultName = "evmos/das/MsgReportDASResult"
)
// NOTE: This is required for the GetSignBytes function
func init() {
RegisterLegacyAminoCodec(amino)
amino.Seal()
}
// RegisterInterfaces register implementations
func RegisterInterfaces(registry codectypes.InterfaceRegistry) {
registry.RegisterImplementations(
(*sdk.Msg)(nil),
&MsgRequestDAS{},
&MsgReportDASResult{},
)
msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc)
}
// RegisterLegacyAminoCodec required for EIP-712
func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {
cdc.RegisterConcrete(&MsgRequestDAS{}, requestDASName, nil)
cdc.RegisterConcrete(&MsgReportDASResult{}, reportDASResultName, nil)
}

8
x/das/v1/types/errors.go Normal file
View File

@ -0,0 +1,8 @@
package types
import errorsmod "cosmossdk.io/errors"
var (
ErrUnknownRequest = errorsmod.Register(ModuleName, 0, "request not found")
ErrInvalidGenesis = errorsmod.Register(ModuleName, 1, "invalid genesis")
)

11
x/das/v1/types/events.go Normal file
View File

@ -0,0 +1,11 @@
package types
// Module event types
const (
EventTypeDASRequest = "das_request"
AttributeKeyRequestID = "request_id"
AttributeKeyStreamID = "stream_id"
AttributeKeyBatchHeaderHash = "batch_header_hash"
AttributeKeyNumBlobs = "num_blobs"
)

28
x/das/v1/types/genesis.go Normal file
View File

@ -0,0 +1,28 @@
package types
const (
DefaultNextRequestID = 0
)
// NewGenesisState returns a new genesis state object for the module.
func NewGenesisState(nextRequestID uint64, requests []DASRequest, responses []DASResponse) *GenesisState {
return &GenesisState{
NextRequestID: nextRequestID,
Requests: requests,
Responses: responses,
}
}
// DefaultGenesisState returns the default genesis state for the module.
func DefaultGenesisState() *GenesisState {
return NewGenesisState(
DefaultNextRequestID,
[]DASRequest{},
[]DASResponse{},
)
}
// Validate performs basic validation of genesis data.
func (gs GenesisState) Validate() error {
return nil
}

1191
x/das/v1/types/genesis.pb.go Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,10 @@
package types
import (
sdk "github.com/cosmos/cosmos-sdk/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)
type StakingKeeperRef interface {
GetValidator(ctx sdk.Context, addr sdk.ValAddress) (validator stakingtypes.Validator, found bool)
}

44
x/das/v1/types/keys.go Normal file
View File

@ -0,0 +1,44 @@
package types
import (
"encoding/binary"
sdk "github.com/cosmos/cosmos-sdk/types"
)
const (
// ModuleName The name that will be used throughout the module
ModuleName = "das"
// StoreKey Top level store key where all module items will be stored
StoreKey = ModuleName
)
// Key prefixes
var (
RequestKeyPrefix = []byte{0x00} // prefix for keys that store requests
ResponseKeyPrefix = []byte{0x01} // prefix for keys that store responses
NextRequestIDKey = []byte{0x02}
)
// GetKeyFromID returns the bytes to use as a key for a uint64 id
func GetKeyFromID(id uint64) []byte {
return Uint64ToBytes(id)
}
func GetResponseKey(requestID uint64, sampler sdk.ValAddress) []byte {
return append(GetKeyFromID(requestID), sampler.Bytes()...)
}
// Uint64ToBytes converts a uint64 into fixed length bytes for use in store keys.
func Uint64ToBytes(id uint64) []byte {
bz := make([]byte, 8)
binary.BigEndian.PutUint64(bz, uint64(id))
return bz
}
// Uint64FromBytes converts some fixed length bytes back into a uint64.
func Uint64FromBytes(bz []byte) uint64 {
return binary.BigEndian.Uint64(bz)
}

57
x/das/v1/types/msg.go Normal file
View File

@ -0,0 +1,57 @@
package types
import (
"encoding/hex"
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)
var _, _ sdk.Msg = &MsgRequestDAS{}, &MsgReportDASResult{}
func NewMsgRequestDAS(fromAddr sdk.AccAddress, streamID, hash string, numBlobs uint32) *MsgRequestDAS {
return &MsgRequestDAS{
Requester: fromAddr.String(),
StreamID: streamID,
BatchHeaderHash: hash,
NumBlobs: numBlobs,
}
}
func (msg MsgRequestDAS) GetSigners() []sdk.AccAddress {
from, err := sdk.AccAddressFromBech32(msg.Requester)
if err != nil {
panic(err)
}
return []sdk.AccAddress{from}
}
func (msg MsgRequestDAS) ValidateBasic() error {
_, err := sdk.AccAddressFromBech32(msg.Requester)
if err != nil {
return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid requester account address (%s)", err)
}
return nil
}
func (msg *MsgReportDASResult) GetSigners() []sdk.AccAddress {
samplerValAddr, err := sdk.ValAddressFromBech32(msg.Sampler)
if err != nil {
panic(err)
}
accAddr, err := sdk.AccAddressFromHexUnsafe(hex.EncodeToString(samplerValAddr.Bytes()))
if err != nil {
panic(err)
}
return []sdk.AccAddress{accAddr}
}
func (msg *MsgReportDASResult) ValidateBasic() error {
_, err := sdk.ValAddressFromBech32(msg.Sampler)
if err != nil {
return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid sampler validator address (%s)", err)
}
return nil
}

511
x/das/v1/types/query.pb.go Normal file
View File

@ -0,0 +1,511 @@
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: zgc/das/v1/query.proto
package types
import (
context "context"
fmt "fmt"
_ "github.com/cosmos/cosmos-proto"
_ "github.com/cosmos/cosmos-sdk/codec/types"
_ "github.com/gogo/protobuf/gogoproto"
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"
_ "google.golang.org/protobuf/types/known/timestamppb"
io "io"
math "math"
math_bits "math/bits"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
type QueryNextRequestIDRequest struct {
}
func (m *QueryNextRequestIDRequest) Reset() { *m = QueryNextRequestIDRequest{} }
func (m *QueryNextRequestIDRequest) String() string { return proto.CompactTextString(m) }
func (*QueryNextRequestIDRequest) ProtoMessage() {}
func (*QueryNextRequestIDRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_d404c1962bca645f, []int{0}
}
func (m *QueryNextRequestIDRequest) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryNextRequestIDRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryNextRequestIDRequest.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryNextRequestIDRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryNextRequestIDRequest.Merge(m, src)
}
func (m *QueryNextRequestIDRequest) XXX_Size() int {
return m.Size()
}
func (m *QueryNextRequestIDRequest) XXX_DiscardUnknown() {
xxx_messageInfo_QueryNextRequestIDRequest.DiscardUnknown(m)
}
var xxx_messageInfo_QueryNextRequestIDRequest proto.InternalMessageInfo
type QueryNextRequestIDResponse struct {
NextRequestID uint64 `protobuf:"varint,1,opt,name=next_request_id,json=nextRequestId,proto3" json:"next_request_id,omitempty"`
}
func (m *QueryNextRequestIDResponse) Reset() { *m = QueryNextRequestIDResponse{} }
func (m *QueryNextRequestIDResponse) String() string { return proto.CompactTextString(m) }
func (*QueryNextRequestIDResponse) ProtoMessage() {}
func (*QueryNextRequestIDResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_d404c1962bca645f, []int{1}
}
func (m *QueryNextRequestIDResponse) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *QueryNextRequestIDResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_QueryNextRequestIDResponse.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *QueryNextRequestIDResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_QueryNextRequestIDResponse.Merge(m, src)
}
func (m *QueryNextRequestIDResponse) XXX_Size() int {
return m.Size()
}
func (m *QueryNextRequestIDResponse) XXX_DiscardUnknown() {
xxx_messageInfo_QueryNextRequestIDResponse.DiscardUnknown(m)
}
var xxx_messageInfo_QueryNextRequestIDResponse proto.InternalMessageInfo
func init() {
proto.RegisterType((*QueryNextRequestIDRequest)(nil), "zgc.das.v1.QueryNextRequestIDRequest")
proto.RegisterType((*QueryNextRequestIDResponse)(nil), "zgc.das.v1.QueryNextRequestIDResponse")
}
func init() { proto.RegisterFile("zgc/das/v1/query.proto", fileDescriptor_d404c1962bca645f) }
var fileDescriptor_d404c1962bca645f = []byte{
// 334 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x91, 0xbf, 0x4b, 0x03, 0x31,
0x14, 0xc7, 0x2f, 0xa2, 0x0e, 0x81, 0x22, 0x1e, 0x22, 0xf6, 0x94, 0x54, 0x0b, 0xfe, 0x1a, 0x9a,
0xb4, 0x3a, 0xb9, 0x16, 0x41, 0x5c, 0x04, 0x5d, 0x04, 0x97, 0x92, 0xbb, 0x8b, 0x69, 0xa0, 0x97,
0x5c, 0x9b, 0x5c, 0x69, 0x3b, 0xba, 0xb8, 0x2a, 0xfe, 0x53, 0x1d, 0x0b, 0x2e, 0x4e, 0xa2, 0x57,
0xff, 0x10, 0xe9, 0xe5, 0x0e, 0xad, 0x28, 0x6e, 0xef, 0xbd, 0xef, 0xf7, 0x7d, 0xf3, 0xe1, 0x05,
0xae, 0x8f, 0x78, 0x40, 0x42, 0xaa, 0x49, 0xbf, 0x41, 0xba, 0x09, 0xeb, 0x0d, 0x71, 0xdc, 0x53,
0x46, 0xb9, 0x70, 0xc4, 0x03, 0x1c, 0x52, 0x8d, 0xfb, 0x0d, 0xaf, 0x1c, 0x28, 0x1d, 0x29, 0xdd,
0xca, 0x14, 0x62, 0x1b, 0x6b, 0xf3, 0xd6, 0xb8, 0xe2, 0xca, 0xce, 0x67, 0x55, 0x3e, 0xdd, 0xe2,
0x4a, 0xf1, 0x0e, 0x23, 0x34, 0x16, 0x84, 0x4a, 0xa9, 0x0c, 0x35, 0x42, 0xc9, 0x62, 0xa7, 0x9c,
0xab, 0x59, 0xe7, 0x27, 0xb7, 0x84, 0xca, 0xfc, 0x55, 0xaf, 0xf2, 0x53, 0x32, 0x22, 0x62, 0xda,
0xd0, 0x28, 0xb6, 0x86, 0xea, 0x26, 0x2c, 0x5f, 0xce, 0x28, 0x2f, 0xd8, 0xc0, 0x5c, 0xb1, 0x6e,
0xc2, 0xb4, 0x39, 0x3f, 0xcd, 0x8b, 0xea, 0x35, 0xf4, 0x7e, 0x13, 0x75, 0xac, 0xa4, 0x66, 0xee,
0x09, 0x5c, 0x91, 0x6c, 0x60, 0x5a, 0x3d, 0xab, 0xb4, 0x44, 0xb8, 0x01, 0xb6, 0xc1, 0xc1, 0x62,
0x73, 0x35, 0x7d, 0xad, 0x94, 0xe6, 0x77, 0x4a, 0xf2, 0x5b, 0x1b, 0x1e, 0x3d, 0x02, 0xb8, 0x94,
0x25, 0xbb, 0xf7, 0x00, 0xce, 0x5b, 0xdd, 0x5d, 0xfc, 0x75, 0x29, 0xfc, 0x27, 0x9b, 0xb7, 0xf7,
0x9f, 0xcd, 0x52, 0x56, 0xf7, 0xef, 0x9e, 0x3f, 0x9e, 0x16, 0x76, 0xdc, 0x0a, 0xa9, 0xf3, 0xa0,
0x4d, 0x85, 0x2c, 0x3e, 0x67, 0x46, 0x54, 0xcb, 0xd9, 0x6b, 0x22, 0x6c, 0x9e, 0x8d, 0xdf, 0x91,
0x33, 0x4e, 0x11, 0x98, 0xa4, 0x08, 0xbc, 0xa5, 0x08, 0x3c, 0x4c, 0x91, 0x33, 0x99, 0x22, 0xe7,
0x65, 0x8a, 0x9c, 0x9b, 0x43, 0x2e, 0x4c, 0x3b, 0xf1, 0x71, 0xa0, 0x22, 0x52, 0xe7, 0x1d, 0xea,
0x6b, 0x52, 0xe7, 0x35, 0x1b, 0x38, 0x28, 0x22, 0xcd, 0x30, 0x66, 0xda, 0x5f, 0xce, 0x2e, 0x7b,
0xfc, 0x19, 0x00, 0x00, 0xff, 0xff, 0xd5, 0x9e, 0xd6, 0x49, 0x0a, 0x02, 0x00, 0x00,
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion4
// QueryClient is the client API for Query service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type QueryClient interface {
NextRequestID(ctx context.Context, in *QueryNextRequestIDRequest, opts ...grpc.CallOption) (*QueryNextRequestIDResponse, error)
}
type queryClient struct {
cc grpc1.ClientConn
}
func NewQueryClient(cc grpc1.ClientConn) QueryClient {
return &queryClient{cc}
}
func (c *queryClient) NextRequestID(ctx context.Context, in *QueryNextRequestIDRequest, opts ...grpc.CallOption) (*QueryNextRequestIDResponse, error) {
out := new(QueryNextRequestIDResponse)
err := c.cc.Invoke(ctx, "/zgc.das.v1.Query/NextRequestID", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// QueryServer is the server API for Query service.
type QueryServer interface {
NextRequestID(context.Context, *QueryNextRequestIDRequest) (*QueryNextRequestIDResponse, error)
}
// UnimplementedQueryServer can be embedded to have forward compatible implementations.
type UnimplementedQueryServer struct {
}
func (*UnimplementedQueryServer) NextRequestID(ctx context.Context, req *QueryNextRequestIDRequest) (*QueryNextRequestIDResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method NextRequestID not implemented")
}
func RegisterQueryServer(s grpc1.Server, srv QueryServer) {
s.RegisterService(&_Query_serviceDesc, srv)
}
func _Query_NextRequestID_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(QueryNextRequestIDRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(QueryServer).NextRequestID(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/zgc.das.v1.Query/NextRequestID",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(QueryServer).NextRequestID(ctx, req.(*QueryNextRequestIDRequest))
}
return interceptor(ctx, in, info, handler)
}
var _Query_serviceDesc = grpc.ServiceDesc{
ServiceName: "zgc.das.v1.Query",
HandlerType: (*QueryServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "NextRequestID",
Handler: _Query_NextRequestID_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "zgc/das/v1/query.proto",
}
func (m *QueryNextRequestIDRequest) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryNextRequestIDRequest) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryNextRequestIDRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
return len(dAtA) - i, nil
}
func (m *QueryNextRequestIDResponse) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalToSizedBuffer(dAtA[:size])
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *QueryNextRequestIDResponse) MarshalTo(dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *QueryNextRequestIDResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.NextRequestID != 0 {
i = encodeVarintQuery(dAtA, i, uint64(m.NextRequestID))
i--
dAtA[i] = 0x8
}
return len(dAtA) - i, nil
}
func encodeVarintQuery(dAtA []byte, offset int, v uint64) int {
offset -= sovQuery(v)
base := offset
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return base
}
func (m *QueryNextRequestIDRequest) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
return n
}
func (m *QueryNextRequestIDResponse) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.NextRequestID != 0 {
n += 1 + sovQuery(uint64(m.NextRequestID))
}
return n
}
func sovQuery(x uint64) (n int) {
return (math_bits.Len64(x|1) + 6) / 7
}
func sozQuery(x uint64) (n int) {
return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *QueryNextRequestIDRequest) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryNextRequestIDRequest: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryNextRequestIDRequest: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *QueryNextRequestIDResponse) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: QueryNextRequestIDResponse: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: QueryNextRequestIDResponse: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field NextRequestID", wireType)
}
m.NextRequestID = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowQuery
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.NextRequestID |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipQuery(dAtA[iNdEx:])
if err != nil {
return err
}
if (skippy < 0) || (iNdEx+skippy) < 0 {
return ErrInvalidLengthQuery
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipQuery(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
depth := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowQuery
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowQuery
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
case 1:
iNdEx += 8
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowQuery
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if length < 0 {
return 0, ErrInvalidLengthQuery
}
iNdEx += length
case 3:
depth++
case 4:
if depth == 0 {
return 0, ErrUnexpectedEndOfGroupQuery
}
depth--
case 5:
iNdEx += 4
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
if iNdEx < 0 {
return 0, ErrInvalidLengthQuery
}
if depth == 0 {
return iNdEx, nil
}
}
return 0, io.ErrUnexpectedEOF
}
var (
ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow")
ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group")
)

View File

@ -0,0 +1,153 @@
// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
// source: zgc/das/v1/query.proto
/*
Package types is a reverse proxy.
It translates gRPC into RESTful JSON APIs.
*/
package types
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/metadata"
"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 _ = metadata.Join
func request_Query_NextRequestID_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq QueryNextRequestIDRequest
var metadata runtime.ServerMetadata
msg, err := client.NextRequestID(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_Query_NextRequestID_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq QueryNextRequestIDRequest
var metadata runtime.ServerMetadata
msg, err := server.NextRequestID(ctx, &protoReq)
return msg, metadata, err
}
// RegisterQueryHandlerServer registers the http handlers for service Query to "mux".
// UnaryRPC :call QueryServer directly.
// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906.
// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead.
func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error {
mux.Handle("GET", pattern_Query_NextRequestID_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
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_Query_NextRequestID_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Query_NextRequestID_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but
// automatically dials to "endpoint" and closes the connection when "ctx" gets done.
func RegisterQueryHandlerFromEndpoint(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 RegisterQueryHandler(ctx, mux, conn)
}
// RegisterQueryHandler registers the http handlers for service Query to "mux".
// The handlers forward requests to the grpc endpoint over "conn".
func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn))
}
// RegisterQueryHandlerClient registers the http handlers for service Query
// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient".
// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient"
// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in
// "QueryClient" to call the correct interceptors.
func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error {
mux.Handle("GET", pattern_Query_NextRequestID_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_Query_NextRequestID_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_Query_NextRequestID_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
var (
pattern_Query_NextRequestID_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"0gchain", "das", "v1", "next-request-id"}, "", runtime.AssumeColonVerbOpt(false)))
)
var (
forward_Query_NextRequestID_0 = runtime.ForwardResponseMessage
)

1110
x/das/v1/types/tx.pb.go Normal file

File diff suppressed because it is too large Load Diff